var browser = {};
var configuration = {
	debug:true,
	defaultLocale:{
		country:'uk',
		language:'eng',
		locale:'en-gb',
		reportSuiteId:'fmceuukdev'
	}
}
var eventsOutput = '';
var initialLoad = true;
var trackingAttributes;
var xmlDoc;
var xmlObj;

//alert("1. Initialising the wrapper...");
var tracking = {
	init: function(obj){
		configuration.active = obj.active;
		configuration.tagXmlUrl = obj.tagXmlUrl;

		if(configuration.active && typeof(s_account) == 'string'){		
			eventsOutput = '';
			
			//re-initialize storage object for attributes
			trackingAttributes = {};
			
			//identify which browser is being used, in order to use correct method to retrieve and parse tracking XML document
			tracking.browserSniffer();	
			//alert("2. Detecting browser : " + browser.agent);
			
			if(configuration.debug){tracking.logEvent('Sophus origin tag: ' + obj.originalSophusTag);}
			if(configuration.debug){tracking.logEvent('Sophus origin tag (without locale): ' + obj.originalTrackingTag);}

			//load XML file, so that it's parsable (only once)
			tracking.loadAndStoreXML({
				locale:obj.locale,
				originalTrackingTag:obj.originalTrackingTag.toLowerCase(),
				serverType:obj.serverType,
				tagXmlUrl:configuration.tagXmlUrl
			});			
		}
	},
	
	//cross-reference original Sophos tag with Omniture XML
	lookupTag: function(obj){
		//retrieve from XML file all locale-specific XML data, based on XX-XX value (eg: en-eu, en-gb)
		var tagsCount = xmlDoc.getElementsByTagName('locale').length-1;
		var matchedLocale = false;
				
		if(configuration.debug){tracking.logEvent('Server type (Report Suite): ' + obj.serverType);}
		
		for(var i=0; i<=tagsCount; i++){
			var currentTagInXml = xmlDoc.getElementsByTagName('locale')[i];
			var currentTagInXmlId = currentTagInXml.attributes.getNamedItem('id').nodeValue;
				
			if(obj.locale == currentTagInXmlId){
				trackingAttributes.country = currentTagInXml.getElementsByTagName('country')[0].firstChild.nodeValue;
				trackingAttributes.language = currentTagInXml.getElementsByTagName('language')[0].firstChild.nodeValue;
				trackingAttributes.locale = obj.locale;
				
				configuration.reportSuiteId = currentTagInXml.getElementsByTagName('reportSuiteId' + obj.serverType)[0].firstChild.nodeValue;
				
				matchedLocale = true;
				
				if(configuration.debug){tracking.logEvent('Locale match in XML: country=' + trackingAttributes.country + ', language=' + trackingAttributes.language + ', locale=' + trackingAttributes.locale + ', reportSuiteId=' + configuration.reportSuiteId);}
			}
		}
		
		//provide default locales if no matches were found in XML
		if(!matchedLocale){
			trackingAttributes.country = configuration.defaultLocale.country;
			trackingAttributes.language = configuration.defaultLocale.language;
			trackingAttributes.locale = configuration.defaultLocale.locale;
			
			configuration.reportSuiteId = configuration.defaultLocale.reportSuiteId;
			
			if(configuration.debug){tracking.logEvent('No locale match in XML. Defaulting to: country=' + trackingAttributes.country + ', language=' + trackingAttributes.language + ', locale=' + trackingAttributes.locale + ', reportSuiteId=' + configuration.reportSuiteId);}
		}
		
		//retrieve from XML file all dynamic tag content (for generation of Omniture tracking tag)
		var tagsCount = xmlDoc.getElementsByTagName('tag').length-1;
		for(var i=0; i<=tagsCount; i++){
			var currentTagInXml = xmlDoc.getElementsByTagName('tag')[i];
			var currentTagInXmlId = currentTagInXml.attributes.getNamedItem('id').nodeValue.toLowerCase();
			
			//identify which type of tag is being called
			//Omniture calls either s.t() or s.tl() depending on which 
			//<tag id="/en-eu/MONDEO/Homepage/Loaded/5door" trackType="track"> - Omniture uses s.t()
			//<tag id="/en-eu/MONDEO/Homepage/Rotate/5door" trackType="trackLink"> - Omniture usess.tl()
			//by default, set the tracking type to be 'track'
			var currentTagTrackingType = 'track';
			if(currentTagInXml.attributes.getNamedItem('trackType').nodeValue == 'trackLink'){
				currentTagTrackingType = 'trackLink';
			}
			if(obj.originalTrackingTag == currentTagInXmlId){	
				if(configuration.debug){tracking.logEvent('Sophus tag matched in site Omniture XML: ' + currentTagInXmlId);}
				if(configuration.debug){tracking.logEvent('track or trackLink?: ' + currentTagTrackingType);}

				//assign 's' object for Omniture tracking
				//Commented out line below as per request on 16/03/2011
				//var s = s_gi(configuration.reportSuiteId);
				
				var genericObj = currentTagInXml.getElementsByTagName('generic')[0];
				
				//retrieve '<generic>' node list
				//check to see if a <generic> child XML node object exists before adding to trackingAttributes object
				if(tracking.genericNodeExists(genericObj.getElementsByTagName('pageName')[0])){trackingAttributes.pageName = genericObj.getElementsByTagName('pageName')[0].firstChild.nodeValue;}
				if(tracking.genericNodeExists(genericObj.getElementsByTagName('channel')[0])){trackingAttributes.channel = genericObj.getElementsByTagName('channel')[0].firstChild.nodeValue;}
				if(tracking.genericNodeExists(genericObj.getElementsByTagName('hier1')[0])){trackingAttributes.hier1 = genericObj.getElementsByTagName('hier1')[0].firstChild.nodeValue;}
				//if(tracking.genericNodeExists(genericObj.getElementsByTagName('hier2')[0])){trackingAttributes.hier2 = genericObj.getElementsByTagName('hier2')[0].firstChild.nodeValue;}
				//if(tracking.genericNodeExists(genericObj.getElementsByTagName('campaign')[0])){trackingAttributes.campaign = genericObj.getElementsByTagName('campaign')[0].firstChild.nodeValue;}
				
				//retrieve additional nodes for items being tracked using 'trackLink' rather than 'track'
				if(currentTagTrackingType == 'trackLink'){
					if(tracking.genericNodeExists(genericObj.getElementsByTagName('linkName')[0])){trackingAttributes.linkName = genericObj.getElementsByTagName('linkName')[0].firstChild.nodeValue;}
					if(tracking.genericNodeExists(genericObj.getElementsByTagName('linkType')[0])){trackingAttributes.linkType = genericObj.getElementsByTagName('linkType')[0].firstChild.nodeValue;}
				}

				//retrieve '<eVars>' node list
				tracking.xmlRetrieveNodeList({currentTagInXml:currentTagInXml,nodeType:'eVars'});
				
				//replace -{country} with the dynamic country value for eVar14
				if(trackingAttributes.eVar14.indexOf('{country}')> -1){
					trackingAttributes.eVar14 = trackingAttributes.eVar14.replace(/{country}/,trackingAttributes.country);
				}
				//replace -{language} with the dynamic language value for eVar4
				if(trackingAttributes.eVar4.indexOf('{language}') > -1){
					trackingAttributes.eVar4 = trackingAttributes.eVar4.replace(/{language}/,trackingAttributes.language);
				}				
				
				
				
				//retrieve '<props>' node list					
				tracking.xmlRetrieveNodeList({currentTagInXml:currentTagInXml,nodeType:'props'});
				
				//replace -{country} with the dynamic country value for prop14
				if(trackingAttributes.prop14.indexOf('{country}') > -1){
					trackingAttributes.prop14 = trackingAttributes.prop14.replace(/{country}/,trackingAttributes.country);
				}
				//replace -{language} with the dynamic language value for prop4
				if(trackingAttributes.prop4.indexOf('{language}') > -1){
					trackingAttributes.prop4 = trackingAttributes.prop4.replace(/{language}/,trackingAttributes.language);
				}		

				//retrieve '<events>' node list		
				tracking.xmlRetrieveNodeList({currentTagInXml:currentTagInXml,nodeType:'events'});
				trackingAttributes.events = "";
				if(eventsOutput != ''){trackingAttributes.events = eventsOutput.substr(0,eventsOutput.length-1);}
				
				//output content to screen, including final Omniture tag
				var output = '';		
				var attributes = '';
				for(attribute in trackingAttributes){
					output = 's.' + attribute + ' = ' + trackingAttributes[attribute];
					attributes += attribute + ',';
					if(configuration.debug){tracking.logEvent('Omniture parameter: ' + output);}
				}
				
				//assign attributes to Omniture tracking object
				for(attribute in trackingAttributes){
					s[attribute] = '';
					s[attribute] = trackingAttributes[attribute];
				}
				
				//process differences for if trackLink is being executed (rather than track)
				if(currentTagTrackingType == 'trackLink'){					
					s.linkTrackVars = attributes.substr(0,attributes.length-1);
					if(configuration.debug){tracking.logEvent('Omniture parameter: s.linkTrackVars=' + s.linkTrackVars);}
					
					if(trackingAttributes.events != undefined){
						s.linkTrackEvents = trackingAttributes.events;
						if(configuration.debug){tracking.logEvent('Omniture parameter: s.linkTrackEvents=' + s.linkTrackEvents);}
					}
				}
				
				//send request over to Omniture
				var s_code = (currentTagTrackingType == 'track' ? s.t() : s.tl(true,trackingAttributes.linkType,trackingAttributes.linkName));
				if(s_code)document.write(s_code)
				if(navigator.appVersion.indexOf('MSIE')>=0){
					//document.write(unescape('%3C')+'\!-'+'-')
				}
			}
		}
	},
	
	//check to see if a <generic> child XML node object exists before adding to trackingAttributes object
	genericNodeExists: function(nodeObj){
		return typeof(nodeObj) == 'object' ? true : false;
	},	
	
	//load (and store) XML file, so that it's parsable
	loadAndStoreXML: function(obj){
		if(!initialLoad){
			//retrieve from XML file all locale-specific XML data, based on XX-XX value (eg: en-eu, en-gb)
			//cross-reference original Sophos tag with Omniture XML
			tracking.lookupTag({
				locale:obj.locale,
				originalTrackingTag:obj.originalTrackingTag,
				serverType:obj.serverType
			});
			
			return false;
		}
		
		if(!browser.isIe6){
			xmlObj = new XMLHttpRequest();
		}
		else{
			xmlObj = new ActiveXObject("Microsoft.XMLHTTP");
		}

		xmlObj.onreadystatechange = function(){
			if(xmlObj.readyState == 4 && xmlObj.status == 200){
				xmlDoc = xmlObj.responseXML;
				//retrieve from XML file all locale-specific XML data, based on XX-XX value (eg: en-eu, en-gb)
				//cross-reference original Sophos tag with Omniture XML
				tracking.lookupTag({
					locale:obj.locale,
					originalTrackingTag:obj.originalTrackingTag,
					serverType:obj.serverType
				});
				initialLoad = false;
			}
		}
		
		xmlObj.open('GET',obj.tagXmlUrl,true);
		xmlObj.send();
	},
	
	//identify which browser is being used, in order to use correct method to retrieve and parse tracking XML document
	browserSniffer: function(){
		browser.agent = navigator.userAgent.toLowerCase();
		browser.isMajor = parseInt(navigator.appVersion);
		
		browser.isIe = (browser.agent.indexOf('msie') != -1);
		browser.isIe6 = (browser.isIe && (browser.isMajor == 4) && browser.agent.indexOf('msie 6.') != -1);
	},
	
	//whitespace is handled as a node within Firefox (although whitespace carries a nodeType value of 3 rather than 1)
	//only parse valid nodes if they report a nodeType of 1	
	nodeWhitespaceTrim: function(obj){
		if(obj.node.nodeType == 1){
			//populate global object storing data for tracking tag
			if(obj.nodeType == 'events'){
				eventsOutput += obj.node.firstChild.nodeValue + ',';
			}
			else{
				trackingAttributes[obj.node.nodeName] = obj.node.firstChild.nodeValue;
			}
		}
	},	
	
	xmlRetrieveNodeList:function(obj){
		var nodeObj = obj.currentTagInXml.getElementsByTagName(obj.nodeType)[0];
		
		//only process if a value XML nodelist is identified
		if(typeof(nodeObj) == 'object'){
			var nodeListObj = obj.currentTagInXml.getElementsByTagName(obj.nodeType)[0];
			var nodesCount = nodeListObj.childNodes.length-1;
			for(var x=0; x<=nodesCount; x++){
				tracking.nodeWhitespaceTrim({
					node:nodeListObj.childNodes[x],
					nodeType:obj.nodeType
				});
			}
		}
	},
	
	//global mechanism for tracking events to the browser console
	logEvent: function(event){
		if(window.console && window.console.log){
			console.log(event)
		}
	}	
}
