var promoFlag = "on";
var codeboxID = "";
var keywords = "";
var keywordsMod = "";
var layoutCodeID = "";
var adID = "";
var URL = location.href;
var referrerMod = "";
var sitematch = "";

var browserSniff = navigator.userAgent;
if (browserSniff.indexOf("MSIE") != -1) {
	browserType = "ie";
	} else if (browserSniff.indexOf("Gecko") != -1) {
	browserType = "mozilla";
	} else if (browserSniff.indexOf("Opera") != -1) {
	browserType = "opera";
	} else {
	browserType = "notKnown";
}

// TEST REFERRERS
// ------------------------------
var referrer = document.referrer;


// SET UP PAGE (HIDE PLR BOX IF JS ENABLED, LOAD KWD)
function setPage() {
	if (URL.indexOf("localhost") != -1) {
		sitematch = "http://localhost/ironspider/";
	} else if (URL.indexOf("ironspider.ca/") != -1) {
		sitematch = "ironspider.ca/";
	}

	adID = (document.getElementById("PLR_Wrapper_01")) ? "PLR_Wrapper_01" : "PLR_Wrapper_02";
	document.getElementById(adID).className = "PLR_WrapperStyle"; // Set PLR Box display: none;
	document.getElementById("MoreDetailsLink").href = "javascript:cmlPage();"; // Rewrite href to cmlPage();
	if (document.getElementById("SPDirectLink")) {
		document.getElementById("SPDirectLink").href = "javascript:cmlPage('direct');"; // Rewrite href to cmlPage();
	}
	if (document.getElementById("NTY")) {
		document.getElementById("NTY").style.display = "block"; 
	}
	loadKWD();

	if (referrer.indexOf("google") != -1) {
		getSearchKWD("google","q=");
	} else if (referrer.indexOf("yahoo") != -1) {
		getSearchKWD("yahoo","p=");
	} else if (referrer.indexOf(sitematch) != -1) {
		srchstr = (referrer.indexOf("/index.htm") != -1) ? "/myspace" : "/"; 
		filename = getEndLastIndex(referrer,srchstr);
		referrerMod = "(ironspider) " + filename;
	} else {
		referrerMod = "(external) " + referrer;
	}
}

function getSearchKWD(se,start) {
	searchKWDend = getEnd(referrer,start);
	if (searchKWDend) { // If referrer is Google or Yahoo plus search term
		searchKWD = getFront(searchKWDend,"&");
		regexp3 = /%../g;
		referrerMod = se + " -- " + searchKWD.replace(regexp3," ");
	} else { // If referrer is Google or Yahoo but NO search term
		referrerMod = "(external) " + referrer;
	}
}

// STRING FUNCTIONS
// extract back end of string after searchString
function getEnd(mainStr,searchStr) {
	foundOffset = mainStr.indexOf(searchStr);
	if (foundOffset == -1) {
		return null;
	}
	return mainStr.substring(foundOffset+searchStr.length,mainStr.length);
}

function getEndLastIndex(mainStr,searchStr) {
	foundOffset = mainStr.lastIndexOf(searchStr);
	if (foundOffset == -1) {
		return null;
	}
	if (searchStr == "/myspace") {
		return mainStr.substring(foundOffset,mainStr.length);
	} else {
		return mainStr.substring(foundOffset+searchStr.length,mainStr.length);
	}
}

// extract front part of string prior to searchString (if no searchString, return mainStr)  
function getFront(mainStr,searchStr){
	foundOffset = mainStr.indexOf(searchStr);
	if (foundOffset == -1) {
		return mainStr;
	}
	return mainStr.substring(0,foundOffset);
}

function loadKWD() {
	if (URL.indexOf("free-myspace-layout") != -1) {
		keywordsMod = "webmasters_choice";
	} else if (URL.indexOf("adv_laygen") != -1) {
		keywordsMod = "advanced_editor";
	} else if (URL.indexOf("basic_laygen") != -1) {
		keywordsMod = "basic_editor";
	} else {
		var titleRaw = document.title; 
		if (titleRaw.indexOf("&") != -1) {
			regexp1 = /&/g;
			var title = titleRaw.replace(regexp1, "and");
		} else {
			var title = titleRaw;
		}
		titleWordsArray = title.split(" ");
		for (var i=0; i<titleWordsArray.length; i++) { // Find word count of "Background"
			if (titleWordsArray[i].indexOf("Background") != -1) {
				var backgroundCount = i;
				break;
			} else {
				var backgroundCount = 999
			}
		} // End for 
		for (var i=0; i<titleWordsArray.length; i++) { // Find word count of "Layout"
			if (titleWordsArray[i].indexOf("Layout") != -1) {
				var layoutCount = i;
				break;
			} else {
				var layoutCount = 999
			}
		} // End for 
		if (backgroundCount == 999 && layoutCount == 999) { // If neither "Background" or "Layout" exists in title
			var lastWordCount = titleWordsArray.length - 1;
		} else { // If "Background" or "Layout" exists in title
			var lastWordCount = (layoutCount < backgroundCount) ? layoutCount : backgroundCount;
		}
		for (var i=0; i < lastWordCount; i++) { // Add all words except last one plus a space after each word 
			keywords += titleWordsArray[i] + " ";
		}
		keywords += titleWordsArray[lastWordCount]; // Add last word 
		regexp = / /g;
		keywords2 = keywords.replace(regexp, "_").toLowerCase(); // Replace space with underscore
		regexp2 = /,/g;
		keywordsMod = keywords2.replace(regexp2, ""); // Remove comma
	} // End if else
} 

// GET COOKIE VALUE
var cookieValue2 =  getCookieValue("plr_promo");

// IF COOKIE VALUE EXISTS, DO THIS...
// TO TURN OFF LRL PROMO POPUP ACROSS THE SITE, SET BOTH VALUES TO "off".
promoFlag = (cookieValue2) ? "off" : "off";

// OPEN PROMO BOX or SELECT CODE
function selectCode(happy) {
	codeboxID = happy;
	if (promoFlag == "on") {
		var y = 0;
		document.getElementById(happy).blur();
		offsetPointer =	document.getElementById(happy);
		while (offsetPointer) {
			y += offsetPointer.offsetTop;
			offsetPointer = offsetPointer.offsetParent;
			finalOffset = y - 200 + "px";
			document.getElementById(adID).style.display = "block";
			document.getElementById(adID).style.top = finalOffset;
		}
		if (URL.indexOf("laygen") != -1) { 
			document.getElementById(happy).disabled = true;
			if (browserType == "ie") {
				// IE needs the following two to truly disable copy-and-paste 
				document.getElementById(happy).style.overflow = "hidden";
				document.getElementById(happy).style.paddingTop = "100px";
			}
		}
	} else {
		document.getElementById(happy).select();
	}
	// Get cookie value and set to variable
	cookieValue2 =  getCookieValue("plr_promo");
	if (cookieValue2) {
		mspi("GetCode",codeboxID);
	} else {
		mspi("Prospect",codeboxID);
	}
	if (document.PLR_01) {
		document.PLR_01.os1.value = layoutCodeID + "__" + adID;
	}
}

// CLOSE PROMO BOX FUNCTION (SETS COOKIE)
function closePLR_Promo() {
	promoFlag = "off";

	// Set cookie
	var newDate = new Date();
	newDate.getTime();
	newDate.setTime(newDate.getTime() + 86400000); // 86400000 = one day --- 10000 = ten seconds (for testing)
	document.cookie = "plr_promo=" + escape("Declined") + ";expires=" + newDate.toGMTString() + ";path=/";

	// Get cookie value and set to variable
	cookieValue2 =  getCookieValue("plr_promo");

	// Tracking 
	mspi("Declined",codeboxID);

	// Close promo box
	document.getElementById(adID).style.display = "none";
	if (URL.indexOf("laygen") != -1) { 
		document.getElementById(codeboxID).disabled = false;
		if (browserType == "ie") {
			document.getElementById(codeboxID).style.overflow = "auto";
			document.getElementById(codeboxID).style.paddingTop = "0px";
		}
	}
}

// GET COOKIE VALUE BASED ON COOKIE NAME FUNCTION
function getCookieValue(cookieName) {
	if (document.cookie.length > 0) {
		// Get index of beginning of cookie name
		var cookieStart = document.cookie.indexOf(cookieName + "=");
		if (cookieStart != -1) { // If cookie name exists in document.cookie...
			var cookieEnd = document.cookie.indexOf(";",cookieStart + 1); // Get index of end of cookie (;)
			if (cookieEnd == -1) {cookieEnd = document.cookie.length} // If no (;), only 1 cookie in document.cookie
				var cookieValue = unescape(document.cookie.substring(cookieStart + cookieName.length+1, cookieEnd));
		}
	}
	return cookieValue;
}

// function cmlPage
function cmlPage(directLink) {
	adIDshort = (adID == "PLR_Wrapper_01") ? "Ad_01" : "Ad_02";
	if (directLink) {
		adIDshort = directLink;
		mspi('SalesPage',codeboxID,adIDshort);
	} else {
		mspi('SalesPage',codeboxID);
	}
	document.MoreDetails.kwd.value = layoutCodeID + "__" + adIDshort;
	document.MoreDetails.submit();
}

function mspi(action,codeID,isDirect) {
	var baseURL = (sitematch == "http://localhost/ironspider/") ? sitematch : "http://www.ironspider.ca/";
	regexp2 = /src/g;
	var codeID_Mod = codeID.replace(regexp2,"_");
	layoutCodeID = (keywordsMod.indexOf("editor") != -1) ? keywordsMod : keywordsMod + codeID_Mod;
	adID2 = (isDirect) ? isDirect : adID;
	var d = new Date();
	// Format date and time
	var curr_date = d.getDate();
	var curr_month = d.getMonth();
	curr_month++;
	var curr_year = d.getFullYear();
	var curr_hour = d.getHours();
	var curr_min = d.getMinutes();
	curr_min = curr_min + "";
	curr_min = (curr_min.length == 1) ? "0" + curr_min : curr_min;
	var curr_sec = d.getSeconds();
	curr_sec = curr_sec + "";
	curr_sec = (curr_sec.length == 1) ? "0" + curr_sec : curr_sec;
	var dateStyle = curr_month + "/" + curr_date + "/" + curr_year + " -- " + curr_hour + ":" + curr_min + ":" + curr_sec;
	// Create image object 
	var myImage = new Image();
    myImage.src= baseURL + "adv/myspace/gumshoe.php?time=" + dateStyle + "&referrer=" + referrerMod + "&kwd=" + layoutCodeID + "&action=" + action + "&adID=" + adID2;
	// Comment hack to get Firefox to register sp clicks
    return true;
}
