/*
 * jQuery BBQ: Back Button & Query Library - v1.2.1 - 2/17/2010
 * http://benalman.com/projects/jquery-bbq-plugin/
 *
 * Copyright (c) 2010 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */
(function($,p){var i,m=Array.prototype.slice,r=decodeURIComponent,a=$.param,c,l,v,b=$.bbq=$.bbq||{},q,u,j,e=$.event.special,d="hashchange",A="querystring",D="fragment",y="elemUrlAttr",g="location",k="href",t="src",x=/^.*\?|#.*$/g,w=/^.*\#/,h,C={};function E(F){return typeof F==="string"}function B(G){var F=m.call(arguments,1);return function(){return G.apply(this,F.concat(m.call(arguments)))}}function n(F){return F.replace(/^[^#]*#?(.*)$/,"$1")}function o(F){return F.replace(/(?:^[^?#]*\?([^#]*).*$)?.*/,"$1")}function f(H,M,F,I,G){var O,L,K,N,J;if(I!==i){K=F.match(H?/^([^#]*)\#?(.*)$/:/^([^#?]*)\??([^#]*)(#?.*)/);J=K[3]||"";if(G===2&&E(I)){L=I.replace(H?w:x,"")}else{N=l(K[2]);I=E(I)?l[H?D:A](I):I;L=G===2?I:G===1?$.extend({},I,N):$.extend({},N,I);L=a(L);if(H){L=L.replace(h,r)}}O=K[1]+(H?"#":L||!K[1]?"?":"")+L+J}else{O=M(F!==i?F:p[g][k])}return O}a[A]=B(f,0,o);a[D]=c=B(f,1,n);c.noEscape=function(G){G=G||"";var F=$.map(G.split(""),encodeURIComponent);h=new RegExp(F.join("|"),"g")};c.noEscape(",/");$.deparam=l=function(I,F){var H={},G={"true":!0,"false":!1,"null":null};$.each(I.replace(/\+/g," ").split("&"),function(L,Q){var K=Q.split("="),P=r(K[0]),J,O=H,M=0,R=P.split("]["),N=R.length-1;if(/\[/.test(R[0])&&/\]$/.test(R[N])){R[N]=R[N].replace(/\]$/,"");R=R.shift().split("[").concat(R);N=R.length-1}else{N=0}if(K.length===2){J=r(K[1]);if(F){J=J&&!isNaN(J)?+J:J==="undefined"?i:G[J]!==i?G[J]:J}if(N){for(;M<=N;M++){P=R[M]===""?O.length:R[M];O=O[P]=M<N?O[P]||(R[M+1]&&isNaN(R[M+1])?{}:[]):J}}else{if($.isArray(H[P])){H[P].push(J)}else{if(H[P]!==i){H[P]=[H[P],J]}else{H[P]=J}}}}else{if(P){H[P]=F?i:""}}});return H};function z(H,F,G){if(F===i||typeof F==="boolean"){G=F;F=a[H?D:A]()}else{F=E(F)?F.replace(H?w:x,""):F}return l(F,G)}l[A]=B(z,0);l[D]=v=B(z,1);$[y]||($[y]=function(F){return $.extend(C,F)})({a:k,base:k,iframe:t,img:t,input:t,form:"action",link:k,script:t});j=$[y];function s(I,G,H,F){if(!E(H)&&typeof H!=="object"){F=H;H=G;G=i}return this.each(function(){var L=$(this),J=G||j()[(this.nodeName||"").toLowerCase()]||"",K=J&&L.attr(J)||"";L.attr(J,a[I](K,H,F))})}$.fn[A]=B(s,A);$.fn[D]=B(s,D);b.pushState=q=function(I,F){if(E(I)&&/^#/.test(I)&&F===i){F=2}var H=I!==i,G=c(p[g][k],H?I:{},H?F:2);p[g][k]=G+(/#/.test(G)?"":"#")};b.getState=u=function(F,G){return F===i||typeof F==="boolean"?v(F):v(G)[F]};b.removeState=function(F){var G={};if(F!==i){G=u();$.each($.isArray(F)?F:arguments,function(I,H){delete G[H]})}q(G,2)};e[d]=$.extend(e[d],{add:function(F){var H;function G(J){var I=J[D]=c();J.getState=function(K,L){return K===i||typeof K==="boolean"?l(I,K):l(I,L)[K]};H.apply(this,arguments)}if($.isFunction(F)){H=F;return G}else{H=F.handler;F.handler=G}}})})(jQuery,this);
/*
 * jQuery hashchange event - v1.2 - 2/11/2010
 * http://benalman.com/projects/jquery-hashchange-plugin/
 *
 * Copyright (c) 2010 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */
(function($,i,b){var j,k=$.event.special,c="location",d="hashchange",l="href",f=$.browser,g=document.documentMode,h=f.msie&&(g===b||g<8),e="on"+d in i&&!h;function a(m){m=m||i[c][l];return m.replace(/^[^#]*#?(.*)$/,"$1")}$[d+"Delay"]=100;k[d]=$.extend(k[d],{setup:function(){if(e){return false}$(j.start)},teardown:function(){if(e){return false}$(j.stop)}});j=(function(){var m={},r,n,o,q;function p(){o=q=function(s){return s};if(h){n=$('<iframe src="javascript:0"/>').hide().insertAfter("body")[0].contentWindow;q=function(){return a(n.document[c][l])};o=function(u,s){if(u!==s){var t=n.document;t.open().close();t[c].hash="#"+u}};o(a())}}m.start=function(){if(r){return}var t=a();o||p();(function s(){var v=a(),u=q(t);if(v!==t){o(t=v,u);$(i).trigger(d)}else{if(u!==t){i[c][l]=i[c][l].replace(/#.*/,"")+"#"+u}}r=setTimeout(s,$[d+"Delay"])})()};m.stop=function(){if(!n){r&&clearTimeout(r);r=0}};return m})()})(jQuery,this);

(function($) {

    $.initQuotes = function(speed, delay) {
        var totalItems = $('.quotes-carousel li').length;
        var btns = [];
        for (var i = 0; i < totalItems; i++) {
            btns.push(".quote-link-"+i);
        }

        $('.quotes-carousel').jCarouselLite({
            speed: speed,
            auto: delay,
            circular: true,
            btnGo: btns,
            visible: 1,
            afterEnd: function(carousel, idx) {
                if (idx > totalItems) {
                    idx = idx%totalItems;
                }
                else if (idx == 0) {
                    idx = totalItems;
                }

                $('.quote-nav-list a').removeClass('selected');
                $('.quote-nav-list a:eq('+(idx-1)+')').addClass('selected');
            }
        });

		var total = $('.quote-nav-list a').length;
        var w = $('.quote-nav-list a:first').width() * total + $('.quote-nav-list a').length * 6;
        $('.quote-nav-list').css('padding-left', Math.floor(($('.quote-container').width() - w))/2);
    };

    /**
	 * Carousel for the home page
	 */
	$.fn.carousel = function(options) {
		var defaults = {
			duration: 8000,
			speed: 1200,
            prev: '#page-prev',
            next:'#page-next'
		};

		var curIdx = 0, animInterval = null, totalItems = 0;
		options = $.extend(defaults, options);

		var el = $(this);
        var info = $('#gallery-info');
        var next = $(options.next);
        var prev = $(options.prev);

		totalItems = el.find('.carousel').length;

		var navigation = '<div id="'+el.attr('id')+'-navigation"><ul>';
		for (var i = 0; i < totalItems; i++) {
			navigation += '<li><a rel="'+i+'" class="'+(i == curIdx ? 'selected' : '')+'"></a></li>';
		}

		navigation += '</ul></div>';
		this.after(navigation);
		navigation = $('#'+el.attr('id')+'-navigation');
		navigation.css('left', Math.floor((el.width() - navigation.width())/2));

		navigation.find('a').click(function() {
			var idx = $(this).attr('rel');
			el.find('.carousel:eq('+curIdx+')').fadeOut(options.speed);
            info.find('.carousel:eq('+curIdx+')').fadeOut(options.speed);
			navigation.find('li:eq('+curIdx+') a').removeClass('selected');
			el.find('.carousel:eq('+idx+')').fadeIn(options.speed);
            info.find('.carousel:eq('+idx+')').fadeIn(options.speed);
			navigation.find('li:eq('+idx+') a').addClass('selected');
			curIdx = idx;

			window.clearInterval(animInterval);
			startInterval();
			return false;
		});

        function doAnimate(add) {

            add = add || true;

            el.find('.carousel:eq('+curIdx+')').fadeOut(options.speed);
            info.find('.carousel:eq('+curIdx+')').fadeOut(options.speed);
            navigation.find('li:eq('+curIdx+') a').removeClass('selected');

            if (add) {
                curIdx++;
                if (curIdx >= totalItems) {
                    curIdx = 0;
                }
            }
            else {
                curIdx--;
                if (curIdx < 0) {
                    curIdx = totalItems-1;
                }
            }

            el.find('.carousel:eq('+curIdx+')').fadeIn(options.speed);
            info.find('.carousel:eq('+curIdx+')').fadeIn(options.speed);
            navigation.find('li:eq('+curIdx+') a').addClass('selected');
        }

		function startInterval() {
			animInterval = window.setInterval(doAnimate, options.duration);
		}

        prev.click(function() {
            window.clearInterval(animInterval);
            doAnimate(false);
            startInterval();
            return false;
        });

        next.click(function() {
            window.clearInterval(animInterval);
            doAnimate();
            startInterval();
            return false;
        })

		startInterval();
	};

    $('#gallery').carousel();

    $('#award-btns a').click(function() {
        window.location.href = this.href;
        return false;
    });

    if ($('#award-btns').length) {
        $(window).bind('hashchange', function(e) {
            var hash = $.param.fragment();
            if (hash) {
                $('#award-btns a').each(function() {
                    var el = $(this);
                    var href = el.attr('href');
                    if (href == '#'+hash) {
                        el.parent().addClass('selected');
                    }
                    else {
                        el.parent().removeClass('selected');
                    }
                });

                $('.award-subsection').fadeOut(200);
                $('#section-'+hash).fadeIn(200);
            }
        });

        $(window).trigger("hashchange");
    }

    var scrollToPlayer = function() {
        $('html, body').animate({
            scrollTop: $('#player-container').offset().top
        },
        1000);
    };

    if ($('.BrightcoveExperience').length) {
        brightcove.createExperiences();
    }

    if ($('#player-container').length) {
        var player, video, content, exp, menu, ads, social, cueVideoId;
        var duration = 700;

        var selectCurrentVideo = function() {
            var el = $('#'+video.getCurrentVideo().id);
            $('.video-list li').removeClass('playing');
            el.parents('li').addClass('playing');
            $('.playlist-play').fadeIn(duration);
            $('.now-playing').fadeOut(duration);
            el.siblings('.now-playing').fadeIn(duration);
            el.fadeOut(duration);

            $.get(window.location.href, {video:video.getCurrentVideo().id, method:'getVideoDetails'}, function(response) {
                response.title = response.title || '';
                response.description = response.description || '';
                $('#video-meta .info-subtitle').html(response.title);
                $('#video-meta p').html(response.description);
            });

            return el;
        }

        window.onTemplateLoaded = function(experienceID) {
            player = brightcove.getExperience(experienceID);

            video   = player.getModule(APIModules.VIDEO_PLAYER);
            content = player.getModule(APIModules.CONTENT);
            exp 	= player.getModule(APIModules.EXPERIENCE);
            menu 	= player.getModule(APIModules.MENU);
            ads 	= player.getModule(APIModules.ADVERTISING);
            social 	= player.getModule(APIModules.SOCIAL);

            // update share url when video change
            video.addEventListener(BCVideoEvent.VIDEO_CHANGE, function() {
                if (exp.getReady()) {
                    var el = $('#'+video.getCurrentVideo().id);
                    var shareUrl = el.attr('href');
                    social.setLink(shareUrl);
                }
            });

            video.addEventListener(BCMediaEvent.BEGIN, selectCurrentVideo);

            video.addEventListener(BCMediaEvent.COMPLETE, function() {
                var el = $('#'+video.getCurrentVideo().id).parents('li');
                try {
                    el.next().find('.playlist-play').click();
                }
                catch (e) {}
            });

            // player loaded. Check to see if someone previously clicked on a video to load.
            content.addEventListener(BCContentEvent.VIDEO_LOAD, function() {
                if (cueVideoId) {
                    video.loadVideo(cueVideoId);
                    cueVideoId = null;
                    scrollToPlayer();
                }
            });
        };
    }

    if (!IS_MOBILE && $('#client-playlist').length > 0) {
        $('.playlist-play').click(function() {
            if (exp.getReady()) {
                video.loadVideo(this.id);
                scrollToPlayer();
            }
            else {
                cueVideoId = this.id;
            }
            return false;
        });
    }

})(jQuery);
