/*
 * Google analytics support for Smilehouse Workspace.
 * 
 */

// this global is set later
var WSGA = null;

// page title configuration
var __wsgaConfObject = {
	pageTitles: { 
	           3:'/tuotteet',
	           4:'/ostoskori',  
	           5:'/tilauslomake',
	           6:'/overridelater',
	           7:'/rekisterointilomake',
	           8:'/tilaustiedot',
	           9:'/tuote',
	           10:'/etusivu',
	           11:'/rekisterointitiedot',
	           12:'/rekisterointivahvistus',
	           13:'/tilaushistoria/tilaukset',
	           14:'/tilaushistoria/tilaus',
	           15:'/tallennettuostoskori',
	           16:'/pikatilaus',
	           17:'/pikatilaustiedot',
	           19:'/salasananpalautus',
	           20:'/hakutulokset',
	           21:'/toivelista',
	           22:'/salasanapalautettu'
	           },
	           themeTitles: 
	           {},
	//comment this if you don't want theme based logging , otherwise write your theme names here
	/*{
		1:'/julkinen',
		2:'/others',
		3:'/others',
		4:'/kirjautunut',
		5:'/others',
		6:'/others',
		7:'/others',
		8:'/others',
		9:'/others',
		10:'/others'
	}*/
	
	freepageTitle : '/vapaasivu',
	orderSuccessTitle : '/tilausonnistui',
	orderCancelledTitle : '/tilausperuutettu', 
	orderFailedTitle : '/tilauskeskeytetty', 
	advancedSearchTitle : '/erikoishaku',
	basicSearchTitle : '/pikahaku',
	offsiteTitle : '/offsite'
	
};

/*
 * Tracking 
 */
function WSGoogleAnalytics(pageTracker){	
	this.version = "1.0";
	this.releaseDate = "2008-01-17";
	
	// init page tracker
	pageTracker._initData();
	this.pageTracker = pageTracker;
	
	// loggedUrl keeps record of what was last sent to google analytics
	this.loggedUrl = '';
	
	// should transaction tracking be called
	this.trackTransaction = false;
	
	// This can be set to true if logging is needed
	// Add wga.writeLog = true; in script block before call to wga.trackPage()
	this.writeLog = false;
	
	// Write log messages only to a FireBug console. For this to take effect writeLog must be set to true.
	// UseConsoleLogOnly can be set to true if logging to a separate browser window is not wanted.
	// Just add wga.useConsoleLogOnly = true; in script block before call to wga.trackPage()
	this.useConsoleLogOnly = false;
		
	WSGA = this;
}

WSGoogleAnalytics.prototype = {
  
  trackPage:function(){
    this.wsga_log('WSGA: -- New page --');
  	
  	//get title (also calls page object to perform transaction grouping if appropriate)
    var pageObj = this.wsga_buildpagemeta();
    var title = this.wsga_buildtitle( pageObj );
    
    this.wsga_log("WSGA: Page title is " + title);
    
    this.wsga_report(title);
    
    if (this.trackTransaction){
      this.wsga_setuptransaction();  
    }
    
    this.wsga_log('WSGA: Add listeners');
    //add a listener for exit and search links
    var links = document.getElementsByTagName("a");
    for(var i=0; i<links.length;i++){
      this.wsga_addListener(links[i], 'click', this.wsga_linkclickhandler);
    }
    
    //add a listener for search forms
    var forms = document.getElementsByTagName("form");
    for(var i=0; i<forms.length;i++){
      this.wsga_addListener(forms[i], 'submit', this.wsga_submithandler);
    }
  },
  
  // call googe analytics
  wsga_report : function(r) {
    this.loggedUrl = r;    
    
   	if(!r)
   	  this.pageTracker._trackPageview();
    else
   	  this.pageTracker._trackPageview(r);
   	  
   	this.wsga_log("WSGA: sending to tracker: " + r);
 },
   
  // Cross-browser implementation of element.addEventListener()
  wsga_addListener : function(element, type, expression, bubbling){
    var bubbling = bubbling || false;
    if(window.addEventListener)    { // Standard
       element.addEventListener(type, expression, bubbling);
       return true;
    } else if(window.attachEvent) { // IE
       element.attachEvent('on' + type, expression);
       return true;
    } else 
       return false;   
  },   
  
  wsga_buildpagemeta : function (){
    this.wsga_log('WSGA: wsga_buildpagemeta');
    var pageMetas = document.getElementById("wsgametadata").value.split(";=;");    
    var tmpId=pageMetas[1];
	  var pageObj = {	
      theme:pageMetas[0],
  		pageId:tmpId, 
  	 	pageName:pageMetas[2],
  	 	groupName:pageMetas[3],
  		groupPath:pageMetas[4], 
  	  productItemCode:pageMetas[5],
  	  productName:pageMetas[6],
  		getPaymentResult: function(){   	  
  	     var inputElem = document.getElementById("wsgapayresult");
  	     if(inputElem)
  	       return inputElem.value;
  	     else
  	       return;
         },
 		  	
 		  	markGrouping: function(param){
  	 			WSGA.pageTracker._setVar(WSGA.wsga_clean(param));
  	 		},
  	 		
  	 		url:document.location.href
  	 	};
	  return pageObj;
  },
  
  wsga_buildtitle:function(wspage){
    this.wsga_log('WSGA: wsga_buildtitle');
    
    //start building pretty title
 	  var wsgaTitle="";
 	
   	//add theme
   	if(__wsgaConfObject.themeTitles && __wsgaConfObject.themeTitles[wspage.theme])
   	  wsgaTitle+=__wsgaConfObject.themeTitles[wspage.theme];
 	  
 	  //page specific reporting 	
  	if(wspage.pageId==3){ //productlisting page
  		wsgaTitle+=__wsgaConfObject.pageTitles[wspage.pageId]+'/'+this.wsga_clean(wspage.groupPath);
     	return wsgaTitle;
  	}else if(wspage.pageId==6){ //payment return page
  		var orderResult = wspage.getPaymentResult();
  		if(orderResult=="success"){
  		  //add listener to mark transaction 
  		  //wspage.markTransaction();
  		  this.trackTransaction = true;
  		  wsgaTitle+=__wsgaConfObject.orderSuccessTitle;
     	  return wsgaTitle;
  		}else if(orderResult=="cancel"){
  		  wsgaTitle+=__wsgaConfObject.orderCancelledTitle;
     	  return wsgaTitle;
  		}else if(orderResult=="fail"){
  		  wsgaTitle+=__wsgaConfObject.orderFailedTitle;
     	  return wsgaTitle;
  		}else{
  		  return;
  		}
  	}else if(wspage.pageId==9){ //single product page
  	 	//product based grouping
  	 	wspage.markGrouping(wspage.productName);
  	 	wsgaTitle+=__wsgaConfObject.pageTitles[wspage.pageId]+'/'+this.wsga_clean(wspage.productItemCode)+'/'+this.wsga_clean(wspage.productName);
     	return wsgaTitle;
     	
  	}else if(__wsgaConfObject.pageTitles[wspage.pageId]){ //some known default page
  		wsgaTitle+=__wsgaConfObject.pageTitles[wspage.pageId];
     	return wsgaTitle;
     	
  	}else if(wspage.pageId>=100){ //freepage
  		var pgn = this.wsga_clean(wspage.pageName);
	 	if(pgn!="")
	 	    return(wsgaTitle+__wsgaConfObject.freepageTitle + '/'+pgn);
	 	else
	 	  	return;
	 	  	
  	}else if(wspage.pageId==""){ //empty (means file include) -> try to get file name from parameters
	 	 var untrustedPageIDParameter = this.wsga_parametermap(wspage.url)["pageID"]; 
	 	 var cleanedPageIdParameter = this.wsga_clean(untrustedPageIDParameter);
	 	 if(cleanedPageIdParameter!=""){
           wsgaTitle += __wsgaConfObject.freepageTitle+"/"+cleanedPageIdParameter;
	 	   return wsgaTitle;
	 	 }else{
	 	   return
	 	 }
  	}	  
  },
  
  wsga_setuptransaction:function(){
    this.wsga_log('WSGA: wsga_setuptransaction');
    
  	// get order data rows from textarea called 'utmtrans'
  	var ta = document.getElementById("utmtrans");
  	var cleanedInfo = this.wsga_cleanTransactionInfo(ta.value);
  	var textRows = cleanedInfo.split('\n');
  	
  	// add transaction
  	var transItems = textRows[0].split('|');  	
  	this.pageTracker._addTrans(
    	transItems[1], // order id - required
    	transItems[2], // affiliation or store name
    	transItems[3], // total - required
    	transItems[4], // tax
    	transItems[5], // shipping
    	transItems[6], // city
    	transItems[7], // state or province
    	transItems[8]  // country  	
  	);
  	
  	this.loggedUrl = 'Transaction:\n' + transItems.join(', ') + '\nItems:';
  	
  	// add ordered items
  	for (var rowNum=1;rowNum<textRows.length;rowNum++){
    	var itemItems = textRows[rowNum].split('|');
    	this.pageTracker._addItem(
    	 itemItems[1], // order id - required
    	 itemItems[2], // SKU/code
    	 itemItems[3], // product name  	
    	 itemItems[4], // catagory or variation
    	 itemItems[5], // unit price - required
    	 itemItems[6]  // quantity - required
    	);
    	
    	this.loggedUrl+='\n';
    	this.loggedUrl+=itemItems.join(', ');
  	}
  	  	
  	this.pageTracker._trackTrans();
  	  	  
  	this.wsga_log("WSGA: Tracked transaction \n" + this.loggedUrl);	
  },
 
  wsga_cleanTransactionInfo:function (transactionInfo){
    this.wsga_log('WSGA: wsga_cleanTransactionInfo');
  	var result ="";
  	var lines = transactionInfo.split("UTM:");
  	var orderId="";
  	for(var i=0; i<lines.length; i++){
  		var line = lines[i].split("|");
  		if(line[0]=="T"){
  			orderId=line[1];
  			line[4]=this.removecurrency(line[4]); //VAT total sum
  			line[5]=this.removecurrency(line[5]); //delivery cost
  			result+="UTM:"+line.join("|");
  		}else if(line[0]=="I"){
  			line[1]=orderId;
  			line[5]=this.removecurrency(line[5]); //product unit price
  			result+="UTM:"+line.join("|");	
  		}
  	}
    return result;
  },
  
  //searchform tracking
  wsga_submithandler:function(evt){
    WSGA.wsga_log('WSGA: wsga_submithandler');
  	var form = (window.event) ? evt.srcElement : evt.target;
  	var params={};
  	for(var i=0; i<form.elements.length; i++){
  		params[form.elements[i].name]=form.elements[i].value;
  	}
  	//check for product searchform, if it is a search, title is found
  	var wsgaTitle= WSGA.wsga_search_title(params);
    if(wsgaTitle){
  		WSGA.wsga_report(wsgaTitle);
	  }
  },
  
  //offsite and search link tracking
  wsga_linkclickhandler:function(evt){
    WSGA.wsga_log('WSGA: wsga_linkclickhandler');
  	//unfortunately the clicked event target isn't always the link element in all browsers, it can be some childElement inside the link
  	var tg = (window.event) ? evt.srcElement : evt.target;
  	while(tg && tg.tagName!="A" && tg.tagName!="BODY"){
  		tg=tg.parentNode;
  	}
  	if(tg.tagName=="A"){
  		//external link tracking
  		if(tg.href.indexOf(document.location.host) == -1 && tg.href.indexOf("javascript:") == -1){
  			var url = WSGA.wsga_clean(tg.href);
  			var txt = WSGA.wsga_clean(tg.innerHTML);
  			var wsgaTitle = __wsgaConfObject.offsiteTitle+'/' + txt + '-' + url;			
  			WSGA.wsga_report(wsgaTitle);
  		}
  		//Workspace product search link tracking
  		var wsgaTitle= WSGA.wsga_search_title(WSGA.wsga_parametermap(tg.href));
  		if(wsgaTitle){
  			wsgaTitle+='/'+WSGA.wsga_clean(tg.innerHTML); //TODO: might this contain some extra notation?
  		  WSGA.wsga_report(wsgaTitle);
  		}
  	}
  },
  
  //deciphers search parameters to titles, if not a search -> nothing is returned		
  wsga_search_title:function(params){ 
    this.wsga_log('WSGA: wsga_search_title');
  	if(params["action"]=="search"){
  		var keywords = params["searchPattern"];
  		var cleaned=this.wsga_clean(keywords);
  		return __wsgaConfObject.basicSearchTitle+"/"+cleaned;
  	}else if(params["action"]=="advancedsearch"){
  		var wsgaTitle = __wsgaConfObject.advancedSearchTitle+"/"; 
  		var searchAttrs = params["advancedsearch.attributes"].split(",");
  		for(var i=0; i<searchAttrs.length; i++){
  			var searchAtt = searchAttrs[i];
  			var val = params["advancedsearch."+searchAtt];
  			if(searchAtt!="" && val && val!=""){
  			  wsgaTitle+=""+this.wsga_clean(searchAtt)+"="+this.wsga_clean(val)+"&";
  			}
  		}
  		wsgaTitle=wsgaTitle.substring(0, wsgaTitle.length-1);
  		return wsgaTitle;
  	}
  },
  
  // remove illegal characters and transform scands to ao
  wsga_clean:function(str){
    this.wsga_log('WSGA: wsga_clean');
  	if(!str)  return "";
  	//trim first
    var str2 = str.replace(/^\s+/, '');
    str2 = str2.replace(/\s+$/, '');
  	str2 = str2.replace(/[ ]/g, "_");
  	str2 = str2.replace(/[ä|Ä]/g, "a");
  	str2 = str2.replace(/[ö|Ö]/g, "o");
  	str2 = str2.replace(/[å|Å]/g, "o");
  	return str2.replace(/[^a-z|A-Z|0-9|\-|\/]/g, "_");
  },
  
  //Check that this works with your shop's currency settings
	removecurrency: function(priceWithCurrencyLabels){
	  var noLabel = priceWithCurrencyLabels.replace(" €", ""); 
	  return noLabel.replace(",", ".");
    },
  
  //parse parameters from given url
  wsga_parametermap:function(url){
    this.wsga_log('WSGA: wsga_parametermap');
  	var end = url.length;
  	if(url.indexOf("#")!=-1)
  	  end=url.indexOf("#");
  	var parameterString = url.substring(url.indexOf('?')+1, end);
    var parameterTokens = parameterString.split("&");
  	var map = {};
      for (i = 0; i < parameterTokens.length; i++){
      	var pair = parameterTokens[i].split("=");
      	if(pair[0] && pair[1]){
  		    map[pair[0]] = pair[1];
      	}
  	}
  	return map;
  },
  
  wsga_log:function(message) {
	 if (this.writeLog==true){
	   this.wsga_writelog (message);  
	 }
  },
  
  
  wsga_writelog:function(message) {
    // write to firebug console if it is present
    if (typeof(console) != "undefined"){
       console.log(message)
    }
    
    // if log is not wanted also to a separate window return
    if (this.useConsoleLogOnly==true){
      return;
    }
    
    // write to separate debug window
    if (!this.debugWindow || this.debugWindow.closed) {
        var win = window.open("", "Debug Log", "width=800,height=600," +
                              "scrollbars=yes,resizable=yes,status=no," +
                              "location=no,menubar=no,toolbar=no");
        if (!win) return;
        var doc = win.document;
        doc.write("<html><head><title>Debug Log</title></head>" +
                  "<body></body></html>");
        doc.close();
        this.debugWindow = win;
    }
    var logLine = this.debugWindow.document.createElement("div");
    logLine.appendChild(this.debugWindow.document.createTextNode(message));
    this.debugWindow.document.body.appendChild(logLine);    
  }
};




