// Get today's date
var today  = new Date();
    today  = today.valueOf();  // Convert today's date to milliseconds from the epoch
    today += 86400000;         // Add one day to expiry date, in milliseconds

var expires = new Date(today); // Convert expiry back to Date() format from milliseconds

var affiliateId = 0;

// Check if the user already has a Time Page Cookie (TPC)
function detectTPC(pCookieName) {
	var cookieName = "";

	// Get name of cookie to detect or look for "orangeTPC" by default
	if (!pCookieName) {
		cookieName = "orangeTPC";
	} else {
		cookieName = pCookieName;
	}

	debug("detectTPC: cookieName = " + cookieName);

	// Get current cookies
    var cookieStr = document.cookie.toString();

    if (cookieStr.indexOf(cookieName) != -1) {
        debug("detectTPC: found existing cookie value: [" + getTPCValue(cookieName) + "]");
        return true;
    }
    else {
        debug("detectTPC: no existing " + cookieName + " cookie");
        return false;
    }
}

// Get the orangeTPC parameter value
function getTPCValue(pCookieName) {
	var cookieName = "";

	// Get name of cookie to find or look for "orangeTPC" by default
	if (!pCookieName) {
		cookieName = "orangeTPC";
	} else {
		cookieName = pCookieName;
	}

	debug("getTPCValue: cookieName = " + cookieName);
	
    var cookieValue = "";
    var cookieStr   = document.cookie;

    // Split cookie string on '; '. This separates the individual cookies
    // in the document.cookie string into elements of cookiesArray
    var cookiesArray = cookieStr.split("; ");

    debug("getTPCValue: cookiesArray.length = " + cookiesArray.length);

    // Pick out the value associated with orangeTPC
    for (i = 0; i < cookiesArray.length; i++) {
        if (cookiesArray[i].indexOf(cookieName) != -1) {
            cookieValue = cookiesArray[i].substr(cookieName.length+1);
            break;
        }
    }

    debug("getTPCValue: cookieValue = " + cookieValue);
    return cookieValue;
}

// Set a orangeTPC for the user
function setTPC(pQstrValue, pCookieName) {
	var cookieName = "";

	// Get name of cookie to set or set "orangeTPC" by default
	if (!pCookieName) {
		cookieName = "orangeTPC";
	} else {
		cookieName = pCookieName;
	}

	debug("setTPC: cookieName = " + cookieName);

    var newCookieStr = "" + cookieName + "=" + pQstrValue + ";expires="+expires.toGMTString()+";domain=.orange.co.uk;path=/";
    document.cookie = newCookieStr;
}

// Split the query string up into it's NVPairs and return an array of these NVPairs
function getQueryStringNVPairs() {
    var qStr = document.location.search.substring(1);
    var qs_pairs = qStr.split("&");

    debug("getQueryStringNVPairs:\n\nqStr = [" + qStr + "]\nqs_pairs.length = " + qs_pairs.length);

    return qs_pairs;
}

function queryStringDetect() {
    var hasExistingTPC = detectTPC();
	var hasExistingCTA = detectTPC("fromaffiliate");
    var qStrPairs      = new Array();
    var cdSrcValue     = "";

    if (!hasExistingTPC) {
        qStrPairs = getQueryStringNVPairs();

        for (i = 0; i < qStrPairs.length; i++) {
            idx       = qStrPairs[i].indexOf("=");
            itemName  = qStrPairs[i].substring(0, idx);
            itemValue = qStrPairs[i].substring(idx + 1, qStrPairs[i].length);

		// Detect and set TPC using "cd_source" querystring value
            if (itemName=="cd_source") {
                cdSrcValue = itemValue;
                debug("queryStringDetect: cdSrcValue = [" + cdSrcValue + "]");
            }
            if (cdSrcValue != "") { setTPC(cdSrcValue); }
		}
	}

	if (!hasExistingCTA) {
        qStrPairs = getQueryStringNVPairs();

        for (i = 0; i < qStrPairs.length; i++) {
            idx       = qStrPairs[i].indexOf("=");
            itemName  = qStrPairs[i].substring(0, idx);
            itemValue = qStrPairs[i].substring(idx + 1, qStrPairs[i].length);		

		// Detect and set call-to-action graphic (top-right of page header) using "fromaffiliate" querystring value
			if (itemName=="fromaffiliate") {
				affiliateId = itemValue;
				setTPC(affiliateId,"fromaffiliate");
			}
		}
    } else {
		affiliateId = getTPCValue("fromaffiliate");
	}

	// Set the phone number in the call-to-action
	debug("queryStringDetect: affiliateId = [" + affiliateId + "]");
	setAffiliateCallToAction(affiliateId);

}

function goToPAYGReg(pTrackingStr) {
    var url        = "https://www.orange.co.uk/signup/noties/";
    var cdSrcValue = getTPCValue();

	// If redirected_from variable is in the querystring to this function call, tell this function call to ping the user
	// to the act code entry page of PAYG reg, not the regular online start page. 'redirected_from' identifies a sign up
	// as coming from a CD.
	if (pTrackingStr.indexOf("redirected_from") != -1) {
		url += "nt10.cfm";
	}
	else {
		url += "nt20.cfm";
	}

    debug("goToPAYGReg: cdSrcValue = " + cdSrcValue);

    // Append any cd_source querystring stored in the orangeTPC to the URL
    if (cdSrcValue != "") { url = url + "?cd_source=" + cdSrcValue; }

    // Append any querystring values passed as a parameter to the URL, checking
    // first to see if we are dealing with pTrackingStr as ADDITIONAL parameters
    // on the querystring (so requires '&' separator), or as the ONLY parameter
    // (requiring '?' separator)
    if (pTrackingStr != "") {
        if (cdSrcValue != "") { url = url + "&" + pTrackingStr; }
        else                  { url = url + "?" + pTrackingStr; }
    }

    debug("goToPAYGReg(): url = " + url);
    document.location.href = url;
}

function goToAnyTimeReg(pTrackingStr) {
    var url = "https://www.orange.co.uk/signup/anytime/";
    var cdSrcValue = getTPCValue();

	// 'redirected_from' identifies a sign up as coming from a CD, so set target URL
	// accordingly.
	if (pTrackingStr.indexOf("redirected_from") != -1) {
		url += "at10.cfm";
	}
	else {
		url += "at20.cfm";
	}

    debug("goToAnyTimeReg: cdSrcValue = " + cdSrcValue);

    // Append any cd_source querystring stored in the orangeTPC to the URL
    if (cdSrcValue != "") { url = url + "?cd_source=" + cdSrcValue; }

    // Append any querystring values passed as a parameter to the URL, checking
    // first to see if we are dealing with pTrackingStr as ADDITIONAL parameters
    // on the querystring (so requires '&' separator), or as the ONLY parameter
    // (requiring '?' separator)
    if (pTrackingStr != "") {
        if (cdSrcValue != "") { url = url + "&" + pTrackingStr; }
        else                  { url = url + "?" + pTrackingStr; }
    }

    debug("goToAnyTimeReg(): url = " + url);
    document.location.href = url;
}

function goToBBReg(pTrackingStr) {
    var url        = "/time/broadbandaccess/online.htm";
    var cdSrcValue = getTPCValue();

    debug("goToBBReg: cdSrcValue = " + cdSrcValue);

    // Append any cd_source querystring stored in the orangeTPC to the URL. Switch
    // the target URL only if we are handling a cd_source parameter in the querystring
    // since we need to redirect users in this instance to the NOACT.do flow of
    // BB Reg.
    if (cdSrcValue != "") { 
        url = "/time/broadbandaccess/cd.htm";
        url = url + "?cd_source=" + cdSrcValue;
    }

    // Append any querystring values passed as a parameter to the URL, checking
    // first to see if we are dealing with pTrackingStr as ADDITIONAL parameters
    // on the querystring (so requires '&' separator), or as the ONLY parameter
    // (requiring '?' separator)
    if (pTrackingStr != "") {
        if (cdSrcValue != "") { url = url + "&" + pTrackingStr; }
        else                  { url = url + "?" + pTrackingStr; }
    }

    debug("goToBBReg(): url = " + url);
    document.location.href = url;
}

function goToBBRegCdAct(pTrackingStr) {
    var url        = "/time/broadbandaccess/cdact.htm";
    var cdSrcValue = getTPCValue();

    // Append any cd_source querystring stored in the orangeTPC to the URL
    if (cdSrcValue != "") { url = url + "?cd_source=" + cdSrcValue; }

    debug("goToBBRegCdAct: cdSrcValue = " + cdSrcValue);

    // Append any querystring values passed as a parameter to the URL, checking
    // first to see if we are dealing with pTrackingStr as ADDITIONAL parameters
    // on the querystring (so requires '&' separator), or as the ONLY parameter
    // (requiring '?' separator)
    if (pTrackingStr != "") {
        if (cdSrcValue != "") { url = url + "&" + pTrackingStr; }
        else                  { url = url + "?" + pTrackingStr; }
    }

    debug("goToBBRegCdAct(): url = " + url);
    document.location.href = url;
}

function goToBBRegCd(pTrackingStr) {
    var url        = "/time/broadbandaccess/cd.htm";
    var cdSrcValue = getTPCValue();

    // Append any cd_source querystring stored in the orangeTPC to the URL
    if (cdSrcValue != "") { url = url + "?cd_source=" + cdSrcValue; }

    debug("goToBBRegCd: cdSrcValue = " + cdSrcValue);

    // Append any querystring values passed as a parameter to the URL, checking
    // first to see if we are dealing with pTrackingStr as ADDITIONAL parameters
    // on the querystring (so requires '&' separator), or as the ONLY parameter
    // (requiring '?' separator)
    if (pTrackingStr != "") {
        if (cdSrcValue != "") { url = url + "&" + pTrackingStr; }
        else                  { url = url + "?" + pTrackingStr; }
    }

    debug("goToBBRegCd(): url = " + url);
    document.location.href = url;
}

// For Duplo - remembers which product was requested so that it can be reproduced in the mobile shop and goes to the splitter page

function writeHomeProductCookie(pProductChoice, pIsUnique, pIsLandingPage) {
	var URL = "";

	switch (pProductChoice) {
		case "starter":
		case "select":
		case "max":
			URL = "/offerinfo/cli_check.cfm";
			break;
		case "unique":
		case "ustarter":
		case "uselect": // For ImageCL
		case "umax":
			URL = "/offerinfo/cli_check.cfm";
			break;
		default:
	}

	if (pIsLandingPage) {
		URL += "?isLandingPage=" + pIsLandingPage;
	}

	var productCookieStr  = "homeProduct=" + pProductChoice + ";expires="+expires.toGMTString()+";domain=.orange.co.uk;path=/";
	var isUniqueCookieStr = "isUnique=" + pIsUnique + ";expires="+expires.toGMTString()+";domain=.orange.co.uk;path=/";

    document.cookie = productCookieStr;
	document.cookie = isUniqueCookieStr;
    document.location.href = URL;
}

// Function is used to set CD-signup context in Internet Shop pages, based on either the value of the cd_source
// querystring parameter provided on a page URL or the cd_source value contained in the orangeTPC cookie
function setCdContext() {
	var cdContextFlag = 0; // default to "false"
	var qStr          = document.location.search; // Capture any querystring provided
	var tpc           = getTPCValue(); // See if we have an existing orangeTPC available, and grab any cd_source value contained therein

	// Set CD-context flag; first see if a cd_source querystring value was provided on the URL; this overrides any
	// cd_source value contained in an orangeTPC
	if (qStr.indexOf("cd_source=") != -1) {
		cdContextFlag = 1;
	} else if (tpc != "") {
		// So no querystring was provided. Now see if we already have an orangeTPC available,
		// and if that contains a cd_source value
		cdContextFlag = 1;
	}

	return cdContextFlag;
}

function returnAffiliateCTANumber(pAffiliateId) {
	var ctaNumber = "0800 072 5563"; // Default Orange phone number to call (for non-affiliate traffic)

	switch (pAffiliateId) {
		case "1": // Networking Links BB Checker - www.broadbandchecker.co.uk
			ctaNumber = "0800 072 4224"; break;
		case "2": // BB.co.uk - www.broadband.co.uk
			ctaNumber = "0800 072 0739"; break;
		case "3": // UK Web Media - www.broadbandfinder.co.uk
			ctaNumber = "0800 072 2357"; break;
		case "4": // Formula Digital - www.top10-broadband.co.uk
			ctaNumber = "0800 072 4046"; break;
		case "5": // Web Offer Marketing - www.broadbandinternetuk.com
			ctaNumber = "0800 072 4136"; break;
		case "6": // Decision Tech - www.broadbandchoices.co.uk
			ctaNumber = "0800 072 4137"; break;
		case "7": // MoneySupermarket - www.moneysupermarket.com
			ctaNumber = "0800 072 4138"; break;
		case "8": // Top 10 Broadband - www.top10broadband.co.uk
			ctaNumber = "0800 072 4054"; break;
		case "9": // Money Supermarket - http://www.moneysupermarket.com
			ctaNumber = "0800 408 1887"; break;
		case "10": // UK Web Media - http://www.broadband-finder.co.uk
			ctaNumber = "0800 072 4209"; break;
		case "11": // Genie Venture - http://www.broadbandgenie.co.uk
			ctaNumber = "0800 294 7338"; break;
		case "12": // Networking Links - http://www.broadbandchecker.co.uk
			ctaNumber = "0800 294 7339"; break;
		case "13": // BB.co.uk - http://www.broadband.co.uk
			ctaNumber = "0800 294 7340"; break;
		case "14": // Web Offer Marketing Limited - http://www.broadbandinternetuk.com
			ctaNumber = "0800 316 3482"; break;
		case "15": // Decision Technologies Limited - http://www.broadbandchoices.co.uk
			ctaNumber = "0800 316 3483"; break;
		case "16": // Affili8 - http://www.broadband-store.net/mobile-broadband
			ctaNumber = "0800 316 3484"; break;
		case "17": // Black Snow - http://top10broadband.co.uk
			ctaNumber = "0800 408 1804"; break;
		case "18": // Formula Digital - http://www.top10-broadband.co.uk
			ctaNumber = "0800 408 1805"; break;
		case "19": // U-switch - http://www.uswitch.com/
			ctaNumber = "0800 408 1825"; break;
		case "20": // Google - www.google.co.uk
			ctaNumber = "0800 408 1806"; break;
		case "21": // Yahoo - www.yahoo.co.uk
			ctaNumber = "0800 408 1807"; break;
		case "22": // MSN - www.msn.co.uk
			ctaNumber = "0800 408 1809"; break;
		default:
	}
	return ctaNumber;
}

function setAffiliateCallToAction(pAffiliateId) {
	// Grab the correct affiliate call-to-action number
	var ctaNumber = returnAffiliateCTANumber(pAffiliateId);
	
	// Now reveal the correct affiliate using prototype and scriptaculous effects. Detect if the
	// affiliate ID is in the valid range (0..22). If not, force affiliate ID to zero and use the
	// default call-to-action number. Check ctaImg element exists before attempting any of this
	// to prevent script errors on pages that do not possess a ctaImg element (e.g. popups).
	if (document.getElementById("ctaImg")) {
		// Check pAaffiliateId is within the allowable range
		if (pAffiliateId < 0 || pAffiliateId > 22) {
			$('ctaImg').setAttribute('src','/images/shared/illustrations/buy_online_0.gif');		
		} else {
			$('ctaImg').setAttribute('src','/images/shared/illustrations/buy_online_'+pAffiliateId+'.gif');
		}
		// Set alt text for the affiliate image, accordingly
		$('ctaImg').setAttribute('alt','buy online or call '+ ctaNumber);

		// If in CD-signup mode, ID of header DIV where affiliate-link CTA should appear is "time_banner_landing"
		if (document.getElementById('time_banner')) {
			$('time_banner').appear();
		} else if (document.getElementById('time_banner_landing')) {
			$('time_banner_landing').appear();
		}
	}
}