﻿// Create namespace
var	LM			= new Object();
LM.Initialised	= false;
LM.SiteId		= "c4af492e-efa1-429b-80b0-55afe466ea51";
LM.Domain		= "http://lm.locayta.com";
LM.UID			= null;
LM.SID			= null;
LM.RequestTime	= null;
LM.ResponseTime	= null;
LM.ServerTime	= null;
LM.Zones		= [];
LM.Config		= null;
LM.OnComplete	= null;

//#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#
// Main method, this works out which zones are in the page and then
// makes call to servers to get content for each zone.
// The request to get data for each zone is packaged into a single
// call.
//#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#
LM.init = function() {
	if (LM.Initialised) return;
	LM.Initialised = true;

	// Tracking
	LM.UID = LM.syncCookie("UID", "P");
	LM.SID = LM.syncCookie("SID", "S");

	// Gather all the information we can from zones
	// and build into query string
	var __lm_divs = document.body.getElementsByTagName("div");
	for (var ii=0; ii<__lm_divs.length; ii++) {
		var __lm_div		= __lm_divs[ii];
		var	__lm_div_zattr	= __lm_div.attributes["locayta:lmzone"];
		if (__lm_div_zattr && __lm_div.id) {
			__lm_div.locayta_lmstart = new Date(); // add date so we can monitor performance
			var __lm_meta = {"zone": __lm_div_zattr.value, "domid": __lm_div.id};
			if (__lm_div.attributes["locayta:facetdomid"]) __lm_meta["facetdomid"] = __lm_div.attributes["locayta:facetdomid"].value;
			LM.Zones.push(__lm_meta);
		}
	}

	// Build all params as query
	var __lm_query = "?siteId=" + LM.SiteId + "&UID=" + LM.UID + "&SID=" + LM.SID + "&referrer=" + encodeURIComponent(document.referrer);
	for (var ii=0; ii<LM.Zones.length; ii++) {
		for (var __lm_key in LM.Zones[ii]) {
			__lm_query += "&" + __lm_key + ii + "=" + encodeURIComponent(LM.Zones[ii][__lm_key]);
		}
	}

	// Allow dynamic/debug
	if (LM.Config != null) {
		for (var __lm_key in LM.Config) {
			__lm_query += "&config_" + __lm_key.toLowerCase() + "=" + encodeURIComponent(LM.Config[__lm_key]);
		}
	}

	// Now we have all the details to send to the server
	// create script tag and append to header to initiate call
	LM.RequestTime	= new Date();
	var __lmHeadTag	= document.getElementsByTagName("head")[0];
	var	__lmScript	= document.createElement("script");
	__lmScript.type	= "text/javascript";
	__lmScript.src	= LM.Domain + "/zones-js.aspx" + __lm_query;
	__lmHeadTag.appendChild(__lmScript);
}

//#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#
// Set/get cookie value
//#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#
LM.syncCookie = function(__lmCookieName, __lmCookieType) {
	var __lmCookieValue = LM.getCookie(__lmCookieName);
	if (__lmCookieValue == null || __lmCookieValue == "") __lmCookieValue = LM.GUID();
	var __lmCookieStr	= __lmCookieName + "=" + escape(__lmCookieValue) + "; path=/";
	if (__lmCookieType == "S") {
		// session cookie
		var __lmDate = new Date();
		__lmDate.setTime(__lmDate.getTime()+(60*60*1000)+(15*60*1000)); // session time of 15 minutes
		__lmCookieStr += "; expires=" + __lmDate.toGMTString();
	}
	else {
		// permanent cookie
		var __lmDate = new Date();
		__lmDate.setTime(__lmDate.getTime()+(1000*24*60*60*1000)); // session time of 15 minutes
		__lmCookieStr += "; expires=" + __lmDate.toGMTString();
	}
	// always reset cookie
	document.cookie = __lmCookieStr;
	return __lmCookieValue;
}
LM.getCookie = function(__lmCookieName) {
	var _lmMatch = document.cookie.match ("(^|;) ?" + __lmCookieName + "=([^;]*)(;|$)");
	if ( _lmMatch ) {
		return (unescape( _lmMatch[2]));
	}
	else {
		return null;
	}
}

//#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#
// Generate unique(ish) user id
//#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#
LM.GUID = function() {
   return (LM.Random4()+LM.Random4()+"-"+LM.Random4()+"-"+LM.Random4()+"-"+LM.Random4()+"-"+LM.Random4()+LM.Random4()+LM.Random4());
}
LM.Random4 = function() {
   return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
}


//#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#
// Called by server and sets/generates the
// zone html
//#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#
LM.buildZone = function(__lm_Params) {
	__lm_target									= document.getElementById(__lm_Params["target"]);
	__lm_target.locayta_lmName					= __lm_Params["name"];
	__lm_target.locayta_lmRuleDuration			= __lm_Params["ruleExecutionTime"];
	__lm_target.locayta_lmRuleSearchDuration	= __lm_Params["ruleSearchExecutionTime"];
	__lm_target.locayta_lmRule					= __lm_Params["ruleTitle"];
	__lm_target.locayta_lmRenderStart			= new Date();
	__lm_target.innerHTML						= __lm_Params["html"];
	if (__lm_Params["facetTarget"] && __lm_Params["facetHtml"] != null) { // search facets
		document.getElementById(__lm_Params["facetTarget"]).innerHTML = __lm_Params["facetHtml"];
	}
	__lm_target.locayta_lmRenderEnd				= new Date();
}

//#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#
// Fires when all zones have been populated
//#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#
LM.buildComplete = function(__lm_Params) {
	LM.ResponseTime = new Date();
	LM.ServerTime	= __lm_Params["serverTime"];
	// run any custom scripts
	if (LM.OnComplete) LM.OnComplete();
}

//#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#
// Setup "onready" event so that init fires when the DOM loads.
//#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#
if (navigator.appName == "Microsoft Internet Explorer") {
	// IE only ... script.onreadystatechange gives better response than document.readyState,
	// so no need for both when IE
	var voidUrl = location.protocol == "https:" ? "https://javascript:void(0)" : "javascript:void(0)";
	document.write("<script id=\"__ie_script_onready\" defer src=\"" + voidUrl + "\"><\/sc" + "ript>");
	var script = document.getElementById("__ie_script_onready");
	script.onreadystatechange = function() {
		if (this.readyState == "complete") {
			LM.init();
		}
	};
}
else {
	// DOMContentLoaded is ideal, but document.readyState isn't a bad backup method
	if (document.addEventListener) {
		document.addEventListener("DOMContentLoaded", LM.init, false);
	}
	if (document.readyState) {
		var _lmTimer = setInterval(function() {
			if (/loaded|complete/.test(document.readyState)) {
				clearInterval(_lmTimer);
				LM.init();
			}
		}, 5);
	}
}
// Fallback methods
if (window.addEventListener) {
	window.addEventListener("load", LM.init, false);
}
else if (document.addEventListener) {
	document.addEventListener("load", LM.init, false);
}
else if (window.attachEvent) {
	window.attachEvent("onload", LM.init);
}
else if (document.attachEvent) {
	document.attachEvent("onload", LM.init);
}
else {
	window.onload = LM.init;
}

