﻿// the "Juicy Fruit" framework (c) Nickelodeon - Scott Miller

var section = window.location.pathname.split('/')[1];
var subsection = '';
if(window.location.pathname.split('/')[3]) subsection = window.location.pathname.split('/')[3].split('.')[0].toLowerCase();

var QSo = "###"; // Query string object
if(window.location.search!="") 
{   
    QSo = new Object;
    QSo = getQueryStringObject(window.location.search);
}

var sizing=false;
var numOfBGs = 7;// number of backgrounds. Names:1,2,3,etc.

var s_account = "";
if(window.location.hostname=="www.nick.co.uk" || window.location.hostname=="nick.co.uk") s_account="nickelodeonukprod"; // omniture live account
else s_account="nickelodeonukdev" // omniture dev account

var pagingCreated=false;

$(document).ready(function(){
    
    randomBG();
    
    $('#search label').click(function(){
        if($(this).siblings('input').val()=='') {
            $(this).fadeOut(250);
            $(this).siblings('input').focus();
        }
    });
    
    $('#search input,.field input,.field textarea').focus(function(){
        if($(this).val()=='') $(this).siblings('label').fadeOut(300);
    });
    
    $('#search input,.field input,.field textarea').blur(function(){
        if($(this).val()=='') $(this).siblings('label').fadeIn(200);
    });
    
    $('#button-search').click(function(){
        if($('#search input').val() != "") 
            window.location="/search.aspx?search="+$('#search input').val(); 
    });
    
    $('#search input').keypress(function(e){
        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
			$('#button-search').click();
			return false;
		} else {
			return true;
		}     
    });
    
    initCarousel();
    
    $('.whatson-list .row').click(function(){
        if(!$(this).hasClass('on')) {
            $('.on').removeClass('on').children('.desc').slideUp(500);
            $(this).addClass('on').children('.desc').slideDown(500);
        } else {
            $(this).removeClass('on').children('.desc').slideUp(500);
        }    
    });
    
    $('.help-list .question').click(function(){
        if(!$(this).parent().hasClass('on')) {
            $('.on').removeClass('on').children('.desc').slideUp(500);
            $(this).parent().addClass('on').children('.desc').slideDown(500);
        } else {
            $(this).parent().removeClass('on').children('.desc').slideUp(500);
        }
    });
    
    $('.help-list .row a[href*="#"]').click(function()
    {
        var anchor = $(this).attr('href').replace('#','');
        anchor--;
        $('.help-list span.on').children('.desc').slideUp(500,function(){
            $('.help-list span.on').removeClass('on');
            $('.help-list .row:eq('+anchor+')').addClass('on').children('.desc').slideDown(500);
        });
        return false;
    });
    
    $('.field input[value!=""],.field textarea[value!=""]').siblings('label').hide();
    
    // external links
    $('a[rel="external"],a[rel="ext"]').attr('title',function(){ return this.title+' (opens in a new window)'}).click(function(){
        window.open(this.href);
        return false;
    });
});

/* Target attribute is now deprecated so instead use rel="external" */
function externalLinks() {
    if (!document.getElementsByTagName) return;
    var anchors = document.getElementsByTagName('a');
    
    for (var i=0; i<anchors.length; i++) 
    {
        var anchor = anchors[i];
        if (anchor.getAttribute('href') && anchor.getAttribute('rel') == 'external') {
            anchor.target = '_blank';
            anchor.title += ' (opens in new window)';
        }
    }
}
window.onload = externalLinks;


function goPagingPage(thisPagingPage)
{
    var newTop = (thisPagingPage * 38)-38;
    $('#pages').css({ top:-(newTop)+'px' });
    pagingPage=thisPagingPage;
}

function goPage(thisPage, show, showPageSet)
{   
    var isShowSite = false;
    if(section == "clips") var list = "#list-clips";
    else if(section == "games") var list = "#list-games";
    else if(section == "shows")
    {   
        isShowSite=true;
        if(subsection=="clips") var list = "#list-clips";
        else if(subsection=="games")
        {
            var list = "#list-games";
        }
    }
    else if(section=="search.aspx") 
    {
        var list = "#list-results";   
    }
    
    $('#pages a.on').removeClass('on');
    page = Number(thisPage);
    var newTop = ((page-1) * pageHeight);
    if(!show) {
        $(list).css({ top:-(newTop)+'px' });
    }
    else {
        $(showlist).css({ top:-(newTop)+'px' });
    }        
    $('#pages #page'+page).addClass('on'); 
    
    // - new paging count
    if(!pagingCreated) {
        var pagingCurr = $('<div id="paging-curr"><span>Page <span id="paging-current">1</span> of <span id="paging-total">1</span></span></div>');
        $('#button-next').after(pagingCurr);
        pagingCreated=true;
    }
    $('#paging-current').html(page);
    $('#paging-total').html(pageCount);
    //
    
    $('#button-next, #button-back').removeClass('disabled');        
    if(page==1) $('#button-back').addClass('disabled');
    if(page==pageCount) $('#button-next').addClass('disabled');
    
    if(page<=10 && pagingPage!=1) goPagingPage(1);
    if(page>10 && page<=20 && pagingPage!=2) goPagingPage(2);
    if(page>20 && page<=30 && pagingPage!=3) goPagingPage(3);
    if(page>30 && page<=40 && pagingPage!=4) goPagingPage(4);
    if(page>40 && page<=50 && pagingPage!=5) goPagingPage(5);
    if(page>50 && page<=60 && pagingPage!=6) goPagingPage(6);
    if(page>60 && page<=70 && pagingPage!=7) goPagingPage(7);
    if(page>70 && page<=80 && pagingPage!=8) goPagingPage(8);
    if(page>80 && page<=90 && pagingPage!=9) goPagingPage(9);
    if(page>90 && page<=100 && pagingPage!=10) goPagingPage(10);
    
    if(list=="#list-clips" && page!=1) 
    {
        if(!showPageSet) trackFeatured("clips page"+page, s_account, $("#paging-page #page"+page));
        else trackFeatured("clips pagingPage", s_account, $("#paging-page #page"+page));
    }
    else if(list=="#list-games" && page!=1)
    {
        if(!showPageSet) trackFeatured("games page"+page, s_account, $("#paging-page #page"+page));
        else trackFeatured("games pagingPage", s_account, $("#paging-page #page"+page));
    }
}

function showMorePages()
{
    if(page%10==0) page--;
    var newPage=page+10;
    newPage = (Math.floor(newPage / 10)*10)+1;
    goPage(newPage, false, true); 
}
function showLessPages()
{
    goPage((pagingPage-1)*10, false, true); 
}

/**
 * .disableTextSelect - Disable Text Select Plugin
 *
 * Version: 1.1
 * Updated: 2007-11-28
 *
 * Used to stop users from selecting text
 *
 * Copyright (c) 2007 James Dempster (letssurf@gmail.com, http://www.jdempster.com/category/jquery/disabletextselect/)
 *
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 **/
/**
 * Requirements:
 * - jQuery (John Resig, http://www.jquery.com/)
 **/
(function($){if($.browser.mozilla){$.fn.disableTextSelect=function(){return this.each(function(){$(this).css({"MozUserSelect":"none"})})};$.fn.enableTextSelect=function(){return this.each(function(){$(this).css({"MozUserSelect":""})})}}else{if($.browser.msie){$.fn.disableTextSelect=function(){return this.each(function(){$(this).bind("selectstart.disableTextSelect",function(){return false})})};$.fn.enableTextSelect=function(){return this.each(function(){$(this).unbind("selectstart.disableTextSelect")})}}else{$.fn.disableTextSelect=function(){return this.each(function(){$(this).bind("mousedown.disableTextSelect",function(){return false})})};$.fn.enableTextSelect=function(){return this.each(function(){$(this).unbind("mousedown.disableTextSelect")})}}}})(jQuery)


/* play clip function - to reload video player. needs to be here as referenced on shows/clips as well as clips hub
vars:
videoID = umaID
show name
clip title
string to pass to related clips service 
bool - true is for clips played within a show template */
function playClip(videoID, show, title, related, showclips)
{   
    $('#end-slate').hide();
    $('#clips-title').html(title);
    $('#clips-show').html(show);
    $('#clips #tabs').css({'top':'468px'});
    $('#clips #breadcrumb').css({'top':'515px'});
    $('#clips #list-clips-wrap').css({'top':'557px'});
    $('#clips #paging').css({'top':'926px'});
    //$('#clips').height(949); - before new paging
    $('#clips').height(986);
    
    $('#clips-title,#clips-show').show();
    if(showclips) $('body').scrollTo(470, 500);
    else $('body').scrollTo(320, 500);
    
    $('#videoplayer').html('').removeClass('loaded');
    
    configUrl = "";
	if (configUrl == "") {
		configUrl = devHost + '/player/configuration.jhtml';
	} else {
		configUrl = devHost + configUrl;
	}	
	
	configUrl += "?ads=" + ads;
	configUrl += "&uri=" + 'mgid:uma:video:nick.co.uk:'+videoID;
	configUrl += "&css=" + css;
	configUrl += "&full=" + fullEpisode;
	configUrl += "&autoPlay=" + autoPlay;
	configUrl += "&continuousPlay=" + continuousPlay;
	configUrl += "&sitePath=" + sitePath;
	configUrl += "&playerPath=" + playerPath;
	configUrl += "&resize=" + resize;
	configUrl += "&screenMode=" + screenMode;
	configUrl += "&getUrl=" + getUrl;
	configUrl += "&defaultLang=" + defaultLang;
	configUrl += "&jsMode=" + jsMode;
	configUrl += "&embed=" + embed;
	configUrl += "&isLive=" + isLive;
	configUrl += "&moreVideos=" + moreVideos;
	configUrl += "&endSlate=" + endSlate;
	configUrl += "&version=" + version;
	configUrl += keyValuePair;
	
	configUrl = configUrl.replace(/\:/g, "%7C");
	configUrl = configUrl.replace(/\?/g, "%3F");
	configUrl = configUrl.replace(/\=/g, "%3D");
	configUrl = configUrl.replace(/\&/g, "%26");
	configUrl = configUrl.replace(/\http%7C/g, "http:");	
	
	var so = new SWFObject("http://intl.esperanto.mtvi.com/global/apps/player/flex/Loader.swf","embeddedPlayer", "100%", "100%", "9.0.115.0", 	"#cccccc");
    so.addVariable("CONFIG_URL",configUrl);
    so.addParam("allowFullScreen",true);
    so.addParam("enableJavascript",true);
    so.addParam("allowScriptAccess","always");
    so.addParam("swliveconnect",true);
    so.addParam("menu", false);
    so.addParam("wmode", "transparent");
    so.addParam("bgcolor", "#000000");
    so.write("videoplayer");

    bindRelated(show, showclips);
}

function bindRelated(show, showclips, endslate)
{
    show = show.replace("&amp;","&").replace("'","&#39;");
    $.ajax(
    {
        type: "POST",
	    url: "/services/relatedcontent.asmx/RelatedClips",
	    beforeSend: function(xhr) {                            
	        xhr.setRequestHeader("Content-type", "application/json; charset=utf-8");
	    },
	    data: "{'show':'"+ show +"','genre':'all'}",
	    contentType: "application/json; charset=utf-8",
	    dataType: "json",
	    success: function(json)
        {  
            var clipData = json.d;
            if(clipData.length>0) 
            {
                if(!endslate) {
                    $('#list-related-clips').html('');
	                $('#related-clips').show();
	            } else {
	                $('#end-slate').show().html('');
	            }    
                for(var i=0; i<=2; i++) {
                    var thisClip = clipData[i];    				
                    var elm = '<a title="Watch '+ thisClip.Show +' - '+ thisClip.Description +'" rel="'+ thisClip.Umaid +'">';
                    elm += '<span class="list-img">';
                    if(thisClip.Thumb=="") thisClip.Thumb = "/global/img/thumb.gif";
                    elm += '<img src="'+ thisClip.Thumb +'" alt="'+ thisClip.Description +'" />';
                    elm += '<span class="clip-hover"></span>';
                    elm += '</span>';
                    if(showclips) elm += '<span class="list-show" rel="'+thisClip.ShowUrl+'">'+ thisClip.Show +'</span>';
                    else elm += '<span class="list-show">'+ thisClip.Show +'</span>';
                    elm += '<span class="list-title">'+ thisClip.Description +'</span>';
                    elm += '<span class="playing"></span>';
                    elm += '</a>';
                    if(!endslate) $('#list-related-clips').append(elm);
                    else $('#end-slate').append(elm);
                }
                if(!endslate) {
                    if(showclips)
                    {
                        $('#list-related-clips a').unbind().click(function(){ 
                            window.location = $(this).children('span.list-show').attr('rel');
                            trackFeatured('shows:clips:relatedClip:'+$(this).attr('rel'),s_account,this);
                        });
                    } else {
                        $('#list-related-clips a').unbind().click(function(){ 
                            $('#list-clips a.on,#list-related-clips a.on').removeClass('on');
                            playClip($(this).attr('rel'),$(this).children('.list-show').html(),$(this).children('.list-title').html(),true,false);                            
                            trackFeatured('clips:relatedClip:'+$(this).attr('rel'),s_account,this);
                        });
                    }
                } else {
                    $('#end-slate a').unbind().click(function(){ 
                        $('#list-clips a.on,#list-related-clips a.on').removeClass('on');
                        $('#end-slate').html('');                        
                        playClip($(this).attr('rel'),$(this).children('.list-show').html(),$(this).children('.list-title').html(),true,false);
                        trackFeatured('clips:endslate:'+$(this).attr('rel'),s_account,this);
                    });
                }
            }
        },
        error: function(){
           errorHandler('#related-clips');
        }
    });
}

function onPlayerLoaded(controller){
	player = controller.player;
}

function randomBG()
{
    var folder = "";
    var BGnum = Math.floor(Math.random()*numOfBGs+1); // random num 0-3
    
    if(subsection=="" || subsection=="default")
    {
        if(section=="" || section=="default" || section=="shows") 
        {
            $('#bg-character').css({'background-image':'url(/global/img/bgs/home/'+BGnum+'.jpg)', 'background-color':'#fff'});
            placeBG();
        }
        else if(section=="games" || section=="clips" || section=="win" || section=="whatson") 
        {
            $('#bg-character').css({'background-image':'url(/global/img/bgs/'+BGnum+'.jpg)', 'background-color':'#fff','top':'-5px'}); 
            placeBG();
        }
    }
}
$(window).resize(placeBG);
function placeBG()
{
    if(!sizing){
        sizing=true;
        var winH = $(document).height();
        $('#bg-character').css({'height':winH}); 
        setTimeout(function(){sizing=false}, 1000)
    }
}

function getQueryStringObject(str)
{
    try
    {
        var qs=[];
        var a=str.indexOf("?")>-1?str.split("?")[1].split("&"):str.split("&");
        for(var x=0;x<a.length;x++){var b=a[x].split("=");qs[b[0]]=b[1].split('%20').join(' ');}
        return qs;
    }
    catch(e){}
}

function errorHandler(o)
{
    $(o).hide();
    trackFeatured("ajax-error:"+o, s_account, this);
}


/* func to fire event on dropdown selects:
$('#MyDropDown').selected(function() { });
*/
(function($) {
    $.fn.selected = function(fn) {
        return this.each(function() {
            var clicknum = 0;
            $(this).click(function() {
                clicknum++;
                if (clicknum == 2) {
                    clicknum = 0;
                    fn();
                }
            });
        });
    }
})(jQuery);
