/**
 * 움직이는 배너 Jquery Plug-in
 * @author  cafe24
 */

;(function($){

    $.fn.floatBanner = function(options) {
        options = $.extend({}, $.fn.floatBanner.defaults , options);

        return this.each(function() {
            var aPosition = $(this).position();
            var node = this;

            $(window).scroll(function() {
                var _top = $(document).scrollTop();
                _top = (aPosition.top < _top) ? _top : aPosition.top;

                setTimeout(function () {
                    $(node).stop().animate({top: _top}, options.animate);
                }, options.delay);
            });
        });
    };

    $.fn.floatBanner.defaults = {
        'animate'  : 500,
        'delay'    : 500
    };

})(jQuery);

/**
 * 문서 구동후 시작
 */
$(document).ready(function(){
    $('#banner:visible, #quick:visible').floatBanner();
});

/**
 *  썸네일 이미지 엑박일경우 기본값 설정
 */
$(window).load(function() {
    $("img.thumb,img.ThumbImage,img.BigImage").each(function($i,$item){
        var $img = new Image();
        $img.onerror = function () {
                $item.src="//img.echosting.cafe24.com/thumb/img_product_big.gif";
        }
        $img.src = this.src;
    });
});
//window popup script
function winPop(url) {
    window.open(url, "popup", "width=300,height=300,left=10,top=10,resizable=no,scrollbars=no");
}
/**
 * document.location.href split
 * return array Param
 */
function getQueryString(sKey)
{
    var sQueryString = document.location.search.substring(1);
    var aParam       = {};

    if (sQueryString) {
        var aFields = sQueryString.split("&");
        var aField  = [];
        for (var i=0; i<aFields.length; i++) {
            aField = aFields[i].split('=');
            aParam[aField[0]] = aField[1];
        }
    }

    aParam.page = aParam.page ? aParam.page : 1;
    return sKey ? aParam[sKey] : aParam;
};

$(document).ready(function(){
    // tab
    $.eTab = function(ul){
        $(ul).find('a').click(function(){
            var _li = $(this).parent('li').addClass('selected').siblings().removeClass('selected'),
                _target = $(this).attr('href'),
                _siblings = '.' + $(_target).attr('class');
            $(_target).show().siblings(_siblings).hide();
            return false
        });
    }
    if ( window.call_eTab ) {
        call_eTab();
    };
});
(function($){
$.fn.extend({
    center: function() {
        this.each(function() {
            var
                $this = $(this),
                $w = $(window);
            $this.css({
                position: "absolute",
                top: ~~(($w.height() - $this.outerHeight()) / 2) + $w.scrollTop() + "px",
                left: ~~(($w.width() - $this.outerWidth()) / 2) + $w.scrollLeft() + "px"
            });
        });
        return this;
    }
});
$(function() {
    var $container = function(){/*
<div id="modalContainer">
    <iframe id="modalContent" scroll="0" scrolling="no" frameBorder="0"></iframe>
</div>');
*/}.toString().slice(14,-3);
    $('body')
    .append($('<div id="modalBackpanel"></div>'))
    .append($($container));
    function closeModal () {
        $('#modalContainer').hide();
        $('#modalBackpanel').hide();
    }
    $('#modalBackpanel').click(closeModal);
    zoom = function ($piProductNo, $piCategoryNo, $piDisplayGroup) {
        var $url = '/product/image_zoom.html?product_no=' + $piProductNo + '&cate_no=' + $piCategoryNo + '&display_group=' + $piDisplayGroup;
        $('#modalContent').attr('src', $url);
        $('#modalContent').bind("load",function(){
            $(".header .close",this.contentWindow.document.body).bind("click", closeModal);
        });
        $('#modalBackpanel').css({width:$("body").width(),height:$("body").height(),opacity:.4}).show();
        $('#modalContainer').center().show();
    }
});
})(jQuery);
$(document).ready(function () {
    balloon_Moving();
});

// 아이콘 움직임
function balloon_Moving() {
    $("#img_ball")
    .animate({ marginTop: "5px" }, 500, "", function () {
        $(this)
        .animate({ marginTop: "0px" }, 500, "", function () {
        // 자기 호출
        balloon_Moving(); });
    });
}
var TINY={};

function T$(i){return document.getElementById(i)}
function T$$(e,p){return p.getElementsByTagName(e)}

TINY.dropdown=function(){
	var p={fade:1,slide:1,active:0,timeout:200}, init=function(n,o){
		for(s in o){p[s]=o[s]} p.n=n; this.build()
	};
	init.prototype.build=function(){
		this.h=[]; this.c=[]; this.z=1000;
		var s=T$$('ul',T$(p.id)), l=s.length, i=0; p.speed=p.speed?p.speed*.1:.5;
		for(i;i<l;i++){
			var h=s[i].parentNode; this.h[i]=h; this.c[i]=s[i];
			h.onmouseover=new Function(p.n+'.show('+i+',1)');
			h.onmouseout=new Function(p.n+'.show('+i+')')
		}
	};
	init.prototype.show=function(x,d){
		var c=this.c[x], h=this.h[x];
		clearInterval(c.t); clearInterval(c.i); c.style.overflow='hidden';
		if(d){
			if(p.active&&h.className.indexOf(p.active)==-1){h.className+=' '+p.active}
			if(p.fade||p.slide){
				c.style.display='block';
				if(!c.m){
					if(p.slide){
						c.style.visibility='hidden'; c.m=c.offsetHeight; c.style.height='0'; c.style.visibility=''
					}else{
						c.m=100; c.style.opacity=0; c.style.filter='alpha(opacity=0)'
					}
					c.v=0
				}
				if(p.slide){
					if(c.m==c.v){
						c.style.overflow='visible'
					}else{
						c.style.zIndex=this.z; this.z++; c.i=setInterval(function(){slide(c,c.m,1)},20)
					}
				}else{
					c.style.zIndex=this.z; this.z++; c.i=setInterval(function(){slide(c,c.m,1)},20)
				}
			}else{
				c.style.zIndex=this.z; c.style.display='block'
			}
		}else{
			c.t=setTimeout(function(){hide(c,p.fade||p.slide?1:0,h,p.active)},p.timeout)
		}
	};
	function hide(c,t,h,s){
		if(s){h.className=h.className.replace(s,'')}
		if(t){c.i=setInterval(function(){slide(c,0,-1)},20)}else{c.style.display='none'}
	}
	function slide(c,t,d){
		if(c.v==t){
			clearInterval(c.i); c.i=0;
			if(d==1){
				if(p.fade){c.style.filter=''; c.style.opacity=1}
				c.style.overflow='visible'
			}
		}else{
			c.v=(t-Math.floor(Math.abs(t-c.v)*p.speed)*d);
			if(p.slide){c.style.height=c.v+'px'}
			if(p.fade){var o=c.v/c.m; c.style.opacity=o; c.style.filter='alpha(opacity='+(o*100)+')'}
		}
	}
	return{init:init}
}();

var dropdown=new TINY.dropdown.init("dropdown", {id:'gnb', active:'menuhover'});
$(function () {
  var msie6 = $.browser == 'msie' && $.browser.version < 7;
  if (!msie6) {
    var gnb = $('#gnb_bg').offset().top - parseFloat($('#gnb_bg').css('margin-top').replace(/auto/, 0));  // 상단메뉴 영역

    $(window).scroll(function (event) {
      var y = $(this).scrollTop();

      // 상단메뉴 영역
      if (y >= gnb) {
        $('#gnb_bg').addClass('fixed');
      } else {
        $('#gnb_bg').removeClass('fixed');
      }
    });
  }
});

// 전체카테고리 레이어 출력
var vi = "off";
$(function(){
    $(".all_categories").click(function(){
        if(vi == "off"){
            $(".open_cate").slideDown(100);
            $(".btn_categories_view").slideDown(100);
            vi = "on";
        }else{
            $(".open_cate").slideUp(100);
            $(".btn_categories_view").slideUp(100);
            vi = "off";
        }
    });
    $(".open_cate_close").click(function(){
         $(".open_cate").slideUp(100);
         $(".btn_categories_view").slideUp(100);
         vi = "off";
    });

	// 열린 전체카테고리에서 마우스가 벗어나면 레이어가 사라짐
    $('.open_cate').mouseleave(function(e) {
        $(".open_cate").slideUp(100);
        $(".btn_categories_view").slideUp(100);
		vi = "off";
    });

    // 상단메뉴에 마우스오버시 열린 전체카테고리 레이어가 사라짐
	$('#gnb').mouseover(function(e) {
        $(".open_cate").slideUp(100);
        $(".btn_categories_view").slideUp(100);
		vi = "off";
    });
});
/*
 * uger agent 체크, ie 아닐경우 window blur 이벤트 구분
 */
var ugeragent = navigator.userAgent;
ugeragent = ugeragent.toLowerCase();
var ie = false;
if(-1 < ugeragent.indexOf('msie')){
	ie = true;
}
var window_focus = 'focus';
if(ie == false){
	window.addEventListener('focus', function() {
		window_focus = 'focus';
	},false);
	window.addEventListener('blur', function() {
		window_focus = 'blur';
	},false);
}

var initMainVisual = function(){
	var visual = jQuery("#mainVisual"),
	visuals = visual.find("div.visuals"),
	items = visuals.find("> a"),
	nums = items.length - 1,
	flag = 0,
	circle = visual.find("div.circle"),
	circles = '',
	speed = 500,
	interval = 3000; // 메인 자동롤링 인터벌

	var timerMainVisual;

	timerMainVisual = setInterval(function(){
		if(window_focus == "focus"){
			visual.find("a.next").trigger('click');
		}else{
			return;
		}
	}, interval);
	visual.bind({
		mouseenter: function() {
			clearInterval(timerMainVisual);
		},
		mouseleave: function(){
			timerMainVisual = setInterval(function(){
				if(window_focus == "focus"){
					visual.find("a.next").trigger('click');
				}else{
					return;
				}
			}, interval);
		}
	});
	// 롤링 동작 처리
	var rollingVisual = function(){
		if(flag < 0){
			flag = nums;
		}else if(flag > nums){
			flag = 0;
		}
		items.css("z-index","");
		visuals.find("a").eq(flag).css("display","block").css("z-index","1").fadeTo(speed,1,function(){
			visuals.find("a").each(function(index, element) {
				if($(this).index() != flag){
					$(this).css("display","block").css("opacity","0").css("z-index","")
				}
			});
		});
		circle.find("a").removeClass("active");
		circle.find("a").eq(flag).addClass("active");
	};

	// 초기 비주얼 하나만 보이게 처리하고 비주얼 갯수만큼 버튼 생성
	visuals.find("a").each(function(index, element) {
		if($(this).index() == 0){
			$(this).css("display","block").css("opacity","1").css("z-index","1");
			circles += '<a class="active" href="#'+$(this).attr("href")+'">'+$(this).index()+'</a>';
		}else{
			$(this).css("display","block").css("opacity","0").css("z-index","");
			circles += '<a href="#'+$(this).attr("href")+'">'+$(this).index()+'</a>';
		}
	});
	circle.html(circles);

	// 비주얼 롤링 버튼 클릭 바인딩
	circle.find("a").click(function(){
		var eq = $(this).index();
		if(eq != flag){
			flag = eq;
			rollingVisual();
		}
	});

	// 좌우 버튼 클릭 바인딩
	visual.find("a.spinn").click(function(){
		if($(this).hasClass("prev")){
			flag = flag - 1;
			rollingVisual()
		}else if($(this).hasClass("next")){
			flag = flag + 1;
			rollingVisual()
		}
		return false;
	});
};
// 로드시 initMainVisual 함수 실행
jQuery(function(){
	initMainVisual();
});
(function($) {
	$(document).ready(function() {
		// 맨 위로 이동
		$('#on_top').click(function(e) {
			$('body, html').stop().animate({scrollTop:0}, 500);
			e.preventDefault();
		});
		var scrollTimer = null;
		$(window).scroll(function(e) {
			clearTimeout(scrollTimer);
			scrollTimer = setTimeout(function() {
				var scrollTop = $(window).scrollTop();
				if(scrollTop > 100) $('#on_top').fadeIn(600);
				else $('#on_top').fadeOut(200);
			}, 100);
		});
	});
}(jQuery));
