// 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 setCookie(name, value, days){
	$.cookie(name, value, days);
}

// 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 = $.cookie(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 = $.cookie(cookieName);
		var urlParamValue = getURLParamValue(cookieName);
		//alert("CookieName is: " + cookieName + " | CookieValue is: " + cookieValue + " | urlParamValue is: " + urlParamValue);
		// Check if cookie with the same name as parameter in URL exists and its value is set
		if (cookieValue == "") {
			var paramValue = urlParamValue;
			//alert("Setting " + cookieName + " to value: " + paramValue);
			setCookie(cookieName, paramValue, cookieExpirationDays);
		} else {
			// Parameter already exists. Check if value changed. If yes, then update it in cookie
			if (urlParamValue != cookieValue && getURLParamValue(cookieName) != '') {
				//alert("Updating " + cookieName + " with value: " + getURLParamValue(cookieName));
				setCookie(cookieName, getURLParamValue(cookieName), cookieExpirationDays);
			}
		}
	}
}