function Set_Cookie( name, value, expires, path, domain, secure ) {
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );
	
	if ( expires ) {
		expires = expires * 1000 * 60 * 60 * 24;
		}
	var expires_date = new Date( today.getTime() + (expires) );
	
	document.cookie = name + "=" +escape( value ) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
	( ( path ) ? ";path=" + path : "" ) +
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
}

function Get_Cookie( check_name ) {
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f
	
	for ( i = 0; i < a_all_cookies.length; i++ ) {
		a_temp_cookie = a_all_cookies[i].split( '=' );
	
	
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
	
		if ( cookie_name == check_name ) {
			b_cookie_found = true;
			if ( a_temp_cookie.length > 1 ) {
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
				}
			return cookie_value;
			break;
			}
		a_temp_cookie = null;
		cookie_name = '';
		}
	if ( !b_cookie_found ) {
		return null;
		}
}


// this deletes the cookie when called
function Delete_Cookie( name, path, domain ) {
	if ( Get_Cookie( name ) ) document.cookie = name + "=" +
	( ( path ) ? ";path=" + path : "") +
	( ( domain ) ? ";domain=" + domain : "" ) +
	";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

//global vars for use later
var rstring = '';
var referrer = '';
var siteName = '';
var merchantID = '';

//randomizing code function for Priority Code in Footer
function randomString() {
	var chars = "ABCDEFGHIJKLMNOPQRSTUVWXTZ";
	var string_length = 2;
	for (var i=0; i<string_length; i++) {
		var rnum = Math.floor(Math.random() * chars.length);
		rstring += chars.substring(rnum,rnum+1);
		}	
}

//function to get a specific parameter for a passed in value.
function getParameter(paramName) {
	var searchString = window.location.search.substring(1),
	i, val, params = searchString.split("&");
	
	for (i=0;i<params.length;i++) {
		val = params[i].split("=");
		if (val[0] == paramName) {
			return unescape(val[1]);
		}
	}
	return null;
}

//spliting Google Analytics cookies
function _uGC(l,n,s) {
	if (!l || l=="" || !n || n=="" || !s || s=="") return "-";
	var i,i2,i3,c="-";
	i=l.indexOf(n);
	i3=n.indexOf("=")+1;
	if (i > -1) {
	i2=l.indexOf(s,i); if (i2 < 0) { i2=l.length; }
	c=l.substring((i+i3),i2);
	}
	return c;
}

//Getting referrer values from GA UMTZ cookie
function getReferrer() {
	referrer = document.referrer;
	var UTM = _uGC(document.cookie, '__utmz=', ';'); 
	
	var breakLine = UTM.indexOf("|");
	var equalLine = UTM.indexOf("=");
	equalLine = equalLine + 1;
	UTM = UTM.substring(equalLine, breakLine);
	  
	if(referrer.indexOf("google") != -1) {
		referrer = "Google";
	}		  
	else if(referrer.indexOf("bing") != -1) {
		referrer = "Bing";
	}	  
	else if(referrer == "") {
		referrer = "Direct";
	}
	else if(referrer != "") {
		var breakStart = referrer.indexOf(".");
		breakStart = breakStart + 1;
		referrer = referrer.substring(breakStart);
		var breakEnd = referrer.indexOf(".");
		referrer = referrer.substring(0, breakEnd);
	};
	return referrer
}

//getting site values from DOM
function getSite() {
	siteName = window.location;
	siteName = siteName.host;
	
	merchantID = window.location;
	merchantID = merchantID.host;
	//console.log(merchantID);
	
	merchantID = merchantID.substr(4);
	//console.log(merchantID);
	
	var merLength = merchantID.length;
	merLength = merLength - 4;
	
	merchantID = merchantID.substr(0, merLength);
	//console.log(merchantID);
}

// get rawGACookie


function getGACookie()
{
//    if (newTracker != null)
//        return newTracker.Tb();
//    else
//        return _ubd.cookie;

	var rawCookie = document.cookie;
	var startPos = rawCookie.search('__utma');
	var newCookie = rawCookie.substring(startPos);
	return newCookie;
}

//Get GA Keywords
function getKeywords()
{
	try
	{
		var temp = getGACookie();
		if (temp != null && temp != "")
		{
			var startPos = temp.indexOf("|utmctr=");
			if (startPos == -1) return "";
			startPos += 8;
			
			var endPos = temp.indexOf("|", startPos + 1);
			var endPosSemiColon = temp.indexOf(";", startPos + 1);
			
			//GA Keywords are terminated with "|" for organic and ";" when passed from an adwords click-through
			if(endPos > -1 && endPosSemiColon == -1){
				return temp.substring(startPos, endPos);
			}else if(endPos == -1 && endPosSemiColon > -1){
				return temp.substring(startPos, endPosSemiColon);
			}else if(endPos > -1 && endPosSemiColon > -1){
				// Pick the closer end point
				if(endPos < endPosSemiColon)
					return temp.substring(startPos, endPos);
				else
					return temp.substring(startPos, endPosSemiColon);
			}else if(endPos == -1) {
				return temp.substring(startPos);
			}else
				return "";
		}
				
		return "";
	}
	catch (e)
	{
		debug("Unexpected error in getGAKeywords().\r\n" + e + "\r\nTemp: " + temp);
	}
}

// get analytics medium type
function getGAReferralType()
{
	try
	{
		var temp = getGACookie();
		if (temp != null && temp != "")
		{
			var startPos = temp.indexOf("utmcmd=");
			var clickIdPos = temp.indexOf(".utmgclid=");
			
			if(clickIdPos > -1)
				return "cpc";
			
			if (startPos == -1)
				return "";
			
			startPos += 7;

			var endPos = temp.indexOf("|", startPos + 1);
			var endPosAlt = temp.indexOf(";", startPos + 1);

			if (endPos > -1) {
				return temp.substring(startPos, endPos);
				}
			else if (endPosAlt > -1) {
				return temp.substring(startPos, endPosAlt);
				}
			else {
				return temp.substring(startPos); 
				}
		}

		return "";
	}
	catch (e)
	{
		debug("Unexpected error in getGAReferralType().\r\n" + e + "\r\nTemp: " + temp);
	}
}

// get landing page location
function getCurrentPage() {
	var url = document.location.host;
	var path = document.location.pathname;
	
	var temp = url + path + ""

	return temp;
}


//function to check where are are on the site and to post everything back to NetSuite.
function setRKG() {
	//console.log("started");
	var LOCALID = Get_Cookie("session_id");
	
	var currentLocation = window.location;
	currentLocation += "";
	
	//Check for checkout area or not.  If no
	if (currentLocation.indexOf("checkout") == -1) {
		//console.log("checkout no");
		
		//RKG not in URL, cookie exists
		if(LOCALID != null) {
			//console.log("old cookie");
			document.getElementById("sessionIDText").innerHTML = LOCALID;
		}
		
		else {
			//console.log("new cookie");
			var d = new Date();
			
			var minute = d.getMinutes();
			minute += "";
			
			var hour = d.getHours();
			hour += "";
			
			var date = d.getDate();
			date += "";
			
			var month = d.getMonth() + 1;
			month += "";
			
			var year = d.getFullYear();
			year += "";
			year = year.substring(2);
			
			randomString();
            getReferrer();
            getSite();
		
			var sessionValue = year + month + date + hour + minute + rstring;
			
			Set_Cookie("session_id", sessionValue, '30', '/', '', '');
			
			document.getElementById("sessionIDText").innerHTML = sessionValue;
			
			var postURL;
			postURL = "https://forms.netsuite.com/app/site/hosting/scriptlet.nl?script=50&deploy=1&compid=924241&h=8ec40056aee8a2d05204&" + "refId=" + "2862" + "&refSesId=" + "(Not Set)" + "&intSesId=" + sessionValue + "&offSiteRefCh=" + referrer + "&website=" + siteName + "&refMerId=" + merchantID;
			document.getElementById("postRKG").src = postURL;
		}
	}
}


//function to check where are are on the site and to post everything back to NetSuite.
function setMagNew() {
	var LOCALID = Get_Cookie("xession_id");
	
	var currentLocation = window.location;
	currentLocation += "";
	
	//Check for checkout area or not.  If no
	if (currentLocation.indexOf("checkout") == -1) {
		
		//RKG not in URL, cookie exists
		if(LOCALID != null) {
			//document.getElementById("sessionIDText").innerHTML = LOCALID;
		}
		
		else {
			console.log("new cookie");
			var d = new Date();
			
			var minute = d.getMinutes();
			minute += "";
			
			var hour = d.getHours();
			hour += "";
			
			var date = d.getDate();
			date += "";
			
			var month = d.getMonth() + 1;
			month += "";
			
			var year = d.getFullYear();
			year += "";
			year = year.substring(2);
			
			randomString();
			getReferrer();
			getSite();

			var medium = getGAReferralType();
			var keyword = getKeywords();
			var cookies = getGACookie();
			var currentPageURL = getCurrentPage();
		
			var sessionValue = year + month + date + hour + minute + rstring;
				
			Set_Cookie("xession_id", sessionValue, '30', '/', '', '');
			
			document.getElementById("sessionIDText").innerHTML = sessionValue;
			
			var postURLNEW;
			postURLNEW = "https://forms.netsuite.com/app/site/hosting/scriptlet.nl?script=59&deploy=1&compid=924241&h=4f08e21c71ca9289a2ea&" + "refId=" + "2862" + "&refSesId=" + "(Not Set)" + "&intSesId=" + sessionValue + "&offSiteRefCh=" + referrer + "&website=" + siteName + "&refMerId=" + merchantID + "&medium=" + medium + "&keyword=" + keyword + "&currentURL=" + currentPageURL + "&gaCookie=" + cookies ;
			document.getElementById("postRKGNEW").src = postURLNEW;
		}
	}
}

$jQ(document).ready(function($){
	setMagNew();
});
