
/* GA: BEGIN - Main */

	/* Variables Definition */
	var gaAccount = 'UA-18623180-1'; //Site account
	var gaRollAccount = 'UA-18623180-4'; //Roll-up account
	var gaDomain = ".coverfx.com";
	var gaTimeout = 2592000; //cookie timeout
	
	if(location.host.indexOf('220.37.223') > 0){
  		//alert("test works");
  		gaAccount = 'UA-22484301-1'; //Staging Site account
		gaRollAccount = 'UA-22484301-2'; //Staging Roll-up account
	}
	
	/* Plugins */
	function gup( name ) //Get URL parameter
	{
		name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
		var regexS = "[\\?&]"+name+"=([^&#]*)";
		var regex = new RegExp( regexS );
		var results = regex.exec( window.location.href );
		if( results == null )
			return "";
		else
			return results[1];
	} 

       //Trim Function - Remove heading and trailing spaces  (TODO:copy to live website) 
	String.prototype.trim = function () {
    	return this.replace(/^\s*/, "").replace(/\s*$/, "");
	}
	
	function urlMatch( token )
	{
		token = token.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
		var regexS = token;
		var regex = new RegExp( regexS );
		var results = regex.exec( window.location.href );
		if( results == null )
			return false;
		else
			return true;
	}

	function setContentType(){
	}
	
	function setAttibution(){}
	
	function setVisitor(){
			//if: https://www.coverfx.com/Canada/Checkout/Receipt.aspx?OrderNumber=2042&OrderId=54
			//Type is not Med-Pract or Makeup
			//Receipt Page AND OrderNumber > 0 AND OrderID > 0	
	
		_gaq.push(function() {
			var pageTracker = _gat._getTrackerByName();
			var v3 = pageTracker._getVisitorCustomVar(3);
			//alert ("V3: " + v3);
		 	if (!v3) { 
		 		//alert("empty variable");
		 		pageTracker._setCustomVar(3,'VType', 'Visitor-Only', 1);
		 	}
		});
		//_gaq.push(['_setCustomVar', 3, 'VType', 'Visitor_Type', 1])
		//_gaq.push(['tr._setCustomVar', 3, 'VType', 'Visitor_Type', 1])
	}
	
	function setLifeCycle(){
		/*var lcValue;
		//Product
		if (window.location.href.indexOf("Product.aspx?ProductId=")>0 || urlMatch("-P[0-9]{1,3}C[0-9]{1,3}\.aspx"){
			//cvar_track("Product",pageTracker);
			lcValue = "1_Product";
			//alert(lcValue);
		}
		//Basket
		if (window.location.href.indexOf("Basket.aspx")>0){
			//cvar_track("Product",pageTracker);
			lcValue = "2_Basket";
			//alert(lcValue);
		}
		
		_gaq.push(function() {
		  var pTrack = _gat._getTrackerByName();
		  var pTrackRollup = _gat._getTrackerByName('tr');
		  var v3 = pTrack._getVisitorCustomVar(3);
		  
		  if (v3 == undefined){
		  	pTrack._setCustomVar(3,'VType','End-User',1); //Visitor Type Set
		  	pTrack._trackEvent('VType-v3', 'request-sent', 'undefined');
		  	pTrackRollup._setCustomVar(3,'VType','End-User',1); //Visitor Type Set
		  	pTrackRollup._trackEvent('VType-v3', 'request-sent', 'undefined');
		  	
		} 		
		*/
	}
	
	function setRecipe(){};
	
	/* GA Calls */
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', gaAccount]);
  _gaq.push(['_setAllowAnchor', true]);
  _gaq.push(['_setDomainName', gaDomain]);
  _gaq.push(['_setNamespace', 'main']);
  _gaq.push(['_setSessionCookieTimeout', gaTimeout]);
  _gaq.push(['_addOrganic', 'images.google.com', 'prev']);
  _gaq.push(['_setMaxCustomVariables', 10]);
  //Custom Vars
  //_gaq.push(['_setCustomVar', 1, 'Content-Type', 'TBD:Content-Type:Page-Type', 3]); //Content Type
  //_gaq.push(['_setCustomVar', 2, 'V#-Channel_Code', 'Visitor_ID-Source_Name', 2]); //Attribution
  //_gaq.push(['_setCustomVar', 3, 'VType', 'Visitor_Type', 1]); //Visitor Type
//setVisitor();
  //_gaq.push(['_setCustomVar', 4, 'LifeC', 'Visitor_Stage_Name-Database_Status', 1]); //Visitor Lifecycle
  //_gaq.push(['_setCustomVar', 5, 'RecipeAB', 'Recipe-Name', ]); //Testing Recipe Name
  _gaq.push(['_trackPageview']);

/* GA: END - Main */


/* GA: BEGIN - Rollup */
  var _gaq = _gaq || [];
  _gaq.push(['tr._setAccount', gaRollAccount]);
  _gaq.push(['tr._setAllowAnchor', true]);
  _gaq.push(['tr._setDomainName', gaDomain]);
  _gaq.push(['tr._setNamespace', 'rollup']);
  _gaq.push(['tr._setSessionCookieTimeout', gaTimeout]);
  _gaq.push(['tr._addOrganic', 'images.google.com', 'prev']);
  _gaq.push(['tr._setMaxCustomVariables', 10]);
  _gaq.push(['tr._trackPageview']);

/* GA: END - Rollup */


/* GA E-commerce tracking */
	
//if (gup("test") == 1){ //TODO: Remove after testing
	if (window.location.pathname.indexOf("/Checkout/Receipt.aspx")>0){	
		if (gup("OrderNumber")){
			
			//_gaq.push(function() {
			jQuery(document).ready(function() {
					//Order ID:
				var orderId = gup("OrderNumber") + "-" + gup("OrderId");
					//Store
				var affStore = "CoverFX Online - " + (window.location.pathname.indexOf("/Canada/")>=0 ? "Canada" : "US"); //TODO: read parameter to identify affiliates.
					//Total Order Value
				var orderVal = document.getElementById('ctl00_wpm_ReceiptPage_ctl04_OrderTotalSummary1_Subtotal').innerHTML;
				orderVal = orderVal.substring(orderVal.indexOf('$')+1).trim();			
						//Tax
				var taxVal = document.getElementById('ctl00_wpm_ReceiptPage_ctl04_OrderTotalSummary1_Taxes').innerHTML;
				taxVal = taxVal.substring(taxVal.indexOf('$')+1).trim(); //ctl00_wpm_ReceiptPage_ctl04_OrderTotalSummary1_Taxes
					//Shipping
				shipVal = document.getElementById('ctl00_wpm_ReceiptPage_ctl04_OrderTotalSummary1_Shipping').innerHTML;
				shipVal = shipVal.substring(shipVal.indexOf('$')+1).trim();//ctl00_wpm_ReceiptPage_ctl04_OrderTotalSummary1_Shipping
				
					//City & Country
				var address = jQuery('.address');
				var splitAddress = address[0].innerHTML.split('<br>');		
				cityName = splitAddress[2].substring(0,splitAddress[2].length - 8).trim();
				countryName = splitAddress[3].trim();
				
					//Get Items
			
				//Product Name
				prodObj = jQuery('span').filter(function() {
    				return this.id.match(/.*_SKU/);
				}).parent().next(); //TODO: extract product name from AbleCommerce
				
				//Category
				prodCateg = "Missing"; //TODO: extract category from AbleCommerce
				
				//Quantity	
				qty = jQuery('span').filter(function() {
			        return this.id.match(/.*_Quantity/);
			    })
				
				//SKU/code
				sku = jQuery('span').filter(function() {
        			return this.id.match(/.*_SKU/);
    			})
				
				//Unit Price
				unit = jQuery('span').filter(function() {
        			return this.id.match(/.*_Price/);
    			})
		
			
			//});
		
			//Start building E-commerce tracking - Main GA Profile
			_gaq.push(['_addTrans',
  			  orderId, 	    // order ID - required
			  affStore,   	// affiliation or store name
			  orderVal,     // total - required
			  taxVal, 		// tax
			  shipVal,  // shipping
			  cityName,     // city
			  '', 		    // state or province
			  countryName,  // country
			]);
			
			//Start building E-commerce tracking - Main GA Profile - Added Nov.01.2010
			_gaq.push(['tr._addTrans',
  			  orderId, 	    // order ID - required
			  affStore,   	// affiliation or store name
			  orderVal,     // total - required
			  taxVal, 		// tax
			  shipVal,  // shipping
			  cityName,     // city
			  '', 		    // state or province
			  countryName,  // country
			]);
			
			// Read Qty, SKU, Prod Name and Price using JQuery
			// Iteraty for (length-1) and avoid the SHIPPING SKU. >> Make one push for every item. 
			
			for (i=0; i<sku.length; i++){
					
				auxProd = prodObj[i].innerHTML;
				prodName = auxProd.substring(0,auxProd.indexOf("<ul")-1).trim();
					
					//ADD Item Call
				if(sku[i].innerHTML != 'SHIPPING'){
					_gaq.push(['_addItem',
					  orderId,          // order ID - required
					  sku[i].innerHTML, // SKU/code
					  prodName,         // product name
					  prodCateg,   		// category or variation - MISSING
					  unit[i].innerHTML,// unit price - required
					  qty[i].innerHTML  // quantity - required
					]);
					_gaq.push(['tr._addItem', // Added - Nov.01.2010
					  orderId,          // order ID - required
					  sku[i].innerHTML, // SKU/code
					  prodName,         // product name
					  prodCateg,   		// category or variation - MISSING
					  unit[i].innerHTML,// unit price - required
					  qty[i].innerHTML  // quantity - required
					]);
				}
			
			}
			
			_gaq.push(['_trackTrans']);
			_gaq.push(['tr._trackTrans']);
			
			});
			
		}
		else			
			if (gup("test") == 1) alert ("Not valid order ID");
	}
//} //TODO: Remove - End Test Loop

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    //ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/u/ga_debug.js';
	ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();


//Custom interactions tracking

// Tracking Wishlist additions
if(window.location.pathname.indexOf("/Basket.aspx")>0){
	jQuery(document).ready(function() {
		//jQuery('a:contains("Move to wishlist")').click(function() {
		jQuery('#ctl00_wpm_Basket_ctl04_BasketGrid_ctl02_SaveItemButton').click(function() {
		    if (gup("test") == 1) alert('Move to wish-list - Handler for .click() called - START .');
		    //var tempA = jQuery('a:contains("Move to wishlist")').prev().prev();
		    var eventPath = jQuery('#ctl00_wpm_Basket_ctl04_BasketGrid_ctl02_SaveItemButton').prev().prev()[0].innerText.replace(/\s/g,'-');
		    _gaq.push(['_trackPageview','/vpv/whishlist-move/' + eventPath]);
		    _gaq.push(['tr._trackPageview','/vpv/whishlist-move/' + eventPath]);  
		    if (gup("test") == 1) alert('Move to wish-list - Handler for .click() called - END.');
		});
	});
	

}

//Track Pro FX Inner Circle
try{
	//Conversion
	//if(window.location.pathname.indexOf("ThankyouJoin.aspx")>0){
	if(window.location.href.indexOf("ThankyouJoin.aspx?Thankyou=Pro&mainSection=4&subSection=0&id=")>0){  
		//VType
		_gaq.push(function() {
		  var pTrack = _gat._getTrackerByName();
		  var pTrackRollup = _gat._getTrackerByName('tr');
		  var v3 = pTrack._getVisitorCustomVar(3);
		  
		  if (v3 == undefined){
		  	pTrack._setCustomVar(3,'VType','Makeup-Req',1); //Visitor Type Set
		  	pTrack._trackEvent('VType-v3', 'request-sent', 'undefined');
		  	pTrackRollup._setCustomVar(3,'VType','Makeup-Req',1); //Visitor Type Set
		  	pTrackRollup._trackEvent('VType-v3', 'request-sent', 'undefined');
		  	
		  	/*_gaq.push(['_setCustomVar',3,'VType','Makeup-Req',1]); //Visitor Type Set
		  	_gaq.push(['_trackEvent', 'VType-v3', 'request-sent', 'undefined']);"
			_gaq.push(['tr._setCustomVar',3,'VType','Makeup-Req',1]); //Visitor Type Set
			_gaq.push(['tr._trackEvent', 'VType-v3', 'request-sent', 'undefined']);"*/
		  } else if (!(v3.indexOf("Makeup")>0)){
		  	pTrack._setCustomVar(3,'VType','Makeup-Req',1); //Visitor Type Set
		  	pTrack._trackEvent('VType-v3', 'vtype-change', v3);
		  	pTrackRollup._setCustomVar(3,'VType','Makeup-Req',1); //Visitor Type Set
		  	pTrackRollup._trackEvent('VType-v3', 'vtype-change', v3);
		  	
		  	/*_gaq.push(['_setCustomVar',3,'VType','Makeup-Req',1]); //Visitor Type Change
		  	_gaq.push(['_trackEvent', 'VType-v3', 'vtype-change', v3]);"
			_gaq.push(['tr._setCustomVar',3,'VType','Makeup-Req',1]); //Visitor Type Change
			_gaq.push(['tr._trackEvent', 'VType-v3', 'vtype-change', v3]);"*/
		  }
		});
		
		//Print Button
		jQuery(document).ready(function() {
			jQuery('.divProFXMethodForthContent').children('a').mouseup(function() {
			    _gaq.push(['_trackPageview','/vpv/pro-fx-inner-circle/print-application-button']);
		        _gaq.push(['tr._trackPageview','/vpv/pro-fx-inner-circle/print-application-button']); 	
			});
		});
		
	}
} catch(err) {}


//Track Med FX Inner Circle
try{
	//Conversion
	if(window.location.href.indexOf("ThankyouJoin.aspx\?mainSection=3&subSection=-3")>0){  
		//VType
		_gaq.push(function() {
		  var pTrack = _gat._getTrackerByName();
		  var pTrackRollup = _gat._getTrackerByName('tr');
		  var v3 = pTrack._getVisitorCustomVar(3);
		  
		  if (v3 == undefined){
		  	pTrack._setCustomVar(3,'VType','Med-Pract-Req',1); //Visitor Type Set
		  	pTrack._trackEvent('VType-v3', 'request-sent', 'undefined');
		  	pTrackRollup._setCustomVar(3,'VType','Med-Pract-Req',1); //Visitor Type Set
		  	pTrackRollup._trackEvent('VType-v3', 'request-sent', 'undefined');
		  	
		  } else if (!(v3.indexOf("Med-Pract")>0)){
		  	pTrack._setCustomVar(3,'VType','Med-Pract-Req',1); //Visitor Type Set
		  	pTrack._trackEvent('VType-v3', 'vtype-change', v3);
		  	pTrackRollup._setCustomVar(3,'VType','Med-Pract-Req',1); //Visitor Type Set
		  	pTrackRollup._trackEvent('VType-v3', 'vtype-change', v3);
		  	
		  }
		});		
	}
} catch(err) {}


//Track End User Inner Circle
try{
	//Steps
	if(window.location.pathname.indexOf("JoinGenCoverFX.aspx")>0){ 
		jQuery(document).ready(function() {
			if(jQuery('img#ctl00_wpm_JoinFrm_ctl06_imgMatchStep1').attr('src').indexOf('InnerStep1Active')>0){
				_gaq.push(['_trackPageview', window.location.pathname + '#end-user-inner-step1']);
				_gaq.push(['tr._trackPageview', window.location.pathname + '#end-user-inner-step1']);
				//alert("step1");
			}
			else if(jQuery('img#ctl00_wpm_JoinFrm_ctl06_imgMatchStep2').attr('src').indexOf('InnerStep2Active')>0){
				_gaq.push(['_trackPageview', window.location.pathname + '#end-user-inner-step2']);
				_gaq.push(['tr._trackPageview', window.location.pathname + '#end-user-inner-step2']);
				//alert("step2");
			}
			else if(jQuery('img#ctl00_wpm_JoinFrm_ctl06_imgMatchStep3').attr('src').indexOf('InnerStep3Active')>0){
				_gaq.push(['_trackPageview', window.location.pathname + '#end-user-inner-step3']);
				_gaq.push(['tr._trackPageview', window.location.pathname + '#end-user-inner-step3']);
				//alert("step3");
			}
		});

	}
	//Conversion
	if(window.location.href.indexOf("Thankyou.aspx")>0){  
		//VType
		_gaq.push(function() {
		  var pTrack = _gat._getTrackerByName();
		  var pTrackRollup = _gat._getTrackerByName('tr');
		  var v3 = pTrack._getVisitorCustomVar(3);
		  
		  if (v3 == undefined){
		  	pTrack._setCustomVar(3,'VType','End-User',1); //Visitor Type Set
		  	pTrack._trackEvent('VType-v3', 'request-sent', 'undefined');
		  	pTrackRollup._setCustomVar(3,'VType','End-User',1); //Visitor Type Set
		  	pTrackRollup._trackEvent('VType-v3', 'request-sent', 'undefined');
		  	
		  } 		
		  
		});		
	}

} catch(err) {}



//

/*  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();
*/



