﻿// Initialise namespace + container vars
var	LM			= new Object();
LM.Initialised	= false;
LM.SiteId		= "3ec8a079-f11a-47bf-9913-af5e370b4d5f";
LM.Domain		= "http://esp.locayta.com";
LM.SiteReferrer	= "";
LM.UID			= null;
LM.SID			= null;
LM.Currency		= null;
LM.Language		= null;
LM.Sku			= null;
LM.Category		= null;
LM.SearchTerm   = null;
LM.RequestTime	= null;
LM.ResponseTime	= null;
LM.ServerTime	= null;
LM.EventTime	= new Date();
LM.Zones		= [];
LM.BasketItems  = [];
LM.OrderHeader  = {};
LM.OrderItems   = [];
LM.Config		= {};
LM.OnComplete	= null; // deprecated
LM.OnPreInit	= null; // deprecated
LM._preInit		= [];
LM._complete	= [];

//#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#
// Allow custom event handlers
//#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#
LM.preInit = function(__lm_function) {
	LM._preInit.push(__lm_function);
}
LM.complete = function(__lm_function) {
	LM._complete.push(__lm_function);
}

//#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#
// Initialise .... calls when DOM has loaded
//#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#
LM.init = function(__lm_event_method) {
	if (LM.Initialised) return;
	LM.Initialised = true;

	// run any custom scripts
	for (var ii = 0; ii < LM._preInit.length; ii++) {
		if (typeof (LM._preInit[ii]) === "function") LM._preInit[ii]();
	}
	if (LM.OnPreInit != null) LM.OnPreInit(); // legacy

	// Tracking
	LM.UID = LM.syncCookie("LMUID", "P");
	LM.SID = LM.syncCookie("LMSID", "S");

	// If referrer is not current site keep track of referrer
	if (document.referrer) {
		var __lmReferrerHostname = document.referrer.replace("http://", "").replace("https://", "");
		if (__lmReferrerHostname.indexOf("/") != -1) __lmReferrerHostname = __lmReferrerHostname.substring(0, __lmReferrerHostname.indexOf("/"));
		if (__lmReferrerHostname != window.location.hostname) {
			LM.setCookie("LMSITEREFERRER", document.referrer, "S");
		}
	}
	LM.SiteReferrer = LM.getCookie("LMSITEREFERRER") || "";
	LM.refresh();
}

//#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#
// The request to get data for each zone is packaged into a single
// call.
//#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#
LM.refresh = function() {
    if (!LM.Initialised) return;
    LM.Zones = [];
    // 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 == null) __lm_div_zattr = __lm_div.attributes["lmzone"];
        if (__lm_div_zattr) {
            __lm_div.locayta_lmstart = new Date(); // add date so we can monitor performance
            var __lm_meta = { "zone": __lm_div_zattr.value, "element": __lm_div };
            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) + "&sitereferrer=" + encodeURIComponent(LM.SiteReferrer);
    for (var ii = 0; ii < LM.Zones.length; ii++) {
        __lm_query += "&zone" + ii + "=" + encodeURIComponent(LM.Zones[ii]["zone"]);
    }
    // Search term
    if (LM.SearchTerm != null) __lm_query += "&searchterm=" + encodeURIComponent(LM.SearchTerm);
    // Currency
    if (LM.Currency != null) __lm_query += "&currency=" + encodeURIComponent(LM.Currency);
    // Language
    if (LM.Language != null) __lm_query += "&language=" + encodeURIComponent(LM.Language);
    // Sku
    if (LM.Sku != null) __lm_query += "&sku=" + encodeURIComponent(LM.Sku);
    // Category
    if (LM.Category != null) __lm_query += "&category=" + encodeURIComponent(LM.Category);
    // Track add to basket
    for (var ii = 0; ii < LM.BasketItems.length; ii++) {
        for (var __lm_key in LM.BasketItems[ii]) {
            __lm_query += "&basketItem__" + ii + "_" + __lm_key.toLowerCase() + "=" + encodeURIComponent(LM.BasketItems[ii][__lm_key]);
        }
    }
    // Track order header
    for (var __lm_key in LM.OrderHeader) {
        __lm_query += "&orderHeader__" + __lm_key.toLowerCase() + "=" + encodeURIComponent(LM.OrderHeader[__lm_key]);
    }
    // Track purchases
    for (var ii = 0; ii < LM.OrderItems.length; ii++) {
        for (var __lm_key in LM.OrderItems[ii]) {
            __lm_query += "&orderItem__" + ii + "_" + __lm_key.toLowerCase() + "=" + encodeURIComponent(LM.OrderItems[ii][__lm_key]);
        }
    }

    // Custom vars
    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;
	}
}
LM.setCookie = function(__lmCookieName, __lmCookieValue, __lmCookieType) {
	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;
}

//#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#
// 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);
}


//#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#
// Add custom fields
//#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#
LM.addCustomField = function(__lm_field_name, __lm_field_value) {
	LM.Config[__lm_field_name] = __lm_field_value;
}

//#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#
// Track item in basket
//#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#
LM.addBasketItem = function(__lm_Params) {
	LM.BasketItems.push(__lm_Params);
}

//#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#
// Track new order
//#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#
LM.addOrder = function(__lm_Params) {
	LM.OrderHeader.push(__lm_Params);
}

//#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#
// Track order line purchase
//#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#
LM.addOrderItem = function(__lm_Params) {
	LM.OrderItems.push(__lm_Params);
}

//#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#
// Called by server and sets/generates the
// zone html
//#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#
LM.buildZone = function(__lm_Params) {
	var	__lm_idx								= parseInt(__lm_Params["idx"]);
	var	__lm_target								= LM.Zones[__lm_idx]["element"];
	__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"];
	try {
		var __lm_facetAttr = __lm_target.attributes["facetdomid"] || __lm_target.attributes["locayta:facetdomid"];
		if (__lm_facetAttr) document.getElementById(__lm_facetAttr.value).innerHTML = __lm_Params["facetHtml"] || "";
	}
	catch (__lm_ex) {}

	try {
		var __lm_filterAttr = __lm_target.attributes["filterdomid"] || __lm_target.attributes["locayta:filterdomid"];
		if (__lm_filterAttr) document.getElementById(__lm_filterAttr.value).innerHTML = __lm_Params["filterHtml"] || "";
	}
	catch (__lm_ex) {}
	__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
	for (var ii = 0; ii < LM._complete.length; ii++) {
		if (typeof (LM._complete[ii]) === "function") LM._complete[ii]();
	}
	if (LM.OnComplete) {
		LM.OnComplete();
	}
	// admin
	var __lmAID = null;
	var __lmAIDCookie = LM.getCookie("LMAID");
	if (window.location.search.length > 43 && window.location.search.substring(0, 8) == "?_lmkey=") {
		__lmAID = location.search.substring(8);
		//alert("AID: get from query");
	}
	else if (__lmAIDCookie != null && __lmAIDCookie != "") {
		__lmAID = __lmAIDCookie;
		//alert("AID: get from cookie");
	}
	if (__lmAID != null) {
		//alert("__lmAID: " + __lmAID + "\n\n" + location.search);
		LM.setCookie("LMAID", __lmAID, "S");
		var __lmHeadTag = document.getElementsByTagName("head")[0];
		var __lmAdminScript = document.createElement("script");
		__lmAdminScript.type = "text/javascript";
		__lmAdminScript.src = LM.Domain + "/zones-admin-js.aspx?aid=" + __lmAID;
		__lmHeadTag.appendChild(__lmAdminScript);
	}
}

//#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#
// Setup "onready" event so that init fires when the DOM loads.
//#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#
if (navigator.appName == "Microsoft Internet Explorer") {
	// similar to onload (fires quite late), but better suited to iframes/frames
	document.attachEvent("onreadystatechange", function() {
		if (document.readyState === "complete") {
			document.detachEvent("onreadystatechange", arguments.callee);
			LM.init("onreadystatechange");
		}
	});
	// uses doScroll trick to find when DOM ready (only works for non frames)
	if (document.documentElement.doScroll && window == window.top)
		(function() {
			try {
				document.documentElement.doScroll("left");
				LM.init("doScroll");
			}
			catch (_lm_error) {
				setTimeout(arguments.callee, 0);
				return;
			}
		})();
}
else {
	// DOMContentLoaded is ideal ...
	if (document.addEventListener) {
		document.addEventListener("DOMContentLoaded", function() { LM.init("DOMContentLoaded"); }, false);
	}
	// ... but document.readyState isn't a bad backup method
	if (document.readyState) {
		var _lmTimer = setInterval(function() {
			if (/loaded|complete/.test(document.readyState)) {
				clearInterval(_lmTimer);
				LM.init("readyState");
			}
		}, 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;
}
