// LEAVE THIS FUNCTION AT THE TOP PLEASE
// ----------------------------------------------
// Check if DOM available (http://www.cherny.com)
// ----------------------------------------------
if(typeof(disableDocumentDomainSet)=='undefined' 
    || disableDocumentDomainSet==null 
    || disableDocumentDomainSet==false)
{
    doms = window.location.host.split('.');
    if(doms.length>1)
    {
        document.domain=doms[doms.length-2] + '.' + doms[doms.length-1];
    }
} 

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;
	}
	
};


function checkRegion(){
    
    //this has been changed not to use jquery, as some third parties don't use it.
    var objCookieVals, strRegionUrl = "http://www.itv.com/local/", strRegionText = "Local", strCookieRegion = readCookie("ITV-NBR-MENU");
     
    // Does the cookie exist? If so, overwrite the default local values.
    if (strCookieRegion && document.getElementById("Local")!=null)
    {
  
        objCookieVals = strCookieRegion.split("~", 2);
        strRegionText = unescape(objCookieVals[0].replace(/%7E/, "~"));    
        strRegionUrl = unescape(objCookieVals[1].replace(/%7E/, "~"));

        // Change the vales of the primary nav link
        localLink=document.getElementById("Local").firstChild;
        localLink.href=strRegionUrl;
        localLink.title=strRegionText;
        localLink.innerHTML=strRegionText;
    }
}

if (window==window.parent)
    DomLoaded.load ( checkRegion ); 
  
function trackLinks()
{
    var links = document.getElementsByTagName('a');
    	    
	if(BCMRunning)
    {
	    for ( var a = 0; a < links.length; a++ )
	    {
	       if ((links[a].className!='itv-recommend')&&(links[a].className!='itv-mwv'))
	            addEvent(links[a],'click', BCM); //now in BCM.js
	       
        }
    }
}
DomLoaded.load ( trackLinks ); 


//----------------------------------------------
//Set any global vars here
//----------------------------------------------
var bookmarkRef; //this is set from player.html, used to avoid bookmarking issue with IE.
var isTVGuide = false;
// ----------------------------------------------
// function to open links in new window (replaces target="_blank" attribute as is invalid XHTML)
// ----------------------------------------------
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";
    }

}

DomLoaded.load ( externalLinks ); 


  var flashOpen = false;
	
	function flashToggle(position,flashOpen){
		if (document.getElementById('CatchUpNavigationTop'))
		{
		    whichDiv='CatchUpNavigationTop';
		} else {whichDiv='CatchUpNavigationBottom';}
		
		if(flashOpen=='true') {
		var itvDIV = document.getElementById(whichDiv);
			itvDIV.style.height = '500px';
			if(document.getElementById('secOne-cu-1-0')&&Itv.ClientCaps.ISIE){document.getElementById('placeholder2').style.zIndex=-1;}
		} else {
		var itvDIV = document.getElementById(whichDiv);
			if (whichDiv=='CatchUpNavigationTop'){itvDIV.style.height = '88px';}
			else {itvDIV.style.height = '130px';}
			if(document.getElementById('secOne-cu-1-0')&&Itv.ClientCaps.ISIE){
			document.getElementById('placeholder2').style.zIndex=1;
			}

		}
	}
	

var flashOpenBtm = false;
	
function flashToggleBtm(position,flashOpenBtm){
	if(flashOpenBtm == 'true') {
	
		var itvDIV = parent.document.getElementById('thisFlash');
		itvDIV.style.height = '400px';
		itvDIV.style.top = '0px';
		
		var gibbleD = parent.document.getElementById('gibble');
		gibbleD.style.marginTop = '-50px';
	} else {

		var itvDIV = parent.document.getElementById('thisFlash');
	        itvDIV.style.height = '130px';
	        itvDIV.style.top = '270px';
	        
	        var gibbleD = parent.document.getElementById('gibble');
		    gibbleD.style.marginTop = '-320px';
	}
}



function UpdateReadyState()
{
    readyStateHandler++;
}

DomLoaded.load ( UpdateReadyState );

//------------------------------------------
// function for 3rd party 2nd nav options
//------------------------------------------
var thirdPartySecNav="";
function doThirdPartyNav() {
    try {
        if ( thirdPartySecNav != "" ) {
           document.getElementById(thirdPartySecNav).className="active";
        }
    } catch(e) { }
}

DomLoaded.load ( doThirdPartyNav );

//------------------------------------------
// function for getting param from url
//------------------------------------------
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];
}

function isHttps()
{
	//	Determine whether the page is using https
	return (location.protocol.toLowerCase() == "https:");
}

//------------------------------------------
// function for opening popup windows
//------------------------------------------

function genPopUp(url,w,h,name,resizable,scrollbar,menu,tool,status,directories,x,y){
	new popUp(url,w,h,name,resizable,scrollbar,menu,tool,status,directories,x,y)
	return false;
}

function popUp(url,w,h,name,resizable,scrollbar,menu,tool,status,directories,x,y){
	this.strUrl = url;
	this.intX = x;
	this.intY = y;
	this.strName = name;
	this.strResizable = (resizable=="yes" || resizable==1) ? "resizable=yes" : "";
	this.strScroll = (scrollbar=="yes" || scrollbar==1) ? "scrollbars=yes" : "";
	this.strMenu = (menu=="yes" || menu==1) ? "menubar=yes" : "";
	this.strTool = (tool=="yes" || tool==1) ? "toolbar=yes" : "";
	this.strStatus = (status=="yes" || status==1) ? "status=yes" : "";
	this.strDirectories = (directories=="yes" || directories==1) ? "directories=yes" : "";
	this.intW = (!isNaN(w)) ? "width="+w: "";
	this.intH = (!isNaN(h)) ? "height="+h: "";

	this.arrOptions = new Array(this.strResizable,this.strScroll,this.strMenu,this.strTool,this.strStatus,this.strDirectories,this.intW,this.intH);
	this.strOptions = "";
	//build the options
	for(var i=0;i<this.arrOptions.length;i++){
		if(this.arrOptions[i].length>0){
			this.strOptions+=this.arrOptions[i]+",";
		}
	}
	//remove any trailing ","
	if(this.strOptions.length>0){
		this.strOptions=this.strOptions.substring(0,this.strOptions.length-1);
	}
	this.win=window.open(this.strUrl,this.strName,this.strOptions);
	this.win.focus();
}
//------------------------------------------
// Advertising Age Calculation from FriendsReunited
//------------------------------------------
function GetITVCookie()
{
    var c_friendsTxt = "";
    var allValues = "";
   
    if (document.cookie.length>0)
    {        
        // isolate FriendsReunited       
        c_friendsTxt = Get_Cookie("ITV-FriendsReunited");
        
        if (c_friendsTxt != null){        
            var parameters = c_friendsTxt.split("&");
            
            for(i=0; i<parameters.length; i++){            
                c_start=parameters[i].indexOf("A=");
                if (c_start!=-1) // DOB
                {             
                    c_end = (c_start+2) + 7; //MMMYYYY
                    var findDob = unescape(parameters[i].substring(c_start,c_end));
                    findDob = findDob.replace(/&/g, '/');
                    //return '/'+ FindDOB(findDob);
                    allValues += '/'+ FindDOB(findDob);
                } 
                else 
                {
                    if (parameters[i].indexOf("Read")<0){
                        allValues += '/'+ unescape(parameters[i]);                            
                    }
                }
            } 
        }     
        
    }
    return allValues;
}

function FindDOB(findDob)
{
    var strings = findDob.split('/');
    var newString = ";";
    for(var i = 0; i<strings.length; i++)
    {
        if(strings[i].length > 3)
        {
            newString += "A=" + GetAgeFromDOB(strings[i].substr(2, strings[i].length)) + '/';
        }
        else
        {
            newString += strings[i] + '/';
        }
    }
    
    return newString.substr(1, newString.length-2);
}

function GetAgeFromDOB(findDob)
{    
    var today = new Date();
    var currentmonth = today.getMonth();
    var currentyear = today.getFullYear();
    
    var birthDate = findDob;
    var usermonth = birthDate.substr(0,3);
    var useryear = birthDate.substr(3,4);
    usermonth = GetMonthInArray(usermonth);
    // +1 for use next month as day not used
    usermonth = usermonth ++;
    
    // handle if pushed into next year
    if (usermonth > 12)
    {
        useryear++;
        usermonth = usermonth - 12;        
    }
       
    // handle if not birthday this year yet 
    if(currentmonth <= usermonth)
    {
        currentyear--;
    }
        
    //alert(currentyear +' ' +useryear);
    return currentyear - useryear;
}

function GetMonthInArray(month)
{
    var ar = new Array ('JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC');
    for(var i = 0; i<ar.length; i++)
    {
        if(ar[i].toLowerCase() == month.toLowerCase())
        {
            return i;
        }
    }
}


//------------------------------------------
// functions to change search field text
//------------------------------------------
// if you change this function please also change 
// the version in /cmn/js/header.js
//need to leave these functions in for archived content
function clearSearch (theValue) {

}
function checkSearch (theValue) {

}
function submitSearch()
{
    theTxtBox = document.getElementById('q');    
    if (theTxtBox!=null&&typeof(theTxtBox)!='undefined'&&theTxtBox.value=='Search site') {
		theTxtBox.value='';
	}
	return true;
}

function populateContext()
{
    contextTxtBox = document.getElementById('searchContext');
    pathArr = window.location.pathname.split( '/' );
    contextTxtBox.value = pathArr[1].toUpperCase();
}

// populate the search context  
DomLoaded.load(populateContext);

//------------------------------------------
// Catch up TV page - logic to hide/show & re-colour search results info pane on catch up tv page
//------------------------------------------
if(navigator.appName.indexOf("Microsoft") > -1){
	var tableRowBlock = 'block';
} else {
	var tableRowBlock = 'table-row';
}

openInfo="";
openInfoIsEven="";
function toggleProgInfo(which,isEven) {
	if (openInfo!=which) {closeInfo(openInfo,openInfoIsEven)}
	whichTitle=which+'Title';
	whichInfo=which+'Info';
	whichActive=which+'Active';
	whichLink=which+'Link';
	if (document.getElementById(whichInfo).style.display==tableRowBlock){//hide
		document.getElementById(whichInfo).style.display='none'; // hide the info pane
			document.getElementById(whichLink).className="closed";//change the link arrow
		document.getElementById(whichActive).className="active";//re-colour the active (sort by) column
		if (isEven=='even') { // color the even table rows the even background colour, otherwise no class name
			document.getElementById(whichTitle).className="even";
		} else {
			document.getElementById(whichTitle).className=""; 
		}
	} else {//open
		document.getElementById(whichInfo).style.display=tableRowBlock;
		document.getElementById(whichTitle).className="title";
		document.getElementById(whichLink).className="open";
		document.getElementById(whichActive).className="title";
		openInfo=which;
		openInfoIsEven=isEven
	}
}
function closeInfo(closeWhich,isEven){
	if (closeWhich!=""){
	openTitle=closeWhich+'Title';
	openInfo=closeWhich+'Info';
	openActive=closeWhich+'Active';
	openLink=closeWhich+'Link';
		document.getElementById(openInfo).style.display='none';
		document.getElementById(openActive).className="active";
			document.getElementById(whichLink).className="closed";
		if (isEven=='even') { 
			document.getElementById(openTitle).className="even";
		} else {
			document.getElementById(openTitle).className=""; 
		}	
	}

}
//------------------------------------------
// End Catch up TV page
//------------------------------------------

//------------------------------------------
// 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
//------------------------------------------


// for the navigation
/* 
sfHover = function() {
	if (document.getElementById("nav") != null)
	{
	    var sfEls = document.getElementById("nav").getElementsByTagName("LI");
	    for (var i=0; i<sfEls.length; i++) {
		    sfEls[i].onmouseover=function() {
			    this.className+=" sfhover";
		    }
		    sfEls[i].onmouseout=function() {
			    this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
		    }
	    }
	}
}
if (window.attachEvent) window.attachEvent("onload", sfHover);
*/
//------------------------------------------
// Shortcut for getElementByID()
//------------------------------------------
function $() {
	var elements = [];
	for (var i = 0; i < arguments.length; i++) {
		var element = arguments[i];
		if (typeof element == "string") {
			element = document.getElementById(element);
			if (arguments.length == 1 && element) return element;
			if(element) elements.push(element);
		}
	}
	if(elements.length) return elements;
	else return false;
}

//<-------------- Start LOGIN and IFRAME scripts------------------->
//---------------------------------------------------------
// To allow an Iframe to automatically size to its contents
// used by the IFRAME CMS module.
//----------------------------------------------------------

function resizeiframe(iframe) {
if(iframe)
    {
    var IEBugHeight;
        if(document.getElementById && !(document.all)) 
        {
            h = iframe.contentDocument.body.scrollHeight;
            iframe.style.height = h+35+'px';
         }
        else if(document.all) 
        {
          
            iframe.style.height=0;//fix for a bug in IE, whereby on multiple loads of Iframe (search page for eg) the height is incremented each time.
            h=iframe.document.body.scrollHeight+35
            iframe.style.height = h+35;
        }
        
        // reloads the iframe to set querystring parameters if necessary
        loadiframe(iframe);
    }    
}

function updateIFrame( height, iFrameId ) {
    if(typeof(height)=="number"){
        height+=20;
        var iframe = document.getElementById( iFrameId );
        
        var maxHeight = 1024;
        if(height > maxHeight){
            height = maxHeight;
        }
        
        iframe.setAttribute( 'height', height );
    }
}
      

var _setQueryString = false;
function loadiframe(iframe)
{   
    var querystring = window.location.search;

    var path = iframe.src;            
    //if the parent page has the get parameter, forwardParams=1, and the inner IFrame has the get parameter ignoreCall=true
    if (((querystring.indexOf("forwardParams=1") > -1) || (path.toLowerCase().indexOf("_app/dynamic/")>-1)) && (path.indexOf("ignoreCall")>-1))
    {
        path = path.replace("ignoreCall=true", "");
        querystring = querystring.replace("forwardParams=1&", "");
        querystring = querystring.replace("forwardParams=1", "");

        var iframeSrc = path + "&" + querystring.substr(1);
        iframe.src = iframeSrc;
        _setQueryString = true;
    } 
}

//--------------------------------------------
//To allow an IFRAME to set the main page url.
//used by registration and login to navigate
//back to the origin page.
//--------------------------------------------
function setwindowurl(url)
{
   if(url)
   {
    window.location.href = url;
   }
}

//------------------------------------------------------------------------
// Check for the login session cookie. If present change signin to signout
// and change the login href to be a cookie delete script
//------------------------------------------------------------------------

function checkLoginWithParamters(signInLinkId, registerLinkId, canChangeLoginLink)
{
    //alert("loading");
     var loginlink=document.getElementById(signInLinkId);
     var registerlink=document.getElementById(registerLinkId);
     
     if(registerlink)
     {
       //registerlink.href="https:\/\/"+window.location.host+"\/"+window.location.pathname.split("\/",2)[1]+"\/"+"register\/default.html";
       if (window.location.host.indexOf(".itv.com")>0){
            //registerlink.href="https:\/\/sso.itv.com\/"+"register\/default.html";
       }
       else
       {
            registerlink.href="https:\/\/"+window.location.host+"\/"+"register\/default.html";
       }
     }
     
     if(checkcookie('.CommunityServer'))
     {
       try
       {
             //check if we are being redirected from a page that needs to log in
            var redirectURL=getURLParam("OriginPage");
             if(''==redirectURL)
             {
                redirectURL=getURLParam("ReturnUrl");
             }
             
             if(redirectURL)
             {//we are on the login page, pass the origin page parameter to the login iframe 
                if (window.location.href.toLowerCase().indexOf(window.location.host.toLowerCase() + "\/register\/signin.html")>0)
                {
                    window.location = redirectURL;
                }
             }
            loginlink.firstChild.nodeValue="Sign out";
            registerlink.firstChild.nodeValue="Account";
            //modify the link to call the cookie delete 
            loginlink.href="javascript:logout();";
        }
        catch(e)
        {
            //Domloaded has lied...
        }
     }
     else
     {
        var forcelogin=document.getElementById("ForceLogin");
        if(forcelogin)
        { //navigate to the login page...
           var origin = window.location.href;
           //window.location.pathname.split("\/",2)[1]+"\/"+
           if (origin.indexOf(".itv.com")>0)
           {
                window.location.href="https:\/\/sso.itv.com\/"+"register\/signin.html"+"?OriginPage="+origin;
           }
           else
           {
                window.location.href="https:\/\/"+window.location.host+"\/"+"register\/signin.html"+"?OriginPage="+origin;
           }
           return true; //?need this?
        }
        
//        if(loginlink)
//        {
//            loginlink.firstChild.nodeValue="Sign in";
//            registerlink.firstChild.nodeValue="Register";
//            var origin = window.location.href;
//            
//            if(canChangeLoginLink)
//            {
//                if (origin.indexOf(".itv.com")>0)
//                {
//                //+window.location.pathname.split("\/",2)[1]+"\/"
//                    loginlink.href="https:\/\/sso.itv.com\/"+"register\/Signin.html?OriginPage="+origin;
//                }
//                else
//                {
//                    loginlink.href="https:\/\/"+window.location.host+"\/"+"register\/Signin.html?OriginPage="+origin;
//                }
//            }
//            if(document.getElementById("ITVSingleSignOn1_Login1"))
//            {        
//                ShowLoggedOutView();
//            }
//         }
     }
}

var checklogin =function ()
{  
    loginControlID = "signinlink";
    registerControlID  = "registerlink";
    canChangeLoginLink = true;
    
    loginControl = document.getElementById('LoginControlID');
    registerControl = document.getElementById('RegisterControlID');
    
    if(loginControl!=null && registerControl!=null)
    {
        loginControlID = loginControl.value;
        registerControlID = registerControl.value;
        canChangeLoginLink = false;
    }
    checkLoginWithParamters(loginControlID, registerControlID, canChangeLoginLink);
}

addEvent(window,'load',checklogin);

function getURLParam(strParamName){
  var strReturn = "";
  var strHref = window.location.href;
  if ( strHref.indexOf("?") > -1 ){    
    var strQueryString = strHref.substr(strHref.indexOf("?"));
    var aQueryString = strQueryString.split("&");
    for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
      if (
aQueryString[iParam].indexOf(strParamName + "=") > -1 ){
        var aParam = aQueryString[iParam].split("=");
        strReturn = aParam[1];
        break;
      }
    }
  }
  return unescape(strReturn);
}

function checkcookie (name) {    	   
    var arg = name + "=";
    var alen = arg.length;
    var clen = document.cookie.length;
    var i = 0;
    while (i < clen) {
    var j = i + alen;
        if (document.cookie.substring(i, j) == arg)
                
        return true;                
    i = document.cookie.indexOf(" ", i) + 1;
        if (i == 0) break; 
        }
    //Cookie not found
    return false;
}
//----------------------------------------------------------------------
// Delete the login cookie and reset the link to point to the login page
//----------------------------------------------------------------------

function logout()
{
    logoutWithParameters('','');
}

function logoutWithParameters(signInLinkId, registerLinkId)
{
  if(document.cookie!="")
  {
    var path = "/";
    var domain = Get_Cookie("ITVCookieDomain");
    deleteCookie(".CommunityServer", path, domain);
    deleteCookie('.CSRoles', path, domain);
    deleteCookie ('SSOMail', path, domain);
    
    // pluck (commenting) authentication cookies
    deleteCookie ('at', path, domain);
    deleteCookie ('hd', path, domain);
  }
  if(""==signInLinkId)
  {
    checklogin();
  }
  else
  {
    checkLoginWithParamters(signInLinkId,registerLinkId, false);
  }
  window.location = window.location.href;
}

//--------------------------------------------------------
// A cookie utility. Delete a named cookie by expiring it.
//--------------------------------------------------------
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;
}
//<-------------- end LOGIN and IFRAME scripts------------------->

//------------------------------------------
// 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;
	}
}


//------------------------------------------
// Performs rollover of form submit images
//------------------------------------------
function rollFormBtn (e) {
	tHeight =  this.height || this.offsetHeight;
	if (e.type == 'mouseover') {this.style.backgroundPosition = '0px '+tHeight+'px';}
	else if (e.type == 'mouseout') {this.style.backgroundPosition = '0px 0px';}
}
//------------------------------------------
// Adds rollover event to form submit images
//------------------------------------------
function setFormBtns () {
	var btns = getElementsByClass('formbtn',document,'input');
	for (var i=0;i<btns.length;i++) {
		addEvent(btns[i],'mouseover',rollFormBtn);
		addEvent(btns[i],'mouseout',rollFormBtn);
	}
}
//DomLoaded.load(setFormBtns);


//------------------------------------------
// Switches an element between displaying/hiding
//------------------------------------------
function toggle(el) {
	if(typeof el == "string" && typeof $(el) == "object") {
		el = $(el);
	} else if(typeof el != "object") return;
	if ( el.style.display != 'none' ) {
		el.style.display = 'none';
	} else {
		el.style.display = '';
	}
}

//------------------------------------------
// 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 resizeIFrameforNSAT(applyDenton)
{
    if (getParentElementsByClass('body','iframe-5col','iframe')!='')
    {
        theIframe=getParentElementsByClass('body','iframe-5col','iframe');
    }
    else
    {
        theIframe=getParentElementsByClass('body','iframe-4col','iframe');
    }
   
    if ( window.innerHeight && window.scrollMaxY ) // Firefox 
    {
        currHeight = window.innerHeight + window.scrollMaxY;
    }   
    else if( document.body.scrollHeight > document.body.offsetHeight ) // all but Explorer Mac
    {
        currHeight = document.body.scrollHeight;
    }
    else if ((document.documentElement.offsetHeight)&& !(document.all))// failsafe for FF
    {
     currHeight = document.documentElement.offsetHeight;
    }
    else // works in Explorer 6 Strict, Mozilla (not FF) and Safari
    {
        currHeight = document.body.offsetHeight + document.body.offsetTop; 
    } 
    
    var applyDentonHeight=0;
    if (applyDenton=="yes")
    {
        if  (currHeight<=800)
        {
            applyDentonHeight=950-currHeight;
        }
    }
   
    theIframeID=theIframe[0].id;
    if(document.getElementById && !(document.all)) 
    {
        if (window.parent.document.getElementById(theIframeID)){
            window.parent.document.getElementById(theIframeID).style.height=currHeight+20+applyDentonHeight+'px';
        }
     }
     else if(document.all)  
     { 
        if (window.parent.document.getElementById(theIframeID))
        {
            window.parent.document.getElementById(theIframeID).style.height=currHeight+20+applyDentonHeight;            
        }    
     }  
}


function GetHTML(thePage,theDiv)
{
    if (document.getElementById('nsatDiv'))
    {
       Itv.Video.NSAT.closeNSAT('no'); 
    }
     
    var domainName="";
    domainName = document.getElementsByTagName('base')[0].href;
    if (domainName=='' || domainName==null){domainName=window.parent.document.getElementsByTagName('base')[0].href}
    var html = GetAjaxResponse(domainName+'_app/video/'+thePage);
    var obody = document.getElementsByTagName("body")[0];
    var odiv = document.createElement("div");
    odiv.id="nsatDiv"
    if (Itv.Video.NSAT.isCatchUp){odiv.className="catchupBodyNSAT"}
    odiv.innerHTML = html;
    obody.appendChild(odiv); 
    odiv.style.zIndex = 1;
}

function CallFootballService(strUrl,isMwv)
{
    if (isMwv) {strUrl = strUrl.replace('&amp;','&');}
    var domainName="";
    domainName = document.getElementsByTagName('base')[0].href;
    if (domainName=='' || domainName==null){domainName=window.parent.document.getElementsByTagName('base')[0].href}
    if (strUrl.indexOf("?") > -1)
		strUrl += "&"
	else
		strUrl += "?"
	strUrl += "cacheBuster=" + new Date().getTime();
	var html = GetAjaxResponse(domainName+strUrl);
    document.writeln(html);
}

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 )
{
    loadPlayer('ace2cf60-e503-4711-9900-453213c079a4',videoToPlay.VODCRID,true,false,null,Itv.Video.Mercury.defaultVideoPlayerId,false,true)
}

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://itv.com/' ) ) {
	            currVideoTargetVodcrid.VODCRID = 'crid://itv.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;
};

//------------------------------------------
// Ad call v3.0 # Andrew Gordon
//------------------------------------------

var AdIndex = 0;
var AdStack = new Array();
function ResizeAdIframe(id,width,height)
{
    placeholder = document.getElementById(id);
    if(typeof(placeholder)!='undefined'&&placeholder!=null)
    {
        iframe=placeholder.getElementsByTagName('iframe')[0];
        if(height!=null&&width!=null){
            iframe.style.height=height+'px';
            iframe.style.width=width+'px';
            iframe.style.border='none';
        }
    }
    refreshNextAdvert();
}

var itvJServerOverride = false;

var FirstAdSite = null;
var FirstAdArea = null;
var pageNum = Math.round(Math.random() * 10000000000);

function BrowserCanRefreshAds()
{
    var agt=navigator.userAgent.toLowerCase();
    var is_major = parseInt(navigator.appVersion);
    var is_minor = parseFloat(navigator.appVersion);
    var is_ie     = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
    var is_ie3    = (is_ie && (is_major < 4));
    var is_ie4    = (is_ie && (is_major == 4) && (agt.indexOf("msie 4")!=-1) );
    var is_ie5    = (is_ie && (is_major == 4) && (agt.indexOf("msie 5.0")!=-1) );
    var is_ie5_5up =(is_ie && !is_ie3 && !is_ie4 && !is_ie5);
    var is_ie6    = (is_ie && (is_major == 4) && (agt.indexOf("msie 6.0")!=-1) );
    var is_ie7    = (is_ie && (is_major == 4) && (agt.indexOf("msie 7.0")!=-1) );
    var is_ie7_up = (is_ie && !is_ie3 && !is_ie4 && !is_ie5 && !is_ie6);
    if (is_ie7) {return true;} else {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;
}

function AddAdCallToStack(tAdServer,tItvSite,tItvArea,tPosition,tDimensions,tShowDebug,tTargetId,tSegmentName)
{
    //because we were told at the last minute...overrides CMS2 ad calls for PS3 browser
    var areaNames = tItvArea.toString().split(".");
    if (areaNames[0].toLowerCase()=='itvplayer' && (typeof(ITVPlayer) != 'undefined')){
        if(isPS3){
           var areaNameEnd="";
           var segNameEnd="";
           var segNames=tSegmentName.toString().split(".");
          
           for(i=1;i<areaNames.length;i++){
                areaNameEnd+="." + areaNames[i];
           }
          
           for(i=1;i<segNames.length;i++){
                segNameEnd+="." + segNames[i];
           }
           tItvArea="ITVPLAYERPS3" + areaNameEnd; 
           tSegmentName="ITVPLAYERPS3" + segNameEnd;
        } 
        
    }

     
    var tItvtestcookie = 'OFF';
    
    var itvtestCK = readCookie('itvtestcookie');
    
    if (itvtestCK=='Yes')
    {
        tItvtestcookie='ON';
    }
    
    if(FirstAdSite==null)
    {
        FirstAdSite=tItvSite;
    }
    if(FirstAdArea==null)
    {
        FirstAdArea=tItvArea;
    }
    
    RevenueScienceString = GetRevenueScienceString();
    
    var loc = '';
    
    try
    {
        loc = window.top.location.href;
    }
    catch ( locErr )
    {
        loc = '';
    }
    
    loc = loc.toLowerCase();
    
    if ( itvJServerOverride == false && ( ( loc.indexOf('http://www.itv.com') == 0 || loc.indexOf('http://localhost') == 0 || loc.indexOf('itvbb') > -1 ) && BrowserCanRefreshAds() ) )
    {
        AddAdCallToStackIframe(tAdServer,tItvSite,tItvArea,tPosition,tDimensions,tShowDebug,tTargetId,tSegmentName);
    }
    else
    {
        AddAdCallToStackJserver(tAdServer,tItvSite,tItvArea,tPosition,tDimensions,tShowDebug,tTargetId,tSegmentName,tItvtestcookie,RevenueScienceString);
    }
}

function AddAdCallToStackJserver ( tAdServer, tItvSite, tItvArea, tPosition, tDimensions, tShowDebug, tTargetId, tSegmentName, tItvtestcookie, tRSString )
{
    var sAdTarget= "/SITE="+tItvSite+"/AREA="+tItvArea+"/SEG="+tSegmentName+"/POSITION="+tPosition+"/TEST="+tItvtestcookie;
    switch (tDimensions)
    {
        case '150x113':sAdTarget+='/AAMSZ=SPONSORBUTTON';break;
        case '163x64':sAdTarget+='/AAMSZ=FOOTBALLSPONSORBUTTON';break;
        case '1x1':sAdTarget+='/AAMSZ=OUTOFPAGE'; break;
        default:sAdTarget+='/AAMSZ=' + tDimensions;break;
    }
    sAdTarget += '/RS=' + tRSString;
    var random = Math.round(Math.random() * 10000000000);
    var itvCookieValue = GetITVCookie();
    sUrl = tAdServer+'/jserver/acc_random='+random+sAdTarget+itvCookieValue+'/pageid='+pageNum;
    document.write('<SCR');document.write('IPT SRC="' + sUrl + '">');document.write('</SCR');document.write('IPT>');
}
function AddAdCallToStackIframe(tAdServer,tItvSite,tItvArea,tPosition,tDimensions,tShowDebug,tTargetId,tSegmentName,tItvtestcookie)
{
    iframe = GetAdIFrame(tAdServer,tItvSite,tItvArea,tPosition,tDimensions,tShowDebug,tTargetId,tSegmentName,tItvtestcookie);
    AdStack[AdStack.length]=iframe;
}
function GetAdIFrame(tAdServer,tItvSite,tItvArea,tPosition,tDimensions,tShowDebug,tTargetId,tSegmentName,tItvtestcookie)
{
    targetDiv=document.getElementById(tTargetId);
    iframe=targetDiv.getElementsByTagName('iframe')[0];
    if(iframe == null){
        iframe = document.createElement('iframe');
        iframe.style.width='0px';
        iframe.style.height='0px';
        iframe.scrolling='no';
        iframe.allowTransparency='true';
        iframe.frameBorder='0';
        iframe.style.borderColor='#FFF';
        targetDiv.appendChild(iframe);
    }
    iframe.AdString = '/_app/AdTools/adproxy.html?adserver='
        + escape(tAdServer)
        + '&itvsite='
        + tItvSite
        + '&itvarea='
        + tItvArea
        + '&SEG='
        + tSegmentName
        + '&position='
        + tPosition
        + '&dimensions='
        + tDimensions
        + '&showdebug='
        + tShowDebug
        + '&targetid='
        + tTargetId
        + '&pagenum='
        + pageNum
        + '&test='
        + tItvtestcookie;
    return iframe;
}
function refreshAdvert()
{
    AdIndex=0;
    refreshNextAdvert();
}
function refreshNextAdvert()
{
    if(AdIndex==-1||AdIndex>=AdStack.length)
    {
        AdIndex=-1;
    }
    else
    {
        AdStack[AdIndex].src = AdStack[AdIndex].AdString+'&randid='+Math.round(Math.random() * 10000000000);
        AdIndex++;
    }
}
function ServeAds(){refreshAdvert();}
DomLoaded.load(ServeAds);

//Take the control object surrounding the ad to be displayed.
//If blank ad is returned from ad server, control.innerHTML is set to ""
//NM: Setting display = none as there is still a gap when dropping innerhtml
function HideBlankAd (control)
{
    if (AdStack.length==0 && control != null)
	{
	    control=eval("document.getElementById('"+control+"')");

	    if ((typeof (control) != 'undefined' && control != null) &&
	        (control.innerHTML.indexOf('AE0.gif') > 0 ||
	         control.innerHTML.indexOf('AE1.gif') > 0))
	    {
	        control.innerHTML = "";
	        control.style.display = "none";
	    }
	}

}

function RedirectToQuickLinkUrl(dropDownId)
{
    // Get information about the dropdown instance
    var dropdown = document.getElementById(dropDownId);
    var box = dropdown.options;
    var chosen_value = box[box.selectedIndex].value;

    // Extract the Url information from the selected option
    var chosen_pageId = chosen_value.substring(chosen_value.indexOf('^')+1);
    var chosen_url = chosen_value.substring(0,chosen_value.indexOf('^'));
        
    // The CMS allows some external links to appear in the same window
    // The url is prefixed with 'ExternalInSameWindow|' if this is the case
    var ExternalInSameWindow = chosen_value.substring(0, 20);
    
    if ( ExternalInSameWindow == 'ExternalInSameWindow' )
        chosen_url = chosen_value.substring(chosen_value.indexOf('|')+1,chosen_value.indexOf('^'));
    
    // Redirect to the url   
    if ( chosen_value != 'DefaultOption' )
    {  
        if ( chosen_pageId > 0 || ExternalInSameWindow == 'ExternalInSameWindow' )
            window.location = chosen_url; // Open in same window
        else
            window.open(chosen_url);      // Open in new window
    }    
}

// ========================================================= //
// 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 Itv.Video.PlayVodcrid()
    Itv.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();
}

// ========================================================= //
// Ticker js
// ========================================================= //

var theCharacterTimeout    = 50;
var theStoryTimeout        = 5000;
var theWidgetOne           = "_";
var theWidgetTwo           = "-";
var theWidgetNone          = "";
var theLeadString          = "ITV RSS Ticker:&nbsp;";//publish this value?
var refreshRSSFeedInterval = 300000;
var theSummaries           = new Array();
var theSiteLinks           = new Array();
var theDescription         = new Array();
var theItemCount           = 0;
var rssFeedURL             = "NetFX.xml";

function InitialiseTicker(url)
{
    rssFeedURL = url;
    RefreshFeed();
}

function RefreshFeed()
{
    var rssFeedDocument = GetRSSFeedDocument(rssFeedURL);
    if(rssFeedDocument.childNodes && rssFeedDocument.childNodes.length>0)
    {
        var rssFeed = rssFeedDocument.getElementsByTagName('item');
        PopulateNewsList(rssFeed);
        
        var rssChannel = rssFeedDocument.getElementsByTagName('channel');
        UpdateLeadString(rssChannel);
    }
    setTimeout("RefreshFeed()", refreshRSSFeedInterval); // Call up the next cycle of the feed refresh
}

function PopulateNewsList(rssFeed)
{
    theSummaries = new Array();
    theSiteLinks = new Array();
    
    theItemCount = rssFeed.length;
    
    var buffer = "";

	for(var i=0; i< rssFeed.length; i++) 
	{
        theSummaries[i] = getNode(rssFeed, 'title', i);
        theSiteLinks[i] = getNode(rssFeed, 'link', i)
        theDescription[i] = getNode(rssFeed, 'description', i)
	}
}

function UpdateLeadString(rssChannel)
{
    theLeadString = getNode(rssChannel, 'title', 0);
    if (theLeadString == null)
		theLeadString = '';
}

/* 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;
}

/* NEW FUNCTION */
function GetRSSFeedDocument(rssFeed) 
{
    var client = GetAjaxObject();
    var response;
    if(client) {
        client.open('GET', rssFeed, false);
        client.setRequestHeader("If-Modified-Since", "Thu, 1 Jan 1970 00:00:00 GMT");
        client.send(null);
        response = client;
    }
    
    var xmldoc;
    if (window.ActiveXObject) { 
        xmldoc = response.responseXML;
    }
    else if (window.XMLHttpRequest) { 
        // Use the DOMParser in FireFox due to the cross-domain security issues when loading Xml Document directly.
        var parser = new DOMParser();
        var doc = parser.parseFromString(response.responseText, 'text/xml');
        xmldoc = doc.documentElement;
    }

    return xmldoc;
}

// Ticker startup
function StartTicker()
{
    RefreshFeed();
	// Define run time values
	theCurrentStory     = -1;
	theCurrentLength    = 0;
	
	// Locate base objects
	if (document.getElementById) 
	{	
        theAnchorObject = document.getElementById("tickerAnchor");
        runTheTicker();   	
    }
	else 
	{
        document.write("<style>.ticki{display:none;}.ticko{border:0px; padding:0px;}</style>");
        return true;
	}
}

// Ticker main run loop
function runTheTicker()
{
	var myTimeout;  
	
	if(theItemCount > 0)
	{
	    // Go for the next story data block
	    if(theCurrentLength == 0)
	    {
		    theCurrentStory++;
		    theCurrentStory      = theCurrentStory % theItemCount;
		    theStorySummary      = theSummaries[theCurrentStory].replace(/&quot;/g,'"');		
		    theTargetLink        = theSiteLinks[theCurrentStory];
            theAnchorObject.href = theTargetLink;
            if (typeof(theDescription[theCurrentStory])!='undefined')
				theAnchorObject.title = theDescription[theCurrentStory];
		    thePrefix 	         = "<span class=\"tickls\">" + theLeadString + "</span>";
		    
		    if(typeof(theTargetLink)=='undefined')
		    {
		       disableAnchor(theAnchorObject, true);
		    }
	    }
    	
	    // Stuff the current ticker text into the anchor
	    theAnchorObject.innerHTML = thePrefix + 
	    theStorySummary.substring(0,theCurrentLength) + whatWidget();
    	
	    // Modify the length for the substring and define the timer
	    if(theCurrentLength != theStorySummary.length)
	    {
		    theCurrentLength++;
		    myTimeout = theCharacterTimeout;
	    }
	    else
	    {
		    theCurrentLength = 0;
		    myTimeout = theStoryTimeout;
	    }
	    
	    // Call up the next cycle of the ticker
	    setTimeout("runTheTicker()", myTimeout);
	}
}

function disableAnchor(obj, disable)
{
  if(disable)
  {
    var href = obj.getAttribute("href");
    if(href && href != "" && href != null)
    {
       obj.setAttribute('href_bak', href);
    }
    obj.removeAttribute('href');
  }
  else
  {
    obj.setAttribute('href', obj.attributes['href_bak'].nodeValue);
  }
}

// Widget generator
function whatWidget()
{
	if(theCurrentLength == theStorySummary.length)
	{
		return theWidgetNone;
	}

	if((theCurrentLength % 2) == 1)
	{
		return theWidgetOne;
	}
	else
	{
		return theWidgetTwo;
	}
}

/* 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;
}


//********************************************************//
//Smart Skycraper Ad js
//Date: 07,01,08
//********************************************************//

//Check if browser exceeds Width
function IsBrowserWidthGreaterThan(iMinWidth)
{
    isBrowserWidthGreaterThan = false;
//TODO (RPF): strAdServer has to be published during publication

    width = GetDocumentWidth();
    isBrowserWidthGreaterThan = (width>=iMinWidth);

    return isBrowserWidthGreaterThan;
}

//function to display skyscraper advert
var smartSkyScraperAdStackValue;
function DisplaySkyScraperAd()
{
    //advertextra element contains the SITE, AREA and SEG parameters
    advertextraElement = document.getElementById('advertextra');
    if(typeof(strAdServer)!='undefined' && advertextraElement!=null && IsBrowserWidthGreaterThan(1004 + 160))
    {
        //Get parameters for ad call
        tAdServer = strAdServer;
        tItvSite = '';
        tItvSiteRestriction = '';
        tItvArea = '';        
        tSegmentName = '';

        params = advertextraElement.value.split('&');
        
        for(  i = 0, l = params.length; i < l; ++i ) 
        {
          parts = params[i].split( '=' );
          
          switch( parts[0] ) 
          {
            case 'SITE':
              tItvSite = parts[1];
              break;
            case 'RESTRICTION':
              tItvSiteRestriction = parts[1];
              break;
            case 'AREA':
              tItvArea = parts[1];
              break;
            case 'SEG':
              tSegmentName = parts[1];
          }
        }

        if(tItvSiteRestriction.toLowerCase() == 'kids')
            tItvSite = tItvSite + 'K';
        
        AddAdCallToSmartSkyScraper('SmartSkyscraper', tAdServer,tItvSite,tItvArea,'1','160x600','False','SmartSkyscraper',tSegmentName)

    }
    else
    {
        RemoveSkyScraperAd('SmartSkyscraper');
    }
}

function AddAdCallToSmartSkyScraper( smartSkyScraperDivIdName, tAdServer, tItvSite, tItvArea, tPosition, tDimensions, tShowDebug, tTargetId, tSegmentName, tItvtestcookie )
{  
    existingDiv = document.getElementById(smartSkyScraperDivIdName);
    if(existingDiv==null || typeof(existingDiv)=='undefined')
    {
        smartSkyScraperDiv = document.createElement('div');
        smartSkyScraperDiv.setAttribute('id',smartSkyScraperDivIdName);
        smartSkyScraperDiv.setAttribute('width',160);
        smartSkyScraperDiv.setAttribute('height',600);
        document.body.appendChild(smartSkyScraperDiv);
    
        targetDiv = smartSkyScraperDiv;
        iframe=GetAdIFrame(tAdServer,tItvSite,tItvArea,tPosition,tDimensions,tShowDebug,tTargetId,tSegmentName,tItvtestcookie);
        iframe.AdString+="&IsSmart=true";
        document.body.appendChild(smartSkyScraperDiv);

        iframe.src = iframe.AdString+'&randid='+Math.round(Math.random() * 10000000000);
    }
}

function RemoveSkyScraperAd(divIdName)
{
  oldDiv = document.getElementById(divIdName);
  if(oldDiv != null)
  {
    iframe = oldDiv.getElementsByTagName('iframe')[0];
    if(iframe!=null)
    {
        oldDiv.removeChild(iframe);
    }
    document.body.removeChild(oldDiv);
  }
}
addEvent(window,'load',DisplaySkyScraperAd);
//********************************************************//
//END Smart Skycraper Ad js
//********************************************************//

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;
}

//********************************************************//
//START: Document width and supporting (+reuseable) functions
//********************************************************//

var property_cache = {};
var ua = navigator.userAgent.toLowerCase();
var isOpera = (ua.indexOf('opera') > -1);
var isSafari = (ua.indexOf('safari') > -1);
var isIE = (window.ActiveXObject);

var cacheConvertedProperties = function(property) {
  property_cache[property] = {
     camel: toCamel(property),
     hyphen: toHyphen(property)
  };
};

var toCamel = function(property) 
{
      var convert = function(prop) 
      {
         var test = /(-[a-z])/i.exec(prop);
         return prop.replace(RegExp.$1, RegExp.$1.substr(1).toUpperCase());
      };
      
      while(property.indexOf('-') > -1) 
      {
         property = convert(property);
      }

      return property;
      //return property.replace(/-([a-z])/gi, function(m0, m1) {return m1.toUpperCase()}) // cant use function as 2nd arg yet due to safari bug
}
   
var toHyphen = function(property) 
{
      if (property.indexOf('-') > -1) 
      { // assume hyphen
         return property;
      }
      
      var converted = '';
      for (var i = 0, len = property.length;i < len; ++i) 
      {
         if (property.charAt(i) == property.charAt(i).toUpperCase()) 
         {
            converted = converted + '-' + property.charAt(i).toLowerCase();
         } 
         else 
         {
            converted = converted + property.charAt(i);
         }
      }
      return converted;
}

function GetDocumentWidth()
{
     var docWidth=-1,bodyWidth=-1,winWidth=-1;
     var marginRight = parseInt(GetStyle(document.body, 'marginRight'), 10);
     var marginLeft = parseInt(GetStyle(document.body, 'marginLeft'), 10);
     
     var mode = document.compatMode;
     
     if (mode || isIE) 
     { // (IE, Gecko, Opera)
        switch (mode) 
        {
           case 'CSS1Compat': // Standards mode
              docWidth = document.documentElement.clientWidth;
              bodyWidth = document.body.offsetWidth + marginLeft + marginRight;
              winWidth = self.innerWidth || -1;
              break;
              
           default: // Quirks
              bodyWidth = document.body.clientWidth;
              winWidth = document.body.scrollWidth;
              break;
        }
     } 
     else 
     { // Safari
        docWidth = document.documentElement.clientWidth;
        bodyWidth = document.body.offsetWidth + marginLeft + marginRight;
        winWidth = self.innerWidth;
     }
  
     var w = [docWidth,bodyWidth,winWidth].sort(function(a, b){return(a-b);});
     return w[2];//Return the last value in the sorted array.
}

function GetStyle(el, property)
{
     var f = function(el) 
     {
        var value = null;
        var dv = document.defaultView;
        
        if (!property_cache[property]) 
        {
           cacheConvertedProperties(property);
        }
        
        var camel = property_cache[property]['camel'];
        var hyphen = property_cache[property]['hyphen'];

        if (property == 'opacity' && el.filters) 
        {// IE opacity
           value = 1;
           try 
           {
              value = el.filters.item('DXImageTransform.Microsoft.Alpha').opacity / 100;
           } 
           catch(e) 
           {
              try 
              {
                 value = el.filters.item('alpha').opacity / 100;
              } 
              catch(e) {}
           }
        } 
        else if (el.style[camel]) 
        { // camelCase for valid styles
           value = el.style[camel];
        }
        else if (isIE && el.currentStyle && el.currentStyle[camel]) 
        { // camelCase for currentStyle; isIE to workaround broken Opera 9 currentStyle
           value = el.currentStyle[camel];
        }
        else if ( dv && dv.getComputedStyle ) 
        { // hyphen-case for computedStyle
           var computed = dv.getComputedStyle(el, '');
           
           if (computed && computed.getPropertyValue(hyphen)) 
           {
              value = computed.getPropertyValue(hyphen);
           }
        }
  
        return value;
     };
     
     return Batch(el, f, null, false);
}

function Get(el) 
{
    if (typeof el != 'string' && !(el instanceof Array) ) 
    { // assuming HTMLElement or HTMLCollection, so pass back as is
        return el;
    }

    if (typeof el == 'string') 
    { // ID
        return document.getElementById(el);
    }
    else 
    { // array of ID's and/or elements
        var collection = [];
        for (var i = 0, len = el.length; i < len; ++i) 
        {
           collection[collection.length] = Get(el[i]);
        }

        return collection;
    }

    return null; // safety, should never happen
}

function Batch(el, method, o, override) 
{
    var id = el;
    el = Get(el);

    var scope = (override) ? o : window;

    if (!el || el.tagName || !el.length) 
    { // is null or not a collection (tagName for SELECT and others that can be both an element and a collection)
    if (!el) {
       return false;
    }
    return method.call(scope, el, o);
    } 

    var collection = [];

    for (var i = 0, len = el.length; i < len; ++i) {
    if (!el[i]) {
       id = id[i];
       logger.log(id + ' not available', 'error', 'Dom');
    }
    collection[collection.length] = method.call(scope, el[i], o);
    }

    return collection;
}

// ========================================================= //
// HTMLGallery js
// ========================================================= //
    
function opacity(id, opacStart, opacEnd, millisec) 
{ 
    var speed = Math.round(millisec / 100); 
    var timer = 0; 

    //determine the direction for the blending, if start and end are the same nothing happens 
    if(opacStart > opacEnd) 
    { 
        for(i = opacStart; i >= opacEnd; i--) 
        { 
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed)); 
            timer++; 
        } 
    } 
    else if(opacStart < opacEnd) 
    { 
        for(i = opacStart; i <= opacEnd; i++) 
        { 
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed)); 
            timer++; 
        } 
    } 
} 

//change the opacity for different browsers 
function changeOpac(opacity, id) 
{ 
    var object = document.getElementById(id).style; 
    object.opacity = (opacity / 100); 
    object.MozOpacity = (opacity / 100); 
    object.KhtmlOpacity = (opacity / 100); 
    object.filter = "alpha(opacity=" + opacity + ")"; 
} 


function shiftOpacity(id, millisec) 
{ 
    //if an element is invisible, make it visible, else make it ivisible 
    if(document.getElementById(id).style.opacity == 0) 
        opacity(id, 0, 100, millisec); 
    else 
        opacity(id, 100, 0, millisec); 
} 

function HTMLGallerySetMainImage( moduleId, index )
{
    var objMainImage = document.getElementById('mainImg_' + moduleId);
    var loadingIndicator = document.getElementById('loadingContentBox_' + moduleId);
    var objSelectedImage = document.getElementById('thumbMain_' + moduleId + '_' + index );
    var objSelectedThumb = document.getElementById('thumbImg_' + moduleId + '_' + index );

    // Copy the new image information from the hidden controls to the main image
    objMainImage.src = objSelectedThumb.src;
    objMainImage.alt = objSelectedImage.alt;
    objMainImage.style.width = objSelectedImage.style.width;
    objMainImage.style.height = objSelectedImage.style.height;
    objMainImage.style.left = objSelectedImage.style.left;
    objMainImage.style.top = objSelectedImage.style.top;
    
    //	Ensure the loading image indicator is hidden and the main image displayed
    objMainImage.style.display = '';
    loadingIndicator.style.display = 'none';
}

function HTMLGallerySetSponsorImage( moduleId, index )
{
    var objSponsorImage = document.getElementById('SponsorImg_' + moduleId);
    var objSelectedImage = document.getElementById('thumbSponsor_' + moduleId + '_' + index );
    var objSponsorDiv = document.getElementById('SponsImgDiv_' + moduleId);

    if ( objSelectedImage.style.width == '0px')
        objSponsorDiv.style.display = 'none';
    else
        objSponsorDiv.style.display = 'block';        

    // Copy the new image information from the hidden controls to the sponsor image
    objSponsorImage.src = objSelectedImage.src;
    objSponsorImage.alt = objSelectedImage.alt;
    objSponsorImage.style.width = objSelectedImage.style.width;
    objSponsorImage.style.height = objSelectedImage.style.height;
}

function HTMLGallerySetActiveThumbnail(thumbnailImageId, moduleId, thumbIndex)
{
    // Get Information about the last click
    var objGallerySelectedIndexHiddenField = document.getElementById('gallerySelectedIndex_' + moduleId);

    // Thumbnail attributes
    changeOpac(100, thumbnailImageId);

    // Store the index of the current thumbnail
    objGallerySelectedIndexHiddenField.value = thumbIndex;
}

function HTMLGalleryCopyText( moduleId, thumbIndex)
{
	var reg = new RegExp("\n", "g");
	
    // Update the Title and Description    
    var objTitleDiv = document.getElementById('TitleDiv_' + moduleId);
    var objDescriptionDiv = document.getElementById('DescriptionDiv_' + moduleId);
    var objSourceTitle = document.getElementById('thumbTitle_' + moduleId + '_' + thumbIndex);
    var objSourceDescription = document.getElementById('thumbDesc_' + moduleId + '_' + thumbIndex);    

    objTitleDiv.innerHTML = objSourceTitle.innerHTML;
    objDescriptionDiv.innerHTML = objSourceDescription.innerHTML.replace(reg, "<br />");

    // Update the Image 1 of N span message
    var objImageInfo = document.getElementById('imageInfo_' + moduleId );
    var objGalleryItemCount = document.getElementById('galleryItemCount_' + moduleId );

    objImageInfo.innerHTML = 'Image ' + (thumbIndex + 1) + ' of ' + objGalleryItemCount.value;

    // Update the link
    var objSourceLink = document.getElementById('thumbLink_'+ moduleId + '_' + thumbIndex );
    var objTargetLink = document.getElementById('thumbLink_'+ moduleId);
    var objLinkDiv = document.getElementById('LinkDiv_'+ moduleId);
    
    if ( objSourceLink.innerHTML == '' )
        objLinkDiv.style.display = 'none';
    else
        objLinkDiv.style.display = 'block';

    objTargetLink.href = objSourceLink.href;
    objTargetLink.innerHTML = objSourceLink.innerHTML;
    objTargetLink.target = objSourceLink.target;
}

function HTMLGalleryResetLastThumbnail( moduleId, thumbIndex)
{
    // Get Information about the last click
    var objGallerySelectedIndexHiddenField = document.getElementById('gallerySelectedIndex_' + moduleId);
    var objLastThumbNailClicked = document.getElementById('thumbImg_' + moduleId + '_' + objGallerySelectedIndexHiddenField.value);

    // Reset the appearance so long as the user hasn't clicked the same one twice
    if ( objGallerySelectedIndexHiddenField.value != thumbIndex )
        changeOpac(45, objLastThumbNailClicked.id);
}

function HTMLGallerySetPreviousButton( moduleId, thumbIndex )
{
    var objGalleryPreviousImage = document.getElementById('prevImg_' + moduleId ); 
    var objGalleryPreviousLink = document.getElementById('prevLink_' + moduleId ); 

    if ( thumbIndex > 0 )
    {
        changeOpac(100,objGalleryPreviousImage.id);
        objGalleryPreviousLink.style.color = '#4068a8';
    }
    else  // Disable the Previous button if the first thumbnail is selected
    {
        changeOpac(20, objGalleryPreviousImage.id);
        objGalleryPreviousLink.style.color = '#d9e1ee';
    }
}

function HTMLGallerySetNextButton( moduleId, thumbIndex )
{
    var objGalleryItemCount = document.getElementById('galleryItemCount_' + moduleId );
    var objGalleryNextImage = document.getElementById('nextImg_' + moduleId );
    var objGalleryNextLink = document.getElementById('nextLink_' + moduleId );

    if ( thumbIndex < objGalleryItemCount.value - 1)
    {
        changeOpac(100,objGalleryNextImage.id);
        objGalleryNextLink.style.color = '#4068a8';
    }
    else // Disable the NEXT Image if the last thumbnail is selected
    {
        changeOpac(20,objGalleryNextImage.id);
        objGalleryNextLink.style.color = '#d9e1ee';
    }
}

function HTMLGalleryThumbnailClick( source, moduleId, index )
{
    HTMLGalleryResetLastThumbnail( moduleId, index);
    HTMLGallerySetMainImage( moduleId, index );
    HTMLGallerySetSponsorImage( moduleId, index );
    HTMLGalleryCopyText( moduleId, index);
    HTMLGallerySetPreviousButton( moduleId, index );
    HTMLGallerySetNextButton( moduleId, index );
    HTMLGallerySetActiveThumbnail(source.id, moduleId, index);   // Execute last as this stores the new index
} 

function HTMLGalleryShowImageAndRefresh(moduleId, imageIndex)
{
	var scrollPosition = GetScrollbarPosition();
	var thumbScroll = document.getElementById("thumbViewDiv_" + moduleId);
	var thumbScrollPosition;
	var newQueryString;
	
	//	Determine the thumb scroll position depending on orientation of gallery
	if(HTMLGalleryIsPortrait(moduleId))
		thumbScrollPosition = thumbScroll.scrollTop;
	else
		thumbScrollPosition = thumbScroll.scrollLeft;
	
	//	We need to reload the page so that the adverts get refreshed.
	//	We'll pass on the querystring the image we need to show when the page has reloaded
	
	newQueryString = AddToQueryString(window.location.search, "ModuleId", moduleId);
	newQueryString = AddToQueryString(newQueryString, "ImageIndex", imageIndex);
	newQueryString = AddToQueryString(newQueryString, "XPos", scrollPosition[0]);
	newQueryString = AddToQueryString(newQueryString, "YPos", scrollPosition[1]);
	newQueryString = AddToQueryString(newQueryString, "ThumbScrollPos", thumbScrollPosition);

	window.location.href = window.location.pathname + newQueryString;
}

function AddToQueryString(queryString, key, value)
{
	var keyIndex;
	var queryStringLower;
	var keyLower;
	var nextKeyIndex
	var newQueryString;
	
	queryStringLower = queryString.toLowerCase();
	keyLower = key.toLowerCase();
	
	keyIndex = queryStringLower.indexOf(keyLower + "=");
	
	if(keyIndex == -1)
	{
		//	The key is not in the querystring so just add it onto the end
		if(queryString.length == 0)
			newQueryString = "?" + key + "=" + value;
		else
			newQueryString = queryString + "&" + key + "=" + value;
	}
	else
	{
		//	Construct the querystring before the key value pair
		newQueryString = queryString.substring(0, keyIndex) + key + "=" + value;
		
		//	Now construct the querystring after the key value pair
		nextKeyIndex = queryString.indexOf("&", keyIndex);
		
		if(nextKeyIndex != -1)
			newQueryString += queryString.substring(nextKeyIndex, queryString.length)
	}
	
	//alert("Old: " + queryString + "\nNew: " + newQueryString);
	return newQueryString;
}

//
//	Loads the image and it's related pieces (title, description etc)	
//
function HTMLGalleryLoadImage(moduleId)
{
	var imageIndex;
	var mainImageBox;
	var thumbScroll;
	
	mainImageBox = document.getElementById('mainImg_' + moduleId);
	imageIndex = getURLParam("ImageIndex");
	
	//	load the 1st image if not defined in the querystring
	if(imageIndex && imageIndex.length > 0)
		imageIndex = parseInt(imageIndex);
	else
		imageIndex = 0;
	
	if(mainImageBox)
	{
		HTMLGalleryResetLastThumbnail(moduleId, imageIndex);
		HTMLGallerySetMainImage(moduleId, imageIndex);
		HTMLGallerySetSponsorImage(moduleId, imageIndex);
		HTMLGalleryCopyText(moduleId, imageIndex);
		HTMLGallerySetPreviousButton(moduleId, imageIndex);
		HTMLGallerySetNextButton(moduleId, imageIndex);
		HTMLGallerySetActiveThumbnail('thumbImg_' + moduleId + '_' + imageIndex, moduleId, imageIndex);
		
		try
		{
			if(getURLParam("XPos"))
			{
				//	Move to the original scrollbar position and the thumb scroll
				window.scrollTo(getURLParam("XPos"), getURLParam("YPos"));
				thumbScroll = document.getElementById("thumbViewDiv_" + moduleId);
				
				//	Determine the thumb scroll position depending on orientation of gallery
				if(HTMLGalleryIsPortrait(moduleId))
					thumbScroll.scrollTop = getURLParam("ThumbScrollPos");
				else
					thumbScroll.scrollLeft = getURLParam("ThumbScrollPos");
			}
		}
		catch(e){}
	}

}

function GetScrollbarPosition()
{
    var x = 0;
    var y = 0;

    if(typeof(window.pageYOffset) == 'number')
    {
        // Netscape
        x = window.pageXOffset;
        y = window.pageYOffset;
    }
    else if(document.body && (document.body.scrollLeft || document.body.scrollTop))
    {
        // DOM
        x = document.body.scrollLeft;
        y = document.body.scrollTop;
    }
    else if(document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop))
    {
        // IE6 standards compliant mode
        x = document.documentElement.scrollLeft;
        y = document.documentElement.scrollTop;
    }
    return [x, y];
}

function HTMLGalleryThumbnailOnMouseOver( source )
{
    changeOpac(100, source.id);
    source.style.cursor = 'hand';
}

function HTMLGalleryThumbnailOnMouseOut( source, moduleId, index )
{
    var objSelectedIndex = document.getElementById('gallerySelectedIndex_' + moduleId);

    if ( objSelectedIndex.value != index )
    {
        changeOpac(45, source.id);
        source.style.cursor = 'default';   
    }
}

var GallerySmoothTimer;

function HTMLGalleryScrollLeft(source, moduleId)
{
    if ( HTMLGalleryItemScrollAmount(moduleId) > 0 )
    {
        // Enable the right arrow
        var objThumbRightArrow = document.getElementById('thumbRightImg_' + moduleId );
        changeOpac(100,objThumbRightArrow.id); 
        objThumbRightArrow.style.cursor = 'hand';

        var intervalParam = "document.getElementById('thumbViewDiv_" + moduleId + "').scrollLeft -= 2";
        GallerySmoothTimer = setInterval(intervalParam, 15);
    }
}

function HTMLGalleryScrollRight(source, moduleId )
{  
    if ( HTMLGalleryItemScrollAmount(moduleId) > 0 )
    {
        // Enable the left arrow
        var objThumbLeftArrow = document.getElementById('thumbLeftImg_' + moduleId );
        changeOpac(100,objThumbLeftArrow.id); 
        objThumbLeftArrow.style.cursor = 'hand';

        var intervalParam = "document.getElementById('thumbViewDiv_" + moduleId + "').scrollLeft += 2";
        GallerySmoothTimer = setInterval(intervalParam, 15);
    }
}

function HTMLGalleryStopLeftScroll( source, moduleId)
{
    clearInterval(GallerySmoothTimer);

    if ( document.getElementById('thumbViewDiv_' + moduleId ).scrollLeft == 0 ) 
    {
        changeOpac(20, source.id);
        source.style.cursor = 'default';   
    }
}

function HTMLGalleryStopRightScroll( source, moduleId )
{
    clearInterval(GallerySmoothTimer);
     
    if ( document.getElementById('thumbViewDiv_' + moduleId ).scrollLeft == HTMLGalleryItemScrollAmount(moduleId)  )
    {
        changeOpac(20, source.id);
        source.style.cursor = 'default';   
    }
} 

function HTMLGalleryScrollUp( source, moduleId )
{
    if ( HTMLGalleryItemScrollAmount(moduleId) > 0 )
    {
        // Enable the Down arrow
        var objThumbDownArrow = document.getElementById('thumbDownImg_' + moduleId );
        changeOpac(100,objThumbDownArrow.id); 
        objThumbDownArrow.style.cursor = 'hand';

        var intervalParam = "document.getElementById('thumbViewDiv_" + moduleId + "').scrollTop -= 2";
        GallerySmoothTimer = setInterval(intervalParam, 15);
    }
}

function HTMLGalleryScrollDown( source, moduleId )
{
   if ( HTMLGalleryItemScrollAmount(moduleId) > 0 )
    {
        // Enable the Up arrow
        var objThumbUpArrow = document.getElementById('thumbUpImg_' + moduleId );
        changeOpac(100,objThumbUpArrow.id); 
        objThumbUpArrow.style.cursor = 'hand';

        var intervalParam = "document.getElementById('thumbViewDiv_" + moduleId + "').scrollTop += 2";
        GallerySmoothTimer = setInterval(intervalParam, 15);
    }
}

function HTMLGalleryStopUpScroll( source, moduleId)
{
    clearInterval(GallerySmoothTimer);

    if ( document.getElementById('thumbViewDiv_' + moduleId ).scrollTop == 0 ) 
    {
        changeOpac(20, source.id);
        source.style.cursor = 'default';   
    }
}

function HTMLGalleryStopDownScroll( source, moduleId )
{
    clearInterval(GallerySmoothTimer);
     
    if ( document.getElementById('thumbViewDiv_' + moduleId ).scrollTop == HTMLGalleryItemScrollAmount(moduleId)  )
    {
        changeOpac(20, source.id);
        source.style.cursor = 'default';   
    }
} 

function HTMLGalleryNextItem( moduleId )
{
    // Get Information about the last click
    var objGallerySelectedIndexHiddenField = document.getElementById('gallerySelectedIndex_' + moduleId);
    var currentIndex = objGallerySelectedIndexHiddenField.value;
    var objGalleryItemCount = document.getElementById('galleryItemCount_' + moduleId );

    // Check if last item
    if ( currentIndex != objGalleryItemCount.value - 1 )
    {
        currentIndex++;
        HTMLGalleryFindItem( moduleId, currentIndex );
    }        
}

function HTMLGalleryPreviousItem( moduleId )
{
    // Get Information about the last click
    var objGallerySelectedIndexHiddenField = document.getElementById('gallerySelectedIndex_' + moduleId);
    var currentIndex = objGallerySelectedIndexHiddenField.value;

    // Check if first item
    if ( currentIndex != 0 )
    {
        currentIndex--;
        HTMLGalleryFindItem( moduleId, currentIndex );
    }
}

function HTMLGalleryItemScrollAmount( moduleId )
{
    // The amount the slider can scroll is the difference in width 
    // between the viewable div and the container div
    var gClassName = document.getElementById('HTMLGallery_' + moduleId).className.toString();
    
    if ( gClassName == 'module Portrait-4col m4col')
    {
        var viewHeight = parseInt(document.getElementById('thumbViewDiv_' + moduleId).style.height.replace('px',''));
        var containerHeight = parseInt(document.getElementById('thumbContainerDiv_' + moduleId).style.height.replace('px',''));

        if ( containerHeight > viewHeight )
            return containerHeight - viewHeight;
        else
            return 0;
    }
    else
    {
        var viewWidth = parseInt(document.getElementById('thumbViewDiv_' + moduleId).style.width.replace('px',''));
        var containerWidth = parseInt(document.getElementById('thumbContainerDiv_' + moduleId).style.width.replace('px',''));

        if ( containerWidth > viewWidth )
            return containerWidth - viewWidth;
        else
            return 0;
    }
}

function HTMLGalleryFindItem( moduleId, itemIndex )
{
    var itemScrollIndex = document.getElementById('galleryScrollIndexes_' + moduleId).value.split('|')[itemIndex];
    var gClassName = document.getElementById('HTMLGallery_' + moduleId).className.toString();
    
    if ( gClassName == 'module Portrait-4col m4col')
    {
        if ( itemScrollIndex > document.getElementById('thumbViewDiv_' + moduleId).scrollTop )
            scrollDivDown('thumbViewDiv_' + moduleId, itemScrollIndex);
        else
            scrollDivUp('thumbViewDiv_' + moduleId, itemScrollIndex);
    }
    else
    {
        if ( itemScrollIndex > document.getElementById('thumbViewDiv_' + moduleId).scrollLeft )
            scrollDivRight('thumbViewDiv_' + moduleId, itemScrollIndex);
        else
            scrollDivLeft('thumbViewDiv_' + moduleId, itemScrollIndex);
    }   
    
    HTMLGalleryShowImageAndRefresh(moduleId, itemIndex);
}

function HTMLGalleryIsPortrait(moduleId)
{
	//	This is rubbish so could do with re-working, but is currently how it does it.
    var className = document.getElementById('HTMLGallery_' + moduleId).className.toString();
    
    return (className == 'module Portrait-4col m4col');
}

function scrollDivRight( viewDiv , scrollIndex )
{ 
    while( document.getElementById(viewDiv).scrollLeft < scrollIndex )
    {
        if ( document.getElementById(viewDiv).scrollLeft + 8 > scrollIndex )
            document.getElementById(viewDiv).scrollLeft = scrollIndex;
        else
            document.getElementById(viewDiv).scrollLeft += 8;
        var GalleryClickTimer=setTimeout("scrollDivRight('" + viewDiv + "')",1);
    }
} 

function scrollDivLeft( viewDiv , scrollIndex)
{ 
    while( document.getElementById(viewDiv).scrollLeft > scrollIndex )
    {
        if ( document.getElementById(viewDiv).scrollLeft - 8 < scrollIndex )
            document.getElementById(viewDiv).scrollLeft = scrollIndex;
        else
            document.getElementById(viewDiv).scrollLeft -= 8;
        var GalleryClickTimer=setTimeout("scrollDivLeft('" + viewDiv + "')",1);
    }
} 

function scrollDivUp( viewDiv , scrollIndex)
{ 
    while( document.getElementById(viewDiv).scrollTop > scrollIndex )
    {
        if ( document.getElementById(viewDiv).scrollTop - 8 < scrollIndex )
            document.getElementById(viewDiv).scrollTop = scrollIndex;
        else
            document.getElementById(viewDiv).scrollTop -= 8;
        var GalleryClickTimer=setTimeout("scrollDivUp('" + viewDiv + "')",1);
    }
} 

function scrollDivDown( viewDiv , scrollIndex )
{ 
    while( document.getElementById(viewDiv).scrollTop < scrollIndex )
    {
        if ( document.getElementById(viewDiv).scrollTop + 8 > scrollIndex )
            document.getElementById(viewDiv).scrollTop = scrollIndex;
        else
            document.getElementById(viewDiv).scrollTop += 8;
        var GalleryClickTimer=setTimeout("scrollDivDown('" + viewDiv + "')",1);
    }
} 

//********************************************************//
//END: Document width and supporting (+reuseable) functions
//********************************************************//

//********************************************************//
// CatchUp js
//********************************************************//

function GetCatchUpDataHandlerString(catchUpModuleID, catchUpViewType, columnWidth)
{
    var _catchUpModuleID = catchUpModuleID;
    
    return GetCatchUpDataHandlerRequest(ShowCatchUpData, catchUpModuleID, catchUpViewType, columnWidth);
}

function SetCatchUpModuleID(moduleID)
{
    //var _catchUpModuleID = moduleID;
}

function GetCatchUpModuleID(webServiceResult)
{
    //HACK: this rubbish to get the moduleID
    moduleIdRegEx = new RegExp("SetCatchUpModuleID.[0-9]*");
    moduleIdRegExMatch = moduleIdRegEx.exec(webServiceResult)[0].toString();

    moduleId = moduleIdRegExMatch.split("(")[1];

    _catchUpModuleID = moduleId;
    return _catchUpModuleID;
}

function ShowCatchUpData(webServiceResult)
{
    catchUpElement = document.getElementById('CatchUpDataDiv_' + GetCatchUpModuleID(webServiceResult));
    catchUpElement.innerHTML = webServiceResult;
    
    //  Process the link elements so they get setup to play videos correctly when
    //  they call Itv.Video.PlayVodcrid()
    //Itv.Video.RenderVideoLinks(watchNowElement);
    //this is a bit of a hack to work out what page is being served. 
    //catchup video player
    if (document.getElementById('cu-2-0-VideoID')){Itv.Video.SetUpCatchUp()}
    //results list
    if (document.getElementById('secOne-cu-1-0')&&(Itv.ClientCaps.ISIE)){
       //move the footer onload, so footer exists.
       addEvent(window,'load',moveFooter);
        
    }
    
}

function GetCatchUpDataHandlerRequest(callback, catchUpModuleID, catchUpViewType, columnWidth) 
{

    filter = getURLParam('Filter');

    parentUrl = "http:\/\/" + window.location.host;
    //TODO: Pass and get filter and column width
    url = parentUrl + '/_app/Dynamic/CatchUpData.ashx'
          + '?ViewType=' + catchUpViewType 
          + '&Filter=' + filter 
          + '&moduleID=' + catchUpModuleID 
          + '&columnWidth=' + columnWidth;
    
    return MakeWebServiceGETRequest(url, callback, false);
}

function moveFooter()
{
    try
	{
		var catchUpContentDiv = document.getElementById("placeholder2");
		var catchUpSideDiv = document.getElementById("secFour-cu-1-0");
		var contentHeight=catchUpContentDiv.offsetHeight>catchUpSideDiv.offsetHeight?catchUpContentDiv.offsetHeight:catchUpSideDiv.offsetHeight
		document.getElementById('itv-footer').style.marginTop = contentHeight-480;
        
	}
    catch(ex){}
    
}

function ChangeCurrentUrlFilterParam(newFilterNameAndValue)
{
//    if(window.location.search.indexOf("?")==-1)
//    {
        newFilterNameAndValue = "?" + newFilterNameAndValue;
//    }
    //Maintain existing queryString (after which, it could be overloaded to take in any parameter name)
//    filter = getURLParam('Filter');
//    if(filter!='')
//    {
//    
//    }
//    else
//    {
//        filter = getURLParam('filter');
//        if(filter!='')
//        {
//    }
//    newWindowLocationSearch = window.location.search.replace('Filter',''
    queryString = newFilterNameAndValue;
    window.location = window.location.protocol + "//" +window.location.host +window.location.pathname + queryString;
}


function StartScroll(objSpan)
{
	
    clearTimeout(ScrollTimerId);
    if((tmp = document.getElementById("spanid")))
    {
        tmp.id = "";
        
    }
    
    if(objSpan.innerHTML.length > 18)
    {
        if(!objSpan.HasScrolled)
        {
            objSpan.innerHTML += ' - '
        }
        
        objSpan.id = "spanid";
        objSpan.HasScrolled = true;
        scrollText(objSpan.id);
    }
    
}

function StopScroll()
{
    
    clearTimeout(ScrollTimerId);
}

var ScrollTimerId = 0;

function scrollText(spanId)
{
	var objSpan = document.getElementById(spanId);
	var message = objSpan.innerHTML;
	var speed = 175;
	var charactersToMove = 1;
	
	//	IE is helpfully removing all spaces when we use innerHTML, so use innerText for IE.
	if(document.all)
		message = objSpan.innerText;
	else
		message = objSpan.innerHTML;
	
	if(message.length > 0)
	{
		//	if we have html encoded stuff in the string (just deals with '&amp;' for now) then we need
		//	to move these as a whole from the front to the back of the string.
		if(message.length > 4 && message.substr(0, 5) == "&amp;")
		{
			charactersToMove = 5;
		}
		
		//	Add the characters from the beginning to the end of the string
		message += message.substr(0, charactersToMove);
		//	Strip out those characters from the beginning of the string
		message = message.substr(charactersToMove, message.length);
		
		if(document.all)
			objSpan.innerText = message;
		else
			objSpan.innerHTML = message;

		ScrollTimerId = setTimeout("scrollText('" + spanId + "')", speed);
	}
}

//********************************************************//
// End CatchUp js
//********************************************************//

//********************************************************//
// Bingo
//********************************************************//

function showMyWinsLink()
{
	var link = document.getElementById("bingoMyWinsLink");
	var login = document.getElementById("bingoMyWinsLogin");
	
	if (link != "undefined" && login != "undefined" && checkcookie('.CommunityServer'))
	{
		link.style.display='block';
		login.style.display='none';
	}
	else
	{
		link.style.display='none';
		login.style.display='block';
	}
	
	//Must add this to the page:
	//addEvent(window,'load',showMyWinsLink);
}

function changeBingoNav()
{
	var link = document.getElementById("bingoRegisterLink");
	
	if (link != "undefined" && checkcookie('.CommunityServer'))
	{
		link.innerHTML = "My Details";
	}
	else
	{
		link.innerHTML = "Register";
	}
	
	//Must add this to the page:
	//addEvent(window,'load',showMyWinsLink);
}

function launchBingoGetCards(href)
{
    try {
	    var getCards = new popUp(href, 1000, 700, 'getcards', 1, 1, 0, 0, 0, 0, 20, 100);
	    var itvBingo = new popUp('/_app/dynamic/bingonightlive/ItvBingoPopunder.aspx', 320, 464, 'itvbingo_under', 0, 0, 0, 0, 0, 0, 200, 100);
    	
	    getCards.win.focus();
	} catch(e) {
	}
	
	return false;
}

function launchItvBingo(href)
{
	popUp(href,1000,700,'itvbingo',1,1,0,0,0,0,20,100);
	return false;
}

function launchBingoTerms(href)
{
	popUp(href,800,700,'',1,1,0,0,0,0,20,100);
	return false;
}

function launchBingoMyWins(href)
{
	popUp(href,650,770,'',1,1,0,0,0,0,20,100);
	return false;
}

var bingoLobbyWindow = null;

function launchBingo(){
	
	if(bingoLobbyWindow != null && !bingoLobbyWindow.closed) {
		bingoLobbyWindow.focus();
		return;
	}
	var dateObj = new Date();
	var mytitle = "FlashClient" + dateObj.getDate();//getDateString();
	//outerheight=570, outerwidth=788. deltaHeight:33, deltaWidth:7
	if(navigator.appName && navigator.appName.indexOf("Netscape") == -1 && navigator.appVersion.indexOf("Netscape") != -1){
		bingoLobbyWindow = window.open("http://router.itvbingo.itv.com/itvbingo/MainApp.html?lid=en_US&wm=",mytitle,"fullscreen=yes toolbar=no,status=no,height=950,width=900,resizable=yes");
	}else{
		bingoLobbyWindow = window.open("http://router.itvbingo.itv.com/itvbingo/MainApp.html?lid=en_US&wm=",mytitle,"toolbar=no,status=no,height="+(screen.height-30)+",width="+(screen.width-5)+",resizable=yes");
	}
	
}

function refreshLoginPanel()
{
	if ( ! document.getElementsByTagName ) return;
	
	var placeholder = document.getElementById("placeholder10");
	
	if (placeholder != null)
	{
		var iframes = placeholder.getElementsByTagName("iframe");
	
		if (iframes != null && iframes[0] != null)
		{
		    // HACK: set to about:blank so that IE6 refreshes the login panel correctly
		    iframes[0].src = "about:blank";
			iframes[0].src = "/_app/Dynamic/BingoNightLive/Login.aspx";
		}
    }
}

//********************************************************//
// End Bingo
//********************************************************//

//Calls ASPX Page so can get ClientIP 
function GetClientIP() 
{
    var clientResponse = GetAjaxResponse("_app/Dynamic/WhatIsMyIP.aspx");
    clientResponse = clientResponse.split("<", 1);
    return clientResponse;     
}

//RS
function GetRevSci()
    {
    	//var theVal = Get_Cookie("rsi_segs");
    	var theVal = GetRevenueScienceString();
		var adextra = document.getElementById("advertextra");
		if(null != adextra)
		{
		    adextra.value += "&RS="+ theVal;
		}
		
    }

DomLoaded.load ( GetRevSci ); 

//This is for when picks is set to true and there is a vodcrid in the url
function SilverlightQueryStringVodrcridAutoplay()
{
      //checks at least version 2 is installed
	  if(Silverlight.isInstalled('2.0.0.0'))
      {
	    	var query = location.search;
		    if(query.indexOf("vodcrid") > 0)
		    {
		        var retrievedVodcrid = query.split("=",2);
		        retrievedVodcrid = retrievedVodcrid[1];
		        retrievedVodcrid = retrievedVodcrid.split("&",1);
	            finalVodcrid = '' + retrievedVodcrid;
	            InitialisePlayer(document.getElementById('ace2cf60-e503-4711-9900-453213c079a4'), finalVodcrid, null, true, null, false);
            }
      }
}

