/*
	(c) Brock Judkins 2006
	brockjudkins (at) gmail.com
*/

wc_sessionID="";
wc_computerID="";
wc_dataGroupID="";

var wc_errlogger = "http://dml.cs.byu.edu/webcol/err.php";

// Log errors instead of displaying them in the browser
//self.onerror = function (errmsg, errurl, errline) {
	//raiseError(errmsg,errurl,errline);
//return true;
//}

/**************************************************************************
 Error handling functions
**************************************************************************/

function wc_handleError (errmsg, errurl, errline) {

	if (!errurl) errurl = 'no url';
	if (!errline) errline = 'no line';


	// the error didn't come from this script, pass it along
	if (errurl.indexOf('webcol.js') == -1){
		return false;
	}

	var URL = wc_errlogger + "?" + "errmsg=" + escape(errmsg) +
		"&" + "line=" + errline +
		"&" + "agent=" + escape(navigator.userAgent) +
		"&" + "userid=" + wc_sessionID + // TODO: include both IDs
		"&" + "url=" + escape(errurl);
		
	var imgette = document.createElement("img");
	imgette.style.visibility = 'hidden';
	imgette.setAttribute("src", URL);

	// returning true tells the browser that this
	// error has been handled, no need for the browser
	// to whine about it
	return true;
}

// Log errors instead of displaying them in the browser
// I don't think that this handles syntax errors, however
self.onerror = wc_handleError;






/**************************************************************************
 Cookie helper functions
**************************************************************************/


function wc_createCookie(name,value,days)
{
	if (days)
	{
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+
		"; path=/; domain=" + wc_getBaseDomain ();
}

function wc_readCookie(name) 
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++)
	{
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function wc_eraseCookie(name)
{
	createCookie(name,"",-1);
}

//*** This code is copyright 2003 by Gavin Kistner, gavin@refinery.com
//*** It is covered under the license viewable at http://phrogz.net/JS/_ReuseLicense.txt
//*** Reuse or modification is free provided you abide by the terms of that license.
//*** (Including the first two lines above in your source code satisfies the conditions.)


//***Cross browser attach event function. For 'evt' pass a string value with the leading "on" omitted
//***e.g. AttachEvent(window,'load',MyFunctionNameWithoutParenthesis,false);

function AttachEvent(obj,evt,fnc,useCapture){
	if (!useCapture) useCapture=false;
	if (obj.addEventListener){
		obj.addEventListener(evt,fnc,useCapture);
		return true;
	} else if (obj.attachEvent) return obj.attachEvent("on"+evt,fnc);
	else{
		MyAttachEvent(obj,evt,fnc);
		obj['on'+evt]=function(){ MyFireEvent(obj,evt) };
	}
} 

//The following are for browsers like NS4 or IE5Mac which don't support either
//attachEvent or addEventListener
function MyAttachEvent(obj,evt,fnc){
	if (!obj.myEvents) obj.myEvents={};
	if (!obj.myEvents[evt]) obj.myEvents[evt]=[];
	var evts = obj.myEvents[evt];
	evts[evts.length]=fnc;
}
function MyFireEvent(obj,evt){
	if (!obj || !obj.myEvents || !obj.myEvents[evt]) return;
	var evts = obj.myEvents[evt];
	for (var i=0,len=evts.length;i<len;i++) evts[i]();
}

/**************************************************************************
 Webcol Constants
**************************************************************************/
var wc_sessionCookieName = "sessionid";
var wc_computerCookieName = "computerid";
var wc_collectURL = "http://dml.cs.byu.edu/webcol/col.php";

/**************************************************************************
 Main functions
**************************************************************************/

// figures out the what domain we should set our
// cookie for, which basically means chop off
// the www from the domain name if it's there
function wc_getBaseDomain (){

	var re = /(https{0,1}:\/\/){0,1}([\w\.]+)/ig;
	var url = document.URL;
									
	var match = re.exec(url);
	if (match){

		// beginning of URL minus the http stuff
		var domain = match[2];

		// split domain into array by the dots/periods
		var toks = domain.split(".");

		var firstTok = 0;

		//chop off the www from domains
		if (toks[0] == "www") {
			var baseDomain = "";
			var i;
			for (i=1; i<toks.length; i++)
				baseDomain += "." + toks[i];
			return baseDomain;
		}

		return domain;

	}

	return null;
}

function wc_getRandomID (idLen){
	
	if (idLen==null)
		idLen = 20;

	var id = "";

	var i;
	for (i = 0; i < idLen; i++) {
		var c = Math.floor(Math.random()*62);
		if (c >= 36)
			c += 61; // capitals
		else if (c >= 10)
			c += 55; // lowercase
		else
			c += 48; // numeric

		id += String.fromCharCode(c);
	}
	
	return id;
}

function wc_getIDFromCookie (cookieName, days){
	// Get the cookie id from the browser's saved cookies
	var cookieID = wc_readCookie(cookieName);

	// Set the cookie if it's not there
	if (cookieID == null){
		wc_createCookie(cookieName, wc_getRandomID(20), days);
		cookieID = wc_readCookie(cookieName);
	}

	return cookieID;
}

function wc_sendInfo (dataArray) {
	var flatData = dataArray.join("&");
	var URL = wc_collectURL + "?" + flatData;
	
	var imgette = document.createElement("img");
	imgette.style.visibility = 'hidden';
	imgette.setAttribute("src", URL);


	if (URL.length>2000)
		wc_handleError("wc_sendInfo trying to send a URL too long! (" + URL.length + ")", "webcol.js");
}



function wc_parseDocument () {
	
	if (!wc_sessionID)
		return;

	// start a data package
	var sendMe = new Array ();
	sendMe[sendMe.length] = ("dg=" + wc_dataGroupID);
	sendMe[sendMe.length] = ("sessionid=" + wc_sessionID);
	sendMe[sendMe.length] = ("computerid=" + wc_computerID);

	// get the HTML body
	var html = document.getElementsByTagName("body")[0].innerHTML;
	var allHtml = document.getElementsByTagName("html")[0].innerHTML;

	// some of the main regexes
	var re_cartInfo = /Your Cart: ([0-9]+) Items{0,1}, Total \$([0-9]+\.[0-9]{2})/ig;
	var re_cartID = /Cart #([0-9]+)/ig;
	var re_itemNum = /Item\s*\w*\s*#([0-9\-\w]+)/ig;
	

	var itemStrings = html.match(re_itemNum);



	if (itemStrings != null){

	  var len = itemStrings.length;
	  var nums = new Array ();
	  
	  var re_itemNum2 = /#([0-9\-\w]*)/ig;

	  for (i=0; i<len; i++) {

	    var numMatches = itemStrings[i].match(re_itemNum2);
	    if (numMatches != null) { //should always be true
	      nums[nums.length] = (numMatches[0].substr(1)); //last match should be num
	    }
	  }
	  if (nums.length>0) {
	    sendMe[sendMe.length] =("itemnums=" + escape(nums.join(",")));
	  }
	}

	// record the cart id
	/*
	var match = re_cartID.exec(allHtml);
	if (match != null) {
		var cartID = match[1];
		sendMe[sendMe.length] = "cartid=" + cartID;
	}
	*/

	// return first matches  along with info in capturing parens
	var cartMatches = re_cartInfo.exec(html);
	if (cartMatches != null){
	  var cartCount = cartMatches[1];
	  var cartTotal = cartMatches[2] * 100;
	  sendMe[sendMe.length] = ("ccount=" + cartCount);



	  sendMe[sendMe.length] = ("ctot=" + cartTotal);
	}
	
	// send this if there is anything to send
	if (sendMe.length > 2) {
	  wc_sendInfo (sendMe);
	}
}





// init the collection system
function webcol(cartID) {
	
	

	wc_sessionID = wc_getIDFromCookie (wc_sessionCookieName);
	wc_computerID = wc_getIDFromCookie (wc_computerCookieName, 36500); // expires in 100 years

	wc_dataGroupID = wc_getRandomID (10);
	

	// wc_parseDocument() will run when the page is done loading
	AttachEvent(window,'load',wc_parseDocument,false);


	if (wc_sessionID != null){

		var sendMe = new Array ();
		sendMe[sendMe.length] = ("dg=" + wc_dataGroupID);
		sendMe[sendMe.length] = ("sessionid=" + wc_sessionID);
		sendMe[sendMe.length] = ("computerid=" + wc_computerID);
		sendMe[sendMe.length] = ("cartid=" + cartID);
		sendMe[sendMe.length] = ("agent=" + escape(navigator.userAgent));
		sendMe[sendMe.length] = ("ref=" + escape(document.referrer));
		sendMe[sendMe.length] = ("resx=" + screen.width);
		sendMe[sendMe.length] = ("resy=" + screen.height);
		sendMe[sendMe.length] = ("title=" + escape(document.title));
		sendMe[sendMe.length] = ("url=" + escape(document.location));
		
		wc_sendInfo (sendMe);




		/*
		var sendMe2 = new Array ();
		sendMe2.push ("storeitems"=$storeItems);
		sendMe2.push ("storeprices"=$storePrices);
		sendMe2.push ("cartinfo"=$cartInfo);
		*/

	}



}





