//base_partone.js
if(!window.ItvJs)
    window.ItvJs = {};
    
    
// LEAVE THIS FUNCTION AT THE TOP PLEASE
// ----------------------------------------------
// Check if DOM available (http://www.cherny.com)
// ----------------------------------------------

var readyStateHandler = 0;  

var DomLoaded =
{
	onload: [], 
	ready: false,
	loaded: function()
	{
		DomLoaded.ready = true;
		for (z = 0;z < DomLoaded.onload.length;z++) {
			if (!DomLoaded.onload[z].done) {
				DomLoaded.onload[z]();
				DomLoaded.onload[z].done = true;
			}
		}
	},
	load: function(fireThis)
	{
		this.onload.push(fireThis);
		if (DomLoaded.ready) {
			DomLoaded.loaded();
			return;
		}
		if (document.addEventListener) 
			document.addEventListener("DOMContentLoaded", DomLoaded.loaded, null);
		if (/KHTML|WebKit/i.test(navigator.userAgent))
		{ 
			var _timer = setInterval(function()
			{
				if (/loaded|complete/.test(document.readyState))
				{
					clearInterval(_timer);
					delete _timer;
					DomLoaded.loaded();
				}
			}, 10);
		}
		/*@cc_on @*/
		/*@if (@_win32)
		var proto = "src='javascript:void(0)'";
		if (location.protocol == "https:") proto = "src=//0";
		document.write("<scr"+"ipt id=__ie_onload defer " + proto + "><\/scr"+"ipt>");
		var script = document.getElementById("__ie_onload");
		script.onreadystatechange = function() {
			if (this.readyState == "complete") {
				DomLoaded.loaded();
			}
		};
		
		/*@end @*/
		
		// window.onload = DomLoaded.loaded;
	}
	
};

//------------------------------------------
// Get any element by it's Class
//------------------------------------------
function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp('(^|\\s)'+searchClass+'(\\s|$)');
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}

//------------------------------------------
// Cross browser addEvent
//------------------------------------------

function addEvent( obj, type, fn ) {
	// Check for dom load events
	if(type == 'DOMContentLoaded') { DomLoaded.load(fn); return; }
		
	if (obj.addEventListener) {
		obj.addEventListener( type, fn, false );
		if(EventCache)
		{
		    EventCache.add(obj, type, fn);
		}
	}
	else if (obj.attachEvent) {
		obj["e"+type+fn] = fn;
		obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
		obj.attachEvent( "on"+type, obj[type+fn] );
		if(EventCache)
		{
		    EventCache.add(obj, type, fn);
		 }
	}
	else {
		obj["on"+type] = obj["e"+type+fn];
	}
}
var EventCache = function(){
	var listEvents = [];
	return {
		listEvents : listEvents,
		add : function(node, sEventName, fHandler){
			listEvents.push(arguments);
		},
		flush : function(){
			var i, item;
			try
			{
			    for(i = listEvents.length - 1; i >= 0; i = i - 1){
				    item = listEvents[i];
				    if(item[0].removeEventListener){
					    item[0].removeEventListener(item[1], item[2], item[3]);
				    };
				    if(item[1].substring(0, 2) != "on"){
					    item[1] = "on" + item[1];
				    };
				    if(item[0].detachEvent){
					    item[0].detachEvent(item[1], item[2]);
				    };
				    item[0][item[1]] = null;
			    };
			}
			catch(e){}
		}
	};
}();
addEvent(window,'unload',EventCache.flush);

//------------------------------------------
// Prevent the default action of an event
//------------------------------------------
function preventDefault(e) {
	if(!e) e = window.event;
	if(e.preventDefault) {
		e.preventDefault(); 
	} else {
		e.returnValue = false;
	}
}


//------------------------------------------
// add, check for, or remove a class to any element(s) or element ID(s)
//------------------------------------------	
function addClass(el,newClass) {
	if(typeof el == "string" && typeof $(el) == "object") {
		el = $(el);
	} else if(typeof el != "object") return;
	if(el.length) {
		for(var i=0, len=el.length; i<len; i++) addClass(el[i],newClass)
	} else {
		if(!hasClass(el,newClass)) {
			if(el.className) el.className += " " + newClass;
			else el.className = newClass;
		}
	}
}

function removeClass(el, remClass) {
	if(typeof el == "string" && typeof $(el) == "object") {
		el = $(el);
	} 
	if(el.length) {
		for(var i=0, len=el.length; i<len; i++) removeClass(el[i],remClass)
	} else {
		var regexp = new RegExp("(^|\\s)" + remClass + "(\\s|$)");
		el.className = el.className.replace(regexp, "$2");
	}
}

function hasClass(el, chkClass) {
	if(typeof el == "string" && typeof $(el) == "object") {
		el = $(el);
	} else if(typeof el != "object") return;
	if(el.length) {
		for(var i=0, len=el.length; i<len; i++) hasClass(el[i],chkClass)
	} else {
		var regexp = new RegExp("(^|\\s)" + chkClass + "(\\s|$)");
		return regexp.test(el.className);
	}
}


//------------------------------------------
// Vod playing
//------------------------------------------


// CSS Browser Selector   v0.2.5
// Documentation:         http://rafael.adm.br/css_browser_selector
// License:               http://creativecommons.org/licenses/by/2.5/
// Author:                Rafael Lima (http://rafael.adm.br)
// Contributors:          http://rafael.adm.br/css_browser_selector#contributors
var css_browser_selector = function() {
      var 
            ua=navigator.userAgent.toLowerCase(),
            is=function(t){ return ua.indexOf(t) != -1; },
            h=document.getElementsByTagName('html')[0],
            b=(!(/opera|webtv/i.test(ua))&&/msie (\d)/.test(ua))?('ie ie'+RegExp.$1):is('gecko/')? 'gecko':is('opera/9')?'opera opera9':/opera (\d)/.test(ua)?'opera opera'+RegExp.$1:is('konqueror')?'konqueror':is('applewebkit/')?'webkit safari':is('mozilla/')?'gecko':'',
            os=(is('x11')||is('linux'))?' linux':is('mac')?' mac':is('win')?' win':'';
      var c=b+os+' js';
      h.className += h.className?' '+c:c;
}();

var BCMRunning = false;
function IsBCMRunning(blnRunning)
{
    BCMRunning = blnRunning;
}


//TODO: DO WE NEED THESE
var vodcridGlobal;
var IFrameID='';
var G_AutoRoll = false;



function getParentElementsByClass(node,searchClass,tag) 
{
    var classElements = new Array();
    var els = window.parent.document.getElementsByTagName(tag); // use "*" for all elements
    var pattern = new RegExp('\\b'+searchClass+'\\b');

    for ( var i = 0; i < els.length; i++ )
        if ( pattern.test(els[i].className) ) classElements[classElements.length] = els[i];

    return classElements;
}
    



function GetHTML(thePage,theBaseHref)
{
    if (document.getElementById('nsatDiv'))
    {
       ItvJs.Video.NSAT.closeNSAT('no'); 
    }
    var domainName="";
    if (theBaseHref!=''){domainName=theBaseHref;}
    else {domainName = document.getElementsByTagName('base')[0].href;}
    
    if (domainName=='' || domainName==null){domainName=window.parent.document.getElementsByTagName('base')[0].href}
    
    var html = GetAjaxResponse(domainName+thePage); 
   
    var obody = document.getElementsByTagName("body")[0];
    var odiv = document.createElement("div");
    odiv.id="nsatDiv"
    if (ItvJs.Video.NSAT.isCatchUp){odiv.className="catchupBodyNSAT"}
    odiv.innerHTML = html;
    obody.appendChild(odiv); 
    odiv.style.zIndex = 1000;
}



function GetAjaxResponse(strUrl)
{
    var client = GetAjaxObject();
    var response;
    if(client)
    {
        client.open('GET', strUrl, false);
        client.send(null);
        response = client.responseText;
    }
    else
    {
        response = "-1";
    }
    return response;
}

function GetAjaxObject()
{
    if(window.XMLHttpRequest)
    {
        return new XMLHttpRequest();
    }
    else if(window.ActiveXObject)
    {
        var msxmls = new Array('Msxml2.XMLHTTP.5.0', 
                'Msxml2.XMLHTTP.4.0', 
                'Msxml2.XMLHTTP.3.0', 
                'Msxml2.XMLHTTP', 
                'Microsoft.XMLHTTP');
        for(var i = 0; i < msxmls.length; i++)
        {
            try
            {
                return new ActiveXObject(msxmls[i]);
            }
            catch(e){}
        }
    }
}

/*
3rd parties link directly to this function, when no nsat is required.
do not change without informing.
pls merge this comment to the trunk.
*/
function AutoPlayVodcrid ( videoToPlay, isThirdParty, url)
{
	var playInSitu = false;
	var vodCridToPlay;
	
	if ( videoToPlay != null )
	{
		if ( url && url.length > 0 )
		{
			url = url.toLowerCase();
			
			//	HACK: This is a temporary fix until the back-end CMS module, that manages the links, is fixed and released.
			//	HACK: Remove the forward slash that the back-end is helpfully putting there!
			if (url.indexOf("/") == 0)
			{
				url = url.substr(1);
			}
			
			//	HACK: If the link is the home page then just play in situ
			if (url == "http://" + location.host.toLowerCase() + "/default.html" || 
				url == "http://" + location.host.toLowerCase() + "/" || 
				url == "http://" + location.host.toLowerCase())
			{
				playInSitu = true;
			}
			//	END HACK
			
			//	If we already on the page then also just play in situ
			if (url == location.href.toLowerCase())
			{
				playInSitu = true;
			}
		}
		else
		{
			playInSitu = true;
		}
		
		if (!playInSitu)
		{
			//	This allows videos to be played on a different area/page in the site, rather than in situ
			//	So, redirect to this url and let it deal with playing the video.
		
			if ( typeof(videoToPlay) == 'object' )
				vodCridToPlay = videoToPlay.VODCRID;
			else
				vodCridToPlay = videoToPlay;
			
			location.href = url + "?VODCRID=" + vodCridToPlay;
		}
		else
		{
			// if a 3rd party or simulcast is just giving us
			// a string VODCRID, wrap it in a VideoClass. 
			if ( typeof( videoToPlay ) == 'string' )
			{
				thisVideo = new VideoClass;
				thisVideo.VODCRID = videoToPlay;
				PlayVideoWhenReady ( thisVideo );
			}
			else if ( typeof( videoToPlay ) == 'object' )
			{
    			PlayVideoWhenReady ( videoToPlay );
			}
	        
			if (!isThirdParty || isThirdParty == 'false')
			{
				return false;
			}
		}
	}
	else
	{
		// Follow usual href
		return true;
	}
}


var currVideoTargetVodcrid = null;

var timerID = 0;

function PlayVideoWhenReady ( videoToPlay )
{
    if (ItvJs.BB.Silverlight.Player.MustLoadMediaPlayer())
    {
        ItvJs.Video.Play(videoToPlay.VODCRID);
    }
    else
    {
        InitialisePlayer(document.getElementById('ace2cf60-e503-4711-9900-453213c079a4'), videoToPlay.VODCRID, null, true, videoToPlay.Rating, false);
    }
}

function SmcKey(simid)
{
    
    SIMID = simid;
    
    simadpageid = Math.round(Math.random() * 10000000000);
    simadsite = 'ITV';
    simadsimarea = 'SIMULCAST.'+SIMID.toUpperCase();
    simadarea = simadsimarea;
    if(typeof(FirstAdSite)!='undefined'&&FirstAdSite!=null){simadsite = FirstAdSite;}
    if(typeof(FirstAdArea)!='undefined'&&FirstAdArea!=null){simadarea = FirstAdArea;}
    var sTarget = GetAjaxResponse("/_app/dynamic/AsxHandler.ashx?getkey=please");
    sTarget = burl.href+'_app/dynamic/AsxHandler.ashx?key='+sTarget+'&simid='+SIMID+'&itvsite='+simadsite+'&itvarea='+simadarea+'&pageid='+simadpageid;
    play_simulcast(sTarget);
}

var SIMID;

function smchandler()
{
    if ( this.readyState == 4 && this.status == 200 )
    {
        if ( this.responseText )
        {
            sTarget = burl.href+'_app/dynamic/Simulcast.aspx?key='+this.responseText+'&simid='+SIMID;
            play_simulcast(sTarget);
        }
    }
}

function TimeOutTick()
{
    
    if ( readyStateHandler > 2 && window.document.videoController != null )
	{
	    // stop timer
	    if ( timerID ) { clearTimeout ( timerID ); timerID = 0; }
	    
	    // play video
	    
	    // if it's a simulcast
	    if ( currVideoTargetVodcrid.VODCRID.toLowerCase().indexOf('sim') == 0 )
	    {
	        burl = document.getElementById('baseurl');
	        if ( burl ) { SmcKey ( currVideoTargetVodcrid.VODCRID ); }
	    }
	    else
	    {
	        if ( ! currVideoTargetVodcrid.VODCRID.startsWith ( 'crid://ItvJs.com/' ) ) {
	            currVideoTargetVodcrid.VODCRID = 'crid://ItvJs.com/' + currVideoTargetVodcrid.VODCRID;
	        }
		    GetPlayListFromVodCrid ( currVideoTargetVodcrid );
        }
	}
	else if ((window.parent==window&&frames.PlayerFrame.noPlay==true)||(window.parent==window.parent&&window.parent.frames.PlayerFrame.noPlay==true)) {
	    var baseHref = document.getElementsByTagName('base')[0].href;
		if (baseHref=='') {
		baseHref = window.parent.document.getElementsByTagName('base')[0].href;
		window.parent.frames['PlayerFrame'].location=baseHref+'_app/video/player_noplay.html';
		} else {
		    frames['PlayerFrame'].location=baseHref+'_app/video/player_noplay.html';
		}
	}
	else
	{
		timerID = setTimeout("TimeOutTick()",100);
	}
}
    
//new stuff for NSAT - this code needs streamlining
              
Array.prototype.inArray = function (value) {
	var i;
	for (i=0; i < this.length; i++) {
		if (this[i] === value) {
			return true;
		}
	}
	return false;
};



// returms the Revenue Science tracking string
function GetRevenueScienceString()
{
	//	For removing underscores in the revenue string
	var reg = new RegExp("_", "g");
    // get the cookie value
    var rsiSegments = [];
    
    var segmentBegin = document.cookie.indexOf ( 'rsi_segs=' );
    
    if ( segmentBegin >= 0 )
    {
        segmentBegin = document.cookie.indexOf ( '=' , segmentBegin ) + 1;
        
        if ( segmentBegin > 0 )
        {
            var segmentEnd = document.cookie.indexOf ( ';', segmentBegin );
            
            if ( segmentEnd == -1 )
            {
                segs_end = document.cookie.length;
            }
            
            rsiSegments = document.cookie.substring(segmentBegin,segmentEnd).split('|');
        }
    }
    var rsString = '';
    
    for ( var i = 0; i < rsiSegments.length; i++ )
    {
        rsString += ( rsiSegments[i] + '.' );
    }
    rsString = rsString.replace(reg, '');
    
    return rsString;
}



// ========================================================= //
// Simulcast js
// ========================================================= //

function GetIHttpHandlerNowNextString()
{
    return GetIHttpHandlerSimNowNextRequest(ShowSimulcastNowTest);
}

function ShowSimulcastNowTest(webServiceResult)
{
    watchNowElement = document.getElementById('WatchNowModule');
    watchNowElement.innerHTML = webServiceResult;
    
    //  Process the link elements so they get setup to play videos correctly when
    //  they call ItvJs.Video.PlayVodcrid()
    ItvJs.Video.RenderVideoLinks(watchNowElement);
	
    setTimeout("GetIHttpHandlerNowNextString()", 60000);
}

function GetIHttpHandlerSimNowNextRequest(callback) 
{
    parentUrl = "http:\/\/" + window.location.host;
    url = parentUrl + '/_app/Dynamic/AsxHandler.ashx?getnownextconfig=true'
    
    return MakeWebServiceGETRequest(url, callback, false);
}

function MakeWebServiceGETRequest(url, callback, isResponseXml) 
{
    var http_request = false;
    
    http_request = false;
    http_request = GetAjaxObject();
    if (!http_request) 
    {
     alert('Cannot create XMLHTTP instance');
     return false;
    }

    http_request.onreadystatechange = function()
    {
        if (http_request.readyState == 4) 
        {
            if (http_request.status == 200) 
            {
                //alert(http_request.responseText);
                result = GetHttpRequestResponse(http_request, isResponseXml);
                if(result!=null)
                {                    
                    //process return value
                    if(callback)
                    {
                        callback(result);
                    }
                }
                else
                {
                    alert('There was a problem with this request.');
                }
            } 
            else 
            {
                alert('There was a problem with the request.');
            }
        }
    }
    http_request.open('GET', url, true);
    http_request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    http_request.setRequestHeader("Connection", "close");
    http_request.send(null);
}

function GetHttpRequestResponse(http_request, isXmlResponse)
{
    result = null;
    if(isXmlResponse)
    {
        result = GetHttpRequestResponseXml(http_request);
    }
    else
    {
        result = GetHttpRequestResponseText(http_request);
    }
    return result;
}

function GetHttpRequestResponseXml(http_request)
{
    result = null;
    var myXml=http_request.responseXML;
    if(myXml.xml!="" && myXml.childNodes.length>0)
    {
        if (window.ActiveXObject || window.opera)
        {
            result = myXml.childNodes[1].firstChild.nodeValue; 
        }
        else
        {
            result = myXml.childNodes[0].firstChild.nodeValue;
        }
    }
    return result;
}

function GetHttpRequestResponseText(http_request)
{
    result = null;
    var myText=http_request.responseText;
    result = myText;
    return result;
}

function RenderWatchVideoLink(simRef)
{
    link = document.getElementById('WatchNowAnchor'+simRef);
    vodCrid = simRef;
    if(link != null)
	{
		link.vodcrid = vodCrid;
		this.vodcrid = vodCrid;
	}
	return PlayVodcrid();
}
/* Get XML Node
   (Parameters) TagName:'XML Element' node:'Element row number' */
function getNode(rssFeed, TagName, node)
{
	var currentNode = (node == null) ? xmlDoc.getElementsByTagName(TagName) 
                                     : rssFeed[node].getElementsByTagName(TagName);

	if(currentNode.length > 0 && currentNode[0].firstChild!=null)
		return currentNode[0].firstChild.nodeValue;
}



String.prototype.startsWith = function ( s ) {
    return ( this.substring ( 0, s.length ) == s );
}

function VideoClass() {
    this.VODCRID = null;
    this.Rating = null;
    this.Isdf = false;
}

function AutoPlayVideoClass() {
    this.VideoItem = null;
    this.Mute = false;
    this.PlayOnce = false;
}


//RS
function GetRevSci()
    {
    	var theVal = Get_Cookie("rsi_segs");
		var adextra = document.getElementById("advertextra");
		if(null != adextra)
		{
		    adextra.value += "&amp;"+ theVal;
		}
    }

DomLoaded.load ( GetRevSci ); 



function deleteCookie(name,path,domain) 
{
    //  Change it's value so that it will be deleted (instantly within IE)
    if ( Get_Cookie( name ) ) document.cookie = name + "=DELETED" +
        ( ( path ) ? ";path=" + path : "") +
        ( ( domain ) ? ";domain=" + domain : "" ) +
        ";expires=Thu, 01-Jan-1990 00:00:01 GMT";
}
function Get_Cookie (name) 
{
	var start = document.cookie.indexOf( name + "=" );
    var len = start + name.length + 1;
    if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) )
    {
        return null;
    }
    if ( start == -1 ) 
    {
        return null;
    }
    var end = document.cookie.indexOf( ";", len );
    if ( end == -1 ) end = document.cookie.length;
    {
        return unescape( document.cookie.substring( len, end ) );
    }
}
function GetUserSessionID()
{
    var sid=Get_Cookie(".CommunityServer");
    if(sid)
    {
        return(sid);
    }
    return null;
}



//------------------------------------------
// cookies
//------------------------------------------
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}


//------------------------------------------
// end cookie detect
//------------------------------------------

function getUrl ( name )
{
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var results = regex.exec( window.location.href );
    if ( results == null )
        return "";
    else
        return results[1];
}