/* This script has to be referenced somewhere in your web page. I recomend 
   placing this script snippet just after Google Analytics tracking code.
	<script src="/adstracker.js" type="text/javascript"></script>	
*/
var shopTag = 'shopwidget';
var classTracked = "shopwidget1";
var trackedElement = "DIV";

// init shopWidget click tracking after docuement load...
attachOnloadEvent(shopWidgetTrackerInit);
/**
 * This function checks for the elements on the page and if they exist
 *  attaches events to them for tracking
 */
function shopWidgetTrackerInit() {
	var pageHasShopWidget = false;
       
	var el = getElementsByClassName(document, trackedElement, classTracked);
	for (var i=0; i<el.length; i++) {
		var children = getElementsByClassName(el[i], trackedElement, classTracked);
		// there are two divs with the shopwidget class.  1 in nested 
		//    in the other.  So if we are at the other div, keep looking
		if (children.length > 0) continue;
                
		// we have the div we are interested in
		pageHasShopWidget = true;
		children = el[i].childNodes;
		for (var j=0; j<children.length; j++) {
                        // loop through all div elements and handle the a clicks
			if (children[j].nodeName == trackedElement) {
                                var aElements = children[j].getElementsByTagName('a');
                                for (var k=0; k<aElements.length; k++) {
                                        aElements[k].onclick = registerOnClick;
                                }
			}
		}
	}
}

/**
 * This function parses a shopWidget link
 */
function parseShopWidgetUrl(ele) {
        var url = unescape(ele.html
        // constants used for parsing the string
        var startIndex = "http://".length;
        var endOfSiteIndex = url.indexOf('/', startIndex);
        var nameOffset = 5;
        var endName = "~";
        var startCode = "~PD-";
        var endCode = "~FD-";
        var startRetailerCode = "url=";%20%20%20%20%20%20%20%20var%20endRetailerCode%20=.html"&";
        
        // local vars for parsing
        var par = null;
	var retailerName = null;
        var site = "";
        
        // get the whole site URL
        var siteArray = url.substring(startIndex, endOfSiteIndex).split('.');
        // now figure out the main name of the site by how many '.' are in the url
        switch (siteArray.length) {
        case 3:
                site = siteArray[1];
                break;
        case 1:
        case 2:
        default:
                site = siteArray[0];
        }
        // sometimes we need to look to another link to get the information
        //      we need.  The following cases set the correct element to
        //      parse and recall this function
	if (site == "shopping") {
		if (url.search(new RegExp(startCode)) == -1) {
                        //  if clicking on a retailer link, get the name for
                        //      logging
			retailerName = extractStringFromArgs(ele.href, "xMR-", "~MRD");
                	par = ele.parentNode.parentNode.parentNode;
		}
	}
        if (site == "epinions") {
                par = ele.parentNode.parentNode;
        }
        if (site == "dealtime") {
                // get the url from the link for the retailer
                retailerName = extractStringFromArgs(ele.href, startRetailerCode, endRetailerCode);
		retailerName = extractStringFromArgs(retailerName, "http%3A%2F%2F", '%2F');
                par = ele.parentNode.parentNode.parentNode;
        }
        // if parent is set we need to re-run the function with the parents
        //      url to get the info we need
        if (par) {
                var aElements = par.getElementsByTagName('a');
                for (var i=0; i<aElements.length; i++) {
                        if (aElements[i].href.indexOf("shopping") != -1) {
                                var hash = parseShopWidgetUrl(aElements[i]);
                                // replace the site with epinions
                                hash[1] = site;
                                if (retailerName) { 
					hash.splice(2, 0, retailerName);
				}
                                return hash;
                        }
                }
                // something bad happened when parsing the link
                return [site, "error parsing link"];
        }
        // somethimes the code before the name varies, but it is always 5 chars
        //   after the site
        name =  url.substring(endOfSiteIndex+nameOffset,
                                         url.indexOf(endName));
        // get the code from the string
        var code = extractStringFromArgs(url,.html startCode, endCode);
        // construct the elements to log
        var hash = [shopTag, site, name, code];
        return hash;
}

/**
 *
 * Extracts a string between the two strings passed as parameters
 */
function extractStringFromArgs(str, start, end) {
        var startIndex = str.search(new RegExp(start));
        startIndex += start.length;
        var sub = str.substring(startIndex);
        var endIndex = sub.search(new RegExp(end));
        return sub.substring(0, endIndex);
}

/**
 * This function calls parses the click event and call google analytics.
 */
function registerOnClick() {
        var data = parseShopWidgetUrl(this);.html
        var shopWidgetLink = '/'+escape(data.join('/'));
        reportToGoogleAnalytics(shopWidgetLink);
	return true;
}

/**
 * report click to google Analytics
 */
function reportToGoogleAnalytics(reportedUrl) {
	if (typeof urchinTracker == 'function') {
		urchinTracker(reportedUrl);
	}
}

// attach func function to window onload event (crossbrowser compatible)
function attachOnloadEvent(func) {
	if(typeof window.addEventListener != 'undefined') {
		// moz, saf1.2, ow5b6.1
		window.addEventListener('load', func, false);
	} else if (typeof document.addEventListener != 'undefined') {
		// MSN/OSX, op7.50, saf1.2, ow5b6.1
		document.addEventListener('load', func, false);
	} else if (typeof window.attachEvent != 'undefined') {
		// ie5.0w, ie5.5w, ie6w
		window.attachEvent('onload', func);
	} else {
		// all other browsers
		if (typeof window.onload == 'function') {
			var oldonload = onload;
			window.onload = function() {
				oldonload();
				func();
			};
		} else {
				window.onload = func;
		}
	}
}

/*
	Written by Jonathan Snook, http://www.snook.ca/jonathan
	Add-ons by Robert Nyman, http://www.robertnyman.com
*/
function getElementsByClassName(oElm, strTagName, strClassName){
	var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
	var arrReturnElements = new Array();
	strClassName = strClassName.replace(/-/g, "\-");
	var oRegExp = new RegExp("(^|\s)" + strClassName + "(\s|$)");
	var oElement;
	for(var i=0; i<arrElements.length; i++){
		oElement = arrElements[i];
		if(oRegExp.test(oElement.className)){
			arrReturnElements.push(oElement);
		}
	}
	return (arrReturnElements)
}
