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,
phoneDevice = (navigator.userAgent.match(/iPhone/i)),
mobileDevice = ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i))),
ie8 = ($.browser.msie && $.browser.version < 9),
isIE = $.browser.msie;

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',
        playerVars: {
            'wmode' : 'transparent'
        },
        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;

    });

}

var down_x = null;
var up_x = null;

function do_work(){
    if ((down_x - up_x) > 50)
    {
        slide_right();
    }
    if ((up_x - down_x) > 50)
    {
        slide_left();
    }
}
function slide_right(){
    animHero('next');
}
function slide_left(){
    animHero('prev');
}

$(document).ready(function(){

    //lazy load images
    $("#container img").lazyload({
        placeholder : "img/ajax-loader.gif",
        effect: 'fadeIn'
    });
    
    //detect anchor
    $('div.anchors').bind('inview', function(event, isInView, visiblePartX, visiblePartY) {
        if (isInView) {
            // element is now visible in the viewport
            if (visiblePartY == 'top') {
            // top part of element is visible
            } else if (visiblePartY == 'bottom') {
            // bottom part of element is visible
            } else {
                // whole part of element is visible
                var anchn = $('.anchors').index(this);
                current = anchn;
                if( current > 0 ){
                    $('.anchors:eq('+ current +') img').trigger('scroll');
                }
            }
        } else {
    // element has gone out of viewport
    }
    });

    //display back-to-top when scrolled down a bit
    $(window).scroll(function(){
        detectTop();
    }).scroll();
    
    $('.tab-div').hide();

    //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;
        
    });
    $('ul.tab a[href!=#]').click(function(e){
        e.stopPropagation();
    });
    
    function closeTabs(){
        
        if( !animating ) {
        
            tabLinks.removeClass('selected');
            $('#form input').blur();

            if(!animating && expanded){
                animating = true;
                $('#top').animate({
                    'height':0
                },speed,easeType,function(){
                    $('.tab-div').hide();
                    expanded = false;
                    animating = false;
                });
            }
        
        }
        
    }
    
    $('a.our-work-link').click(function(){
        scrollToProject(1);
        return false;
    });
    
    //kettle report overlay
    kettleReport();
    
    //header carousel
    hdCarouselInit();
   
    //hero carousel
    if( !phoneDevice ){
        heroCarousel();
    //slideHero();
    } else {
        $('.hero').css('visibility','visible');
    }
   
    //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;
    });
    $('.hd-anchor').live('click',function(){
        var projectNum = $(this).attr('href').replace('#','');
        scrollToProject(projectNum);
        
        return false;
    })
    
    // Init the form once the document is ready
    $( init );
    
    $('#twitter-feed .element a').attr('target','_blank');

});

var heros = $('.hero');
var currenth = 0;
var heromax = $('.hero').length-1;
var heroc = $('#hero-carousel');
var anim = false;
var herobtns = $('.header .pager-btn');
var winw = $(window).width();
var study = $('.bottom-bar .study');
var autoHero;

function heroCarousel(){
    
    for(var i=0; i<=heromax; i++){
        $('ul.simple-nav').append('<li class="simplenav-'+i+'"><a href="#">'+i+'</a></li>');
    }
    var snav = $('ul.simple-nav a');
    
    $('.hero0').addClass('active');
    $('.hero1').addClass('fromright');
    $('.simplenav-0').addClass('active');
    
    $(window).resize(function(){
        winw = $(window).width();
        heroc.width(winw * (heromax+1));
        
        heros.width(winw).css('visibility','visible');
        if( !isIE ){
            var slidew = currenth * -winw;
            heroc.css({
                "-webkit-backface-visibility": 'hidden',
                "-webkit-transition": "-webkit-transform 0s",
                "-webkit-transform": "translate3d(" + slidew + "px, 0, 0)",
                "-moz-transition": "-moz-transform 0s",
                "-moz-transform": "translate(" + slidew + "px, 0)",
                "-o-transition": "-o-transform 0s",
                "-o-transform": "translate(" + slidew + "px, 0)"
            });
        } else {
            heroc.css({
                'left':winw * -currenth
            });
        }
        
    }).resize();
    
    //previous/next buttons
    herobtns.click(function(){
        if( $(this).hasClass('next') ){
            animHero('next');
        } else {
            animHero('prev');
        }
        clearInterval(autoHero);

        return false;
    });
    //simple nav buttons
    snav.click(function(){
        var ind = $('.simple-nav li a').index(this);
        animHero(ind);
        clearInterval(autoHero);

        return false;
    });
    
    //enable auto carousel
    $('.bottom-bar').css('position', 'absolute');
    study.css('opacity',0);
    $('.header img').imagesLoaded( function(){
        autoHero = setInterval(function(){
            animHero('next');
        }, 6000);
    });
    
}

function animHero(dir){
            
    if( !anim ){
        anim = true;
        //clear classes
        $('.hero').removeClass('active exit enter fromleft fromright');
        $('.simple-nav li').removeClass('active');

        study.fadeTo('fast',0).css('z-index','0');

        $('.hero' + currenth).addClass('exit');

        //stop auto carousel when reaches end
        /*if( currenth == heromax ){
            clearInterval(autoHero);
            animHero(0);
        }*/

        if( dir == 'next' ){

            if( currenth > heromax-1 ){
                currenth = 0;
            } else {
                currenth++;
            }

        } else if( dir == 'prev' ) {
            if( currenth <= 0 ){
                currenth = heromax;
            } else {
                currenth--;
            }
        } else {
            currenth = dir;
        }

        $('.hero' + currenth).addClass('enter');
        $('.simplenav-'+ currenth).addClass('active');

        $('.hero:gt('+ currenth +')').addClass('fromright');
        $('.hero:lt('+ currenth +')').addClass('fromleft');

        if( !isIE ){
            var slidew = currenth * -winw;
            heroc.css({
                "-webkit-backface-visibility": 'hidden',
                "-webkit-transition": "-webkit-transform 1s cubic-bezier(0.230, 1.000, 0.320, 1.000)",
                "-webkit-transform": "translate3d(" + slidew + "px, 0, 0)",
                "-moz-transition": "-moz-transform 1s cubic-bezier(0.230, 1.000, 0.320, 1.000)",
                "-moz-transform": "translate(" + slidew + "px, 0)",
                "-o-transition": "-o-transform 1s cubic-bezier(0.230, 1.000, 0.320, 1.000)",
                "-o-transform": "translate(" + slidew + "px, 0)"
            });
            $('.hero'+currenth).addClass('active');
            $('.study-'+currenth).fadeTo('fast',1, function(){
                anim = false;
            }).css('z-index','20');
        } else {
            heroc.animate({
                'left' : currenth * -winw
            }, 700, easeType, function(){
                $('.hero'+currenth).addClass('active');
                $('.study-'+currenth).fadeTo('fast',1);

                anim = false;
            }).css('z-index','20');
        }

    }
}

function hdCarouselInit(){
    $(window).resize(function(){
        
        var hdh = $(window).height()-40;
        var divs = $('.header, .hero');
        
        divs.height(hdh);
        
    }).resize();
}

function kettleReport(){
    if(!$.cookie('kettlereport')){
        var reportFadein = setTimeout( function(){
            $('#were-hiring').fadeIn();
        }, 1500);
        $('.report-close').click(function(){
            $('#were-hiring').fadeOut();
            $.cookie('kettlereport', 'hidden', {
                path: '/'
            });

            return false;
        });
    }
}

function displayTop(num){
    
    tabDiv = $('.tab-div:eq('+num+')');
    
    $(window).resize(function(){
        
        //get tabs' height
        $('.tab-div').each(function(i){
            tabDivHeight[i] = $('.tab-div:eq('+ i +')').height()+86;
        });
        
    }).resize();
    
    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(){
                    $('.tab-div').hide();
                    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 if( $(document).scrollTop() == 0 ){
        $('#top-link').css('visibility','hidden');
        current = 0;
    }
}

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);
                }
            })
        }*/
        
        if($(this).attr('id') != 'twitter-feed'){
            $(this).find('.element').click(function(){
                changeSlide('next',index);

                return false;
            });
        } else {
            var emtime = $(this).find('#updated'+currentimg[index]).text();
            
            $(this).find('.hd h3 em').text(emtime);
        }
        
        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'){
            $this.find('.prev').addClass('pressed');
            
            if(currentimg[index] === 1){
                currentimg[index] = imagenum[index];
            }else{
                currentimg[index] = currentimg[index] - 1;
            }
        }else{
            $this.find('.next').addClass('pressed');
            
            if(currentimg[index] === imagenum[index]){
                currentimg[index] = 1;
            }else {
                currentimg[index] = currentimg[index] + 1;
            }
        }
        
        if( $this.attr('id') == 'twitter-feed' ){
            var emtime = $this.find('#updated'+currentimg[index]).text();
            
            $this.find('.hd h3 em').text(emtime);
        }
        
        var theimg = $this.find('.element:nth-child('+ currentimg[index] +') img');
        if( theimg.attr('src') && theimg.attr('src').indexOf('ajax-loader.gif') < 0 ){
            $this.find('.element:nth-child('+ currentimg[index] +')').fadeIn(function(){
                $this.find('.pager-btn').removeClass('pressed');
                changing = false;
            });
        } else {
            $this.find('.element:nth-child('+ currentimg[index] +')').show().trigger('scroll');
            var t = setTimeout(
                function(){
                    $this.find('.pager-btn').removeClass('pressed');
                    changing = false;
                    clearTimeout(t);
                }, 300);
        }
        
        $this.find('.pager p').html(currentimg[index] + ' <em>of</em> ' + imagenum[index]);
    }
}

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


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){
            if( current == 0 ){
                animHero('prev');
                clearInterval(autoHero);
            } else {
                changeSlide('prev',current - 1);
            }
            return false;
        }
        //right arrow
        if(e.keyCode == 39){
            if( current == 0 ){
                animHero('next');
                clearInterval(autoHero);
            } else {
                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;
                
                var lazyimgs = $('.anchors:eq('+ num +') img');
                if(lazyimgs.attr('src') && lazyimgs.attr('src').indexOf('ajax-loader.gif') > 0){
                    $('.anchors:eq('+ num +') img').trigger('scroll');
                }
            }
        });
        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() {

    if($('#form').length){
        // 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();
    }
}

function slideHero(){
    var herod = $("#hero-carousel");
    
    herod.mousedown(function(e){
        e.preventDefault();
        down_x = up_x = e.pageX;
        
        mouse_down = true;
        $("body").unbind();
        $("body").mousemove(function(e){
            if (mouse_down){
                var diff = e.pageX - up_x;
                var left = parseInt(herod.css('left').replace('px',''));
                /*if( !isIE ){
                    heroc.css({
                        "-webkit-backface-visibility": 'hidden',
                        "-webkit-transform": "translate3d(" + left+diff + "px, 0, 0)",
                        "-moz-transform": "translate(" + left+diff + "px, 0)",
                        "-o-transform": "translate(" + left+diff + "px, 0)"
                    });
                } else {*/
                heroc.css({
                    'left':(left+diff)
                });
                //}
                clearInterval(autoHero);
                up_x = e.pageX;
            }
        });
        $("body").mouseup(function(e){
            do_work();
            herod.animate({
                'left':0
            });
            $(this).unbind();
            mouse_down = false;
        }); 
    });
    
    herod.bind('touchstart', function(e){
        down_x = e.originalEvent.touches[0].pageX;
        up_x = down_x;
        $("body").unbind();
        $("body").bind('touchmove', function(e){
            e.preventDefault();
            var diff = e.originalEvent.touches[0].pageX - up_x;
            var left = parseInt(herod.css('left').replace('px',''));
            herod.css('left',left+diff);
            up_x = e.originalEvent.touches[0].pageX;
        });
        $("body").bind('touchend', function(e){
            do_work();
            herod.animate({
                'left':0
            });
            $(this).unbind();
        });
    });
}

(function($, undefined) {

    $.fn.imagesLoaded = function( callback ) {
        var $this = this,
        $images = $this.find('img').add( $this.filter('img') ),
        len = $images.length,
        blank = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==';

        function triggerCallback() {
            callback.call( $this, $images );
        }

        function imgLoaded() {
            if ( --len <= 0 && this.src !== blank ){
                setTimeout( triggerCallback );
                $images.unbind( 'load error', imgLoaded );
            }
        }

        if ( !len ) {
            triggerCallback();
        }

        $images.bind( 'load error', imgLoaded ).each( function() {
            // cached images don't fire load sometimes, so we reset src.
            if (this.complete || this.complete === undefined){
                var src = this.src;
                // webkit hack from http://groups.google.com/group/jquery-dev/browse_thread/thread/eee6ab7b2da50e1f
                // data uri bypasses webkit log warning (thx doug jones)
                this.src = blank;
                this.src = src;
            }
        });

        return $this;
    };
})(jQuery);
