/**
 * This file contains functions necessary to gather statistics through omniture.
 * Functionality has been put here in an external file for ease-of-change.
 *
 * It creates/uses a global Philips namespace to put the funtions in.
 * Created by Rezvan (rezvan@backbase.com) on 2009-03-20.
 */
window.Philips = window.Philips || {};

// make sure the function (for some weird reason) doesn't already exist
if (Philips.buyWidgetOmniture == null) {
	
	if (window.s == null) { 				// check for omniture engine
		window.p_measureEnabled = false; 	// disable measuring
		// append philips omniture engine script
		var script = document.createElement('script');
		script.type = 'text/javascript';
		script.src = 'http://www.crsc.philips.com/crsc/scripts/s_code_philipsglobal.js';
		document.getElementsByTagName('head')[0].appendChild(script);
	}
	
	Philips.buyWidgetOmniture = {
		meta: [],
		metasAvailable: true,
		UUIDchars: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split(''),
		// UUIDrequestUrl: 'http://www.crsc.philips.com/crsc/images/mainlogo_full_nl_nl.gif',
		UUIDrequestUrl: 'http://truetag.channelintelligence.com/?eid=48&v=6688506&transactionID=',
		
		tag: function(sType, oParams) {
			var sLastLevel = (this.getParam('productsubcategory') != '') ? this.getParam('productsubcategory') : this.getParam('productcategory');
			sLastLevel = (sLastLevel != '') ? sLastLevel : this.getParam('productgroup');
			
			var aId = oParams.productid.split('_');
			var sProductid = '';
			var sRequestPageName = '';
			if (aId.length > 1){
				sProductid = aId[0].toLowerCase();
				if(isNaN(aId[1])==false){
					sProductid += '/'+ aId[1].toLowerCase();
				 }
			}
			
			switch (sType) {
				case 'button': 	// a buy button has been clicked
					s.linkTrackVars = "eVar3,events,products,eVar14";
					s.linkTrackEvents  = "event21,event24";
					s.eVar3 = s.pageName;
					s.eVar14 = "wtb_widget";
					s.events = "event21,event24";
					s.products = sLastLevel +';'+ sProductid;
					sRequestPageName = s.pageName + "_buy"
					break;
					
				case 'storeLinkPhilips': 	// a PHILIPS shop link has been clicked
					s.linkTrackVars = "eVar3,eVar9,events,products,transactionID,eVar14";
					s.linkTrackEvents  = "event22,event25";
					s.eVar3 = s.pageName;
					s.eVar9 = oParams.storename;
					s.eVar14 = "wtb_widget";
					s.events = "event22,event25";
					s.products = sLastLevel +';'+ sProductid;
					s.transactionID = this.UUID();
					sRequestPageName = s.pageName + "_buyatphilips"
					break;
					
				case 'storeLink': 	// a NON philips shop link has been clicked
					s.linkTrackVars = "eVar3,eVar9,events,products,transactionID,eVar14";
					s.linkTrackEvents  = "event23,event26";
					s.eVar3 = s.pageName;
					s.eVar9 = oParams.storename;
					s.eVar14 = "wtb_widget";
					s.events = "event23,event26";
					s.products = sLastLevel +';'+ sProductid;
					s.transactionID = this.UUID();
					sRequestPageName = s.pageName + "_buyatothers"
					break;
			}
			//setting s.sa if PHILIPS.METRICS.DIVISIONS is empty 
			if(this.getParam('division') == ''){
				s.sa("philipsusoshop");
			}
			// remote request (omniture)
			s.tl (true, "o", sRequestPageName);
			
			if (typeof MetrixLabP10358_ShowInvite !== "undefined" && typeof MetrixLabP10358_ShowInvite === "function") {
                MetrixLabP10358_ShowInvite();
			}
			
			
			// make a request to channel intelligence and pass the data UUID data
			// only request when the transactionID is available
			if (s.transactionID) {
				var sUrl = this.UUIDrequestUrl+s.transactionID;
				this.remoteRequest(sUrl);
			}
			//var sUrl = [this.UUIDrequestUrl +'?']
			//sUrl.push(encodeURIComponent(s.transactionID));
			
			// reset variables
			s.linkTrackVars = "None";
			s.linkTrackEvents = "None";
			
			// allow user to continue to URL after a small timeout
			var addUUID = (s.transactionID)?s.transactionID : '';
			var targetURL = oParams.href+addUUID;
			if (sType == 'storeLinkPhilips' || sType == 'storeLink')
				setTimeout(function() {window.location = targetURL;}, 500);
		},
		
		getParam: function(sParam) {
			var aMetas = this.meta;
			var sParamName = ('PHILIPS.METRICS.'+ sParam).toUpperCase();
			if (aMetas[sParamName] != undefined) {
				return aMetas[sParamName];
			}
			else if (this.metasAvailable == true) {
				var aElms = document.getElementsByTagName('meta');
				var bFound = false;
				for (var i=0; i < aElms.length; i++) {
					if (aElms[i].name.substr(0,7) == 'PHILIPS')	{
						aMetas[aElms[i].name] = aElms[i].content;
						bFound = true;
					}
				};
				if (bFound == false) {
					this.metasAvailable = false;
				} else if (aMetas[sParam] != undefined) {
					return aMetas[sParam];
				}
			}
			return '';
		},
		
	
		UUID: function (len, radix) {
			var chars = this.UUIDchars, uuid = [], rnd = Math.random;
			radix = radix || chars.length;
			
			if (len) {
				// Compact form
				for (var i = 0; i < len; i++) uuid[i] = chars[0 | rnd()*radix];
			} else {
				// rfc4122, version 4 form
				var r;
			
				// rfc4122 requires these characters
				uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
				uuid[14] = '4';
			
				// Fill in random data.  At i==19 set the high bits of clock sequence as
				// per rfc4122, sec. 4.1.5
				for (var i = 0; i < 36; i++) {
					if (!uuid[i]) {
						r = 0 | rnd()*16;
						uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r & 0xf];
					}
				}
			}
			
			return uuid.join('');
		},
		
		// request a remote image (just to send along some stat information)
		remoteRequest: function (sUrl) {
			var oImg = document.createElement('img');
			oImg.src = sUrl;
			oImg.style.display = 'none';
			document.body.appendChild(oImg);
			oImg.parentNode.removeChild(oImg);
		}
	}
}