/* =============================================================================
   Set cast image top style
   ========================================================================== */
$.fn.setTop = function(){
    var el          = $(this);
    var initop      = ($(window).height() / 100) * 20;
    var elheight    = $('>img', this).height();
    var winheight   = $(window).height();

    if(winheight > (initop + elheight)){
        var newtop = (((winheight - elheight) * 100 ) / winheight) + "%";
        el.css({'top': newtop});
    }else{
        el.css({'top': '20%'});
    }
}

/* =============================================================================
   Document Load
   ========================================================================== */
$(function(){

    // Set Direction
    var direction = 'next';
    
    $('.goBack').live('click',function(){direction = 'prev';});
    $('.goForward').live('click',function(){direction = 'next';});
    
    // Hash Change
    $.history.init(function(hash){
        // Eger herhangi bir slide animate etmiyorsa calistir
        if($('.slide:animated').length == 0 && $('.bg:animated').length == 0 && $('.model:animated').length == 0){
            
            if(hash == ""){
                ajaxPageLoad('/home/main', 'prev');
            }else {
                var urlarr = urlSplit(hash);
                switch(urlarr[0]){
                    case 'tum-tboxlar':
                        ajaxPageLoad('/contact', direction);
                        
                        $('.mainNavVertical a').removeClass('active');
                        $('.mainNavVertical #nav3').addClass('active');
                        
                        break;
                    case 'kampanyalar':
                        ajaxCampaignsLoad(urlarr, direction);
                        
                        $('.mainNavVertical a').removeClass('active');
                        $('.mainNavVertical #nav1').addClass('active');
                        
                        break;
                    case 'tepeden-tirnaga':
                        ajaxProductsLoad(urlarr, direction);
                        
                        $('.mainNavVertical a').removeClass('active');
                        $('.mainNavVertical #nav2').addClass('active');
                        
                        break;
                    default:
                        window.location = BASE_URL;
                        break;
                }
            }
            
        }
    },{unescape: ",/"});
    
/* =============================================================================
   Main Page Slider
   ========================================================================== */

    $('.mandb > a').live('click',function(){

        // Animation Check
        if($('.bg:animated').length == 0) {

            var dir = $(this).attr('data-dir'); // direction
            //bg
            var bact = $('.bgs > .active'); // active .bg
            var bindex = bact.index('.bg'); // index of active .bg
            var bsize = $('.bgs > .bg').length; // total .bg

            switch(dir){ 
                case 'prev':
                    bact.stop().animate({left :'100%'}, 1500,'easeInOutExpo');

                    if(bindex > 0){
                        // bg
                        bact.prev().css({'left': '-100%'});
                        bact.prev().stop().animate({left :'0%'}, 1500,'easeInOutExpo',function(){
                            bact.removeClass('active');
                            $(this).addClass('active');
                            $('#siteWrap').css('background-image', $(this).css('background-image'));
                        });
                    }else{
                        // bg
                        $('.bg').last().css({'left': '-100%'});
                        $('.bg').last().stop().animate({left :'0%'}, 1500,'easeInOutExpo',function(){
                            bact.removeClass('active');
                            $(this).addClass('active');
                            $('#siteWrap').css('background-image', $(this).css('background-image'));
                        });
                    }
                    break;
                    
                default:
                    bact.stop().animate({left :'-100%'}, 1500,'easeInOutExpo',function(){$(this).css({'left':'100%'});});
                    
                    if(bindex < (bsize - 1)){
                        // bg
                        bact.next().stop().animate({left :'0%'}, 1500,'easeInOutExpo',function(){
                            bact.removeClass('active');
                            $(this).addClass('active');
                            $('#siteWrap').css('background-image', $(this).css('background-image'));
                        });
                    }else{
                        // bg
                        $('.bg').first().stop().animate({left :'0%'}, 1500,'easeInOutExpo',function(){
                            bact.removeClass('active');
                            $(this).addClass('active');
                            $('#siteWrap').css('background-image', $(this).css('background-image'));
                        });
                    }
                    break;
            }
        }

    });

    // TweetBox
    $('#tweetBtn').live('click',function(){
        $(this).addClass('active');
        $('#tweetBox').show(400, function() {$("#tweetBox").draggable();});
    });
    
    $('#tweetBox > .close a').live({
        click: function() {
            $('#tweetBtn').removeClass('active');
            $('#tweetBox').hide();
            return false;
        },
        mouseover:  function() {$(this).parent('div').addClass("active");},
        mouseout:   function() {$(this).parent('div').removeClass("active");}
    });
    
    // Menu mouseover & mouseout
    $('#mainNav > div > a, .prdNav > div > a').live({
        mouseover:  function() {$(this).parent('div').addClass("active");},
        mouseout:   function() {$(this).parent('div').removeClass("active");}
    });
    
    // Sihirli ayna
    $('.mmBtn').live({
        mouseover:  function() {$('.mmContent').show();},
        mouseout:   function() {$('.mmContent').hide();}
    }); 
    
    $('.btn').live('click',function(e){
        if($('.slide:animated').length > 0 || $('.bg:animated').length > 0 || $('.model:animated').length > 0){
            e.preventDefault();
        }
    });
    
    $('.groups li a').live('click',function(){
        $('.groups li a').removeClass('active');
        $(this).addClass('active');
    });
    
    

});


/* =============================================================================
   Window Load
   ========================================================================== */
$(window).load(function(){
    
    // Get Tweeter
    getTwitters('tweet', {   
        id:             't_boxonline',   
        count:          1,
        enableLinks:    true,   
        ignoreReplies:  true,   
        clearContents:  true,
        template:       '<div class="content">%text%</div><div class="time"> >> %time%</div>'
    });
    
    // Window Resize
    $(window).resize();
    
    // Left Nav visible
    if($('.leftNav').length > 0){$('.mainNavVertical').show();}
    
});

/* =============================================================================
   Window Resize
   ========================================================================== */
$(window).resize(function(){
    
    // Lightbox image resize
    imgResize();
    
    // Cast img initialize
    castTopInit();
});


/* =============================================================================
   Re Initialize Functions
   ========================================================================== */
function initialize(){
    // Background Image
    if($('.bgs').length > 0){$('#siteWrap').css('background-image', $('.bgs > .bg').first().css('background-image'));}

    // Scrollable
    if($('.scrollable').length > 0){$('.scrollable').scrollable({easing : 'jswing', keybord : false});}
    
     // Contact scroll pane
    if($('.scroll-pane').length > 0){$('.scroll-pane').jScrollPane({showArrows: true, arrowScrollOnHover: true})};
    
    // Lightbox image resize
    imgResize();
    
    // Cast img initialize
    castTopInit();
    
    // Left Nav visible
    if($('#mainSlide .leftNav').length > 0){$('.mainNavVertical').show();}
}

function preInitialize(){
    // Scrollable
    if($('.scrollable').length > 0){$('#nextSlide .scrollable, #prevSlide .scrollable').scrollable({easing : 'jswing', keybord : false});}
    
     // Contact scroll pane
    if($('.scroll-pane').length > 0){$('.scroll-pane').jScrollPane({showArrows: true, arrowScrollOnHover: true})};
    
    // Cast img initialize
    castTopInit();
    
    // Left Nav visible
    if($('#nextSlide .leftNav, #prevSlide .leftNav').length == 0){$('.mainNavVertical').fadeOut(250);}
    
}

function postInitialize(){
    // Left Nav visible
    if($('#mainSlide .leftNav').length > 0){$('.mainNavVertical').fadeIn(250);}
}


/* =============================================================================
   Ajax Load and Animate Function
   ========================================================================== */
function ajaxPageLoad(url, direction){
    var wrap    = $('#siteWrap');
    var slider  = $('#'+direction+'Slide'); // Ajax load to

    $.ajax({
        url:SITE_URL + url, 
        success:function (data){
            
            if(data == 'notfind'){
                window.location = BASE_URL;
            }else{
                
                if($('#mainSlide').is(':empty')){
                    $('#mainSlide').append(data);
                    initialize();    
                }else{
                    slider.append(data);

                    preInitialize();

                    if(direction == 'next'){
                        $('#mainSlide').stop().animate({left:'-100%'},2000,'easeInOutExpo',function(){$('#mainSlide').remove();});

                        slider.stop().animate({left:'0%'},2000,'easeInOutExpo',function(){
                            $(this).attr('id', 'mainSlide');
                            wrap.append('<div id="'+direction+'Slide" class="slide"></div>');
                            
                            postInitialize();
                        });
                    }else{
                        $('#mainSlide').stop().animate({left:'100%'},2000,'easeInOutExpo',function(){$('#mainSlide').remove();});

                        slider.stop().animate({right:'0%'},2000,'easeInOutExpo',function(){
                            $(this).attr('id', 'mainSlide');
                            wrap.append('<div id="'+direction+'Slide" class="slide"></div>');
                            
                            postInitialize();
                        });
                    }
                }
                
            }
        }
    });
}

/* =============================================================================
   Campaign Page
   ========================================================================== */
function ajaxCampaignsLoad(urlarr, direction){
    switch(urlarr.length){
        case 1:
            if($('#campaignsPg').length == 0) {
                ajaxPageLoad('/campaigns', direction);                
            }else {
                $('#lightBox').remove();
                $('html').css('overflow', 'auto');
            }
            break;
        case 2:
            if($('#campaignsPg').length > 0){
                $.ajax({
                    url:SITE_URL + '/campaigns/image',
                    type: "POST",
                    data: 'slug='+urlarr[1],
                    success:function (data){
                        $('#lightBox').remove();
                        $('#campaignsPg').append('<div id="lightBox"><div class="container"></div></div>');
                        $('#lightBox > .container').append(data);
                        $('html').css('overflow', 'hidden');
                        $('#lightBox').show();
                        
                        // Lightbox image resize
                        imgResize();
                        
                        // Scrollable
                        if($('.scrollable').length > 0){$('.scrollable').scrollable({easing : 'jswing', keybord : false});}
                    }
                });
            }else{
                $.ajax({
                    url:SITE_URL + '/campaigns/detail',
                    type: "POST",
                    data: 'slug='+urlarr[1],
                    success:function (data){
                        $('#mainSlide').append(data);
                        $('html').css('overflow', 'hidden');
                        $('#lightBox').show();
                        
                        // Lightbox image resize
                        imgResize();
                        
                        // Scrollable
                        if($('.scrollable').length > 0){$('.scrollable').scrollable({easing : 'jswing', keybord : false});}
                    }
                });
            }
            break;
    }
}

/* =============================================================================
   Products Page
   ========================================================================== */
function ajaxProductsLoad(urlarr, direction){
    
    var menu;
    var type;
    var img;
    var backurl;
    
    switch(urlarr.length){
         case 1:
             
            ajaxPageLoad('/products', direction);
            break;
            
        case 2:
            
            if(urlarr[1] == 'manifesto'){
                ajaxPageLoad('/products/manifest', direction);
            }else{
                var menuClass = '#' + urlarr[1];
                
                if($(menuClass).length == 0) {                    
                    ajaxPageLoad('/products/menu/' + urlarr[1], direction);
                    
                }
            }
            break;
            
        case 3:
            
            // Urun Tipi
            if(urlarr[2].search('type=') != -1){
                
                menu    = urlarr[1];
                type    = urlarr[2].replace("type=", "");
                
                // Eger Sayfa Yuklenmis ise
                if($('.prdPg').length > 0){
                    
                    var typeClass = '#' + urlarr[2].replace("type=", "");
                
                    if($(typeClass).length == 0) { 
                        
                        $.ajax({
                            url:SITE_URL + '/products/type/',
                            type: "POST",
                            data: 'menu='+menu+'&type='+type+'&pageExist='+true,
                            success:function (data){
                                
                                if(data == 'notfind'){
                                    window.location = BASE_URL;
                                }else{
                                
                                    $('#lightBox').remove();
                                    $('html').css('overflow', 'auto');
                                    $('.scrollWrap').html(data);

                                    // Scrollable
                                    if($('.scrollable').length > 0){$('.scrollable').scrollable({easing : 'jswing', keybord : false});}
                                }
                            }
                        });
                        
                    }else{
                        $('#lightBox').remove();
                        $('html').css('overflow', 'auto');
                    }
                    
                // Eger Sayfa Yuklenmemis ise    
                }else{
                    $.ajax({
                        url:SITE_URL + '/products/type/',
                        type: "POST",
                        data: 'menu='+menu+'&type='+type+'&pageExist='+false,
                        success:function (data){
                            
                            if(data == 'notfind'){
                                window.location = BASE_URL;
                            }else{
                                $('#mainSlide').append(data);
                            
                                // Scrollable
                                if($('.scrollable').length > 0){$('.scrollable').scrollable({easing : 'jswing', keybord : false});}
                            }
                            
                        }
                    });
                }
            }

            break;
            
        case 4:

            // Is Image
            if(urlarr[3].search('img=') != -1){
                
                menu    = urlarr[1];
                type    = urlarr[2].replace("type=", "");
                img     = urlarr[3].replace("img=", "");
                backurl = urlarr[0] + '/' + urlarr[1] + '/' + urlarr[2]; 
                
                if($('.prdPg').length > 0){
                    $.ajax({
                        url:SITE_URL + '/products/image/',
                        type: "POST",
                        data: 'menu='+menu+'&type='+type+'&img='+img+'&pageExist='+true+'&backurl='+backurl,
                        success:function (data){
                            
                            if(data == 'notfind'){
                                window.location = BASE_URL;
                            }else{
                                $('html').css('overflow', 'hidden');
                                $('#lightBox').remove();
                                $('.prdPg').append('<div id="lightBox"><div class="container"></div></div>');
                                $('#lightBox > .container').append(data);
                                $('#lightBox').show();

                                // Lightbox image resize
                                imgResize();

                                // Scrollable
                                if($('.scrollable').length > 0){$('.scrollable').scrollable({easing : 'jswing', keybord : false});}
                            }
                        }
                    });
                }else{
                    $.ajax({
                        url:SITE_URL + '/products/image/',
                        type: "POST",
                        data: 'menu='+menu+'&type='+type+'&img='+img+'&pageExist='+false+'&backurl='+backurl,
                        success:function (data){
                            
                            if(data == 'notfind'){
                                window.location = BASE_URL;
                            }else{
                                $('html').css('overflow', 'hidden');
                                $('#mainSlide').append(data);
                                $('#lightBox').fadeIn('slow');

                                // Lightbox image resize
                                imgResize();

                                // Scrollable
                                if($('.scrollable').length > 0){$('.scrollable').scrollable({easing : 'jswing', keybord : false});}
                            }
                        }
                    });
                }
                
            }
            break;
            
    }    
}


/* =============================================================================
   Resize Image
   ========================================================================== */
function imgResize(){
    if($('#lightBox').length > 0){
        var height = $(window).height() - 102;
        if( height > 328 ){
            $('.imgWrap').css({'height': height + 'px', 'line-height' : height + 'px'});
        }
    }
}

/* =============================================================================
   Each cast image initilaize
   ========================================================================== */
function castTopInit(){
    $('.bg > .model').each(function(){$(this).setTop();});
}

/* =============================================================================
   URL Split
   ========================================================================== */
function urlSplit(str){
    if(str.indexOf("/") == 0){return (str.substring(1)).split('/');}
    else{return str.split('/');}
}
