var CONSTANTS = new Object();
CONSTANTS.Version = '1.1.2';
CONSTANTS.FlashMovie = "/core/EMERPECp/flash_object.swf";
CONSTANTS.ServerRecieveUrl = "/core/EMERPECp/Receive.php";
CONSTANTS.ServerGuidUrl = "/core/EMERPECp/GetGuid.php";
CONSTANTS.ServerDuplicateUrl = "/core/EMERPECp/Duplicate.php";
CONSTANTS.SSLSupport = document.location.href.match(/^https/i) ? true : false;
CONSTANTS.ServerPixelUrl = "http"+(CONSTANTS.SSLSupport?'s':'')+"://stat.casino.com/pixel/instructions/";
CONSTANTS.clientId = "E802458A-CCF1-4313-AFCE-4B846D52F00D";
CONSTANTS.Greedy = true; // indicates if to wait for a response from the server before deleting event from queue
CONSTANTS.SendAnonymous = true; // indicates if to send events for anonymous users (without serial and guid)
CONSTANTS.ShowErrors = false;
CONSTANTS.FlashEnabled = true;
CONSTANTS.sessionId = '0';
CONSTANTS.account = 0;
CONSTANTS.amount = 0;
CONSTANTS.CurrentGuid = "N/A";
CONSTANTS.CurrentQueue = "N/A";
CONSTANTS.PropertyBag = "N/A";
CONSTANTS.SendEvent = true;
CONSTANTS.SendTemp = false;
CONSTANTS.WaitForFlashPeriod = (navigator.userAgent.match(/MSIE 7/)) ? 10000 : 2000; 
CONSTANTS.CurrentSerial = null;
CONSTANTS.CurrentSerialID = null;
CONSTANTS.CurrentPixel = null;
CONSTANTS.CurrentPixelID = null;
CONSTANTS.CurrentDP = null;
CONSTANTS.CurrentDPID = null;
CONSTANTS.ForceSerialID = null;
CONSTANTS.OnSuccessCallback = callback;
CONSTANTS.OnFailedCallback = errorcallback;
CONSTANTS.SilentMode = true;
CONSTANTS.CurrentClientId = CONSTANTS.clientId;
CONSTANTS.AlwaysSendReferrer = true;
CONSTANTS.ExternalReferrerOnly = false; // indicates if to send events where the referrer is only from a different domain
CONSTANTS.Domain = "."+(document.domain.match(/\./ig).length > 1) ? document.domain.replace(/[^\.]*\./, "") : document.domain;
CONSTANTS.UID_IS_TEMP = -1;
CONSTANTS.SAME_REFERRER = -2;
CONSTANTS.OK = 0;
CONSTANTS.MODE = "qa"; // "dev", "qa", "prod";
CONSTANTS.DOMAINS = new Array();
CONSTANTS.FLASH8 = false;
CONSTANTS.cookies = document.cookie;
try {
	var hasRequestedVersion = DetectFlashVer(8, 0, 0);
        var inPlaytechEnv = false;
        try {
          if (parent.location.href.match(/\/register\//i) || parent.location.href.match(/\/promotions\//i) || parent.location.href.match(/\/clientpromotions\//i)) inPlaytechEnv = true;
			if (top.location.href.match(/\/register\//i) || top.location.href.match(/\/promotions\//i) || top.location.href.match(/\/clientpromotions\//i)) inPlaytechEnv = true;
        } catch (e) {
        }
	if (hasRequestedVersion) {
		CONSTANTS.FLASH8 = true;
		CONSTANTS.FlashMovie = "/core/EMERPECp/flash_object_81.swf"+((inPlaytechEnv) ? "?r="+Math.random()*100000 : "");
	}
} catch (e) {
}
CONSTANTS.TEMP_GUID = "";
CONSTANTS.USER_GUID = "";
CONSTANTS.SupportedPixelEvents = {hphit:false, clientrealreg:true, clientfunreg:true, download:true};
CONSTANTS.SupportedPTEvents = {prerealreg:true, prefunreg:true, clientrealreg:true, clientfunreg:true}

var cookieHandler;
var queue;
//var eventCollector = false;
var __flashLoaded = false;
var ua = navigator.userAgent.toLowerCase();
var is_pc_ie = ( (ua.indexOf('msie') != -1 ) && ( ua.indexOf('win') != -1 ) && ( ua.indexOf('opera') == -1 ) && ( ua.indexOf('webtv') == -1 ) );
var is_ff = (document.addEventListener && !navigator.userAgent.match(/Safari/i));
function InitCookies(callback) {
	function callback1() {
		CONSTANTS.SendEvent = true;
		callback();
	}
	CONSTANTS.SendEvent = false;
	eventCollector = new EventCollector(CONSTANTS.clientId, 'Dummy', CONSTANTS.sessionId, CONSTANTS.account, CONSTANTS.amount, callback1);
}
function CreateMandatoryObjects() {
	if (!document.getElementById("flashPlaceholder")) {
		Debug.write("flashPlaceholder does not exist. create one");
		var flashDiv = document.createElement("div");
		flashDiv.id = "flashPlaceholder";
		flashDiv.style.width = "1px";
		flashDiv.style.height = "1px";
		flashDiv.style.overflow = "hidden";
		document.body.appendChild(flashDiv);
		flashDiv = null;
	} else Debug.write("flashPlaceholder exists.");
	if (!document.getElementById("debugTextarea")) {
		var debugTextarea = document.createElement("textarea");
		debugTextarea.id = "debugTextarea";
		debugTextarea.style.width = "600px";
		debugTextarea.style.height = "250px";
		debugTextarea.style.display = (CONSTANTS.SilentMode) ? "none" : "";
		document.body.appendChild(debugTextarea);
		debugTextarea = null;
	}
	if (!document.getElementById("debugDiv")) {
		var debugDiv = document.createElement("div");
		debugDiv.id = "debugDiv";
		debugDiv.style.display = (CONSTANTS.SilentMode) ? "none" : "";
		document.body.appendChild(debugDiv);
		debugDiv = null;
	}
}
function SendEvents(arr, event) {
	WriteToQueue = true;
	for (var i=0;i<arr.length;i++) SendEvent(arr[i][0], arr[i][1], arr[i][2]);
	WriteToQueue = false;
	SendEvent("", "__pq"+event, "");
}
function SendEvent() {
	// possible parameters:
		// none
		// eventId
		// clientId, eventId
		// clientId, eventId, sessionId
		// clientId, eventId, sessionId, account
		// clientId, eventId, sessionId, account, amount
		// clientId, eventId, sessionId, account, amount, callback
		// clientId, eventId, sessionId, account, amount, callback, errorCallback
	var eventId = (arguments.length == 1) ? arguments[0] : ((arguments.length >= 2) ? arguments[1] : 'HpHit');
	var clientId = (arguments.length > 1) ? arguments[0] : CONSTANTS.clientId;
	var sessionId = (arguments.length >= 3) ? arguments[2] : CONSTANTS.sessionId;
	var account = (arguments.length >= 4) ? arguments[3] : CONSTANTS.account;
	var amount = (arguments.length >= 5) ? arguments[4] : CONSTANTS.amount;
	var callback = (arguments.length >= 6) ? arguments[5] : CONSTANTS.OnSuccessCallback;
	var errorCallback = (arguments.length >= 7) ? arguments[6] : CONSTANTS.OnFailedCallback;
	// Debug.Dispose();
	Ajax.Dispose();
	Debug.Trace(eventId, "event");
	Debug.write("Calling send event:"+eventId);
	CreateMandatoryObjects();
	//ADDED BY NIMROD TO SUPPORT COM WRAPPER
	if ( clientId == null || clientId.length == 0 )
		clientId = CONSTANTS.clientId;
	if ( sessionId == null || sessionId.length == 0 )
		sessionId = CONSTANTS.sessionId;
	if ( account == null || account.length == 0 )
		account = CONSTANTS.account;
	if ( amount == null || amount.length == 0 )
		amount = CONSTANTS.amount;
	// var callback2 = arguments.length > 5 ? callback : null;
	if (eventId.match(/^\?/)) {
		if (CheckReferrer()) {
			Debug.write("Same domain. Send dummy instead.");
			eventId = "DummyEvent";
		} else {
			Debug.write("Not from the same domain, continue.");
		}
		eventId = eventId.replace(/^\?/, "");
	}
	
	if (EventCollectorManager.State != 0) EventCollectorManager.WaitingList[EventCollectorManager.WaitingList.length] = {clientId:clientId, eventId:eventId, sessionId:sessionId, account:account, amount:amount, callback:callback, errorCallback:errorCallback};
	else {
		var eventCollector = new EventCollector(clientId, eventId, sessionId, account, amount, callback, errorCallback);
	}
}
function GetReferrer() {
	var referrer = "";
	try {
		referrer = parent.document.referrer;
		if (!referrer || referrer == "" || referrer+"" == "undefined") referrer = "";
	} catch (e) {
		referrer = document.referrer;
	}
	return referrer;
}
function CheckReferrer() {
	var referrer = GetReferrer();
	var referrerDomain = referrer.replace(/(http[s]*\:\/\/[^\/]*).*$/, "$1");
	var referrerFromSameDomain = document.location.href.indexOf(referrerDomain);
	
	if (referrerFromSameDomain != -1 && referrer != "") return true;
	else return false;
}
var EventCollectorManager = {WaitingList:new Array(), State:0};
// EventHandler object
function EventCollector(clientId, eventId, sessionId, account, amount, callback, errorCallback) {
	EventCollectorManager.State = 1;
	this.clientId = clientId;
	CONSTANTS.CurrentClientId = clientId;
	this.eventId = eventId;
	this.sessionId = sessionId;
	this.account = account;
	this.amount = amount;
	this.doneCallback = callback;
	this.errorCallback = errorCallback;
	this.attachEvent("ondone", function() {
		Debug.Trace(this.eventId, "endevent");
		EventCollectorManager.State = 0;
		if (this.doneCallback && !WriteToQueue) this.doneCallback(self, this.eventId);
		Debug.write("There are "+EventCollectorManager.WaitingList.length+" calls waiting");
		if (EventCollectorManager.WaitingList.length > 0) {
			Debug.write("Handling "+EventCollectorManager.WaitingList[0].eventId+"...");
			SendEvent(EventCollectorManager.WaitingList[0].clientId,
								EventCollectorManager.WaitingList[0].eventId,
								EventCollectorManager.WaitingList[0].sessionId,
								EventCollectorManager.WaitingList[0].account,
								EventCollectorManager.WaitingList[0].amount,
								EventCollectorManager.WaitingList[0].callback,
								EventCollectorManager.WaitingList[0].errorCallback);
			for (var i=0;i<EventCollectorManager.WaitingList.length-1;i++) {
				EventCollectorManager.WaitingList[i] = EventCollectorManager.WaitingList[eval(i+1)];
			}
			EventCollectorManager.WaitingList.length -= 1;
		}
	});
	this.Init();
}
EventCollector.prototype.GetDP = function GetDP() {
	Debug.group("GetDP");
	var dpFromCookie = cookieHandler.GetCookie("dp");
	var dpFromUrl = null;
	try {
		if (document.location.href.match(/^.*(&|\?)DP=([^&]*).*$/i))
			dpFromUrl = document.location.href.replace(/^.*(&|\?)DP=([^&]*).*$/i,"$2");
		else if (parent.document.location.href.match(/^.*(&|\?)DP=([^&]*).*$/i))
			dpFromUrl = parent.document.location.href.replace(/^.*(&|\?)DP=([^&]*).*$/i,"$2");
		else if (top.document.location.href.match(/^.*(&|\?)DP=([^&]*).*$/i))
			dpFromUrl = top.document.location.href.replace(/^.*(&|\?)DP=([^&]*).*$/i,"$2");
	} catch (e) {
		dpFromUrl = null;
	}
	if (dpFromUrl == "") dpFromUrl = null;
	
	CONSTANTS.CurrentDP = dpFromUrl;
	Debug.write("CONSTANTS.CurrentDP:"+CONSTANTS.CurrentDP);
	if (dpFromUrl == null) {
		Debug.write("Could not find dp in url. Continue with dp from cookie");
		Debug.write("dpFromCookie.value:"+dpFromCookie.value);
	} else if (dpFromUrl != dpFromCookie.value) {
		Debug.write("dp in Cookie:"+dpFromCookie.value+".");
		Debug.write("dp in Url:"+dpFromUrl+".");
		Debug.write("dp in cookie is "+((dpFromCookie.value == null) ? "empty" : "not the same as dp from url"));
		cookieHandler.SetCookie("dp", dpFromUrl);
		Debug.write("Should send sync to other domains. Erasing domains list");
		Debug.write("current domains list:"+cookieHandler.GetCookie("ds").value);
		cookieHandler.SetCookie("ds", "");
		cookieHandler.saveHTMLCookie("ds", "");
		Debug.write("new domains list:"+cookieHandler.GetCookie("ds").value);
	}
	cookieHandler.SyncDPs(dpFromUrl);
	Debug.groupend();
}
EventCollector.prototype.ResetDP = function ResetDP() {
	Debug.group("ResetDP");
	cookieHandler.backupCookies["dp"] = "";
	cookieHandler.saveHTMLCookie("dp", "");
	if (this.flashEnabled) cookieHandler.SetCookie("dp", "");
	Debug.groupend();
}
EventCollector.prototype.ResetPixel = function ResetPixel() {
	Debug.group("ResetPixel");
	cookieHandler.saveHTMLCookie("pixel", "");
	if (this.flashEnabled) cookieHandler.SetCookie("pixel", "");
	Debug.groupend();
}
EventCollector.prototype.GetPixel = function GetPixel() {
	Debug.group("GetPixel");
	var pixelFromCookie = cookieHandler.GetCookie("pixel");
	var pixelFromUrl = null;
	try {
		if (document.location.href.match(/^.*(&|\?)PX=([^&]*).*$/i))
			pixelFromUrl = document.location.href.replace(/^.*(&|\?)PX=([^&]*).*$/i,"$2");
		else if (parent.document.location.href.match(/^.*(&|\?)PX=([^&]*).*$/i))
			pixelFromUrl = parent.document.location.href.replace(/^.*(&|\?)PX=([^&]*).*$/i,"$2");
		else if (top.document.location.href.match(/^.*(&|\?)PX=([^&]*).*$/i))
			pixelFromUrl = top.document.location.href.replace(/^.*(&|\?)PX=([^&]*).*$/i,"$2");
	} catch (e) {
		pixelFromUrl = null;
	}
	if (pixelFromUrl == "") pixelFromUrl = null;
	
	CONSTANTS.CurrentPixel = pixelFromUrl;
	Debug.write(CONSTANTS.CurrentPixel+" is the current pixel");
	if (pixelFromUrl == null) {
		Debug.write("Could not find pixel in url. Continue with pixel from cookie");
		Debug.write("pixel from cookie is "+pixelFromCookie.value);
	} else if (pixelFromUrl != pixelFromCookie.value) {
		Debug.write("Pixel in Cookie:"+pixelFromCookie.value+".");
		Debug.write("Pixel in Url:"+pixelFromUrl+".");
		Debug.write("Pixel in cookie is "+((pixelFromCookie.value == null) ? "empty" : "not the same as pixel from url"));
		cookieHandler.SetCookie("pixel", pixelFromUrl);
		Debug.write("Should send sync to other domains. Erasing domains list");
		Debug.write("current domains list:"+cookieHandler.GetCookie("ds").value);
		cookieHandler.SetCookie("ds", "");
		cookieHandler.saveHTMLCookie("ds", "");
		Debug.write("new domains list:"+cookieHandler.GetCookie("ds").value);
	}
	cookieHandler.SyncPixels(pixelFromUrl);
	Debug.groupend();
}
EventCollector.prototype.GetSerial = function GetSerial() {
	Debug.group("GetSerial");
	var serialFromCookie = cookieHandler.GetCookie("serial");
	var serialFromUrl = null;
	
	if (CONSTANTS.ForceSerialID != null) serialFromUrl = CONSTANTS.ForceSerialID;
	else {
		try {
			if (document.location.href.match(/^.*(&|\?)SID=([\d]*).*$/i))
				serialFromUrl = document.location.href.replace(/^.*(&|\?)SID=([\d]*).*$/i,"$2");
			else if (parent.document.location.href.match(/^.*(&|\?)SID=([\d]*).*$/i))
				serialFromUrl = parent.document.location.href.replace(/^.*(&|\?)SID=([\d]*).*$/i,"$2");
			else if (top.document.location.href.match(/^.*(&|\?)SID=([\d]*).*$/i))
				serialFromUrl = top.document.location.href.replace(/^.*(&|\?)SID=([\d]*).*$/i,"$2");
		} catch (e) {
			serialFromUrl = null;
		}
	}
	
	if (serialFromUrl == "") serialFromUrl = null;
	
	CONSTANTS.CurrentSerial = serialFromUrl;
	Debug.Trace(CONSTANTS.CurrentSerial, "serial");
	
	var serialChanged = CONSTANTS.CurrentSerial != null && CONSTANTS.CurrentSerial != serialFromCookie.value;
	
	if (serialFromCookie.value == null && serialFromUrl == null) {
		if (!CONSTANTS.SendAnonymous) throw {description:"Ignore event since SendAnonymous is off and serail is missing from both cookie and url"};
	} else if (serialFromUrl == null) {
		Debug.write("Could not find serial in url. Continue with serail from cookie");
		Debug.write("Sync serials...");
		Debug.Trace(serialFromCookie.value, "serial");
	} else if (serialFromUrl != serialFromCookie.value) {
		Debug.write("Serial in Cookie:"+serialFromCookie.value+".");
		Debug.write("Serial in Url:"+serialFromUrl+".");
		Debug.write("Serial in cookie is "+((serialFromCookie.value == null) ? "empty" : "not the same as serial from url"));
		cookieHandler.SetCookie("serial", serialFromUrl);
		cookieHandler.SetCookie("lu", new Date());
		cookieHandler.SetCookie("fad", DateTime.FormatDate(DateTime.Now()));
		Debug.write("Should send sync to other domains. Erasing domains list");
		Debug.write("current domains list:"+cookieHandler.GetCookie("ds").value);
		cookieHandler.SetCookie("ds", "");
		cookieHandler.saveHTMLCookie("ds", "");
		Debug.write("new domains list:"+cookieHandler.GetCookie("ds").value);
	}
	cookieHandler.SyncSerials(serialFromCookie.value);
	CONSTANTS.CurrentSerialID = (serialFromUrl == null) ? cookieHandler.backupCookies["serial"] : serialFromUrl;
	if (serialChanged) {
		if (CONSTANTS.CurrentPixel == null) {
			this.ResetPixel();
			cookieHandler.SyncPixels("");
		}
		if (CONSTANTS.CurrentDP == null) {
			this.ResetDP();
			cookieHandler.SyncDPs("");
		}
	}
	CONSTANTS.CurrentPixelID = (CONSTANTS.CurrentPixel == null) ? cookieHandler.backupCookies["pixel"] : CONSTANTS.CurrentPixel;
	CONSTANTS.CurrentDPID = (CONSTANTS.CurrentDP == null) ? cookieHandler.backupCookies["dp"] : CONSTANTS.CurrentDP;
	Debug.groupend();
}
EventCollector.prototype.GetGuid = function GetGuid() {
	Debug.group("GetGuid");
	var t = this;
	function callback(status) {
		try {
			if (status.errorCode == 0 && status.responseXML) {
				if (typeof(status.responseXML) == "undefined") throw {description:"XML is corrupted: "+status.ResponseText};
				guid = (status.responseXML.getElementsByTagName("GUID")[0].firstChild != null) ? status.responseXML.getElementsByTagName("GUID")[0].firstChild.nodeValue : "temp";
				cookieHandler.SetCookie("guid", guid);
				cookieHandler.SetCookie("lu", new Date());
				Debug.write("new guid: "+guid);
				cookieHandler.SyncGuid(guid);
			} else {
				// could not get guid from server, continue with temp guid
				Debug.write("Could not get guid from server "+status.reason);
				if (cookieHandler.GetCookie("guid").value == null) {
					cookieHandler.SetCookie("guid", "temp");
					cookieHandler.SetCookie("lu", new Date());
				}
			}
			t.fireEvent("onguidready");
		} catch (e) {
			// could not get guid from server, continue with temp guid
			Debug.write("Could not get guid from server: "+e.description);
			if (cookieHandler.GetCookie("guid").value == null) {
				cookieHandler.SetCookie("guid", "temp");
				cookieHandler.SetCookie("lu", new Date());
			}
			Debug.groupend();
			t.fireEvent("onguidready");
			// t.fireEvent("onjserror");
		}
	}
	var guid = cookieHandler.GetCookie("guid");
	if (guid.value == null || guid.value == "temp") {
		if (cookieHandler.flashEnabled) {
			Debug.write("Try to get guid from HTML cookie");
			var htmlguid = cookieHandler.backupCookies["guid"];
			if (htmlguid != null && typeof(htmlguid) != "undefined" && htmlguid != "" && htmlguid != "temp" && htmlguid != "N/A") {
				cookieHandler.SetCookie("guid", htmlguid);
				cookieHandler.SetCookie("lu", new Date());
				Debug.write("new guid (from HTML): "+htmlguid);
				cookieHandler.SyncQueue();
				cookieHandler.SyncSerial();
				
				Debug.groupend();
				this.fireEvent("onguidready");
				return;
			}
		}
		if (CONSTANTS.TEMP_GUID != "") {
			Debug.write("guid is empty. get it from wrapper temp guid: "+CONSTANTS.TEMP_GUID);
			guid = CONSTANTS.TEMP_GUID;
			cookieHandler.SetCookie("guid", guid);
			cookieHandler.SetCookie("lu", new Date());
			Debug.write("new guid: "+guid);
			cookieHandler.SyncGuid(guid);
			Debug.groupend();
			t.fireEvent("onguidready");		
		} else {
			Debug.write("guid is empty, try to get it from the server: "+CONSTANTS.ServerGuidUrl);
			Debug.write(CONSTANTS.ServerGuidUrl);
			Ajax.Request("GET", CONSTANTS.ServerGuidUrl, "", true, callback);
		}
	} else {
		Debug.write("guid already exists: "+guid.value);
		cookieHandler.SyncGuid(guid.value);
		Debug.groupend();
		this.fireEvent("onguidready");
	}
}
EventCollector.prototype.Init = function InitEventCollector() {
	var t = this;
	this.attachEvent("onjserror", function() {
		if (t.errorCallback) t.errorCallback();
	});
	this.attachEvent("onguidready", function() {
		// if we are here, start the process of sending the event
		MultiDomains.SyncDomains(cookieHandler.GetCookie("guid").value, cookieHandler.GetCookie("serial").value, cookieHandler.GetCookie("ds").value);
		
		Debug.write('ready to start the process');
		function callback() {
			//if (confirm()) debugger;
			t.fireEvent("ondone");
		}
		CONSTANTS.CurrentGuid = cookieHandler.GetCookie("guid").value;
		CONSTANTS.CurrentQueue = cookieHandler.GetCookie("queue").value;
		CONSTANTS.PropertyBag = cookieHandler.GetCookie("pb").value;
		
		if (!CONSTANTS.SendEvent) {
			callback();
			return;
		}

		function sp(pid, eid) {
			var isjs = pid.match(/^js_/i); 
			var obj = parent.document.createElement(isjs ? "script" : "iframe");
                        pid = pid.replace(/^js_/i,"");
			if (!isjs) {
				obj.width = "1";
				obj.height = "1";
				obj.frameBorder = "0";
				if (typeof(CONSTANTS.SupportedPTEvents[eid]) == "function") {
					if (typeof(obj.attachEvent) != "undefined") obj.attachEvent("onload", CONSTANTS.SupportedPTEvents[eid]);
					else obj.addEventListener("load", CONSTANTS.SupportedPTEvents[eid], true);
				}
			}
			obj.src = CONSTANTS.ServerPixelUrl+pid+"/"+eid+"."+(isjs?"js":"html")+"?creferer=UserGUID:"+CONSTANTS.CurrentGuid+";DP:"+CONSTANTS.CurrentDPID+";pixelid:"+CONSTANTS.CurrentPixelID+"&r="+Math.random()*100000+(CONSTANTS.SSLSupport ? "&sps=true" : "");
			parent.document.body.appendChild(obj);
		}
		// handle pixel
		try {
/*			if (CONSTANTS.SupportedPixelEvents[this.eventId.toLowerCase()] && CONSTANTS.CurrentPixelID != null && CONSTANTS.CurrentPixelID != "") {
				Debug.write("should send pixel ("+CONSTANTS.CurrentPixelID+") for "+this.eventId+" event");
				sp(CONSTANTS.CurrentPixelID, this.eventId.toLowerCase());
			}
*/
			var calceventid = "";

			if (CONSTANTS.SupportedPTEvents[this.eventId.toLowerCase()]) {
				sp("__playtech", this.eventId.toLowerCase());
			}
			if (this.sessionId != "") calceventid = ((this.sessionId.match(/f$/) != null) ? "flash" : "client")+this.eventId;
			if (CONSTANTS.SupportedPTEvents[calceventid.toLowerCase()]) {
				sp("__playtech", calceventid.toLowerCase());
			}

		} catch (e) {
			Debug.write("Error sending pixel: "+((typeof(e.description) == "undefined") ? e.message : e.description));
		}
		
 		cookieHandler.queue.HandleEvent(cookieHandler.GetCookie("guid").value,
																		t.clientId,
																		t.eventId,
																		cookieHandler.GetCookie("serial").value,
																		DateTime.FormatDate(DateTime.Now()),
																		cookieHandler.GetCookie("fad").value,
																		t.sessionId,
																		t.account,
																		t.amount,
																		callback);
	});
	// check flash compatibility
	cookieHandler = new CookieHandler();
	cookieHandler.attachEvent("oncookieloaded", function() {
		Debug.Trace("", "cookies");
		cookieHandler.queue = new Queue(cookieHandler.GetCookie("queue").value);
	});
	cookieHandler.attachEvent("oncookieloaded", function() {
		Debug.write(cookieHandler.PrintCookies());
		try {
			t.GetDP();
		} catch (e) {
			if (CONSTANTS.ShowErrors)	alert("(GP) "+e.description);
		}
		try {
			t.GetPixel();
		} catch (e) {
			if (CONSTANTS.ShowErrors)	alert("(GP) "+e.description);
		}
		try {
			t.GetSerial();
		} catch (e) {
			if (CONSTANTS.ShowErrors)	alert("(GS) "+e.description);
		}
		try {
			t.GetGuid();
		} catch (e) {
			if (CONSTANTS.ShowErrors)	alert("(GG) "+e.description);
		}
	});
	cookieHandler.attachEvent("onload", function() {
		if (this.flashError) {
			// html cookies were used already. Consider: synchronizing with Flash cookies
			Debug.write('Flash is finally loaded, sent already with HTML cookies so ignore and keep using the HTML cookies');
			// TODO: check for duplicate
		} else {
			Debug.write("Using Flash Cookies");
			// cancel interval
			window.clearInterval(t.cookieHandlerInterval);
			cookieHandler.flashEnabled = true;
			if (window.flash_object) cookieHandler.flashObject = window.document["flash_object"];
			if (document.flash_object) cookieHandler.flashObject = document.flash_object;
			// load cookies
			t.LoadCookies();
		}
	});
	cookieHandler.attachEvent("onerror", function() {
		this.flashError = true;
		window.clearInterval(t.cookieHandlerInterval);
		Debug.write("Using HTML Cookies");
		cookieHandler.flashEnabled = false;
		cookieHandler.flashObject = false;
		// load cookies
		t.LoadCookies();
	});
	this.cookieHandlerInterval = window.setTimeout(function() {
		cookieHandler.fireEvent("onerror");
	}, CONSTANTS.WaitForFlashPeriod);
	cookieHandler.Init();
}
EventCollector.prototype.LoadCookies = function LoadCookies() {
	Debug.write("reading cookies");
	cookieHandler.ReadCookies(new Array("guid", "serial", "fad", "queue", "lu", "ds", "pixel", "dp", "pb"));
}
// Event object
function Event() {
	var args = (arguments.length == 1) ? arguments[0].split(",") : arguments;
	this.uid = args[0];
	this.cid = args[1]
	this.eid = args[2];
	this.s = args[3];
	this.edate = args[4];
	this.fadate = args[5];
	this.usid = args[6];
	this.ua = args[7];
	this.ea = args[8];
}
Event.prototype.ToString = function EventToString(ignoreUid) {
	return ((!ignoreUid) ? this.uid : "temp")+","+((!ignoreUid) ? this.cid : "d")+","+this.eid+","+this.s+","+this.edate+","+((!ignoreUid) ? this.fadate : "d")+","+this.usid+","+this.ua+","+this.ea;
}
Event.prototype.FindReferrer = function EventFindReferrer() {
	try {
		this.referrer = parent.document.referrer;
		if (!this.referrer || this.referrer == "" || this.referrer+"" == "undefined") this.referrer = "";
	} catch (e) {
		this.referrer = document.referrer;
	}
	var referrerDomain = this.referrer.replace(/(http[s]*\:\/\/[^\/]*).*$/, "$1");
	this.referrerToSend = (document.location.href.indexOf(referrerDomain) == -1 || CONSTANTS.AlwaysSendReferrer) ? escape(this.referrer) : "";
	this.referrerFromSameDomain = document.location.href.indexOf(referrerDomain);
}
Event.prototype.ShouldSend = function EventShouldSend() {
	this.FindReferrer();
	if (this.referrerFromSameDomain == -1) {
		Debug.write("Referrer is from external domain ("+this.referrer+")");
	} else if (this.referrer == "") {
		Debug.write("Referrer was not specified");
	} else {
		Debug.write("Referrer is from the same domain.");
		if (CONSTANTS.ExternalReferrerOnly) return CONSTANTS.SAME_REFERRER;
		Debug.write("Send event anyway.");
	}
	if (this.uid == "temp" && (CONSTANTS.CurrentGuid == "temp" || CONSTANTS.CurrentGuid == "N/A") && !CONSTANTS.SendTemp) {
		return CONSTANTS.UID_IS_TEMP;
	} else {
		return CONSTANTS.OK;
	}
}
Event.prototype.ToUrl = function EventToUrl() {
	if (this.uid == "temp" && CONSTANTS.CurrentGuid != "temp" && CONSTANTS.CurrentGuid != "N/A") {
		Debug.write("uid is temp, replacing it with real uid: "+CONSTANTS.CurrentGuid);
		this.uid = CONSTANTS.CurrentGuid;
	} else if (this.uid == "temp") {
		Debug.write("uid is temp but no real uid exists. keep it with temp...");
	}
	if (this.cid == "d") this.cid = CONSTANTS.CurrentClientId;
	//return "uid="+this.uid+"&cid="+this.cid+"&eid="+this.eid+"&s="+this.s+"&edate="+this.edate+"&fadate="+this.fadate+"&cdate="+DateTime.FormatDate(DateTime.Now())+"&usid="+this.usid+"&ua="+this.ua+"&ea="+this.ea+"&r="+escape(referrer);
	return "uid="+this.uid+"&cid="+this.cid+"&eid="+this.eid+"&s="+this.s+"&edate="+this.edate+"&fadate="+this.edate+"&cdate="+DateTime.FormatDate(DateTime.Now())+"&usid="+this.usid+"&ua="+this.ua+"&ea="+this.ea+"&r="+escape(this.referrerToSend);
}

var WriteToQueue = false;

// Queue object
function Queue(events) {
	this.events = new Array();
	if (events != null) {
		var es = events.split("$");
		for (var i=0;i<es.length;i++) {
			if (es[i] != "") this.events[this.events.length] = new Event(es[i]);
		}
	}
}
Queue.prototype.Merge = function MergeQueue(queue) {
	if (queue) {
		var es = queue.split("$");
		for (var i=0;i<es.length;i++) {
			if (es[i] != "") this.events[this.events.length] = new Event(es[i]);
		}
	}
}
Queue.prototype.GetEvent = function GetEventFromQueue() {
	var event = this.events[0];
	return event;
}
Queue.prototype.HandleEvent = function QueueHandleEvent(uid, cid, eid, s, edate, fadate, usid, ua, ea, callback) {
	var t = this;
	this.callback = callback;
	this.events[this.events.length] = new Event(uid, cid, eid, s, edate, fadate, usid, ua, ea);
	// save data before processing events in queue
	cookieHandler.attachEvent("oncookiesave", function() {
		if (WriteToQueue) {
			t.callback();
			return;
		}
		function ajaxResponse(status) {
			try {
				if (status.errorCode == 0) {
					if (status.dummy || (status.responseXML.getElementsByTagName("status")[0].firstChild != null && status.responseXML.getElementsByTagName("status")[0].firstChild.nodeValue == "OK")) {
						for (var i=0;i<t.events.length-1;i++) t.events[i] = t.events[i+1];
						t.events.length -= 1;
						cookieHandler.SetCookie("queue", t.ToString(CONSTANTS.Greedy));
						cookieHandler.SaveCookies();
					} else {
						throw {description:((statusNode == null) ? "status is null" : statusNode.text)};
					}
				} else {
					throw {description:status.reason};
				}
			} catch (e) {
					Debug.write("Could not send event to server: "+e.description);
					Debug.Trace(eid, "endevent", {description:e.description, type:"error"});
					t.callback();
			}
		}
		Debug.write("Updated cookies:");
		Debug.write(cookieHandler.PrintCookies());
		if (t.events != "" && t.events.length> 0) {
			currEvent = t.GetEvent();
			var returnCode = currEvent.ShouldSend();
			if (returnCode == CONSTANTS.OK) {
				if (currEvent.eid == "DummyEvent" || currEvent.eid.match(/^__pq/)) {
					Debug.write("Dummy event. do not send");
					ajaxResponse({errorCode:0, dummy:true});
				} else {
					Debug.write("Should call server with the following parameters:\n");
					Debug.write(CONSTANTS.ServerRecieveUrl+"?"+currEvent.ToUrl()+"\n");
					Ajax.Request("GET", CONSTANTS.ServerRecieveUrl, currEvent.ToUrl(), true, ajaxResponse);
				}
			} else if (returnCode == CONSTANTS.UID_IS_TEMP) {
				Debug.write("uid is temp, do not send event");
				t.callback();
			} else {
				Debug.write("do not send event");
				ajaxResponse({errorCode:0, dummy:true});
			}
		} else {
			t.callback();
		}
	});
	cookieHandler.SetCookie("queue", this.ToString(CONSTANTS.Greedy));
	cookieHandler.SaveCookies();
}
Queue.prototype.ToString = function QueueToString(keepFirst) {
	var rs = "";
	for (var i=(keepFirst ? 0 : 1);i<this.events.length;i++) {
		rs += this.events[i].ToString(true)+"$";
	}
	return rs;
}
// Cookie object
function CookieHandler() {
	this.flashEnabled = false;
	this.flashObject = false;
	this.cookies = new Array();
	this.GetCookie = function(name) {
		for (var i=0;i<this.cookies.length;i++) {
			if (this.cookies[i].name == name) return this.cookies[i];
		}
		this.cookies[this.cookies.length] = {name:name, value:null};
		return this.cookies[this.cookies.length-1];
	}
	this.SetCookie = function(name, value) {
		for (var i=0;i<this.cookies.length;i++) {
			if (this.cookies[i].name == name) {
				this.cookies[i].value = value;
				return;
			}
		}
		this.cookies[this.cookies.length] = {name:name, value:value};
	}
	this.InitCookieHandling();
}
CookieHandler.prototype.Init = function InitCookieHandler() {
	if (CONSTANTS.FlashEnabled && flashSupported()) {
		if (__flashLoaded) {
			this.fireEvent("onload");
		}	else {
			CreateMandatoryObjects();
			var object = '<OBJECT '+((!is_pc_ie) ? 'style="visibility:hidden;"' : '')+'style="width:100px; height:100px;" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http' + (CONSTANTS.SSLSupport ? 's' : '') + '://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0"  WIDTH="300" HEIGHT="250" id="flash_object" ALIGN="">'+
										'<PARAM NAME=movie VALUE="'+CONSTANTS.FlashMovie+'"> <PARAM NAME=quality VALUE=high> <PARAM NAME=bgcolor VALUE=#006633> <EMBED swliveconnect="true" src="'+CONSTANTS.FlashMovie+'" quality=high bgcolor=#006633  WIDTH="300" HEIGHT="250" NAME="flash_object" ALIGN="" TYPE="application/x-shockwave-flash" PLUGINSPAGE="http' + (CONSTANTS.SSLSupport ? 's' : '') + '://www.macromedia.com/go/getflashplayer"></EMBED>'+
										'</OBJECT>';
			var form1 = getObject("emerpec","flashPlaceholder");
			form1.innerHTML = object;
		}
	} else {
		Debug.write("Flash is not installed. Use HTML");
		this.fireEvent("onerror");
	}
}
CookieHandler.prototype.DeleteHTMLCookies = function DeleteBackupCookies(cookies) {
		for (var i=0;i<cookies.length;i++) {
			this.deleteHTMLCookie(cookies[i]);
		}
}
CookieHandler.prototype.DeleteCookies = function DeleteCookies(cookies, html) {
	if (html) {
		for (var i=0;i<cookies.length;i++) {
			this.deleteHTMLCookie(cookies[i]);
		}
	}
	if (this.flashEnabled) {
		this.cookiesInQueue = cookies;
		this.DeleteNextCookieFromQueue();
	} else {
		for (var i=0;i<cookies.length;i++) {
			this.deleteHTMLCookie(cookies[i]);
		}
		for (var i=0;i<this.cookies.length;i++) this.cookies[i].value = null;
	}
}
CookieHandler.prototype.DeleteNextCookieFromQueue = function DeleteNextCookieFromQueue(name) {
	if (name) {
		this.cookiesInQueue.length -= 1;
		this.SetCookie(name, null);
	}
	if (this.cookiesInQueue.length > 0) this.deleteFlashCookie(this.cookiesInQueue[this.cookiesInQueue.length-1]);
	else this.fireEvent("oncookiedelete");
}
CookieHandler.prototype.SaveCookies = function SaveCookies() {
	if (this.flashEnabled) {
		for (var i=0;i<this.cookies.length;i++) this.cookiesInQueue[i] = this.cookies[i];
		this.SaveNextCookieFromQueue();
	} else {
		for (var i=0;i<this.cookies.length;i++) {
			this.saveHTMLCookie(this.cookies[i].name, this.cookies[i].value);
		}
		this.fireEvent("oncookiesave");
	}
}
CookieHandler.prototype.SaveCookiesEverywhere = function(cookiesToSave) {
	this.cookiesInQueue = new Array();
	if (this.flashEnabled) {
		for (var i=0;i<this.cookies.length;i++) {
			if (cookiesToSave[this.cookies[i].name]) this.cookiesInQueue.push(this.cookies[i]);
		}
		this.SaveNextCookieFromQueue();
	}
	for (var i=0;i<this.cookies.length;i++) {
		if (cookiesToSave[this.cookies[i].name]) this.saveHTMLCookie(this.cookies[i].name, this.cookies[i].value);
	}
	if (!this.flashEnabled) this.fireEvent("oncookiesave");
}
CookieHandler.prototype.SaveNextCookieFromQueue = function SaveNextCookieFromQueue(name) {
	if (typeof(this.cookiesInQueue) != "undefined" && this.cookiesInQueue.length > 0) {
		if (name) this.cookiesInQueue.length -= 1;
		if (this.cookiesInQueue.length > 0) this.saveFlashCookie(this.cookiesInQueue[this.cookiesInQueue.length-1].name, this.cookiesInQueue[this.cookiesInQueue.length-1].value);
		else this.fireEvent("oncookiesave");
	}
}
CookieHandler.prototype.SyncQueue = function SyncQueue() {
	var htmlqueue = cookieHandler.backupCookies["queue"];
	if (htmlqueue != null) {
		Debug.write("add htmlqueue to flash queue");
		this.queue.Merge(htmlqueue);
		cookieHandler.deleteHTMLCookie("queue");
	} else Debug.write("htmlqueue is null");
	
	this.SyncDomains();
}
CookieHandler.prototype.SyncDomains = function SyncDomains() {
	Debug.write("Syncing domains...");
	var htmlDomains = cookieHandler.backupCookies["ds"];
	var flashDomains = 	cookieHandler.GetCookie("ds").value;
	var hDomains = (htmlDomains != null) ? htmlDomains.split(",") : new Array();
	var fDomains = (flashDomains != null) ? flashDomains.split(",") : new Array();
	for (var i=0;i<hDomains.length;i++) {
		var found = false;
		for (a=0;a<fDomains.length;a++) {
			if (fDomains[a] == hDomains[i]) {
				found = true;
				break;
			}
		}
		if (!found) fDomains.push(hDomains[i]);
	}
	Debug.write("new domain list: "+fDomains.join(","));
	
	cookieHandler.saveHTMLCookie("ds", fDomains.join(","));
	cookieHandler.SetCookie("ds", fDomains.join(","));
}
CookieHandler.prototype.SyncSerial = function SyncSerial() {
	cookieHandler.saveHTMLCookie("serial", CONSTANTS.CurrentSerial);
}
CookieHandler.prototype.SyncDPs = function SyncDPs(dp) {
		var htmldp = cookieHandler.backupCookies["dp"];
		var flashdp = this.flashEnabled ? cookieHandler.FindCookie("dp") : null;
		
		if (dp != null) {
			cookieHandler.saveHTMLCookie("dp", dp);
			if (this.flashEnabled) cookieHandler.SetCookie("dp", dp);
		} else {
			if (dp == null) dp = flashdp != null ? flashdp : htmldp;
			if (dp == null) return;
			if (typeof(htmldp) == "undefined" || htmldp == null || htmldp == "") cookieHandler.saveHTMLCookie("dp", dp);
			if (this.flashEnabled && (typeof(flashdp) == "undefined" || flashdp == null || flashdp == "")) cookieHandler.SetCookie("dp", dp);
		}
}
CookieHandler.prototype.SyncPixels = function SyncPixels(pixel) {
		var htmlpixel = cookieHandler.backupCookies["pixel"];
		var flashpixel = this.flashEnabled ? cookieHandler.FindCookie("pixel") : null;
		
		if (pixel != null) {
			cookieHandler.saveHTMLCookie("pixel", pixel);
			if (this.flashEnabled) cookieHandler.SetCookie("pixel", pixel);
		} else {
			if (pixel == null) pixel = flashpixel != null ? flashpixel : htmlpixel;
			if (pixel == null) return;
			if (typeof(htmlpixel) == "undefined" || htmlpixel == null || htmlpixel == "") cookieHandler.saveHTMLCookie("pixel", pixel);
			if (this.flashEnabled && (typeof(flashpixel) == "undefined" || flashpixel == null || flashpixel == "")) cookieHandler.SetCookie("pixel", pixel);
		}
}
CookieHandler.prototype.SyncSerials = function SyncSerials(serial) {
	if (this.flashEnabled) {
		// make sure serial (and pixel) in flash is the same as in html
		var htmlserial = cookieHandler.backupCookies["serial"];
		var htmlpixel = cookieHandler.backupCookies["pixel"];
		var flashpixel = cookieHandler.FindCookie("pixel");
		if (htmlserial != null && typeof(htmlserial) != "undefined") {
			if (htmlserial == serial) {
				Debug.write("Serial in html and flash the same.");
			} else {
				Debug.write("Flash serial:"+serial);
				Debug.write("HTML serial:"+htmlserial);
				Debug.write("Serial in html is not as in flash.");
				Debug.write("HTML last updated:"+cookieHandler.backupCookies["lu"]);
				Debug.write("Flash last updated:"+cookieHandler.FindCookie("lu"));
				
				var flu = cookieHandler.FindCookie("lu");
				var hlu = cookieHandler.backupCookies["lu"];
				if (new Date(hlu) > new Date(flu)) {
					Debug.write("HTML cookie is newer, use serial from html");
					cookieHandler.SetCookie("serial", htmlserial);
					cookieHandler.SetCookie("lu", new Date());
					Debug.write("use pixel from html as well");
					cookieHandler.SetCookie("pixel", htmlpixel);
				} else {
					Debug.write("Flash cookie is newer, use serial from flash");
					cookieHandler.saveHTMLCookie("serial", serial);
					cookieHandler.saveHTMLCookie("lu", new Date());
					Debug.write("use pixel from flash as well");
					cookieHandler.saveHTMLCookie("pixel", flashpixel);
				}
			}
		} else {
			Debug.write("Serial in html is empty. set serial from flash");
			cookieHandler.saveHTMLCookie("serial", serial);
			cookieHandler.saveHTMLCookie("lu", new Date());
			Debug.write("use pixel from flash as well");
			cookieHandler.saveHTMLCookie("pixel", flashpixel);
		}
	}
	Debug.Trace("", "cookies");
}
CookieHandler.prototype.SyncGuid = function SyncGuid(guid) {
	Debug.write("in syncGUID:"+guid);
	if (this.flashEnabled) {
		// make sure guid in flash is the same as in html
		this.SyncQueue();
		Debug.write("after syncQueue");
	
		var htmlguid = cookieHandler.backupCookies["guid"];
		if (htmlguid != null && typeof(htmlguid) != "undefined" && htmlguid != "" && htmlguid != "temp" && htmlguid != "N/A") {
			if (htmlguid == guid) {
				Debug.write("Guid in html and flash the same.");
				//cookieHandler.saveHTMLCookie("serial", CONSTANTS.CurrentSerial);
			} else {
				Debug.write("Flash guid:"+guid);
				Debug.write("HTML guid:"+htmlguid);
				Debug.write("Guid in html is not as in flash. send duplicate command to server");
				Debug.write("HTML last updated:"+cookieHandler.backupCookies["lu"]);
				Debug.write("Flash last updated:"+cookieHandler.FindCookie("lu"));
				var flu = cookieHandler.FindCookie("lu");
				var hlu = cookieHandler.backupCookies["lu"];
				var fserial = cookieHandler.FindCookie("serial");
				var hserial = cookieHandler.backupCookies["serial"];
				if (new Date(cookieHandler.backupCookies["lu"]) > new Date(cookieHandler.FindCookie("lu"))) {
					Debug.write("Flash cookie is older, use flash uid");
					cookieHandler.saveHTMLCookie("guid", guid);
					cookieHandler.saveHTMLCookie("lu", new Date());
					if (CONSTANTS.CurrentSerial != null) {
						Debug.write("Set serial from url");
						cookieHandler.saveHTMLCookie("serial", cookieHandler.FindCookie("serial"));
					} else if (cookieHandler.backupCookies["serial"] != null && typeof(cookieHandler.backupCookies["serial"]) != "undefined") {
						Debug.write("Set serial from html cookie");
						cookieHandler.SetCookie("serial", cookieHandler.backupCookies["serial"]);
					}
				} else {
					Debug.write("HTML cookie is older, use html uid");
					cookieHandler.SetCookie("guid", htmlguid);
					cookieHandler.SetCookie("lu", new Date());
					if (cookieHandler.FindCookie("serial") != null) {
						Debug.write("Set serial from flash cookie");
						cookieHandler.saveHTMLCookie("serial", cookieHandler.FindCookie("serial"));
					}
				}
				Debug.write("Sending duplicate command:\n"+CONSTANTS.ServerDuplicateUrl+"?fguid="+guid+"&hguid="+htmlguid+"&fserial="+fserial+"&hserial="+hserial+"&flu="+flu+"&hlu="+hlu);
				Ajax.Request("GET", CONSTANTS.ServerDuplicateUrl, "fguid="+guid+"&hguid="+htmlguid+"&fserial="+fserial+"&hserial="+hserial+"&flu="+flu+"&hlu="+hlu, true);
			}
		} else {
			Debug.write("Guid in html is empty. set guid from flash.");
			cookieHandler.saveHTMLCookie("guid", guid);
			cookieHandler.saveHTMLCookie("serial", cookieHandler.FindCookie("serial"));
			cookieHandler.saveHTMLCookie("lu", new Date());
		}
	}
}
CookieHandler.prototype.FindCookie = function FindCookie(cookieName) {
	for (var i=0;i<this.cookies.length;i++) if (this.cookies[i].name == cookieName) return this.cookies[i].value;
	return null;
}
CookieHandler.prototype.ReadCookies = function ReadCookies(cookies) {
	this.cookies = new Array();
	// read cookies from HTML
	this.backupCookies = new Array();
	for (var i=0;i<cookies.length;i++) {
		this.backupCookies[cookies[i]] = this.readHTMLCookie(cookies[i]);
	}
	if (this.flashEnabled) {
		this.cookiesInQueue = cookies;
		this.GetNextCookieFromQueue();
	} else {
		for (var i=0;i<cookies.length;i++) {
			this.cookies[this.cookies.length] = {name:cookies[i], value:this.readHTMLCookie(cookies[i])};
		}
		this.fireEvent("oncookieloaded");
	}
}
CookieHandler.prototype.AppendCookieValue = function AppendCookieValue(name, value) {
	var cookie = this.GetCookie(name);
	if (cookie.value != null) this.SetCookie(name, cookie.value+value);
	else this.SetCookie(name, value);
}
CookieHandler.prototype.GetNextCookieFromQueue = function GetNextCookieFromQueue(name, value) {
	if (name) this.cookies[this.cookies.length] = {name:name, value:(value != "null") ? value : null};
	if (this.cookies.length < this.cookiesInQueue.length) this.readFlashCookie(this.cookiesInQueue[this.cookies.length]);
	else cookieHandler.fireEvent("oncookieloaded");
}
CookieHandler.prototype.FixCookieDates = function FixCookieDates(diff) {
	function fixDate(cookie) {
		if (cookie.value != null && cookie.value.match(/^_/)) {
			var newValue = DateTime.Fix(cookie.value, diff);
			Debug.write("original value: "+cookie.value);
			Debug.write("new value: "+newValue);
			return newValue;
		} else return cookie.value;
	}
	this.SetCookie("fad", fixDate(this.GetCookie("fad")));
}
// Cookie handling
CookieHandler.prototype.InitCookieHandling = function() {
	this.saveHTMLCookie = function saveHTMLCookie(name, value) {
		var date = new Date();
		date.setTime(date.getTime()+(1000*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
		document.cookie = name+"="+value+expires+"; path=/"+((CONSTANTS.Domain != "") ? ";domain="+CONSTANTS.Domain : "");
		this.backupCookies[name] = value;
	}
	this.readHTMLCookie = function readHTMLCookie(name) {
		name += "=";
		var cookieArr = document.cookie.split(';');
		for (var i=0;i<cookieArr.length;i++) {
			var c = cookieArr[i];
			while (c.substring(0,1) == ' ') c = c.substring(1, c.length)
			if (c.indexOf(name) == 0) return (c.substring(name.length, c.length) != "null") ? c.substring(name.length, c.length) : null;
		}
		return null
	}
	this.deleteHTMLCookie = function deleteHTMLCookie(name) {
		this.saveHTMLCookie(name, null);
	}
	this.saveFlashCookie = function saveFlashCookie(name, value) {
		if (value == null) setFlashCoockieReturn(name, true);
		else {
			if (CONSTANTS.FLASH8) {
				this.flashObject.saveCookie(name, value+"");
				setFlashCoockieReturn(name, true);
			} else {
				if (is_pc_ie) {
					this.flashObject.SetVariable("operation", "set");
					this.flashObject.SetVariable("cookieName", name);
					this.flashObject.SetVariable("cookieValue", value);
				} else {
					var form1 = getObject("emerpec","flashPlaceholder");
					var object = '<OBJECT '+((!is_pc_ie) ? 'style="visibility:hidden;"' : '')+'style="width:100px; height:100px;" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http' + (CONSTANTS.SSLSupport ? 's' : '') + '://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0"  WIDTH="300" HEIGHT="250" id="flash_object" ALIGN="">'+
													'<PARAM NAME=movie VALUE="'+CONSTANTS.FlashMovie+'"> <PARAM NAME=quality VALUE=high> <PARAM NAME=bgcolor VALUE=#006633> <EMBED swliveconnect="true" src="'+CONSTANTS.FlashMovie+'" quality=high bgcolor=#006633  WIDTH="300" HEIGHT="250" NAME="flash_object" ALIGN="" TYPE="application/x-shockwave-flash" PLUGINSPAGE="http' + (CONSTANTS.SSLSupport ? 's' : '') + '://www.macromedia.com/go/getflashplayer" FlashVars="operation=set&cookieName='+name+'&cookieValue='+value+'"></EMBED>'+
													'</OBJECT>';
					form1.innerHTML = object;
				}
			}
		}
	}
	this.readFlashCookie = function readFlashCookie(name) {
		if (CONSTANTS.FLASH8) {
			var returnValue = this.flashObject.readCookie(name);
			readFlashCoockieReturn(name, returnValue, 1, 1);
		} else {
			if (is_pc_ie) {
				this.flashObject.SetVariable("operation", "read");
				this.flashObject.SetVariable("cookieName", name);
			} else {
				var form1 = getObject("emerpec","flashPlaceholder");
				var object = '<OBJECT '+((!is_pc_ie) ? 'style="visibility:hidden;"' : '')+'style="width:100px; height:100px;" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http' + (CONSTANTS.SSLSupport ? 's' : '') + '://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0"  WIDTH="300" HEIGHT="250" id="flash_object" ALIGN="">'+
												'<PARAM NAME=movie VALUE="'+CONSTANTS.FlashMovie+'"> <PARAM NAME=quality VALUE=high> <PARAM NAME=bgcolor VALUE=#006633> <EMBED swliveconnect="true" src="'+CONSTANTS.FlashMovie+'" quality=high bgcolor=#006633  WIDTH="300" HEIGHT="250" NAME="flash_object" ALIGN="" TYPE="application/x-shockwave-flash" PLUGINSPAGE="http' + (CONSTANTS.SSLSupport ? 's' : '') + '://www.macromedia.com/go/getflashplayer" FlashVars="operation=read&cookieName='+name+'"></EMBED>'+
												'</OBJECT>';
				form1.innerHTML = object;
			}
		}
	}
	this.deleteFlashCookie = function deleteFlashCookie(name) {
		if (CONSTANTS.FLASH8) {
			this.flashObject.deleteCookie(name);
			deleteFlashCoockieReturn(name, true);
		} else {
			if (is_pc_ie) {
				this.flashObject.SetVariable("operation", "delete");
				this.flashObject.SetVariable("cookieName", name);
			} else {
				var form1 = getObject("emerpec","flashPlaceholder");
				var object = '<OBJECT '+((!is_pc_ie) ? 'style="visibility:hidden;"' : '')+'style="width:100px; height:100px;" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http' + (CONSTANTS.SSLSupport ? 's' : '') + '://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0"  WIDTH="300" HEIGHT="250" id="flash_object" ALIGN="">'+
												'<PARAM NAME=movie VALUE="'+CONSTANTS.FlashMovie+'"> <PARAM NAME=quality VALUE=high> <PARAM NAME=bgcolor VALUE=#006633> <EMBED swliveconnect="true" src="'+CONSTANTS.FlashMovie+'" quality=high bgcolor=#006633  WIDTH="300" HEIGHT="250" NAME="flash_object" ALIGN="" TYPE="application/x-shockwave-flash" PLUGINSPAGE="http' + (CONSTANTS.SSLSupport ? 's' : '') + '://www.macromedia.com/go/getflashplayer" FlashVars="operation=delete&cookieName='+name+'"></EMBED>'+
												'</OBJECT>';
				form1.innerHTML = object;
			}
		}
	}
}
// Dispose
CookieHandler.prototype.Dispose = function CookieHandlerDispose() {
	this.detachEvents();
}
EventCollector.prototype.Dispose = function CookieHandlerDispose() {
	this.detachEvents();
}
// called from flash object onload
function flashLoaded() {
	if (__flashLoaded==false) {
		__flashLoaded = true;
		cookieHandler.fireEvent("onload");
	}
}
function readFlashCoockieReturn(name, value, totalPackets, packetNumber){
	if (totalPackets == 1) cookieHandler.GetNextCookieFromQueue(name, value);
	else {
		Debug.write("name:"+name+"\nvalue:"+value+"\ntotal:"+totalPackets+"\npacket:"+packetNumber);
		cookieHandler.AppendCookieValue(name, value);
		if (totalPackets == packetNumber) cookieHandler.GetNextCookieFromQueue();
	}
}
function setFlashCoockieReturn(name, result) {
	cookieHandler.SaveNextCookieFromQueue(name);
}
function deleteFlashCoockieReturn(name, result) {
	cookieHandler.DeleteNextCookieFromQueue(name);
}
var Ajax = {
	getTransport: function() {
		var transports = new Array( function() { return new XMLHttpRequest(); },
									function() { return new ActiveXObject("Microsoft.XMLHTTP"); });
		for (var i=0;i<transports.length;i++) {
			try {
				var x = transports[i]();
				return x;
			} catch (e) {
			}
		}
		return false;
	}
}
Ajax.transports = new Array();
Ajax.transport = Ajax.getTransport();
Ajax.createTransport = function() {
//	for (var i=this.transports.length-1;i>=0;i--) {
//		if (this.transports[i].readyState == 4) return this.transports[i];
//	}
	var position = this.transports.length;
	this.transports[position] = Ajax.getTransport();
	return this.transports[position];
}
Ajax.Request = function AjaxRequest(method, url, parameters, async, callback) {
	this.callback = callback;
	if (method == "GET") url += "?"+parameters+"&random="+Math.random()*100000;
	var transport = this.createTransport();
	try {
		transport.open(method, url, async);
	} catch (e) {
		if (this.callback) this.callback({errorCode:-1, reason:e});
		return;
	}
	if (async) transport.onreadystatechange = function() { Ajax.HandleOnreadystatechange(transport); };
	else this.HandleResponse(transport);
	if (method == "POST") transport.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	transport.send((method == "POST") ? parameters+"&random="+Math.random()*100000 : "");
}
Ajax.HandleOnreadystatechange = function(transport) {
	if (transport.readyState == 4) {
		Ajax.HandleResponse(transport);
	}
}
Ajax.HandleResponse = function(transport) {
	var status = {errorCode:0, reason:""};
	if (transport.status != 200) {
		status.errorCode = "-1"
		status.reason = transport.status+" - "+transport.statusText;
	}
	status.ResponseText = transport.responseText;
	if (transport.responseXML && transport.responseXML.xml != "") status.responseXML = transport.responseXML;
	if (this.callback) this.callback(status);
}
Ajax.Dispose = function() {
}
function XMLObject(xml) {
	this.type = typeof(xml);
	this.xml = xml;
}
XMLObject.prototype.GetNode = function(nodeName) {
	if (this.type == "string") {
		var re = new RegExp("^[^$]*<"+nodeName+">([^<]*)<\/"+nodeName+">[^$]*$", "i");
		var value = this.xml.replace(re, "$1");
		if (value == this.xml) return null;
		else return {text:value}
	} else {
		return this.xml.selectSingleNode(".//"+nodeName);
	}
}
// DateTime
var DateTime = {
	Now: function() { return new Date(); },
	Diff: function(a, b) {
		if (typeof(a) == "string") a = this.ParseDate(a);
		if (typeof(b) == "string") b = this.ParseDate(b);
		return (a-b)/1000;
	},
	ParseDate: function(value) {
		var deval = "new Date("+value.replace(/^([\d]{4})-([\d]{2})-([\d]{2}) ([\d]{2}):([\d]{2}):([\d]{2})[^$]*/,
																					function(a,yyyy,MM,dd,hh,mm,ss) {
																						return yyyy+","+eval(parseInt(MM,10)-1)+","+dd+","+hh+","+mm+","+ss;
																					})+")";
		return eval(deval);
	},
	FormatDate: function(value) {
		function lpad(v) {
			v = v+"";
			if (v.length == 1) return "0"+v;
			else return v;
		}
		return DateTime.FixYear(value.getYear())+"-"+lpad(eval(value.getMonth()+1))+"-"+lpad(value.getDate())+" "+lpad(value.getHours())+":"+lpad(value.getMinutes())+":"+lpad(value.getSeconds());
	},
	FixYear: function(value) {
		return (value < 1000) ? 1900+value : value;
	},
	Fix: function(value, diff) {
		if (typeof(value) == "string") value = this.ParseDate(value);
		value.setSeconds(value.getSeconds()+diff);
		return this.FormatDate(value);
	}
}
// Debug methods
CookieHandler.prototype.PrintCookies = function PrintCookies() {
	var rs = "";
	for (var i=0;i<this.cookies.length;i++) {
		rs += this.cookies[i].name+":"+this.cookies[i].value+"\n";
	}
	return rs;
}
CookieHandler.prototype.PrintBackupCookies = function PrintBackupCookies() {
	var rs = "";
	for (var i in this.backupCookies) {
		rs += i+":"+this.backupCookies[i]+"\n";
	}
	return rs;
}
var Debug = {
	messages: new Array(),
	group: function(value) {
		if (CONSTANTS.cookies.match(/__o=true/) && typeof(console) != "undefined") {
			console.group(value);
		}
	},
	groupend: function() {
		if (CONSTANTS.cookies.match(/__o=true/) && typeof(console) != "undefined") {
			console.groupEnd();
		}
	},
	write: function(value) {
		if (CONSTANTS.cookies.match(/__o=true/) && typeof(console) != "undefined") {
			if (value.match(/^\*/)) console.warn(value);
			else console.info(value);
		}
		if (document.getElementById("debugDiv"))	document.getElementById("debugDiv").innerHTML = value+"<br>"+document.getElementById("debugDiv").innerHTML;
		this.messages[this.messages.length] = value;
		this.Trace(value, "message");
	},
	print: function(output, linebreak) {
		var rs = "";
		for (var i=0;i<this.messages.length;i++) rs += this.messages[i]+"\n";
		if (output) {
			return rs.replace(/\n/g, linebreak);
		} else alert(rs);
	},
	Dispose: function() {
		this.messages = new Array();
	},
	Serial: null, 
	Events: new Array(),
	Pixels: new Array(),
	Requests: new Array(),
	Responses: new Array(),
	Trace: function(value, type) {
		switch (type) {
			case "event":
				this.Events[this.Events.length] = {d:new Date(), v:value, s:"In Progress"};
				break;
			case "endevent":
				for (var i=0;i<this.Events.length;i++) {
					var currentEvent = this.Events[i].v.replace(/^\?/,"");
					if (currentEvent == value && this.Events[i].s == "In Progress") {
						if (arguments[2]) this.Events[i].s = arguments[2].description;
						else this.Events[i].s = "Done";
						break;
					}
				}
				break;
			case "request":
				this.Requests[this.Requests.length] = {d:new Date(), v:value};
				break;
			case "response":
				this.Responses[this.Responses.length] = {d:new Date(), v:value};
				break;
			case "queue":
				this.Queue = value;
				break;
			case "serial":
				this.Serial = value;
				break;
			case "pixel":
				this.Pixels[this.Pixels.length] = {url:value, event:arguments[2]};
				break;
		}
		if (this.debugWindow) {
			this.debugWindow.RefreshData(type, value);
		}
	},
	ShowDebugWindow:function() {
		window.debug = this;
		window.opener = window;
		if (is_pc_ie) this.debugWindow = window.showModelessDialog("/core/EMERPECp/DebugWindow.html", {opener:self, debug:this}, "dialogHeight:500px; dialogWidth:600px; status:no; help:no;");
		else this.debugWindow = window.open("/core/EMERPECp/DebugWindow.html", "debugWindow", "width=700, height=600");
	}
}
// Event handling
CookieHandler.prototype.attachEvent = function(event, handler, source){
	if(!this.__events) this.__events = {}
	if(!this.__events[event]) this.__events[event] = []
	this.__events[event][this.__events[event].length] = {fp:handler,s:source}
}
CookieHandler.prototype.detachEvent = function(event, handler, source){
	if(this.__events && this.__events[event]){
		var o = this.__events[event];
		for(var i=0; i<o.length; i++){
			if (o[i]) {
				if((o[i].s && o[i].s==source) || !o[i].s){
					try {
						if(o[i].fp.toString() == handler.toString()) {
							delete o[i];
						}
					} catch (e) {
					}
				}
			}
		}
	}
}
CookieHandler.prototype.detachEvents = function() {
	this.__events = false;
}
CookieHandler.prototype.fireEvent = function(event){
	var a = arguments;
	if(this.__events && this.__events[event]){
		var o = this.__events[event]
		for(var i=0; i<o.length; i++){
			if(o[i]){
				if(o[i].s){
					o[i].s.__eventhandler = o[i].fp;
					o[i].s.__eventhandler(a[1],a[2],a[3],a[4],a[5],a[6],a[7],a[8],a[9],a[10]);
					delete o[i].s.__eventhandler;
				}
				else{
					this.__eventhandler = o[i].fp;
					this.__eventhandler(a[1],a[2],a[3],a[4],a[5],a[6],a[7],a[8],a[9],a[10]);
					delete this.__eventhandler;
				}
			}
		}
	}
	if(typeof(this[event])=="function"){
		window.setTimeout(function() { this[event](a[1],a[2],a[3],a[4],a[5],a[6],a[7],a[8],a[9],a[10]) }, 1);
	}
}
EventCollector.prototype.attachEvent = function(event, handler, source){
	if(!this.__events) this.__events = {}
	if(!this.__events[event]) this.__events[event] = []
	this.__events[event][this.__events[event].length] = {fp:handler,s:source}
}
EventCollector.prototype.detachEvent = function(event, handler, source){
	if(this.__events && this.__events[event]){
		var o = this.__events[event];
		for(var i=0; i<o.length; i++){
			if (o[i]) {
				if((o[i].s && o[i].s==source) || !o[i].s){
					try {
						if(o[i].fp.toString() == handler.toString()) {
							delete o[i];
						}
					} catch (e) {
					}
				}
			}
		}
	}
}
EventCollector.prototype.detachEvents = function() {
	this.__events.length = 0;
}
EventCollector.prototype.fireEvent = function(event){
	var a = arguments;
	if(this.__events && this.__events[event]){
		var o = this.__events[event];
		for(var i=0; i<o.length; i++){
			if(o[i]){
				if(o[i].s){
					o[i].s.__eventhandler = o[i].fp;
					o[i].s.__eventhandler(a[1],a[2],a[3],a[4],a[5],a[6],a[7],a[8],a[9],a[10]);
					delete o[i].s.__eventhandler;
				}
				else{
					this.__eventhandler = o[i].fp;
					this.__eventhandler(a[1],a[2],a[3],a[4],a[5],a[6],a[7],a[8],a[9],a[10]);
					delete this.__eventhandler;
				}
			}
		}
	}
	if(typeof(this[event])=="function"){
		window.setTimeout(function() { this[event](a[1],a[2],a[3],a[4],a[5],a[6],a[7],a[8],a[9],a[10]) }, 1);
	}
}
function getObject(frame, objectId) {
	if (document.getElementById(objectId)) return document.getElementById(objectId);
	else {
		try {
			if (document.all) {
				if (frame != "") {
					if (parent.document.frames[frame] && praent.document.frames[frame].document.getElementById(objectId)) return parent.document.frames[frame].document.getElementById(objectId);
					else return false;
				} else {
					if (document.getElementById(objectId)) return document.getElementById(objectId);
					else return false;
				}
			} else {
				if (frame != "") {
					if (parent.frames[frame].document.getElementById(objectId)) return parent.frames[frame].document.getElementById(objectId);
					else return false;
				} else {
					if (document.getElementById(objectId)) return document.getElementById(objectId);
					else return false;
				}
			}
		} catch (e) {
			return false;
		}
		return false;
		if(frame==""){
			if(parent.document.getElementById && parent.document.getElementById(objectId))
				return document.getElementById(objectId); // W3C DOM
			else if (parent.document.all && parent.document.all(objectId))
				return parent.document.all(objectId); // MSIE 4 DOM
			else return false;
		}
		else{
			if(top[frame].document.getElementById && top[frame].document.getElementById(objectId))
				return top[frame].document.getElementById(objectId); // W3C DOM
			else if (top[frame].document.all && top[frame].document.all(objectId))
				return top[frame].document.all(objectId); // MSIE 4 DOM
			else return false;
		}
	}
}
function savepropertybag() {
	cookieHandler.saveFlashCookie("pb", CONSTANTS.PropertyBag);
	cookieHandler.saveHTMLCookie("pb", CONSTANTS.PropertyBag);
}
function findproperty(name) {
}
function SetProperty(name, value) {
	var properties = GetPropertyBag();
	var re = new RegExp("\\\$"+name+"=[^\\\$]*[\\\$]?", "g");
	if (properties == null) properties = "";
	properties = properties.replace(re, "$");
	properties += ((!properties.match(/\$$/)) ? "$" : "")+name+"="+value+"$";
	SetPropertyBag(properties);
}
function GetProperty(name) {
	var properties = GetPropertyBag();
	var re = new RegExp("\\\$"+name+"=([^\\\$]*)", "");
	if (properties == null) properties = "";
	var match = properties.match(re, "");
	if (match != null) return match[1];
	else return "";
}
function DeleteProperty(name) {
	var properties = GetPropertyBag();
	var re = new RegExp("\\\$"+name+"=[^\\\$]*[\$]?", "g");
	if (properties == null) properties = "";
	properties = properties.replace(re, "");
	SetPropertyBag(properties);
}
function GetPropertyBag() {
	return CONSTANTS.PropertyBag;
}
function SetPropertyBag(value) {
	CONSTANTS.PropertyBag = value;
	savepropertybag();
}
function SetSerialID(id) {
	Debug.group("SetSerialID");
	if (id == GetSerialID()) return;
	Debug.write("new SID should be "+id);
	CONSTANTS.ForceSerialID = id;
	SendEvent("DummyEvent");
	Debug.groupend();
}
function GetUserID() {
	return ( CONSTANTS.CurrentGuid === '' ? CONSTANTS.TEMP_GUID : CONSTANTS.CurrentGuid );
}
function GetQueue() {
	return CONSTANTS.CurrentQueue;
}
function GetSerialID() {
	return CONSTANTS.CurrentSerialID;
	// return CONSTANTS.CurrentSerial;
}
function GetPixelID() {
	return CONSTANTS.CurrentPixelID;
}
function GetDPID() {
	return CONSTANTS.CurrentDPID;
}
/**************************************************************************/
/* Common                                                                 */
/**************************************************************************/
function callback() {
	var debug1 = getObject("emerpec","debugTextarea");
	debug1.value = Debug.print(true, "\n");
	//window.status = "Ready...";
	if (typeof(initEventCallback) != "undefined") initEventCallback();
}
function errorcallback() {
	try {
		var debug1 = getObject("emerpec","debugTextarea");
		debug1.value = Debug.print(true, "\n");
		//window.status = "Error...";
	} catch (e) {
	}
	if (typeof(initEventCallback) != "undefined") initEventCallback();
}
function InitEvents(eventName, eventAccount, eventAmount) {
	Event.prototype.debug = function(value) {
		if (document.getElementById("debugTextarea")) document.getElementById("debugTextarea").value = document.getElementById("debugTextarea").value+"\n"+value;
	}
	CONSTANTS.FlashEnabled = true;
	var amount, account
	amount = CONSTANTS.amount;
	account = CONSTANTS.account;
	if (arguments.length > 1) account = eventAccount;
	if (arguments.length > 2) amount = eventAmount;
	SendEvent(CONSTANTS.clientId, (eventName) ? eventName : "HpHit", CONSTANTS.sessionId, account, amount, callback, errorcallback);
}
document.onkeydown = function(e) {
	if (e) {
		if (navigator.userAgent.match(/Safari/i)) {
			if (e.ctrlKey && e.shiftKey && e.keyCode == 13) Debug.ShowDebugWindow();
		} else if (e.ctrlKey && e.shiftKey) {
			Debug.ShowDebugWindow();
//			document.getElementById("debugDiv").style.display = "";
//			document.getElementById("debugTextarea").style.display = "";
		}
	} else {
		if (event.ctrlKey && event.shiftKey && event.keyCode == 13) {
			Debug.ShowDebugWindow();
//			document.getElementById("debugDiv").style.display = "";
//			document.getElementById("debugTextarea").style.display = "";
		}
	}
}
var MultiDomains = {}
MultiDomains.SyncDomains = function(guid, serial, domains) {
	this.domains = (domains == null) ? new Array() : domains.split(",");
	Debug.write("take care of multiple domains with guid: "+guid+", and serial: "+serial);
	Debug.write("domains in my list: "+domains);
	for (var i=0;i<CONSTANTS.DOMAINS.length;i++) {
		if (!MultiDomains.IsCurrentDomain(CONSTANTS.DOMAINS[i].domain)) {
			if (MultiDomains.DoesNotExist(CONSTANTS.DOMAINS[i].id)) {
				Debug.write("should send guid to "+CONSTANTS.DOMAINS[i].domain+" :"+CONSTANTS.DOMAINS[i].url);
				MultiDomains.DoSync(CONSTANTS.DOMAINS[i].id, CONSTANTS.DOMAINS[i].url, guid, serial);
			} else Debug.write("no need to send sync for this domain ("+CONSTANTS.DOMAINS[i].domain+") - already in list");
		}
	}
}
MultiDomains.IsCurrentDomain = function(name) {
		return (document.domain == name);
}
MultiDomains.DoesNotExist = function(id) {
	for (var i=0;i<this.domains.length;i++) {
		if (this.domains[i] == id) return false;
	}
	return true;
}
MultiDomains.DoSync = function(did, url, guid, serial) {
	Debug.write("DoSync for "+url);
	var iframe = document.body.appendChild(document.createElement("iframe"));
	var t = this;
	if (document.all) {
		iframe.onreadystatechange = function() {
			if (iframe.readyState == "complete") {
				t.domains.push(did);
				Debug.write("domains list:"+t.domains.join(","));
				// todo: uncomment to save domain in list
				cookieHandler.SetCookie("ds", t.domains.join(","));
				cookieHandler.SaveCookies();
				cookieHandler.saveHTMLCookie("ds", t.domains.join(","));
			}
		}
	} else {
		iframe.onload = function() {
			t.domains.push(did);
			Debug.write("domains list:"+t.domains.join(","));
			// todo: uncomment to save domain in list
			cookieHandler.SetCookie("ds", t.domains.join(","));
			cookieHandler.SaveCookies();
			cookieHandler.saveHTMLCookie("ds", t.domains.join(","));
		}
	}
	iframe.src = url.replace(/\[guid\]/g, guid).replace(/\[serial\]/g, serial);
	Debug.write("iframe src:"+iframe.src);
//	document.body.appendChild(iframe);
}
/******************************************************/
/* debug functions                                    */
/******************************************************/
Queue.prototype.draw = function() {
	var tr = document.createElement("tr");
	for (var i=0;i<p.length;i++) {
		var td = document.createElement("td");
		tr.appendChild(td);
		td.innerText = p[i];
		td.style.fontWeight = "bold";
	}
	queueBody.appendChild(tr);
	for (var i=0;i<this.events.length;i++) {
		var tr = document.createElement("tr");
		for (var x=0;x<p.length;x++) {
			var td = document.createElement("td");
			if (this.events[i][p[x]]) td.innerText = this.events[i][p[x]];
			else td.innerText = " ";
			tr.appendChild(td);
		}
		queueBody.appendChild(tr);
	}
}
function showQueue() {
	if (!debugMode) return;
	for (var i=document.all["queueBody"].children.length-1;i>=0;i--) {
		document.all["queueBody"].children(i).removeNode(true);
	}
	var queue = new Queue();
	queue.draw();
}
function forceGuid(guid) {
	for (var i=0;i<CONSTANTS.DOMAINS.length;i++) {
		if (!MultiDomains.IsCurrentDomain(CONSTANTS.DOMAINS[i].domain)) {
			Debug.write("DoSync for "+CONSTANTS.DOMAINS[i].url);
			var iframe = document.body.appendChild(document.createElement("iframe"));
			iframe.width = "1";
			iframe.height = "1";
			iframe.src = CONSTANTS.DOMAINS[i].url.replace(/\[guid\]/g, guid).replace(/\[serial\]/g, "");
			Debug.write("iframe src:"+iframe.src);
		}
	}
	function forceGuidCallback() {
		cookieHandler = null;
		init();
	}
	cookieHandler = new CookieHandler();
	cookieHandler.attachEvent("oncookieloaded", function() {
		var currentGuid = cookieHandler.FindCookie("guid");
		if (currentGuid == null || currentGuid == "null" || currentGuid != guid) {
			Debug.write("save new guid");
			cookieHandler.SetCookie("guid", guid);
			cookieHandler.SetCookie("lu", new Date());
			
			cookieHandler.SaveCookiesEverywhere({guid:true, lu:true, ds:false, serial:false});
			if (currentGuid != null) {
				Debug.write("should send duplicate");
				Ajax.Request("GET", CONSTANTS.ServerDuplicateUrl, "fguid="+guid+"&sguid="+currentGuid, true, null);
			}
		}
		forceGuidCallback();
	});
	cookieHandler.attachEvent("onerror", function() {
		cookieHandler.ReadCookies(new Array("guid", "serial", "fad", "queue", "lu", "ds", "pixel", "dp", "pb"));
	});
	cookieHandler.attachEvent("onload", function() {
		window.clearInterval(cookieHandlerInterval);
		cookieHandler.flashEnabled = true;
		if (window.flash_object) cookieHandler.flashObject = window.document["flash_object"];
		if (document.flash_object) cookieHandler.flashObject = document.flash_object;
		// load cookies
		cookieHandler.ReadCookies(new Array("guid", "serial", "fad", "queue", "lu", "ds", "pixel", "dp", "pb"));
	});
	var cookieHandlerInterval = window.setTimeout(function() {
		cookieHandler.fireEvent("onerror");
	}, CONSTANTS.WaitForFlashPeriod);
	cookieHandler.Init();
}
function syncDomains() {
	try {
		var parameters = parent.document.location.search.substr(1).split("&");
		function getParam(name) {
			for (var i=0;i<parameters.length;i++) {
				var pair = parameters[i].split("=");
				if (pair[0] == name) return pair[1];
			}
			return "";
		}
		
		var guid = getParam("guid");
		var serial = getParam("serial");
		cookieHandler = new CookieHandler();
		cookieHandler.attachEvent("oncookieloaded", function() {
			var currentGuid = cookieHandler.FindCookie("guid");
			var currentSerial = cookieHandler.FindCookie("serial");
			
			var changed = false;
			if (serial != "undefined") {
				Debug.write("save new serial");
				cookieHandler.SetCookie("serial", serial);
				cookieHandler.SetCookie("lu", new Date());
				changed = true;
			}
			if (currentGuid == null || currentGuid == "null" || currentGuid != guid) {
				Debug.write("save new guid");
				cookieHandler.SetCookie("guid", guid);
				cookieHandler.SetCookie("lu", new Date());
				changed = true;
			}	
			if (changed) {
				var domains = new Array();
				for (var i=0;i<CONSTANTS.DOMAINS.length;i++) {
					if (!MultiDomains.IsCurrentDomain(CONSTANTS.DOMAINS[i].domain)) {
						domains.push(CONSTANTS.DOMAINS[i].id);
					}
				}
				cookieHandler.SetCookie("ds", domains.join(","));
				cookieHandler.SaveCookiesEverywhere({guid:true, lu:true, ds:true, serial:(typeof(serial) != "undefined" && serial != "undefined") ? true : false});
			}
			if (currentGuid != null && currentGuid != "null" && currentGuid != guid) {
				Debug.write("should send duplicate");
				Ajax.Request("GET", CONSTANTS.ServerDuplicateUrl, "fguid="+guid+"&sguid="+currentGuid+"&fserial="+serial+"&sserial="+currentSerial, true);
			}
		});
		cookieHandler.attachEvent("onerror", function() {
			cookieHandler.ReadCookies(new Array("guid", "serial", "fad", "queue", "lu", "ds", "pixel", "dp", "pb"));
		});
		cookieHandler.attachEvent("onload", function() {
			window.clearInterval(cookieHandlerInterval);
			cookieHandler.flashEnabled = true;
			if (window.flash_object) cookieHandler.flashObject = window.document["flash_object"];
			if (document.flash_object) cookieHandler.flashObject = document.flash_object;
	
			// load cookies
			cookieHandler.ReadCookies(new Array("guid", "serial", "fad", "queue", "lu", "ds", "pixel", "dp", "pb"));
		});
		var cookieHandlerInterval = window.setTimeout(function() {
			cookieHandler.fireEvent("onerror");
		}, CONSTANTS.WaitForFlashPeriod);
	
		cookieHandler.Init();
	} catch (err) {
		alert(err.message);
	}
}
function stop() {
	cookieHandler = new CookieHandler();
	cookieHandler.attachEvent("onerror", function() {
		cookieHandler.flashEnabled = false;
		cookieHandler.ReadCookies(new Array("guid", "serial", "fad", "queue", "lu", "ds", "pixel", "dp", "pb"));
	});
	cookieHandler.attachEvent("onload", function() {
		// load cookies
		window.clearInterval(cookieHandlerInterval);
		if (__flashLoaded) {
			cookieHandler.flashEnabled = true;
			//cookieHandler.flashObject = document.getElementById("flash_object");
			if (window.flash_object) cookieHandler.flashObject = window.document["flash_object"];
			if (document.flash_object) cookieHandler.flashObject = document.flash_object;
		}
		
		cookieHandler.ReadCookies(new Array("guid", "serial", "fad", "queue", "lu", "ds", "pixel", "dp", "pb"));
	});
	cookieHandler.attachEvent("oncookieloaded", function() {
			if (parent[Page.callback]) parent[Page.callback](self);
			else top[Page.callback](self);
	});
	var cookieHandlerInterval = window.setTimeout(function() {
		cookieHandler.fireEvent("onerror");
	}, CONSTANTS.WaitForFlashPeriod);
	cookieHandler.Init();
}
function clearCookie() {
	cookieHandler = new CookieHandler();
	cookieHandler.attachEvent("oncookiedelete", function() {
		alert('Done!');
	});
	cookieHandler.attachEvent("oncookieloaded", function() {
		if (confirm("Are you sure you want to delete "+((CONSTANTS.FlashEnabled) ? "flash" : "html")+" cookies:\n"+cookieHandler.PrintCookies())) {
			cookieHandler.DeleteCookies(new Array("guid", "serial", "fad", "queue", "lu", "ds", "pixel", "dp", "pb"), ((CONSTANTS.FlashEnabled) ? confirm("Delete HTML cookies as well?") : true));
		}
	});
	cookieHandler.attachEvent("onerror", function() {
		cookieHandler.ReadCookies(new Array("guid", "serial", "fad", "queue", "lu", "ds", "pixel", "dp", "pb"));
	});
	cookieHandler.attachEvent("onload", function() {
		cookieHandler.flashEnabled = true;
		//cookieHandler.flashObject = document.getElementById("flash_object");
		if (window.flash_object) cookieHandler.flashObject = window.document["flash_object"];
		if (document.flash_object) cookieHandler.flashObject = document.flash_object;
		// load cookies
		cookieHandler.ReadCookies(new Array("guid", "serial", "fad", "queue", "lu", "ds", "pixel", "dp", "pb"));
	});
	cookieHandler.Init();
}
function flashSupported() {
	if (document.all) {
		try {
			var f = eval("new ActiveXObject('ShockwaveFlash.ShockwaveFlash.6');");
			if (f) return true;
			else return false;
		} catch (e) {
			return false;
		}
	} else {
		if (navigator.plugins && navigator.plugins.length) {
			for (var i=0;i<navigator.plugins.length;i++) {
				if (navigator.plugins[i].name.match(/Shockwave Flash/i)) {
					var version = navigator.plugins[i].description.replace(/^Shockwave Flash ([0-9]*).*$/, "$1");
					if (version == navigator.plugins[i].description) return false;
					else if (parseInt(version, 10) >= 6) return true;
					else return false;
				}
			}
		}
		return navigator.plugins;
	}
}
var alreadyran = false;
function init() {
	if (alreadyran) return;
	else alreadyran = true;
	try {
		if (top.document && (typeof(top.document.onkeydown) == "undefined" || top.document.onkeydown == null)) {
			top.document.onkeydown = function(e) {
				if (e) {
					if (e.ctrlKey && e.shiftKey && e.keyCode == 13) {
						if (top.document.getElementById("emerpec")) {
							Debug.ShowDebugWindow();
						}
					}
				} else {
					if (top.event.ctrlKey && top.event.shiftKey && top.event.keyCode == 13) {
						if (top.document.getElementById("emerpec")) {
							Debug.ShowDebugWindow();
						}
					}
				}
			}
		}
	} catch (e) {
		try {
			if (parent.document && (typeof(parent.document.onkeydown) == "undefined" || parent.document.onkeydown == null)) {
				parent.document.onkeydown = function(e) {
					if (e) {
						if (e.ctrlKey && e.shiftKey && e.keyCode == 13) {
							if (parent.document.getElementById("emerpec")) {
								Debug.ShowDebugWindow();
							}
						}
					} else {
						if (parent.event.ctrlKey && parent.event.shiftKey && parent.event.keyCode == 13) {
							if (parent.document.getElementById("emerpec")) {
								Debug.ShowDebugWindow();
							}
						}
					}
				}
			}
		} catch (e) {
		}
	}	
	Debug.write("Flash in use:"+(CONSTANTS.FLASH8 ? "Flash 8+" : "Flash 6-"));
	
	var eventName = Page.eventName;
	var clientId = Page.clientId;
	var sessionId = Page.sessionId;
	var account = Page.account;
	var amount = Page.amount;
	var callback = Page.callback;
	var errorCallback = Page.errorCallback;
	var tempGuid = Page.tempGuid;
	var userGuid = Page.userGuid;
	
	CONSTANTS.TEMP_GUID = tempGuid;
	CONSTANTS.USER_GUID = userGuid;
	
	Debug.write("In "+CONSTANTS.MODE+" mode!");
	Debug.write("Version:"+CONSTANTS.Version);
	CONSTANTS.ExternalReferrerOnly = (Page.externalRefOnly == "true") ? true : CONSTANTS.ExternalReferrerOnly;
	Debug.write("CONSTANTS.ExternalReferrerOnly:"+CONSTANTS.ExternalReferrerOnly);
	
	if (!clientId || clientId  == '') clientId = CONSTANTS.clientId;
	if (!sessionId || sessionId == '') sessionId = CONSTANTS.sessionId;
	if (callback != "") {
try {
		if (parent[callback]) CONSTANTS.OnSuccessCallback = parent[callback];
		else if (top[callback]) CONSTANTS.OnSuccessCallback = top[callback];
		else Debug.write("callback "+callback+" does not exist");
} catch (e) { }
	}
	if (errorCallback != "") {
		if (parent[errorCallback]) CONSTANTS.OnFailedCallback = parent[errorCallback];
		else if (top[errorCallback]) CONSTANTS.OnFailedCallback = top[errorCallback];
		else Debug.write("errorCallback "+errorCallback+" does not exist");
	}
	if (eventName == "NoDummy") return;
	else if (eventName != "" && clientId == "" && sessionId == "" && account == "" && amount == "") SendEvent(eventName);
	else if (eventName != "" && clientId != "" && sessionId == "" && account == "" && amount == "") SendEvent(clientId, eventName);
	else if (eventName != "" && clientId != "" && sessionId != "" && account == "" && amount == "") SendEvent(clientId, eventName, sessionId);
	else if (eventName != "" && clientId != "" && sessionId != "" && account != "" && amount == "") SendEvent(clientId, eventName, sessionId, account);
	else if (eventName != "" && clientId != "" && sessionId != "" && account != "" && amount != "") SendEvent(clientId, eventName, sessionId, account, amount);
	else SendEvent("DummyEvent");
}
//init();


