//Functions used for calculating metrics
function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}

//This function reverses the Document title to generate a meaningful Bread Crump for Omniture.
//If  breadCrumpDocTitle = Santa Fe? Steel Bakery Basket, Black, 18" x 12" | Risers And Display Racks | Displayware items 
// and oldDelimitter = | & newDelimitter = :. The output of this function will be
// Home Page : Displayware items : Risers And Display Racks : Santa Fe? Steel Bakery Basket, Black, 18" x 12"
function reverseBreadCrumb(breadCrumpDocTitle, oldDelimitter , newDelimitter )
{	
	var homePageVar = 'Home Page';
	var reversedBreadCrump = '';	
	var splitResultBreadCrumpDocTitle = breadCrumpDocTitle.split(oldDelimitter);

	for (i=splitResultBreadCrumpDocTitle.length-1; i >= 0; i--)
	{		
		if(splitResultBreadCrumpDocTitle.length != 1)
		reversedBreadCrump = reversedBreadCrump + '' + newDelimitter + '' + splitResultBreadCrumpDocTitle[i] ;
		else 	
		reversedBreadCrump = reversedBreadCrump + splitResultBreadCrumpDocTitle[i] ;	
	}

	if(reversedBreadCrump == homePageVar) 
		return breadCrumpDocTitle;
	else 
		return trim(reversedBreadCrump);

}


//This function is used to strip the patterns  '| from Wasserstrom, at Wasserstrom, - Wasserstrom ' from the doc title 
function stripTitleForOmniture(documentTitle )
{
	
	
	var strippedDocumentTitle = null;
	if(documentTitle.length > 0)
	{
		//Strip of the patterns  '| from Wasserstrom, at Wasserstrom, - Wasserstrom, from Wasserstrom ' from the doc title before sending to Omniture  
		var idx1 = documentTitle.indexOf("| from Wasserstrom");	 
		if(idx1 !=-1) {
			strippedDocumentTitle=documentTitle.substring(0,idx1);
		} else {
				idx1 = documentTitle.indexOf("at Wasserstrom");	
				if(idx1 !=-1) {
					strippedDocumentTitle=documentTitle.substring(0,idx1);
				} else {
					idx1 = documentTitle.indexOf("from Wasserstrom - Wasserstrom");		
					if(idx1 !=-1) {
						strippedDocumentTitle=documentTitle.substring(0,idx1);
					} else {		
						idx1 = documentTitle.indexOf("- Wasserstrom");		
						if(idx1 !=-1) {
								strippedDocumentTitle=documentTitle.substring(0,idx1);
						} else {
								idx1 = documentTitle.indexOf("from Wasserstrom");		
								if(idx1 !=-1) {
									strippedDocumentTitle=documentTitle.substring(0,idx1);
								}
						}
					}
				}
				
		}
								
	}

	if(strippedDocumentTitle == null) 
		return documentTitle;
	else 
		return trim(strippedDocumentTitle);

}
// This function allows only numbers and alphabets.
function allowStringsDigitsOnly(theString){	
	return theString.replace(/[^\w\s-:._]/gi,'');
}

// This function removes the special characters  to remove the special characters  HTML characters, reigistered symbols, trademarks, $ , ' . 
//\w -- all words \s allow white space, allow - , : ,. , _ patterns
function cleanseString(theString){	
	return theString.replace(/[^\w\s-:._]/gi,'');
}

//This function will allow only numbers and . for the price. And removes all other characters from price.
//alert(cleansePrice('fdnvv12.::58v-\n\t\rg=-rwigr-<>";crew!@#$%%^^*&*(&)_+foo['));
function cleansePrice(thePrice){	
	return thePrice.replace(/[^0-9.]/gi,'');
}

//This function will allow only numbers and . for the price. And removes all other characters from price.
function cleanseNumber(thePrice){	
	return thePrice.replace(/[^0-9.]/gi,'');
}

//This function removes special characters from the data passed and concatenates with the delimiter passed.
function formatSingleProductVar(categoryDesc,productDesc,sku,qty,price,delimitter) {
	var productsVar = cleanseString(categoryDesc) + delimitter +
					  cleanseString(sku) + delimitter +
					  cleanseNumber(qty) + delimitter +
					  cleansePrice(price) ;
					  
	return productsVar;
}
//alert(formatSingleProductVar('Category7','ProductDesc','SKU8','2','10.11',';'));


// Assumption : All the category names, skulements are fetched by document.getElementsByName method
// This function formats the products variables to be - s.products="Category7;SKU8;2;10.11,Category9;SKU9;2;10.11,Category10;SKU10;2;10.11"
function formatMultipleProductsVar(wasOrderedCategoryNameElements,wasOrderedProductNameElements,wasOrderedSkuElements , wasOrderedItemQtyElements, wasOrderedPerItemTotalPriceElements, individualElementsDelimitter , productsSetDelimitter ){		 
		 var productsSetVar = "";
		 //Loop through all the elements and generate the product set pattern.
		 for(var i = 0; i < wasOrderedSkuElements.length; i++) {
			productsSetVar = productsSetVar + 
								formatSingleProductVar(	
											wasOrderedCategoryNameElements[i].value , 
											wasOrderedProductNameElements[i].value , 
											wasOrderedSkuElements[i].value , 
											wasOrderedItemQtyElements[i].value , 
											wasOrderedPerItemTotalPriceElements[i].value , 
											individualElementsDelimitter
											);
			if(wasOrderedSkuElements.length > 1 && i<wasOrderedSkuElements.length-1)
			productsSetVar = productsSetVar			+ 	productsSetDelimitter;
		 }
		
		return productsSetVar;
}

//This function is used to generate the pattern like 
//ERP:<UserID>:<OrgName> 
//NONERP-<UserID>
//GUEST:
function generatePatternForUser(wasUserType, wasUserAccountId, wasUserLogonId , wasUserOrganization,delimitter1, delimitter2 ) {
	if(wasUserType) wasUserType = trim(wasUserType);
	if(wasUserLogonId) wasUserLogonId = trim(wasUserLogonId);
	if(wasUserOrganization) wasUserOrganization = trim(wasUserOrganization);
	var userPattern ="";
	//Check for Guest
	if(wasUserType == 'G'){userPattern = "GUEST" +delimitter1;}	
	if(wasUserType == 'R'){
		//Check for ERP
		if(wasUserAccountId != '')  {
			if(wasUserOrganization=='') wasUserOrganization = 'EMPTYERPORGNAME'
			userPattern = "ERP" + delimitter1 + allowStringsDigitsOnly(wasUserLogonId)+ delimitter1 + cleanseString(wasUserOrganization);
		}
		//Check for NONERP
		if(wasUserAccountId == '') userPattern = "NONERP"+delimitter2 + allowStringsDigitsOnly(wasUserLogonId) ;			
	}
	return userPattern;
}

//This function is used to return an array of elements from 
//wasElementsArray(this variable is the document.getlElemnetByNames object
//elementsType - String --->  Formats data asssuming String
//elementsType - Number --->  Formats data asssuming it is number and removes unnecessary characters
//elementsType - Price --->   Formats data asssuming Price and removes unnecessary characters
function retunrArrayForOrderedElements( wasElementsArray, elementsType) {	 
	 var waasArray=new Array();	 
	 for(var i = 0; i < wasElementsArray.length; i++) {	
	 			 if(elementsType == 'String') waasArray[i] = 	cleanseString(wasElementsArray[i].value);	
	 		else if(elementsType == 'Number') waasArray[i] = 	cleanseNumber(wasElementsArray[i].value);
	 		else if(elementsType == 'Price')  waasArray[i] = 	cleansePrice(wasElementsArray[i].value);
	 		else waasArray[i] = 	cleanseString(wasElementsArray[i].value);										
	}
	return waasArray;
}



//This function is used to print all the Omniture variables.
function printOmnitureVars() {
	alert(
				"s.pageName >>" +  	s.pageName  + "<<<\n" +
				"s.server  >>"  +   s.server	+ "<<<\n" +
				"s.prop1 >>"    +  	s.prop1+ "<<<\n" +
				"s.prop2 >>"    +  	s.prop2+ "<<<\n" +
				"s.referrer >>"  + 	s.referrer 
				);	
}    
 

//Global Variables for Metrics - Initialization
if(!wasJSPPgId)var wasJSPPgId="";
if(!wasPageName)var wasPageName="";
if(!wasSrvrName)var wasSrvrName="";
if(!wasChannel)var wasChannel="";
if(!wasPgType)var wasPgType="";
if(!wasUserType)var wasUserType="";
if(!wasNoOfSrchTrmResults)var wasNoOfSrchTrmResults="";

if(!wasCampaigns)var wasCampaigns="";
if(!wasState)var wasState="";
if(!wasZip)var wasZip="";
if(!wasEvents)var wasEvents="";
if(!wasProducts)var wasProducts="";
if(!wasPurchaseId)var wasPurchaseId="";

if(!wasUserTypePtn)var wasUserTypePtn="";
//This value is used to track the revenue generated by user types.
if(!wasUserBasedRevenue)var wasUserBasedRevenue="";
//This variable is set in PDP Page
if(!wasProductId)var wasProductId="";
//this variable is set in the product sub category page. This gives the product details
if(!wassPdSbCtgyBrdCmb)var wassPdSbCtgyBrdCmb="";

//This variable is used to capture the user typed Search term
if(!wasUserTypedSrchTrm)var wasUserTypedSrchTrm="";

// This variable is used to page specific page ids , like checkout page has multiple command names 
if(!wasPageIdFromPgBody)var wasPageIdFromPgBody="";


//Geth the pathname from the window url. And get the last value name for the product subcategory page
var wassCurrentURLPath=window.location.pathname;
var wassCurrentURLPathArray = wassCurrentURLPath.split('/');

//These variables are used by channel intellience which needs an array of the elements.
if(!wasItemIdsArray)var wasItemIdsArray=new Array();
if(!wasItemQtysArray)var wasItemQtysArray=new Array();
if(!wasItemPricesArray)var wasItemPricesArray=new Array();

//wasRealOrTestAccount - This variable is used to identify if the user is test or Real account.
if(!wasRealOrTestAccount)var wasRealOrTestAccount="";


//Calculate the Pagename 
switch(wasJSPPgId){
	case "HomeView":
		wasPageName = "Home Page";
		break;
	case "ProductDetailView":
		wasPageName = "PDP:";
		wasPageName+=''+wasProductId+':';		
		wasPageName+=reverseBreadCrumb( stripTitleForOmniture(document.title) ,'|' ,':' );
		break;		
	case "ProductCategoryView":
		wasPageName = "PCP:";
		wasPageName+=''+wassCurrentURLPathArray[wassCurrentURLPathArray.length-1]+':';
		wasPageName+=reverseBreadCrumb( stripTitleForOmniture(document.title) ,'|' ,':' );		
		//wasPageName+=wassPdSbCtgyBrdCmb;
		break;		
	case "ProductSubCategoryView":
		wasPageName = "PSCP:";
		wasPageName+=''+wassCurrentURLPathArray[wassCurrentURLPathArray.length-1]+':';
		wasPageName+=reverseBreadCrumb( stripTitleForOmniture(document.title) ,'|' ,':' );		
		//wasPageName+=wassPdSbCtgyBrdCmb;
		break;	
	case "OrderOKView":		
		wasPageName=reverseBreadCrumb( stripTitleForOmniture(document.title) ,'|' ,':' ); 
   	 	wasPageName=wasPageName+' ('+wasJSPPgId+') ';
   	 	//If the acccount is a test account dont send order information. 
		if(wasRealOrTestAccount != 'TestBuyer') {
			//This wasEvents, wasProducts, wasPurchaseId are used to send order tax anad shipping data to omniture.				
			wasEvents = "purchase,event6,event7,event8";
			wasProducts =  formatMultipleProductsVar(wasOrderedCategoryNameElements,wasOrderedProductNameElements,wasOrderedSkuElements,wasOrderedItemQtyElements,
										wasOrderedPerItemTotalPriceElements,';',',');	
			//Send the shipping and tax variables through event 5 & event 6 & append the data to wasProducts variable.																	
			wasProducts = wasProducts + ';' + 'event6='+cleansePrice(wasShippingPrice)+'|event7='+cleansePrice(wasOrderTax)+'|event8='+cleansePrice(wasOrderTotalRevenue) ;
			wasPurchaseId = cleanseString(wasOrderId);	
			
			//This variable is used to track revenue based on user types.	
			wasUserBasedRevenue = generatePatternForUser(wasUserType, wasUserAccountId, wasUserLogonId , wasUserOrganization,':','-');	
			
			//Set the User zip code and State 
			wasState=wasOrderState;
			wasZip = wasOrderZip;	
		}		
		//Variables used for CI.
		wasItemIdsArray = retunrArrayForOrderedElements(wasOrderedSkuElements,'String');
		wasItemQtysArray = retunrArrayForOrderedElements(wasOrderedItemQtyElements,'Number');
		wasItemPricesArray  = retunrArrayForOrderedElements(wasOrderedPerItemPriceElements,'Price');					
		break;		
	case "SearchResultsView":
		//Set the page name
		wasPageName=reverseBreadCrumb( stripTitleForOmniture(document.title) ,'|' ,':' ); 
   	 	wasPageName=wasPageName+' ('+wasJSPPgId+') '; 		
   	 	//Pass the exact search term the user typed in 
   	 	//alert(unescape(wasUserTypedSrchTrm));
   	 default:
   	 	wasPageName=reverseBreadCrumb( stripTitleForOmniture(document.title) ,'|' ,':' ); 
   	 	wasPageName=wasPageName+' ('+wasJSPPgId+') '; 
}       

//alert(wasPageName);