/**
 * Data storage container arround Google Analytics tracking code.
 * 
 * Analytics Code should be embedded at the bottom of the page. 
 * The Tracker should be placed there to prevent the entire
 * page from loading slow.
 * 
 * This is a data container which collects data right from the start
 * of the page. At the bottom we will include the GA tracking code,
 * put all data into the _ga object and track the pageview.
 * 
 * This class is capable of collecting all possible data to fit the
 * Google Analytics Tracking API [1]
 * 
 * For eComerce Code look here [3]
 * 
 * [1] http://code.google.com/intl/de-DE/apis/analytics/docs/gaJS/gaJSApi.html
 * [2] http://code.google.com/intl/de-DE/apis/analytics/docs/concepts/gaConceptsOverview.html
 * [3] http://code.google.com/intl/de-DE/apis/analytics/docs/tracking/gaTrackingEcommerce.html
 * @author Arne Becker
 */
gaHandlers = new Array();
function trackingData() {
	var container = new Array();
	var eCommerceTrans = null;
	var eCommerceItem = new Array();
	var d = window.document;
	var body = d.getElementsByTagName('body')[0];
	var isPageViewed = false;
	var debugContainer = null;
	var isDebug = false;
	var self = this;
	var pageTracker = null;
	this.setDebug = function(level) {
		isDebug = level;
	};
	var createElementWithText = function(element, text) {
		var elem = d.createElement(element);
		elem.appendChild(d.createTextNode(text));
		return elem;
	};
	var createDebugContainer = function(){
		d = window.document;
		body = d.getElementsByTagName('body')[0];
		if (debugContainer != null) {
			body.removeChild(debugContainer);
			debugContainer = null;
		}
		debugContainer = d.createElement("FIELDSET");
		debugLegend = createElementWithText("LEGEND","Tracking data:");
		body.appendChild(debugContainer);
		debugContainer.appendChild(debugLegend);
		debugContainer.style.cssFloat="left";
		debugContainer.id="gaDebug";
	};
	var dumpArray2List = function(parentNode, list, title) {
		parentNode.appendChild(createElementWithText("P","['" + title + "']"));
		var ul = parentNode.appendChild(d.createElement("UL"));
		for ( var i = 0; i < list.length; i++) {
			ul.appendChild(createElementWithText("LI",list[i]));
		}
	};
	var dumpData = function() {
		createDebugContainer();
		var hasContent = false;
		for ( var internalType in container) {
			dumpArray2List(debugContainer, container[internalType], internalType);
			hasContent = true;
		}
		if (! hasContent) {
			debugContainer.appendChild(createElementWithText("P","No tracking data collected"));
		}
	};
	var debug = function(message){
		debugContainer.appendChild(createElementWithText("P",message));
	};
	var trackItem = function(type, newValue, trackerMethod) {
		try{
			// injected handler
			if((typeof trackerMethod != "undefined") && (type == null)) {
				var method = trackerMethod.replace(/xxx/g,newValue);
				eval("pageTracker." + method);
				return;
			}
			// known handlers
			if (typeof gaHandlers[type] != "undefined") {
				method = gaHandlers[type].replace(/xxx/g,newValue);
				eval("pageTracker." + method);
				return;
			}
		} catch (e) {
			if (isDebug) {
				debug(e.toString());
			}
		}
		// if nothing helped
		switch (type) {
		case 'attachment':
			pageTracker._trackPageview('/downloads/attachments/' + newValue);
			break;
		case 'searchQuery':
			pageTracker._addOrganic("FAST", newValue);
			break;
		case 'userRole':
			pageTracker._trackPageview('/login/' + newValue);
			break;
		case 'newsletter':
			pageTracker._trackPageview('/subscribed/' + newValue);
			break;
		case 'ainRole':
			pageTracker._setVar(newValue);
			break;
		default:
			break;
		}
	};
	var trackAllItems = function() {
		if (isDebug) {
			dumpData();
		}
		if (!isPageViewed) {
			for ( var internalType in container) {
					trackItem(internalType, container[internalType]);
				}
		} 
	};
	this.addItem = function(type, newValue, trackerMethod) {
		if ((typeof container[type] == "undefined") || container[type] == null) {
			container[type] = new Array();
		}
		container[type][container[type].length] = newValue;
		if (isPageViewed) {
			if (isDebug) {
				dumpData();
			}
			trackItem(type, newValue, trackerMethod);
			return;
		}
	};
	/**
	 * Wrapper arround Google's ecomerce code. 
	 * Stores a transaction with one product.
	 * 
	 * @param transOrderId	String REQUIRED. Internal unique order id number for this transaction.
	 * @param affiliation 	String Partner or store affiliation (undefined if absent). "" if not set
	 * @param total 		String REQUIRED. Total dollar amount of the transaction. "55.95"
	 * @param tax 			String Tax amount of the transaction. "" if not set
	 * @param shipping 		String Shipping charge for the transaction. "" if not set
	 * @param city 			String City to associate with transaction. "" if not set
	 * @param state 		String State to associate with transaction. "" if not set
	 * @param country 		String Country to associate with transaction. "" if not set
	 * @param orderId 		String Internal unique order id number for this product. "" if not set
	 * @param sku 			String REQUIRED. Item's SKU code.
	 * @param name 			String Product name. "" if not set
	 * @param category 		String Product category. "" if not set
	 * @param price 		String REQUIRED. Product price. "55.95"
	 * @param quantity 		String REQUIRED. Purchase quantity.
	 * @return
	 * To test this, add the following code somewhere to your site 
	 * gaTracking.addFullTransaction("transOrderId", "affiliation", "total", "tax", "shipping", "city", "state", "country", "orderId", "sku", "name", "category", "price", "quantity");
	 * gaTracking.addTransactionItem("orderId", "sku", "name", "category", "price", "quantity");
	 */
	this.addFullTransaction = function(transOrderId, affiliation, total, tax, shipping, city, state, country, orderId, sku, name, category, price, quantity) {
		if(eCommerceTrans == null){
			eCommerceTrans = new eCommerceTransClass(transOrderId, affiliation, total, tax, shipping, city, state, country);
			eCommerceItem[eCommerceItem.length] = new eCommerceItemClass(orderId, sku, name, category, price, quantity);
		}
	};
	/**
	 * @see addFullTransaction
	 */
	this.addTransaction = function(orderId, affiliation, total, tax, shipping, city, state, country) {
		if(eCommerceTrans == null){
			eCommerceTrans = new eCommerceTransClass(orderId, affiliation, total, tax, shipping, city, state, country);
		}
	};
	/**
	 * @see addFullTransaction
	 */
	this.addTransactionItem = function(orderId, sku, name, category, price, quantity) {
		if(eCommerceTrans != null){
			eCommerceItem[eCommerceItem.length] = new eCommerceItemClass(orderId, sku, name, category, price, quantity);
		}
	};
	/**
	 * Starts one transaction and adds immediatly the products.
	 * Finally completes the transaction.
	 * */
	var trackTransaction = function() {
		if(eCommerceTrans != null) {
			try{
				if (isDebug) {
					debug("Starting Transaction '" + eCommerceTrans.sOrderId + "' '" + eCommerceTrans.sAffiliation + "' '" + eCommerceTrans.sTotal + "' '" + eCommerceTrans.sTax + "' '" + eCommerceTrans.sShipping + "' '" + eCommerceTrans.sCity + "' '" + eCommerceTrans.sState + "' '" + eCommerceTrans.sCountry + "'");
				}
				pageTracker._addTrans(eCommerceTrans.sOrderId, eCommerceTrans.sAffiliation, eCommerceTrans.sTotal, eCommerceTrans.sTax, eCommerceTrans.sShipping, eCommerceTrans.sCity, eCommerceTrans.sState, eCommerceTrans.sCountry);
				for ( var i = 0; i < eCommerceItem.length; i++) {
					if (isDebug) {
						debug("Product " + i + ": '" + eCommerceItem[i].sOrderId + "' '" + eCommerceItem[i].sSku + "' '" + eCommerceItem[i].sName + "' '" + eCommerceItem[i].sCategory + "' '" + eCommerceItem[i].sPrice + "' '" + eCommerceItem[i].sQuantity + "'");
					}
					pageTracker._addItem(eCommerceItem[i].sOrderId, eCommerceItem[i].sSku, eCommerceItem[i].sName, eCommerceItem[i].sCategory, eCommerceItem[i].sPrice, eCommerceItem[i].sQuantity);
				}
				pageTracker._trackTrans();
				if (isDebug) {
					debug("Transaction successful.");
				}
			} catch (e) {
				if (isDebug) {
					debug("Exception while finalizing eCommerce transaction.");
				}
			}
		}
	};
	this.trackPageViewOnLoad = function(argPageTracker) {
		if (!isPageViewed) {
			//pageTracker = new mytracker();
			pageTracker = argPageTracker;
			trackAllItems();
			isPageViewed = true;
			pageTracker._trackPageview();
			if((eCommerceTrans != null) && (eCommerceItem.length !=0)){
				trackTransaction();
			} else if (isDebug) {
				debug("No eCommerce transaction requested.");
			}
		}
	};
}
eCommerceTransClass = function(orderId, affiliation, total, tax, shipping, city, state, country) {
	this.sOrderId = orderId; 
	this.sAffiliation = affiliation;
	this.sTotal = total;
	this.sTax = tax;
	this.sShipping = shipping;
	this.sCity = city;
	this.sState = state;
	this.sCountry = country;
};
eCommerceItemClass = function(orderId, sku, name, category, price, quantity) {
	this.sOrderId = orderId; 
	this.sSku = sku;
	this.sName = name;
	this.sCategory = category;
	this.sPrice = price;
	this.sQuantity = quantity;
};
mytracker = function(){
	this._trackPageview = function(value){
		alert("got " + value);
	};
	this._addOrganic = function(value1, value2){
		alert("got " + value1 + " and " + value2);
	};
};
gaTracking = new trackingData();
gaUA = null;
forceDebug = false;
