//Runs all custom jQuery and functions
var bannerImgWidth;
var currentImg = 0;
var maxImages = 3;
var speed = 500;
var imgs;
var activeSlider;
var maxProjInColumns = 0;
var initX;
var mouseIsDown = false;

$(function () {
    $('body').supersleight();

    $(".mouseOver").hover(function () {
        if (!$(this).hasClass("active")) {
            $(this).attr("src", $(this).attr("src").split(".").join("_ovr."));
        }
    }, function () {
        if (!$(this).hasClass("active")) {
            $(this).attr("src", $(this).attr("src").split("_ovr.").join("."));
        }
    });

    $('#phVideo').click(function () {
        $('#npVideo').trigger("play", "");
        $('#npVideo_playtoggle').css('background-position', '-78px 0px');
    });

    $('#ctaContainer div').hover(function () {
        var _this = $(this);
    }, function () {
        var _this = $(this);
    });

    if (!$.browser.msie) {
        setTimeout(function () { $('#animAudio').animate({ left: '+=30px', opacity: 1 }, 600, 'easeOutQuad'); }, 300);
        setTimeout(function () { $('#animVideo').animate({ left: '+=30px', opacity: 1 }, 600, 'easeOutQuad'); }, 600);
        setTimeout(function () { $('#animInter').animate({ left: '+=30px', opacity: 1 }, 600, 'easeOutQuad'); }, 900);
        setTimeout(function () { $('#animPrint').animate({ left: '+=30px', opacity: 1 }, 600, 'easeOutQuad'); }, 1200);
        setTimeout(function () { $('#animDone').animate({ left: '+=30px', opacity: 1 }, 600, 'easeOutQuad'); }, 1600);
    }

    $('#lnkFirePast').click(function () {
        $.scrollTo('#lnkFireBottom', 800);
    });

    $('#lgImage a').colorbox({ maxWidth: 960, maxHeight: 800, opacity: 0.6 });
    $('.slide').children('img').mousedown(function (e) {
        e.preventDefault();
    });

    $('.otSlideContainer').hover(function () {
        $(this).children('.otDrag').fadeOut('fast');
    }, function () {
        $(this).children('.otDrag').fadeIn('fast');
    });

    var rndNumber = Math.floor((13 - 1) * Math.random());
    $('.rndBG').css('background-image', 'url(/images/bg/bg_' + rndNumber + '.jpg)');

    var colorArray = new Array('npYellow', 'npBlue', 'npGreen', 'npRed');
    $('.muRow').children().hover(function () {
        var indexInRow = $(this).index();
        var names = $(this).siblings('.detail').children('div').children('h1');
        $(names[indexInRow]).children('span').addClass(colorArray[indexInRow]);
    }, function () {
        var indexInRow = $(this).index();
        var names = $(this).siblings('.detail').children('div').children('h1');
        $(names[indexInRow]).children('span').removeClass(colorArray[indexInRow]);
    });

    $('.muRow').children('.detail').children('div').hover(function () {
        var indexInRow = $(this).index();
        $(this).children('h1').children('span').addClass(colorArray[indexInRow]);
        var names = $(this).parent().siblings('.muColumn');
        $(names[indexInRow]).children('img').css('border-color', '#FFF');
    }, function () {
        var indexInRow = $(this).index();
        $(this).children('h1').children('span').removeClass(colorArray[indexInRow]);
        var names = $(this).parent().siblings('.muColumn');
        $(names[indexInRow]).children('img').removeAttr('style');
    });

    var tallestRow = 260;
    $('.muRow').each(function (i, val) {
        if ($(this).outerHeight() > tallestRow) {
            verlicon($(this).outerHeight());
            tallestRow = $(this).outerHeight();
        }
    });
    $('.muRow').css('height', tallestRow);

    loadBanner();

    $('.otSlides').live('mousedown', function (e) {
        initX = e.pageX;
        mouseIsDown = true;
        e.preventDefault;
    });
    $('.otSlides').live('mousemove', function (e) {
        if (mouseIsDown) {
            mouseIsDown = false;
            var endX = e.pageX;
            var id = $(this).attr('id');
            if (Math.abs(endX - initX)) {
                if (endX < initX) {
                    var dir = 'left';
                    turfMouseMove(id, dir)
                } else if (endX > initX) {
                    var dir = 'right';
                    turfMouseMove(id, dir)
                }
            }
        }
    });

    //$('#owShowMore a').click()

    var overFour = false; //Does any of the columns have over four images?  if not then we don't need to display the show more button
    $('.owColumn').each(function (i, val) {
        if ($(this).children('.projectBox').size() > 4) {
            overFour = true;
            if ($(this).children('.projectBox').size() > maxProjInColumns) {
                maxProjInColumns = $(this).children('.projectBox').size(); //Get the count of the most number of projects in a column
            }
        }
    });
    if (overFour) {
        $('#owShowMore').show();
    } else {
        $('#owShowMore').hide();
    }

    $('#npImage .imgBox:first').addClass('whiteBorder');
    $('#npImage .imgBox').click(function () {
        $('#npImage .imgBox').removeClass('whiteBorder');
        $(this).addClass('whiteBorder');
    });

    //$('.bannerBucket:first').addClass('whiteBorder');
    $('.bannerBucket').click(function () {
        $('.bannerBucket').removeClass('whiteBorder');
        $(this).addClass('whiteBorder');
    });

    if ($('#hidSearchType').val() == 'client') {
        $('#byClient img').attr('src', '/images/interior/btnClient_ovr.jpg');
        $('#byClient img').addClass('active');
        $('#byTag img').attr('src', '/images/interior/btnTag.jpg');
        $('#byTag img').removeClass('active');
    }
    if ($('#hidSearchType').val() == 'tag') {
        $('#byClient img').attr('src', '/images/interior/btnClient.jpg');
        $('#byClient img').removeClass('active');
        $('#byTag img').attr('src', '/images/interior/btnTag_ovr.jpg');
        $('#byTag img').addClass('active');
    }

    $.verlicode(function () {
        window.location = "http://www.youtube.com/watch?v=lSVnt3--Nnk&feature=related";
    });

    $.konami(function () {
        window.location = "http://www.youtube.com/watch?v=xpcUxwpOQ_A";
    });
});

function showMore() {
    var maxHeight = (maxProjInColumns * 220) + 50;  //last two account for the header and top padding
    $('#owColumnsHidden').animate({ height: maxHeight + 'px', opacity: 1 }, 700, 'easeOutQuad');
    $('#owShowMore').hide();
}

function turfMouseMove(id, dir) {
    if (dir == 'right') {
        $('#' + id).cycle('prev');
    } else {
        $('#' + id).cycle('next');
    }
}

function loadOurTurf(id) {
    var slideCount = $(id).children('div').children('img').size();
    var slideWidth = $(id).children('div').children('img').first().outerWidth();
    $(id).css('width', slideWidth * slideCount);

    $(id).cycle({
        timeout: 0,
        fx: 'scrollHorz'
    });

    $(id).touchwipe({
        wipeLeft: function () {
            $(id).siblings('.otDrag').hide();
            $(id).cycle("next");
        },
        wipeRight: function () {
            $(id).siblings('.otDrag').hide();
            $(id).cycle("prev");
        }
    });
}

function gotoBanner(id) {
    verlicon(id);
    var pagerItems = $('#hiddenPager').children('a');
    $(pagerItems[id]).trigger('click', function () { verlicon('triggered'); });
}

function loadBanner() {
    var buckets = $('.bannerBucket');
    $(buckets[0]).addClass('whiteBorder');

    $('#banner').cycle({
        timeout: 8000,
        before: moveBorder,
        fx: 'scrollHorz',
        speed: 700,
        next: '#nextArrow',
        prev: '#prevArrow',
        pager: '#hiddenPager'
    });

    $('#banner').touchwipe({
        wipeLeft: function () {
            $('#banner').cycle("next");
        },
        wipeRight: function () {
            $('#banner').cycle("prev");
        }
    });
}

function changeBanner(currSlideElement, nextSlideElement, options, forwardFlag) {
    var clientName;
    var _title;

    if (options.currSlide == 0 && i == 0) {
        clientName = $(currSlideElement).attr('rel');
        _title = $(currSlideElement).attr('title');
    } else {
        clientName = $(nextSlideElement).attr('rel');
        _title = $(nextSlideElement).attr('title');
    }
    $('.bannerClientName').html(clientName);
    $('.bannerTitle').html(_title);
}

var i = 0;
function moveBorder(currSlideElement, nextSlideElement, options, forwardFlag) {
    changeBanner(currSlideElement, nextSlideElement, options, forwardFlag);
    var buckets = $('.bannerBucket');
    $(buckets).removeClass('whiteBorder');
    if (options.currSlide == 0 && i == 0) {
        $(buckets[options.currSlide]).addClass('whiteBorder');
    } else {
        $(buckets[options.nextSlide]).addClass('whiteBorder');
    }
    i = i + 1;
}

function loadAudio(fileGuid, _color) {
    $('#lgImage').hide();
    $('#phAudio').empty();
    $('#phAudio').show();
    $('#phVideo').empty();
    $('#phVideo').hide();
    $('#phAudio').append("<audio class='npHTML5Audio' id='npAudio' preload='auto' controls width='640' height='40'></audio>");
    $('#npAudio').npHTML5Audio({ mp3: '/uploads/audio/' + fileGuid + '.mp3',
        ogg: '/uploads/audio/' + fileGuid + '.ogg',
        preload: 'auto',
        //flash specific
        color: _color,
        swf: '/swf/np_audioPlayer.swf',
        swfBase: '',
        swfExpressInstall: '/swf/expressinstall.swf'
    });

    var _height = $('#wdShowcaseLeft').innerHeight();
    var _playerHeight = $('#npAudio').height();
    var topPadding = (_height / 2);
    topPadding = topPadding - (_playerHeight / 2);
    $('#phAudio').css('padding-top', topPadding);
}

function loadVideo(fileGuid, poster, _color, projGuid) {
    $('#lgImage').hide();
    $('#phVideo').empty();
    $('#phVideo').show();
    $('#phAudio').empty();
    $('#phAudio').hide();

    if ($.browser.msie) {
        $('#phVideo').append("<span class='npHTML5Video' id='npVideo' preload controls autobuffer poster='/uploads/_md/" + poster + "' width='640' height='360'></span>");
    } else {
        $('#phVideo').html('');
        $('#phVideo').append("<video class='npHTML5Video' id='npVideo' preload controls autobuffer poster='/uploads/_md/" + poster + "' width='640' height='360'></video>");
    }

    $('#npVideo').npHTML5Video({
        swf: '/swf/np_fmsVidPlayer.swf',
        rtmp: 'rtmp://fms.new-perspective.com/vod/fin/',
        streamList: '{file:mp4:newperspective/' + fileGuid + '_700,bitrate:700},{file:mp4:newperspective/' + fileGuid + '_1000,bitrate:1000},{file:mp4:newperspective/' + fileGuid + '_1500,bitrate:1500}',
        color: _color,
        mp4: '/uploads/video/' + fileGuid + '_1000.mp4',
        appleStream: 'http://streaming.new-perspective.com/uploads/iStream/' + fileGuid + '-m3u8-aapl.ism/manifest(format=m3u8-aapl)',
        swfBase: '',
        autoplay: true,
        swfBase: '',
        swfExpressInstall: '/swf/expressinstall.swf'
    });
}

function loadFIREVideo(id, fileGuid, poster, _color) {
    if ($.browser.msie) {
        $('#' + id).append("<span class='npHTML5Video' id='np" + id + "' preload controls autobuffer poster='/uploads/_md/" + poster + "' width='640' height='360'></span>");
    } else {
        $('#' + id).append("<video class='npHTML5Video' id='np" + id + "' preload controls autobuffer poster='/uploads/_md/" + poster + "' width='640' height='360'></video>");
    }

    $('#np' + id).npHTML5Video({
        swf: '/swf/np_fmsVidPlayer.swf',
        mp4: '/uploads/video/' + fileGuid + '_1000.mp4',
        appleStream: 'http://streaming.new-perspective.com/uploads/iStream/' + fileGuid + '-m3u8-aapl.ism/manifest(format=m3u8-aapl)',
        rtmp: 'rtmp://fms.new-perspective.com/vod/fin/',
        streamList: '{file:mp4:newperspective/' + fileGuid + '_700,bitrate:700},{file:mp4:newperspective/' + fileGuid + '_1000,bitrate:1000},{file:mp4:newperspective/' + fileGuid + '_1500,bitrate:1500}',
        color: _color,
        swfBase: '',
        swfExpressInstall: '/swf/expressinstall.swf'
    });
}

function loadMedImage(_src) {
    $('#lgImage').show();
    $('#lgImage a').attr('href', _src);
    $('#lgImage img').attr('src', _src);
}

function validateForm(sender, args) {
    var emailRegEx = new RegExp(/^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/);
    var id = $(sender).attr('id');
    if (id == 'rfv0') {
        $('#txtName').removeClass('npRed');
        if ($('#txtName').val().length == 0) {
            $('#txtName').addClass('npRed');
            args.IsValid = false;
            return;
        }
    }
    if (id == 'rfv1') {
        $('#txtEmail').removeClass('npRed');
        if ($('#txtEmail').val().length == 0 || !emailRegEx.test($('#txtEmail').val())) {
            $('#txtEmail').addClass('npRed');
            args.IsValid = false;
            return;
        }
    }
    args.IsValid = true;
    return;
}

function verlicon(data) {
    if (window.console && window.console.firebug) {
        //Firebug is enabled
        console.log(data);
    } else if (window.console) {
        console.log(data);
    }
}
