/*
 * jquery.simplePopupZone - jQuery 간단한 팝업존 플러그인
 *
 * Copyright (c) 2010 송치완 (nope0102@gmail.com)
 * 수정하든 말든 알아서...
 * 
 * Built on jQuery 1.4.2
 * http://jquery.com
 * 
 * 말이 플러그인이지 접근성 때문에 반의 반쪽짜리 플러그인임.
 * 스타일시트는 index_popup_zone.css쓰도록 하시고(메인페이지에 보면 있음)
 * 마크업도 메인페이지 보면 있으니 고대로 해야함...
 * 
 */          
;(function(){

    $.fn.simplePopupZone = function(option){
        
        var __p = this;
        var anchorDOMs = [];
        var controls = [];
        var total = 0;
        var clock;
        var doingNext = true;
        var doingPrev = false;
        var playing = true;
        
        $("span", __p).hide();
        
        $.each($("img", __p), function(i, el){
            total++;
            var _a = $(el).closest("a");
            var _c = $(_a).prev();
            anchorDOMs[i] = _a;
            i>0 && _a.hide();
            _a.attr("id", "_" + _a.attr("id"));//스크립트 작동시에는 아이디로 해쉬(#)이동 하지 않도록 아이디 바꿈
            controls[i] = _c;
        });
        //기본옵션
        option = $.extend({
            speed: 1000
            ,rollOverSuffix: "_on"
            ,autoSlide: true
            ,control:{
                prev: "#popupPrev"
                ,play: "#popupPlay"
                ,stop: "#popupStop"
                ,next: "#popupNext"
            }
        }, option);

        function init(){
            //팝업 번호 클릭 혹은 키보드 포커스
            $.each(controls, function(i, v){
                var c = this;
                $(c).bind("click focus", function(e){
                    changeImage(i);
                    stop();
                });
                //이미지 롤오버
                $(c).bind("mouseover focus", function(e){
                    var img = $(c).css("background-image");
                    if(img == "none")return;//IE CSS끌떄 background-image 찾지 못해서 스크립트 에러나는거 해소
                    if(img.indexOf(option.rollOverSuffix) != -1){return false;}
                    var prefix = img.substring(0, img.lastIndexOf("."));
                    var suffix = img.substring(img.lastIndexOf("."));
                    $(c).css({backgroundImage: prefix + option.rollOverSuffix + suffix});
                });
                $(c).bind("mouseout blur", function(e){
                    var img = $(c).css("background-image");
                    if(img == "none")return;//IE CSS끌떄 background-image 찾지 못해서 스크립트 에러나는거 해소
                    if(img.indexOf(option.rollOverSuffix) == -1){return false;}
                    var prefix = img.substring(0, img.lastIndexOf(option.rollOverSuffix));
                    var suffix = img.substring(img.lastIndexOf(option.rollOverSuffix) + option.rollOverSuffix.length);
                    $(c).css("background-image", prefix + suffix);
                });
            });
            //포커스 빠져나갈때 재시작
            $("a", $("div:eq(2)", __p)).first().blur(function(e){
                doingNext = true;
                doingPrev = false;
                if(!playing)play();
                $(option.control.stop).show();
                $(option.control.play).show();
				$(option.control.prev).hide();
				$(option.control.next).hide();
            });
            //포커스 빠져나갈때 재시작
            $("a", __p).last().blur(function(e){
                doingNext = true;
                doingPrev = false;
                if(!playing)play();
                $(option.control.stop).show();
                $(option.control.play).show();
				$(option.control.prev).hide();
				$(option.control.next).hide();
            });
            
            //팝업창 이동(링크 혹은 새창)
            $.each(anchorDOMs, function(i, v){
                $(this).bind("click", function(e){
                    if($(this).attr("href").indexOf("popup") != -1){
                        var previewWin = window.open($(this).attr("href"), "popupOpen", "menubar=no, toolbar=no, location=no, status=no, scrollbars=yes, top=0, left=0");
                        return false;
                }else{
                        return true;
                    }
                });
            });
            
            changeImage(0);
            play();
        };
        
        var showIndex = -1;
        //이미지교체 - 교체하면서 마우스오버이벤트 쐈다 죽였다 함...
        function changeImage(i){
            if(i == showIndex){return false;}//click 이나 focus가 발생했으면 둘중 하나만 실행한다.
            showIndex = i;
            //번호 맞는것만 show()하고 나머지 팝업은 hide()
            $.each(anchorDOMs, function(idx, v){
                if(i == idx){
                    $(v).show();
                    $(controls[i]).mouseover();
                }else{
                    $(v).hide();
                }
            });
            $.each(controls, function(c_idx, v){
                if(i != c_idx){
                    $(this).mouseout();
                }
            });
            
            return false;
        }
        
        //시작
        function play(){
            //오토슬라이드 true면 자동으로 움직이고 아니면 걍 냅둠..
            if(option.autoSlide){
                if(doingNext){
                    clock = window.setInterval(function(){
                        $(option.control.next).click();
                    }, option.speed);
                }else if(doingPrev){
                    clock = window.setInterval(function(){
                        $(option.control.prev).click();
                    }, option.speed);
                }
            }else{
                //nothing..
            }
        }
        //정지
        function stop(){
            doingNext = doingNext || false;
            doingPrev = doingPrev || false;
            playing = false;
            window.clearInterval(clock);
        }
        
        $(option.control.prev).click(function(e){
            var popupNo = showIndex - 1 < 0 ? total - 1 : showIndex - 1;
            changeImage(popupNo);
            doingPrev = true;
            doingNext = false;
        });
        
        $(option.control.next).click(function(e){
            var popupNo = showIndex + 1 > total - 1 ? 0 : showIndex + 1;
            changeImage(popupNo);
            doingPrev = false;
            doingNext = true;
        });
        
        $(option.control.stop).click(function(e){
            //이동방향 유지한채로 pause
            stop();
            $(option.control.stop).show();
            $(option.control.play).show();
			$(option.control.prev).hide();
			$(option.control.next).hide();
        });
        
        $(option.control.play).click(function(e){
            if(!doingNext && !doingPrev){return false;}
            play();
            playing = true;
            $(option.control.stop).show();
            $(option.control.play).show();
			$(option.control.prev).hide();
			$(option.control.next).hide();
        });
        init();
        return this;
    };
    
})(jQuery);          
