var current = 0,
projects = new Array,
currentimg = new Array,
imagenum = new Array,
projectId = new Array,
projectName = new Array,
clientList = $('#portfoliowrapper .fivecol li'),
speed = 500,
messageDelay = 10000;
//tab nav
var expanded = false,
animating = false,
easeType = 'easeOutQuint',
tabLinks = $('.tab a.tab-links'),
tabindex,
tabDiv,
tabDivHeight = new Array,
showing,
mobileDevice = ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i)));

var tag = document.createElement('script');
tag.src = "http://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

var hey_walkies_video;

function onYouTubePlayerAPIReady() {
    hey_walkies_video = new YT.Player('hey_walkies_video', {
        height: '390',
        width: '640',
        videoId: 'QOSSz5G41zI',
        events: {
            'onReady': onPlayerReady
        }
    });
}

function onPlayerReady(event){

    $('.poster').click(function(){

        var _this = $(this);
        var videoHolder = _this.siblings('div').attr('id');
        _this.hide();

        if(videoHolder){
            event.target.playVideo();
        }

        return false;

    });

}

$(document).ready(function(){

    //fade in header
    $('.header h1').fadeTo('slow',1);
    $('.header h2').delay(200).animate({'left':0,'opacity':1});
    $('.header p').delay(400).animate({'left':0,'opacity':1});
    $('#our-work').delay(600).animate({'bottom':'65px','opacity':1});

    //display back-to-top when scrolled down a bit
    detectTop();
    $(document).scroll(function(){
        detectTop();
    });

    //back-to-top
    $('#top-link').click(function(){
        scrollToProject(0);
        
        return false;
    });
    
    //close update
    $('.close-update').click(function(){
        $('.update').slideUp(speed,easeType);
        
        return false;
    });
    
    
    //get tabs' height
    $('.tab-div').each(function(i){
        tabDivHeight[i] = $('.tab-div:eq('+ i +')').height()+86;
    });
    
    
    //click anywhere on page, close top tab
    $('html').click(function(){
        if(expanded){
            closeTabs();
            expanded = false;

            return false;
        }
    });
    
    $('#top').not('.anchor-to').click(function(e){
        e.stopPropagation();
    });
    
    //tab link event
    tabLinks.click(function(e){
        e.stopPropagation();
        
        tabindex = tabLinks.index(this);
        
        //alert(index + ': '+ tabDivHeight);
        
        displayTop(tabindex);
        
        return false;
        
    });
    
    function closeTabs(){
        
        if( !animating ) {
        
            tabLinks.removeClass('selected');
            $('#form input').blur();

            if(!animating && expanded){
                animating = true;
                $('#top').animate({
                    'height':0
                },speed,easeType,function(){
                    expanded = false;
                    animating = false;
                });
            }
        
        }
        
    }
    
    $('a#our-work').click(function(){
        scrollToProject(1);
        return false;
    });
   
    //responsiveImgs();
    
    if(!$('#form_container').length){
        initScroll();
    }
    
    initSlideshow();
    
    //create client anchor list
    clientList.each(function(index){
        var clientListName = $(this).text().toLowerCase();
        var projectClient = $.inArray(clientListName,projectName);
        
        if( projectClient > -1 ){
            $(this).html('<a href="#'+ (projectClient + 1) +'" class="anchor-to">'+ $(this).text() +'</a>');
        }
    });
    //client anchors
    $('.fivecol').delegate('.anchor-to','click',function(){
        var projectNum = $(this).attr('href').replace('#','');
        closeTabs();
        scrollToProject(projectNum);
        
        return false;
    });
    
    // Init the form once the document is ready
    $( init );

});

function displayTop(num){
    
    tabDiv = $('.tab-div:eq('+num+')');
    
    if(!animating){
            
        $('.tab-div').hide();
        tabDiv.show();
        
        //animating is true
        //remove/add selected class
        //set about tab to hide form
        animating = true;
            
        tabLinks.removeClass('selected');
        $('.tab-links:eq('+num+')').addClass('selected');
        $('#aboutwrapper .form-content').hide();
        $('#aboutwrapper .content').show();

        //if it's expanded
        if(expanded){

            //close top if clicked on same link the content is displaying
            if(showing == tabindex){
                
                tabLinks.removeClass('selected');
                $('#top').animate({
                    'height':0
                },speed,easeType,function(){
                    animating = false;
                    expanded = false;
                });
                    
            }else{

                showing = tabindex;
                $('#top').animate({
                    'height':tabDivHeight[num]+'px'
                },speed,easeType,function(){
                    animating = false;
                    expanded = true;
                });
                    
            }
                
        } else {

            showing = tabindex;
            //display/drop down #top
            $('#top').animate({
                'height':tabDivHeight[num]+'px'
            },speed,easeType,function(){
                animating = false;
                expanded = true;
            });

        }
    }

}

function detectTop(){
    if( $(document).scrollTop() > 100 ){
        $('#top-link').css('visibility','visible');
    } else {
        $('#top-link').css('visibility','hidden');
    }
}

function initSlideshow(){
    $('.project .element').hide();
    
    projects = $('.project');
    projects.each(function(index, e){
        $(this).find('.element:first').show();
        projectId = $(this);
        if($(this).find('.pager').length > 0){
            currentimg[index] = 1;
            imagenum[index] = $(this).find('.element').length;
            projectId.find('.pager p').html(currentimg[index] + ' <em>of</em> ' + imagenum[index]);
        }
        $(this).find('.pager-btn').click(function(){
            if($(this).hasClass('prev')){
                changeSlide('prev',index);
            }else{
                changeSlide('next',index);
            }
            return false;
        });
        //swipe apple devices
        /*if( (navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i))) {
            $(this).find('.elements img').swipe({
                swipeLeft : function(){
                    changeSlide('next',index);
                },
                swipeRight : function(){
                    changeSlide('prev',index);
                }
            })
        }*/
        $(this).find('.element').click(function(){
            changeSlide('next',index);
            
            return false;
        });
        projectName[index] = $.trim($(this).find('.hd h3 span').text()).toLowerCase();
    });
}

var changing = false;

function changeSlide(direction,index){
    
    //don't change slide if it's changing
    //is the header
    //is the footer
    
    $this = $('.project:eq('+index+')');
    
    if(!changing && (index != (anchor_max-1)) && (index != -1) && ($this.find('.element').length > 1)){
        changing = true;
        
        hideImages(index);
        if(direction == 'prev'){
            
            if(currentimg[index] === 1){
                $this.find('.element:nth-child('+ imagenum[index] +')').fadeIn(function(){
                    changing = false;
                });
                currentimg[index] = imagenum[index];
            }else{
                currentimg[index] = currentimg[index] - 1;
                $this.find('.element:nth-child('+ currentimg[index] +')').fadeIn(function(){
                    changing = false;
                });
            }
        }else{
            
            if(currentimg[index] === imagenum[index]){
                $this.find('.element:first').fadeIn(function(){
                    changing = false;
                });
                currentimg[index] = 1;
            }else {
                currentimg[index] = currentimg[index] + 1;
                $this.find('.element:nth-child('+ currentimg[index] +')').fadeIn(function(){
                    changing = false;
                });
            }
        }
        $this.find('.pager p').html(currentimg[index] + ' <em>of</em> ' + imagenum[index]);
    }
}

function hideImages(index){
    $('.project:eq('+index+')').find('.element').hide();
}

$(window).resize(function(){
    
    //responsiveImgs();
    
    //get tabs' height
    $('.tab-div').each(function(i){
        tabDivHeight[i] = $('.tab-div:eq('+ i +')').height()+86;
    });
    
});


var anchor_max = $('.anchors').length - 1;
var scrollSpeed = 250;
var anchors = $('.anchors').get();
var scrollAnimation = false;

function initScroll(){

    $(document).bind('keydown',function(e){
        //up key
        if (e.keyCode == 38) {
            if( current - 1 < 0 ){
                scrollToProject(anchor_max);
            } else {
                scrollToProject(current - 1);
            }
            return false;
        }
        
        //down key
        if (e.keyCode == 40) {
            if( current+1 > anchor_max ){
                scrollToProject(0);
            } else {
                scrollToProject(current+1);
            }
            return false;
        }
        
        //left arrow
        if(e.keyCode == 37){
            changeSlide('prev',current - 1);
            return false;
        }
        //right arrow
        if(e.keyCode == 39){
            changeSlide('next',current - 1);
            return false;
        }
    });

}

var showSwitch = ($('.header').length) ? true : false;
var scrollOffset = mobileDevice ? 0 : -40;

function scrollToProject(num){
    
    if(!scrollAnimation){
        
        if(showSwitch){
            showSwitch = false;
            $('#switch').fadeIn().delay(3000).fadeOut();
        }
        
        scrollAnimation = true;
    
        $.scrollTo(anchors[num], {
            duration: scrollSpeed, 
            axis:"y",
            offset : scrollOffset,
            onAfter: function(){
                scrollAnimation = false;
            }
        });
        current = parseInt(num,10);
        
    }
}

//load mobile images if device width is less than 480 px
function responsiveImgs(){
    
    var windowWidth = $(window).width();
    
    $('img').each(function(){
        
        if(windowWidth <= 480){
        
            var largeImg = $(this).attr('src'),
            smallImg = largeImg.replace('img/','mobile/');
            
            $(this).attr('src',smallImg);
        
        }else{
        
            $(this).attr('src',$(this).attr('src').replace('mobile/','img/'));
        
        }
        
    });
    
}

 
 
// Initialize the form
 
function init() {

    // Make submitForm() the formâ€™s submit handler.
    $('#form').validate({
        submitHandler : submitForm,
        wrapper : 'div',
        errorLabelContainer : '.error-wrapper'
    });
 
}

// Submit the form via Ajax
 
function submitForm() {
    var contactForm = $('#form');
 
    // Are all the fields filled in?
 
    if ( !$('#name').val() || !$('#email').val() || !$('#message').val() ) {
 
        // No; display a warning message and return to the form
        $('#incompleteMessage').fadeIn();
 
    } else {
 
        // Yes; submit the form to the PHP script via Ajax
 
        $('#sendingMessage').fadeIn();
 
        $.ajax( {
            url: contactForm.attr( 'action' ) + "?ajax=true",
            type: contactForm.attr( 'method' ),
            data: contactForm.serialize(),
            success: submitFinished
        } );
    }
 
    scrollToProject(0);
    // Prevent the default form submission occurring
    return false;
}

// Handle the Ajax response
 
function submitFinished( response ) {
    response = $.trim( response );
    $('#sendingMessage').fadeOut();
 
    if ( response == "success" ) {
 
        // Form submitted successfully:
        // 1. Display the success message
        // 2. Clear the form fields
 
        $('#successMessage').fadeIn();
        $('#form').hide();
        $('#name,#email,#message,#company,#start_time,#completion_time,#estimated_budget').val( "" );
 
    } else {
 
        // Form submission failed: Display the failure message
        $('#failureMessage').fadeIn().delay(messageDelay).fadeOut();
    }
}
