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

(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;

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

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

            /*
            // replace with a
            var a = document.createElement('a');
            $(a).attr('href', $img.attr('src'));
            $(a).attr('rel', 'focus_images');
            $(a).attr('title', $img.attr('alt'));
            $(a).append($img.clone());
            $img.replaceWith($(a));
            */
        }

        $('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;

                $img.attr('rel', 'xe_gallery');

                doResize.call($img, contentWidth);
            });
        });
    });
})(jQuery);

