// Array of parameter names that need to be persisted to cookie
var urlParamNamesArray = new Array();

// Set names
urlParamNamesArray[0] = "channel";
urlParamNamesArray[1] = "subchannel";

// Check if the page is secure and set flag
var isSecure = false;
var loc = new String(window.parent.document.location);
if (loc.indexOf("https://")!= -1) {
	isSecure = true;
}

// Set cookie expiration period (in days)
var cookieExpirationDays = 2;

// Retrieves URL parameter value
function getURLParamValue(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 getCookie(Name){ 
	var re=new RegExp(Name+"=[^;]+", "i");
	if (document.cookie.match(re)){ 
		return document.cookie.match(re)[0].split("=")[1];
	} else {
		return "";
	}
}

function setCookie(name, value, days){
	var expireDate = new Date();
	var expstring=expireDate.setDate(expireDate.getDate()+parseInt(days));
	var cookieValue = name+"="+value+"; expires="+expireDate.toGMTString()+"; path=/";
	if (isSecure) {
		cookieValue += "; secure";
	}
	document.cookie = cookieValue;
}

// Return true if at least one parameter exists; false otherwise
function doesAtLeastOneParamExist() {
	var paramExists = false;
	
	for ( var i=0, len=urlParamNamesArray.length; i<len; ++i ) {
		var cookieValue = getCookie(urlParamNamesArray[i]);
		if (cookieValue != "") {
			paramExists = true;
		}
	}
	return paramExists;
}

// Retrieve parameter values and save them in cookie
if (window.location.href.indexOf("?") > -1) {
	for ( var i=0, len=urlParamNamesArray.length; i<len; ++i ) {
		var cookieName = urlParamNamesArray[i];
		var cookieValue = getCookie(cookieName);
		var urlParamValue = getURLParamValue(cookieName);
		// Check if cookie with the same name as parameter in URL exists and its value is set
		if (cookieValue == "") {
			var paramValue = urlParamValue;
			setCookie(cookieName, paramValue, cookieExpirationDays);
		} else {
			// Parameter already exists. Check if value changed. If yes, then update it in cookie
			if (urlParamValue != cookieValue && getURLParamValue(cookieName) != '') {
				setCookie(cookieName, getURLParamValue(cookieName), cookieExpirationDays);
			}
		}
	}
}