//Server side rate regulator for calling the Iperceptions Invitation layer

function doIPerceptions() {
    //Select the ratio you would like to serve:  the rate is based on 1000 to give more granular results
    var ratio = 40;
	
	var area="",contentarea="",path;
	
	var env = location.hostname.split(".");
	switch(env[1]) {
		case "channel4":
			area = s.prop2;
			contentarea = s.prop4;
		break;
		case "e4":
			area = s.prop1;
			contentarea = s.prop2;
		break;	
		case "film4":
			area = s.prop2;
			contentarea = s.prop4;
		break;
		default:
		break;
	}

	area = encodeURIComponent(area);
	contentarea = encodeURIComponent(contentarea);

	//Iperceptions Cookie functions

	function CC(name,value,days) {if (days) { var expDate = new Date(); expDate.setTime(expDate.getTime()+(days*24*60*60*1000)); var expires = "; expires="+expDate.toUTCString(); }else var expires = ""; document.cookie = name+"="+value+expires+"; path=/";}

	function RC(NameOfCookie) {if (document.cookie.length > 0) {begin = document.cookie.indexOf(NameOfCookie+"=");if (begin != -1) {
		begin += NameOfCookie.length+1; end = document.cookie.indexOf(";", begin); if (end == -1) end = document.cookie.length;
		return unescape(document.cookie.substring(begin, end));}} return null;
	}

	function EC(name) { CC(name, "", -1); }
	

	if(env[0] == "int" || env[0] == "test" || env[0] == "stage") {
		// Dev
		path = "http://ipinvite.iperceptions.com/Invitations/Javascripts/ip_Layer_Invitation_743_dev.aspx?area="+area+"&contentarea="+contentarea;
	} else {
		// Prod
		path = "http://ipinvite.iperceptions.com/Invitations/Javascripts/ip_Layer_Invitation_743.aspx?area="+area+"&contentarea="+contentarea;
	}   

	//session cookie
	var sCN = "IPE_RG_743"; 
	var sCV = "IPE_RG_Session";
    var sCVR = RC(sCN);//session cookie value return
	//test cookie value return
	var tCVName="IPERCEPTIONS_TEST"; 
	var tCVVal="iPe_Test"; 
	var sCValRet; 
	//test if client supports cookies
	var tCVValRet;
	CC(tCVName,tCVVal,1);
	tCVValRet = RC(tCVName);                                     
	EC(tCVName);

    var randomNumber = Math.floor((Math.random() * 1000));
    try {
        if (randomNumber < ratio && tCVValRet !== null && sCVR === null ) {
            loadIPScript(path);
        }
		//set session cookie if doesn't exist
		if (sCVR == null) {CC(sCN, sCV);}
    } catch (err) { }
}
//loads the iperceptions script
function loadIPScript(path) {
    var head = document.getElementsByTagName("head")[0];
    script = document.createElement('script');
    script.type = "text/javascript";
    script.src = path;
    head.appendChild(script);
}
//call the Regulator function
doIPerceptions();
