/**
 * vi:set ts=4 sw=4 expandtab enc=utf8:
 * @brief 일부 코드를 resize_image 애드온에서 따왔습니다.
 **/

function colorbox_callback() {
    var colorbox = document.getElementById('colorbox');
    var $img = jQuery('img', colorbox);
    if (jQuery.browser.msie && jQuery.browser.version <= 7.0) {
        // do not display
    } else {
        display_exif_button($img);
    }
}

// imageinfo callback function(called by ImageInfo.loadInfo)
function display_imageinfo($img) {
    if ($img.cache) {
        $img.cache.css('display', 'block');
        return;
    }

    var imgpos = $img.position();
    var file = $img.attr('src');


    var div = document.createElement('div');
    $div = jQuery(div);
    $div.addClass('ImageInfo');
    var imgIdx = 0;
    if ($img.attr('z-index')) imgIdx = $img.attr('z-index');
    $div.css('z-index', imgIdx+2);

    var ul = document.createElement('ul');
    $ul = jQuery(ul);

    var all = ImageInfo.getAllFields(file);
    for (var f in display_elements) {
        if (!display_elements[f]) continue;
        if (all[f]) $ul.append('<li>' + '<span>' + ExifTags[f] + ' : ' + '</span>' + all[f] + '</li>');
        else if (all['exif'][f]) $ul.append('<li>' + '<span>' + ExifTags[f] + ' : ' + '</span>' + all['exif'][f] + '</li>');
    }

    if ($ul.children().size() == 0) $ul.append('<li>No image information.</li>');

    $div.append($ul);

    $img.cache = $div;

    $panel = jQuery('.ExifPanel', $img.parent());
    $panel.append($div);
}

function display_exif_button($img) {
    var imgSrc = $img.attr('src');
    var imgpos = $img.position();
    var but = document.createElement('span');
    $but = jQuery(but);
    $but.addClass('exifButton');
    /*
    $but.css('top', imgpos.top + 30);
    $but.css('left', imgpos.left + 30);
    */
    var imgIdx = 0;
    if ($img.attr('z-index')) imgIdx = $img.attr('z-index');
    $but.css('z-index', imgIdx+3);
    $but.toggle(
        function() {
            jQuery(this).addClass('active');
            ImageInfo.loadInfo(imgSrc, function() { display_imageinfo($img); });
        },
        function() {
            jQuery(this).removeClass('active');
            if ($img.cache) {
                $img.cache.css('display', 'none');
            }
        }
    );

    var panel = document.createElement('div');
    $panel = jQuery(panel);
    $panel.css('top', imgpos.top + 20);
    $panel.css('left', imgpos.left + 20);
    $panel.addClass('ExifPanel');
    $panel.css('z-index', imgIdx+1);
    $panel.append($but);

    $img.parent().append($panel);

    var hideTimer;

    $img.parent().children().mouseenter(
        function() {
            jQuery('.ExifPanel', jQuery(this).parent()).show();

            if (hideTimer) {
                clearTimeout(hideTimer);
                hideTimer = null;
            }
            if (!jQuery(this).hasClass('ExifPanel')) {
                hideTimer = setTimeout(function() { 
                    $img.trigger('mouseleave');
                }, 2000);
            }
        }
    );

    $img.parent().children().mousemove(function() {
         jQuery(this).trigger('mouseenter');
    });

    $img.mouseleave(function() {
        if (hideTimer) {
            clearTimeout(hideTimer);
            hideTimer = null;
        }
        jQuery('.ExifPanel', jQuery(this).parent()).hide();
    });
}

(function($){
    /* DOM READY */
    jQuery(function($) {
        var regx_skip = /(?:(modules|addons|classes|common|layouts|libs|widgets|widgetstyles)\/)/i;
        var regx_allow_i6pngfix = /(?:common\/tpl\/images\/blank\.gif$)/i;
        /**
         * 본문 폭 구하기 위한 개체
         * IE6에서 본문폭을 넘는 이미지가 있으면 그 크기로 구해지는 문제 우회용
         **/
        var dummy = $('<div style="height:1; overflow:hidden; opacity:0; display:block; clear:both;"></div>');

        /**
         * 리사이즈 실행 함수
         **/
        function doResize(contentWidth, count) {
            // 재시도 회수 제한
            if(!count) count = 0;
            if(count >= 10) return;



            var $img = this;
            var beforSize = {'width':$img.width(), 'height':$img.height()};

            // 이미지 사이즈를 구하지 못했을 때 재시도
            if(!beforSize.width || !beforSize.height) {
                setTimeout(function() {
                    doResize.call($img, contentWidth, ++count)
                }, 200);
                return;
            }

            // image resizing.
            if(beforSize.width > contentWidth) {
				var resize_ratio = contentWidth / beforSize.width;
				$img
					.removeAttr('width').removeAttr('height')
					.css({
						'width':contentWidth,
						'height':parseInt(beforSize.height * resize_ratio, 10)
					});
			}

            // link가 있으면 return
            if ($img.parent('a').length || $img.attr('onclick')) return;

            // 이미 rel이 autofocus_images 이면 return
            if ($img.attr('rel') == 'autofocus_images') return;

            var a = document.createElement('a');
            $(a).attr('href', $img.attr('src'));
            $(a).attr('rel', 'autofocus_images');
            $(a).attr('title', $img.attr('alt'));

            $img.css('cursor', 'pointer');
            $img.attr('rel', 'autofocus_images');
            $img.after($(a));
        }

        // replace for current language
        EXIF.StringValues = ExifStringValues;

        $('div.xe_content').each(function() {
            dummy.appendTo(this);
            var contentWidth = dummy.width();
            dummy.remove();
            if(!contentWidth) return;

            $('img', this).each(function() {
                var $img = $(this);
                var imgSrc = $img.attr('src');
                if(regx_skip.test(imgSrc) && !regx_allow_i6pngfix.test(imgSrc)) return;

                doResize.call($img, contentWidth);

                if (jQuery.browser.msie && jQuery.browser.version <= 7.0) {
                    // do not display
                } else {
                    display_exif_button($img);
                }
            });
        });
    });
})(jQuery);
