
var MAXDEPTH = 10;
var WATCH = {
	"scroll" : false,
	"mousemove" : false,
	"click" : true
};
var CONTROL = String.fromCharCode(255);
var CHECKINTERVAL = 1000 * 5; 

// M - Movement
// C - Click
// A - Click with link
// S - Scroll

var cCurrentEvent = ''; 
var aEventQueue = [];
var oLastEvent = {};

var iStartTime = new Date().getTime();
var oTimer;
var sGotoLink = "";

var iScrollCount = 0;
var iMouseMoveCount = 0;

window.addEvent('domready', function() 
{
	if (!RECORD) {
		WATCH.click = false;
	}
	
	if (WATCH.scroll) {
		window.onscroll = function(event) { 
			if (iScrollCount % 10 === 0) {
				scrollHandler(event);
			}
		};
		/*window.addEvent('scroll', function(event){
			iScrollCount++;
			if (iScrollCount % 5 == 0) {
				//scrollHandler(event);
				alert(document.body.scrollTop);
			}
		});*/
	}
	if (WATCH.mousemove) {
		window.addEvent('mousemove', function(event){
			iMouseMoveCount++;
			if (iMouseMoveCount % 5 === 0) {
				moveHandler(event);
			}
		});
	}
	if (WATCH.click) {
		document.addEvent('click', clickHandler);
	}
	
	// Page Type -> Upload
	/*if (SOURCE == 1) { 
		updateContent();
		updateLinks();
	}*/
		
	//oTimer = window.setTimeout( queueCheck, CHECKINTERVAL );
});

function queueCheck()
{
	//console.log("Check Queue");
	if (aEventQueue.length) queueSend();
	oTimer = window.setTimeout( queueCheck, CHECKINTERVAL )
}

function queueSend()
{
	var sPacket = aEventQueue.join("|"); //encodeURIComponent( 
	//console.log("Check Send", aEventQueue, sPacket, encodeURIComponent(sPacket ));
	
	if ($('external_js')) $('external_js').dispose(); 
	
	var oScriptTag = document.createElement("script");
	oScriptTag.type = "text/JavaScript";
	oScriptTag.id = "external_js";
	oScriptTag.src = BASEURL + 'visitor/record/' + sPacket; //encodeURIComponent(
	
	var oBody = document.getElementsByTagName("body").item(0);
	oBody.appendChild(oScriptTag);
	
	/*var oRequest = new Request( {
		url: BASEURL + 'visitor/record', 
		method: 'post',
		onSuccess: queueSendComplete,
		onFailure: queueSendComplete
	} ).send( "d=" + encodeURIComponent(sPacket) );*/
	
	window.setTimeout( queueSendComplete, 200 );
	
	aEventQueue = [];
	oLastEvent = {};
}

function queueSendComplete(o)
{
	if (sGotoLink) {
		location.href = sGotoLink;
	}
}

function queueEvent( oEvent ) 
{	
	var iCurrentTime = new Date().getTime();
	var iElasped = Math.round( (iCurrentTime - iStartTime) / 100 ); // div by 10 for seconds. max 1.8hrs
	iStartTime = iCurrentTime;
	//console.log(oEvent, Math.round( iElasped / 1 ));
	
	//if (iElasped > 16777216) { } // issue new start time
	
	/*var sBytes = "";
	if (oEvent.code != oLastEvent.code) {
		sBytes = CONTROL + oEvent.code;
	}
	oLastEvent = oEvent;*/
	var aFields = [	iElasped, oEvent.x, oEvent.y ];
	if (oEvent.e) {
		aFields.push(oEvent.e);
	} else {
		aFields.push(0);
	}
	aFields.push(PAGEID);
	aFields.push(VISITORID);
	aEventQueue.push(aFields.join("x"));	
	
	// Compile
	/*sBytes += bytesToString( getBytes( iElasped, 4 ) );
	sBytes += bytesToString( getBytes( oEvent.x, 2 ) );
	sBytes += bytesToString( getBytes( oEvent.y, 2 ) );
	if (oEvent.code == 'A' && oEvent.e) {
		sBytes += bytesToString(getBytes(oEvent.e, 2));
	}
	aEventQueue.push(sBytes);*/
	
	queueSend();
	
	//if (oEvent.code=='A') queueCheck();
}

function scrollHandler(event)
{
	queueEvent({
		code : 'S',
		x : ( event.page.x - event.client.x ),
		y : ( event.page.y - event.client.y )
	});
}

function moveHandler(event)
{
	queueEvent({
		code : 'M',
		x : event.page.x,
		y : event.page.y
	});
}

function clickHandler(event) 
{
	sGotoLink = "";
	var oElement = getClickedElement(event.target);
	if (oElement) {
		var elementID = oElement.id.replace("elementcontent_", "");
		sGotoLink = oElement.parentNode.href;
		event.stop();
		event.stopPropagation();
		event.preventDefault();
	}	
	queueEvent({
		code : (elementID) ? 'A' : 'C',
		x : event.page.x,
		y : event.page.y,
		e : elementID
	});
}

	
function getClickedElement(oTarget)
{
	var elementID = false;
	//if body or #pagewrap skip checking...
	if (oTarget.tagName != "body" && oTarget.id != "pagewrap") 
	{		
		// backup to find the DIV with ".elementcontent"
		var oParent = oTarget;			
		for(i = 0; i < MAXDEPTH; i++) {
			if (oParent.className == "elementcontent") {
				//elementID = oParent.id.replace("elementcontent_", "");
				return oParent;
				//return elementID;
			}
			if (oParent.parentNode) {
				oParent = oParent.parentNode;
			} else {
				return false;
			}
		}		
	}
	return false;
}
		
				
function updateContent() {
	// Update to absolute links	
	// <style href, <script src, <img src, <object, <embed
	if (typeof(HTMLCODE) != "undefined") {
		return false;
	}
	
	var aTypes = [
		"STYLE:href",
		"SCRIPT:src",
		"IMG:src",
		"OBJECT:src",
		"EMBED:src",
		"PARAM:value"
	];
	var iTypesLength = aTypes.length;
	for(var i = 0; i < iTypesLength; i++) {
		var aType = aTypes[ i ].split(":");
		var oElements = document.getElementsByTagName( aType[0] );
		var iElementCount = oElements.length;
		for (var j = 0; j < iElementCount; j++) { 
			var oElement = oElements[ j ];
			var sField = aType[1];
			if (oElement.id.indexOf("skip") === 0) {
				continue;
			}
			var sFilename = oElement[ sField ];
			if (sFilename) {			
				if (sFilename.indexOf("http://") === 0) {
					// Strip absolute URL
					sFilename = sFilename.substr(sFilename.lastIndexOf("/")+1); //lastIndexOf
				}
				oElement[ sField ] = BASEURL + 'cdn/' + PAGEID + '/' + sFilename;
			}
		}
	}
}

function updateLinks() {
	var oElements = document.getElementsByTagName( "A" );
	var iElementCount = oElements.length;
	for (var j = 0; j < iElementCount; j++) {
		var oElement = oElements[ j ];
		if (oElement.href.indexOf("#buy") != -1) {
			oElement.href = BASEURL + 'payment/details/' + PAGEID;
		}
	}
}


function getBytes( x, len ) {
	var bytes = [];
	var i = len;
	do {
		bytes[--i] = x & (255);
		x = x >> 8;
	} while ( i );
	return bytes;
}

function getNum( bytes, len ) { 
	var intTotal = 0;
	for (i=0; i<len; i++) { 
		intTotal += bytes[i] << ((len-1-i)*8);
	}
	return parseInt(intTotal);
}

function bytesToString( bytes ) {
	chars = new Array;
	for (i=0; i<bytes.length; i++) {
		chars[i] = String.fromCharCode( bytes[i] );
	}
	return chars.join("");
}

function stringToBytes( bytestring ) {
	bytes = new Array;
	for (i=0; i<bytestring.length; i++) {
		bytes[i] = bytestring.charCodeAt( i );
	}
	return bytes;
}


