/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


var ktw = {};


ktw.ui = {
    callback : null ,
    init : function(){
        core.ui.comboBoxMenu.enable();
        core.ajaxify.anchorWithCallback(".ajaxify",function(response){
            $.fn.colorbox({html:response , opacity: 0.5});
            if( ktw.ui.callback )
                ktw.ui.callback();
        })

        ktw.traveler.init();
        
    }
}

ktw.slider = {
    width:660 , height: 495 ,
    initlized : false , mapInstance : null , paneInstance : null , slideCount : 0 , currentSlideNo : 0 , interval : null ,
    slideUl : null , selector : null , lock : false ,
    paneInterval : null ,
    loadJSON : function ( json ){
        
    } ,
    front : function( selector ){
       if( selector == undefined ) selector = '#headline-slider';

       this.selector = selector

       var container = $('<div />');
       container.attr('id','container');

       var ul = $('<ul />');
       var li , img ;
       var count = 0;

       ul.css('width',9999).css('position','relative').css('left',-950)

       this.slideCount = count = $(selector+' .item').length ;

       $(selector+' .item img').each( function( idx ) {
           var a = $(this).parent();
           a.click(function(){
               ktw.slider.play( idx );
               
               return false;
           })

           var imgA = $('<a />');
           imgA.attr('href' , a.attr('href')) ; 
           img = $('<img />').attr('className','bigImage');
           img.attr('src',a.prev().val());

           imgA.append(img) ; 
           li = $('<li />');

           

           if( idx < count-1 )
           {li.append( imgA );ul.append( li );}
           else
           {li.prepend( imgA );ul.prepend( li );}
       });

       container.append(ul);

       var info = $('<div />');
       info.addClass('slideinfo');

       container.append( info );


       $(selector).prepend(container);

       this.slideUl = ul;
       this.setCurrent(0);
       this.play();
    } ,
    setCurrent : function( no ){

       this.currentSlideNo = no;
       $(this.selector+ ' .item > p > a').removeClass('active');
       var c = $(this.selector+ ' .item > p > a')[no] ;
       $(c).addClass('active');

       $(this.selector + ' .slideinfo' ).html( $(c).parents('.item').children('.item-content').html() );
       //$(this.selector+ ' .slideinfo dt').text( $(c).attr('title'));
       //$(this.selector+ ' .slideinfo dd').html( $(c).next());

    } ,
    play : function( n )
    {
        var ul = this.slideUl;
        
        if( n == undefined ){

            clearTimeout( this.interval );
            var currentNo = (this.currentSlideNo+1)%this.slideCount;
            

            this.interval = setTimeout( function(){

                var f = ul.children('li')[0];
                var l = $(f).clone();
                $(f).addClass('toremove');
                ul.append(l);

                this.lock = true ;
                ul.animate( {left : -1900} , 1800 , function(){

                   
                   $(this).children('.toremove').remove();
                   $(this).css('left',-950);

                   ktw.slider.setCurrent( currentNo );                   
                   ktw.slider.play();
                   

               });
           } , 3000 );
        }
        else
        {
            if( n == this.currentSlideNo ) return false;
            
            clearTimeout( this.interval );

            var d = n - this.currentSlideNo ;
            
            if( d > 0 ){

                var f, l ;
                

                ktw.slider.setCurrent( n );

                for( var x = 0 ; x < d ; x++ )
                {
                    f = ul.children('li')[x];
                    l = $(f).clone() ;
                    $(f).addClass('toremove');
                    ul.append(l);
                }

                var shift = -950 * (d+1);

                ul.animate( {left : shift} , 1800 , function(){

                    $(this).children('.toremove').remove();
                    $(this).css('left',-950);
                    ktw.slider.play();

               });



            } else if( d < 0 ){


                ktw.slider.setCurrent( n );
                var q = new Array();

                for( var x = 0 ; x < this.slideCount+d ; x++ )
                {
                    f = ul.children('li')[x];
                    l = $(f).clone() ;
                    $(f).addClass('toremove');
                    ul.append(l);
                }
                                
                var shift = -950 * (this.slideCount+d+1);
                
                
                ul.animate( {left : shift} , 1800 , function(){    
                    $(this).children('.toremove').remove();
                    $(this).css('left',-950);                    
                    ktw.slider.play();

               });

            }
        }
    }
    ,
    load : function( selector )
    { //alert('load');
        if( selector == undefined ) selector = '#slideplayer' ;

        var divs = $(selector+' > div');
        divs.each( function(idx){

            var pane = $(this);

            if( $(this).hasClass('map')) {

                var lat = $('dd.lat', pane ).text();
                var lng = $('dd.lng', pane ).text();
                $(this).append("<div id='mapcontainer' style='width:660px;height:495px;'></div>");
                $('.latlng,h2',$(this)).hide();

                ktw.slider.loadMap( 'mapcontainer' , lat , lng );
            }

            var itemsCount = $('.items .item' , pane ).length ;
            if( itemsCount > 0 ){
                
                var wLi = $('.items .item').width() + 2 + parseInt( $('.items .item').css('marginRight') ) ;
                var wContainer = wLi * itemsCount ;
                if( wContainer >  $('.items' , pane ).width() ){
                    
                    //alert( wContainer );

                    $('.item-list' , pane ).wrap('<div class="item-container"></div>').width( wContainer );
                    
                    var prev = $('<li class="prev">Previous</li>');
                    var next = $('<li class="next">Next</li>');

                    prev.click( function(){
                        $('.item-container' , pane ).animate( {scrollLeft : '-=' + wLi});
                    })
                    next.click( function(){
                        $('.item-container' , pane ).animate( {scrollLeft : '+=' + wLi});
                    })

                    var itemNavi = $('<ul class="item-navi"></ul>')
                    itemNavi.append( prev ).append( next );
                    $('.items' , pane ).append( itemNavi);
                }
            }

            $(this).css('position','absolute');
            
            if( idx == 0 ){
                $(this).css('z-index',1);
                ktw.slider.paneInstance = this;
            } else {
                $(this).css('z-index',0);
            }
            
        });

        $(selector+' .tabmenu li a').each( function(idx){
            $(this).click( function(){
                $(selector+' .tabmenu li').removeClass('active');
                $(this).parent().addClass('active');
                divs.css('z-index',0);//讓所有div的z到最下面
                $(divs[idx]).css('z-index',1);//讓該div跑到最上面來

                ktw.slider.paneInstance = divs[idx];
                ktw.slider.playPane();
                return false;
            })
        });

        //close and info
        $(selector+' .close').click(function()
        {
            $(this).parent().hide();
            $(this).parent().parent().find('.info').addClass('turnoff');
        })

        $(selector+' .info').click(function()
        {
            if($(this).hasClass('turnoff')){
                $(this).parent().parent().parent().find(".description").show();
                $(this).removeClass('turnoff');
            }
            else{
                $(this).parent().parent().parent().find(".description").hide();
                $(this).addClass('turnoff');
            }
            return false;
        })
        

        ktw.slider.playPane();

    } ,
    loadMap : function( containerId , latitude , langitude ){

        //alert( latitude + ","+langitude );

        var latlng = new google.maps.LatLng( latitude , langitude  );
        var myOptions = {
          zoom: 13,
          center: latlng,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };


        this.mapInstance = new google.maps.Map(document.getElementById( containerId ), myOptions);

        marker = new google.maps.Marker({
            position: latlng ,
            map: this.mapInstance
        });
        this.mapInstance.panTo( latlng );
        $(window).resize();
    } ,
    playPane : function()
    {
        //alert('playpane') ;
        var pane = $(this.paneInstance );
        if( pane.hasClass('map')) return ;
        //alert('play');
        var slides = $('.slides-container' , pane );
        if( slides.length == 0 ){

            slides = $('<div></div>');
            slides.addClass('slides-container');
            slides.css('position','absolute').css('z-index',-1);
            pane.append(slides);

            var list = $('<ul />');
            list.css('position','relative');
            slides.append(list);
            
            var li = null , img = null ;

            $('.items a img',pane).each( function(idx){
                img = $("<img />");
                img.attr('src',$(this).parent().attr('href'));
                li = $("<li />");
                li.css('position','absolute').hide();
                li.append(img);
                list.append(li);
                
                $(this).parent().click(function(){
                    clearTimeout( ktw.slider.paneInterval );
                    $('li',list).fadeOut();
                    $($('li',list)[idx]).fadeIn();

                    if( $(this).parents('.item').children('.item-content').length )
                        pane.children('.description').html( $(this).parents('.item').children('.item-content').html() );                    

                    var n = $('.items a img',pane)[idx+1];
                    if( !n ){
                        n = $('.items a img',pane)[0];
                    }
                    ktw.slider.paneInterval = setTimeout( function(){$(n).parent().click();} , 6000);

                    return false;
                })

                if( idx == 0)   {
                    $(this).parent().click();
                }
            });
        }

        
    }
}

ktw.traveler = {
    target : null ,
    init : function(){
        return ;
        this.ui.init();
        $(".spotlist > .entry").each( function(){
        
            if( $(this).hasClass('first')) return ;
            var object = $(this).find('a:first-child');
            object.mousedown( function(){                
                ktw.traveler.ui.prePick( object );
                return false;
            });
            object.mouseup( function(){
                ktw.traveler.ui.postPick( object );
            })
            object.click( function(){return false;})
        });
        $('#favorite-area').hover( ktw.traveler.fav.mousein , ktw.traveler.fav.mouseout );
    }
}

ktw.traveler.ui = {
    miniHeight : 60 , isExpanded : false , isHover : false , normalHeight :80 ,
    hasSelected : false , target : null ,
    instance : null ,
    releaseHandler : function(){
        if( ktw.traveler.ui.isHover ) return false;
        ktw.traveler.ui.spread()
        $(document).unbind( 'mouseup' , ktw.traveler.ui.releaseHandler );
    } ,
    init : function(){
        this.onScroll();
        this.instance = $('#traveler');
        $(window).bind('scroll', this.onScroll );

        this.instance.hover( ktw.traveler.ui.mousein , ktw.traveler.ui.mouseout );
        
    },

    prePick : function( obj ){
        this.target = obj
        $(obj).bind( 'mousemove' , ktw.traveler.ui.onPick );
        //ktw.traveler.target.bind( 'mousemove' , ktw.traveler.ui.onPick );
        //ktw.traveler.target.bind( 'mousemove' , ktw.traveler.ui.onPick );
    } ,
    onPick : function(){
        ktw.traveler.ui.hasSelected = true;
        ktw.traveler.ui.target.unbind( 'mousemove' , ktw.traveler.ui.onPick );
        ktw.traveler.ui.expand();
        
        $(document).bind('mouseup' , ktw.traveler.ui.releaseHandler );
    } ,
    
    postPick : function( ){
       if( !this.hasSelected )
           return location.href= this.target.attr('href');

       this.hasSelected = false;
    } ,
    

    mouseout : function(){
        ktw.traveler.ui.isHover = false;
        if( ktw.traveler.ui.hasSelected ){
            ktw.traveler.ui.spread();
        }
    } ,
    mousein : function(){
        ktw.traveler.ui.expand();
        ktw.traveler.ui.isHover = true ;
    },
    
    expand : function(){
        if( ktw.traveler.ui.isExpanded ) return false ;
        ktw.traveler.ui.isExpanded = true;
        var top = ktw.traveler.ui.getTop()-ktw.traveler.ui.miniHeight ;
        $('#traveler').animate( {top : top , height : ktw.traveler.ui.miniHeight} , 500 , function(){
            $(this).children('.inner').show();
        });
    },
    spread : function(){
        if( !ktw.traveler.ui.isExpanded ) return false ;
        ktw.traveler.ui.isExpanded = false;
        var top = ktw.traveler.ui.getTop()+ktw.traveler.ui.miniHeight ;
        $('#traveler').animate( {top : top , height : 0} , 500 , function(){
            $(this).children('.inner').hide();
        });
    },


    getTop : function(){
        return $(window).height() + $(window).scrollTop() - $('#traveler').height();
    } ,
    onScroll : function(){
        //alert('a');
        var top = ktw.traveler.ui.getTop() ;
        if( top > $('body').height() )
        {
            top = $('body').height();
        }
            
        $('#traveler').css('top' , top );
    }
}


ktw.traveler.fav = {
    mousein : function (){
        $('#favorite-area').bind('mouseup', ktw.traveler.fav.putin );
        $('#favorite-area').addClass('hover');
    } ,
    mouseout : function (){
        $('#favorite-area').unbind('mouseup', ktw.traveler.fav.putin );
        $('#favorite-area').removeClass('hover');
    } ,
    putin : function(){
        var obj = ktw.traveler.ui.target ;
        var meta = obj.parent().attr('id').split('-');

        var url = '/rest/favorite/' ;
        var data = 'form[resource_id]=' + meta[1] + '&form[instance_id]=' + meta[2] ;
        alert( 'post to ' + url + '?' + data );
        //alert( obj.pa.children('.id').text() );
    }

}

ktw.comment = {
    commentLabelSelector:'#comment-form-label',commentTextSelector:'#comment-form-text',
    commentParentSelector:'#comment-form-parent',commentFormSelector:'#comment-form',commentFloorSelector:'.comment-floor',
    label:null,text:null,parentId:null,commentInstance:null,

    quote:function(commentInstance,parentId){

        this.commentInstance = commentInstance;
        this.label = $('#'+this.commentInstance.attr('id')+' .comment-label').text()
        this.text = this.addMark();
        this.parentId = parentId;
        this.insertParentHidden();
        
        $(this.commentLabelSelector).val('Re : '+$.trim(this.label));
        $(this.commentTextSelector).val(this.text);
        $(this.commentParentSelector).val(this.parentId);

        window.location.href=this.commentFormSelector;

        $(this.commentTextSelector).focus();
        
    },

    insertParentHidden:function(){
        var parentHidden = $('<input type="hidden" name="form[parent_id]" />').attr('id',this.commentParentSelector.replace('#',''));
        $(this.commentFormSelector).append(parentHidden);

    },

    reset:function(){
        $(this.commentParentSelector).remove();
    },

    addMark:function(){//加上引言的mark
        var mark = '＞ ';
        var text  = $('#'+this.commentInstance.attr('id')+' .hidden-text').html();
        text  = text.replace(/\n/g,'');
        text = mark+text.replace(/<br>/g,'\n'+mark);
        text = text+'\n';

        return text ; 
    },

    floorable:function(){
        var floorNum = $(this.commentFloorSelector).length;
        $(this.commentFloorSelector).each(function(idx){
          $(this).text((floorNum--)+'樓');
        })
    }
}
