
//------------------------------------------

// Ad call v3.0 # Andrew Gordon

//------------------------------------------

// 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 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 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;
}


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);
}



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){

	
    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 '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.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";
            
        }
        
    }
    
    
    
}

