/*
 * cmdatatagutils.js
 * $Id: cmdatatagutils-MASTER.js.txt 150533 2010-06-22 18:13:38Z ablattman $
 * $Revision: 150533 $
 *
 * Version 4.1.0
 *
 * Coremetrics Tag v4.0, 8/7/2006
 * COPYRIGHT 1999-2002 COREMETRICS, INC. 
 * ALL RIGHTS RESERVED. U.S.PATENT PENDING
 *
 * The following functions aid in the creation of Coremetrics data tags.
 * Date		Imp. Eng.		Desc
 * 06/01/06	Hutch White		Added leadTime-cm.pv5 and arrivalDate-cm.pv6 to cmCreatePageViewTag function for custom rpt
 * 11/01/06	Eliot Towb		Added Conversion Event Tag function
 * 11/28/06	Eliot Towb		Added cmSetTest function
 * 03/19/07	Mary Ochoa		Added cmSetTest() Function for 90165498
 * 07/27/07	Hutch White		Add manual and element tags
 * 11/05/07	Hutch White		Update with cmCreatePageviewConversionEventTag combo tag
 * 04/30/08 ABRINK			Added vars cm_Track... to activate Real Estate Impressions
 * 06/03/08	Hutch White		Add IX Survey Parameters to Pageview and Conversion Tags
 * 06/06/08	Mary Ochoa		Enabled Stamp parameters for the Element and Conversion Event tags
 * 11/06/08	HWHITE			Enable Explore Attributes.  Include extra fields in attributes.
 * 11/17/08	HWHITE			Remove reference to maketag in manual tagging
 * 1/8/2009	YHUNT			Added code that makes the techprops tag automatic
 * 08/14/09	ABRINK			Added cm_UseUTF8 var for multibyte
 * 08/17/09	HWHITE			Update tagging to maketag version.  Normalize # sign in link click tags
 * 11/02/09	ABRINK			Add pv10 custom field to Page/Product/TProps tags
 * 11/10/09	ABRINK			Update custom function cmLIVEviewClick to work with current eluminate/IE8
 * 11/11/09	ABRINK			Add pv11 for sessionID to Page/Product/TProps tags **REMOVED 12/10/09
 * 01/29/10	ABRINK			Add Currency code function
 * 05/26/10	ETOWB			Changed cmSetTest function to point to new test system IDs - 60081223;60086566
 * 06/18/10	HWHITE			If pageview  or techprops parameter IATA contains the string cm_mmc= and Destination URL does not then it will be used as cm_mmc parameter
 * 06/22/10	AAB				Modify pageview/techprops. If IATA parameter exists and destination URL does not contain "cm_mmc=" then use IATA as mmc in this format NoPMIDMMC-_-<IATA>-_-NA-_-NA
 * 07/20/10	AAB				Add line to manual_cm_mmc maketag so cm_mmc only appears if manual is not null and not blank ""
 * 08/30/10	ABRINK			Add ihgSession as pv11 / pv-attribute 11; remove general Explore attributes; Add pv5 & pv6 to HotelView
 * 09/17/10 ABRINK			Provision AdTarget for 90086566
 */

var cm_exAttr=new Array();  
var cm_TrackLink = "A";
var cm_TrackImpressions = "RS";
var cm_JSFEnabled = false;
var cm_UseUTF8 = true;

var manual_cm_mmc = "";

var cmJv = "1.0";
if (typeof(isNaN) == "function") cmJv = "1.1";
if (typeof(isFinite) == "function") cmJv = "1.2";
if (typeof(NaN) == "number") cmJv = "1.3";
if (typeof(decodeURI) == "function") cmJv = "1.5";
if (typeof(Array.forEach) == "function") cmJv = "1.6";
if (typeof(Iterator) == "object") cmJv = "1.7";

var cmCheckCMEMFlag = true;

var cm_JSFPCookieDomain = "www.ichotelsgroup.com";  
var cm_Production_HOST = "cls.ichotelsgroup.com"; 
var cm_PartnerDataClientIDs = "90086566"; 
var	cm_ClientID = "90086566";
var cm_ATEnabled = true;
if (typeof cmLoad == 'function') {
	cmLoad();
}
  
/* TAG GENERATING FUNCTIONS */

/*
 * Calling this function points tags to the production database
 */
function cmSetProduction(){
	cm_ClientID="90081223;90086566";
	cm_HOST="cls.ichotelsgroup.com/cm?";
}

/*
 * Calling this function points tags to the test ID (90083552) database
 */
function cmSetTest(){
	cm_ClientID="60081223;60086566";
	cm_HOST="testdata.coremetrics.com/cm?";
}

/*
 * Calling this function points tags to the journey database
 */
function cmSetJourney(){
	cm_ClientID="90086566"; 
	cm_HOST="cls.ichotelsgroup.com/cm?";
}

function cmCreateManualImpressionTag(pageID, trackSP, trackRE) {
		// insert code to get pageID from cmTagControl if pageID is null
		cmMakeTag(["tid","9","pi",pageID,"cm_sp",trackSP,"cm_re",trackRE,"st",cm_ClientTS]);
}

function cmCreateManualLinkClickTag(href,name,pageID) {	
	if (cmCreateLinkTag == null && cM != null) {
		var cmCreateLinkTag = cM;
	}
	if (cmCreateLinkTag != null) {		
		var dt = new Date();
		cmLnkT3 = dt.getTime();
		href=cG7.normalizeURL(href,true);
		cmCreateLinkTag(cm_ClientTS, cmLnkT3, name, href, false, pageID);
	}
}

/* manual PageviewTag for off site page tagging.  Allows client to supply URL and Referring URL
*/
function cmCreateManualPageviewTag(pageID, categoryID,DestinationURL,ReferringURL,searchTerm) {
	cmMakeTag(["tid","1","pi",pageID,"cg",categoryID,"ul",DestinationURL,"rf",ReferringURL,"se",searchTerm]);
}

function cmCreatePageElementTag(elementID, elementCategory, pageID, pageCategoryID, elementLocation,attributes) {
	if (attributes){
		var cm_exAttr=new Array;
		cm_exAttr=attributes.split("-_-");
	}	 
	var datestamp = new Date();	
	var stamp = (Math.floor(Math.random() * 11111111)) + datestamp.valueOf();	
	cmMakeTag(["tid","15","eid",elementID,"ecat",elementCategory,"pflg","0","ex15",stamp,"cm_exAttr",cm_exAttr]);
}


function cmCreatePageviewConversionEventTag(pageID,PVcategoryID,eventID, actionType, CEcategoryID, points,IXCookieID,IXSurveyCode) {
    if(pageID == null) { pageID = cmGetDefaultPageID(); }
	cmMakeTag(["tid","14","cid",eventID,"cat",actionType,"ccid",CEcategoryID,"cpt",points,"cx1",IXCookieID,"cx2",IXSurveyCode,"cg",PVcategoryID,"pc","Y","pi",pageID]);
 }

/*
 * Creates a Tech Props tag.
 * pageID		: required. Page ID to set on this Pageview tag
 */
function cmCreateTechPropsTag(pageID, categoryID, brand, country, language, loginType, splitTest, IATA, ihgSession, promoPrice) {
	if(pageID == null) { pageID = cmGetDefaultPageID(); }
	var cm_exAttr=new Array;
    cm_exAttr[0] = brand;
    cm_exAttr[1] = country; 
    cm_exAttr[2] = language;
    cm_exAttr[9] = loginType;	
    cm_exAttr[10] = ihgSession;
    cm_exAttr[13] = splitTest;
    cm_exAttr[14] = IATA;

	if ( (IATA) && (window.location.href.toLowerCase().indexOf("cm_mmc=")==-1)){
		manual_cm_mmc= "NoPMIDMMC-_-" + IATA + "-_-NA-_-NA";
	}

    if (!loginType){
	cmMakeTag(["tid","6","pi",pageID,"cg",categoryID,"pc","Y","pv1",brand,"pv2",country,"pv3",language,"pv10",promoPrice,"pv11",ihgSession,"pv14",splitTest,"pv15",IATA,"cm_exAttr",cm_exAttr]);		
    } else {
	cmMakeTag(["tid","6","pi",pageID,"cg",categoryID,"pc","Y","pv1",brand,"pv2",country,"pv3",language,"pv10",promoPrice,"pv11",ihgSession,"pv14",splitTest,"pv15",IATA,"li",1,"ps1",pageID,"ps2",loginType,"cm_exAttr",cm_exAttr]);		
    }
}

/*
 * Creates a Pageview tag with the given Page ID
 *
 * pageID	: required. Page ID to set on this Pageview tag
 * categoryID	: optional. Category ID to set on this Pageview tag
 * searchString	: optional. Internal search string enterred by user to reach
 *				  this page.
 *
 * 
 */
function cmCreatePageviewTag(pageID, categoryID, searchString, searchResults,  brand, country, language, loginType, hotelCode, splitTest, IATA,leadTime,arrivalDate,hotelRank,IXCookieID,IXSurveyCode,ihgSession,stpPercent,promoPrice) {
	if (pageID == null) { pageID = cmGetDefaultPageID(); }
	var cm_exAttr=new Array;
	cm_exAttr[0] = brand;
	cm_exAttr[1] = country; 
	cm_exAttr[2] = language;
	cm_exAttr[3] = hotelCode;  
	cm_exAttr[4] = leadTime;			
	cm_exAttr[5] = arrivalDate;	 
	cm_exAttr[6] = hotelRank;			 
	cm_exAttr[7] = IXCookieID;
	cm_exAttr[8] = IXSurveyCode;
	cm_exAttr[9] = loginType; 
	cm_exAttr[10] = ihgSession;	
	cm_exAttr[11] = stpPercent;	
	cm_exAttr[13] = splitTest;
	cm_exAttr[14] = IATA;

	if ( (IATA) && (window.location.href.toLowerCase().indexOf("cm_mmc=")==-1)){
		manual_cm_mmc= "NoPMIDMMC-_-" + IATA + "-_-NA-_-NA";
	}

	if (!loginType){
	    cmMakeTag(["tid","1","pi",pageID,"cg",categoryID,"se",searchString,"sr",searchResults,"pv1",brand,"pv2",country,"pv3",language,"pv4",hotelCode,"pv5",leadTime,"pv6",arrivalDate,"pv7",hotelRank,"pv8",IXCookieID,"pv9",IXSurveyCode,"pv10",promoPrice,"pv11",ihgSession,"pv12",stpPercent,"pv14",splitTest,"pv15",IATA,"cm_exAttr",cm_exAttr]);
	} else {
	    cmMakeTag(["tid","1","pi",pageID,"cg",categoryID,"se",searchString,"sr",searchResults,"pv1",brand,"pv2",country,"pv3",language,"pv4",hotelCode,"pv5",leadTime,"pv6",arrivalDate,"pv7",hotelRank,"pv8",IXCookieID,"pv9",IXSurveyCode,"pv10",promoPrice,"pv11",ihgSession,"pv12",stpPercent,"pv14",splitTest,"pv15",IATA,"li",1,"ps1",pageID,"ps2",loginType,"cm_exAttr",cm_exAttr]);
	}
}

/*
 * Creates a Pageview tag with the default value for Page ID. 
 * Format of Page ID is "x/y/z/MyPage.asp"
 *
 * 
 */
function cmCreateDefaultPageviewTag(categoryID) {
	cmCreatePageviewTag(cmGetDefaultPageID(), categoryID);
}

function cmCreateHotelViewTag(propertyCode, propertyName, categoryID, hotelBrand, siteBrand, siteCountry, language, ZIP, city, state, country, roomImpressionList, splitTest,EF14,IATAno,promoPrice,leadTime,arrivalDate) {
	var cm_exAttr=new Array;
	cm_exAttr[0] = propertyCode;
	cm_exAttr[1] = propertyName;
	cm_exAttr[2] = hotelBrand;
	cm_exAttr[3] = siteBrand;
	cm_exAttr[4] = language;
	cm_exAttr[5] = siteCountry;
	cm_exAttr[6] = ZIP;
	cm_exAttr[7] = city;
	cm_exAttr[8] = state;
	cm_exAttr[9] = country;
	cm_exAttr[10]= roomImpressionList;
	cm_exAttr[11]= splitTest;
	cm_exAttr[12]= categoryID;	
	cm_exAttr[13]= EF14;
	cm_exAttr[14]= IATAno;
	cmMakeTag(["tid","5","pr",propertyCode,"pm",propertyName,"pi","HOTEL VIEW: " + propertyName + " (propertyCode)","cg",categoryID,"pc","Y","pv10",promoPrice,"pv5",leadTime,"pv6",arrivalDate,"li",2,"ps1",propertyCode,"ps2",propertyName,"ps3",hotelBrand,"ps4",siteBrand,"ps5",language,"ps6",siteCountry,"ps7",ZIP,"ps8",city,"ps9",state,"ps10",country,"ps11",roomImpressionList,"ps12",splitTest,"ps13",categoryID,"ps14",EF14,"ps15",IATAno,"cm_exAttr",cm_exAttr]);
}

function cmCreateHotelSelectionTag(propertyCode, propertyName, hotelBrand, categoryID, siteBrand, siteCountry, language, ZIP, city, state, country, roomNights, adultRoomNights, childrenRoomNights, unitPrice, rateType, roomCode, reservationStartDate, numRooms, splitTest,attributes) {
	if ((typeof(cm_currencyCode) == "undefined") || (!cm_currencyCode)) {
		cm_currencyCode = "";
    }
	
	var cm_exAttr=new Array;
	cm_exAttr[0] = hotelBrand;
	cm_exAttr[1]= siteBrand + "|" + siteCountry;
	cm_exAttr[2] = language;
	cm_exAttr[3] = ZIP;
	cm_exAttr[4] = city;
	cm_exAttr[5] = state;
	cm_exAttr[6] = country;
	cm_exAttr[7] = adultRoomNights;
	cm_exAttr[8] = childrenRoomNights;
	cm_exAttr[9] = rateType;
	cm_exAttr[10] = roomCode;
	cm_exAttr[11]=splitTest;
	cm_exAttr[13]= reservationStartDate;
	cm_exAttr[14]= numRooms;
	cmMakeTag(["tid","4","at","5","pr",propertyCode,"pm",propertyName,"qt",roomNights,"bp",unitPrice,"cg",categoryID,"sx1", hotelBrand,"sx2",siteBrand + "|" + siteCountry,"sx3",language,"sx4",ZIP,"sx5",city,"sx6",state,"sx7",country,"sx8",adultRoomNights,"sx9",childrenRoomNights,"sx10",rateType,"sx11",roomCode,"sx14",reservationStartDate,"sx15",numRooms,"li","10","ps1",splitTest,"cc",cm_currencyCode,"cm_exAttr",cm_exAttr]);
}

function cmCreateHotelBookingTag(propertyCode, propertyName, hotelBrand, categoryID, siteBrand, siteCountry, language, ZIP, city, state, country, roomNights, adultRoomNights, childrenRoomNights, unitPrice, rateType, roomCode, travelType, bookingConfirmationNumber, bookingTotal, tax,usedCreditBypass, customerID, priorityClub, userEmail, userCity, userState, userCountry, userZIP, reservationStartDate, numRooms, splitTest, IATA,attributes) {
	if ((typeof(cm_currencyCode) == "undefined") || (!cm_currencyCode)) {
		cm_currencyCode = "";
    }
	var cm_exAttr=new Array;
	cm_exAttr[0] = hotelBrand;
	cm_exAttr[1]= siteBrand + "|" + siteCountry;
	cm_exAttr[2] = language;
	cm_exAttr[3] = ZIP;
	cm_exAttr[4] = city;
	cm_exAttr[5] = state;
	cm_exAttr[6] = country;
	cm_exAttr[7] = adultRoomNights;
	cm_exAttr[8] = childrenRoomNights;
	cm_exAttr[9] = rateType;
	cm_exAttr[10] = roomCode;
	cm_exAttr[11] = usedCreditBypass;
	cm_exAttr[12] = priorityClub;
	cm_exAttr[13] = reservationStartDate;
	cm_exAttr[14] = numRooms + "|" + travelType;
	cmMakeTag(["tid","4","at","9","pr",propertyCode,"pm",propertyName,"qt",roomNights,"bp",unitPrice,"cg",categoryID,"on",bookingConfirmationNumber,"tr",bookingTotal,"sg",tax,"cd",customerID,	"sx1", hotelBrand,"sx2",siteBrand + "|" + siteCountry,"sx3",language,"sx4",ZIP,"sx5",city,"sx6",state,"sx7",country,"sx8",adultRoomNights,"sx9",childrenRoomNights,"sx10",rateType,"sx11",roomCode,"sx12",usedCreditBypass,"sx13",priorityClub,"sx14",reservationStartDate,"sx15",numRooms + "|" + travelType,"pc","N","li","11","ps1",splitTest,"cc",cm_currencyCode,"cm_exAttr",cm_exAttr]);
	var cm_exAttr=new Array;
	cm_exAttr[14]=IATA;
	cmMakeTag(["tid","3","on",bookingConfirmationNumber,"tr",bookingTotal,"sg",tax,"cd",customerID,"osk","|" + propertyCode + "|" + unitPrice + "|" + roomNights + "|","sa",userState,"ct",userCity,"zp",ZIP,"or15",IATA,"cc",cm_currencyCode,"cm_exAttr",cm_exAttr]);
	var cm_exAttr=new Array;
	cmMakeTag(["tid","2","cd",customerID,"em",userEmail,"sa",userState,"ct",userCity,"zp",ZIP,"rg11",priorityClub,"rg12",userCountry,"cc",cm_currencyCode,"cm_exAttr",cm_exAttr]);
}

function cmCreateConversionEventTag(eventID, actionType, categoryID, points,IXCookieID,IXSurveyCode,attributes) {
	var datestamp = new Date();	
	var stamp = (Math.floor(Math.random() * 11111111)) + datestamp.valueOf();	
	var cm_exAttr=new Array;
 	if (attributes){
		cm_exAttr=attributes.split("-_-");
	}		  
    cm_exAttr[0]=IXCookieID;
    cm_exAttr[1]=IXSurveyCode;
	cmMakeTag(["tid","14","cid",eventID,"cat",actionType,"ccid",categoryID,"cpt",points,"cx1",IXCookieID,"cx2",IXSurveyCode,"cm_exAttr",cm_exAttr]);
}

function cmCreateRegistrationTag(customerID,userEmail,userCity,userState,userZIP,userCountry,priorityClub, attributes) {
 	if (attributes){
		var cm_exAttr=new Array;
		cm_exAttr=attributes.split("-_-");
	}
	cmMakeTag(["tid","2","cd",customerID,"em",userEmail,"ct",userCity,"sa",userState,"zp",userZIP,"cy",userCountry,"rg11",priorityClub,"cm_exAttr",cm_exAttr]);
}

/* Creates an Error Tag
 *
 */
function cmCreateErrorTag(pageID, categoryID) {
	if(pageID == null) {
		pageID = cmGetDefaultPageID();
	}
	cmMakeTag(["tid","404","pi",pageID,"cg",categoryID,"pc","Y"]);
}

function cmLIVEviewClick(href,name) {
	cmCreateManualLinkClickTag(href,name);
}

function cmMakeTag(__v) {
	var cm = new _cm("vn2", "e4.0");
	var i;
	for (i = 0; i < __v.length; i += 2) {
		var _n = __v[i];
		var _v = __v[i + 1];
		cm[_n] = _v;
	}
	
	var datestamp = new Date();	
	var stamp = (Math.floor(Math.random() * 11111111)) + datestamp.valueOf();	
	cm.rnd = stamp;
	
	if (cm.tid == "6") {
		cm.addTP();
		document.cookie = "cmTPSet=Y; path=/";
	}

	if (cm.tid == "1") {
		if (cI("cmTPSet") != 'Y') {
			cm.tid = "6";
			cm.pc = "Y";
			cm.addTP();
			document.cookie = "cmTPSet=Y; path=/";
		}
	}

	if (typeof(cm.cm_exAttr)!="undefined"){
		switch(cm.tid){
			case "6":
				prefix="pv";
				break;
			case "1":
				prefix="pv";
				break;
			case "2":
				prefix="rg";
				break;
			case "4":
				prefix="s";
				break;
			case "5":
				prefix="pr";
				break;
			case "3":
				prefix="o";
				break;
			case "14":
				prefix="c";
				break;
			case "15":
				prefix="e";
				break;
			default:
				break;
		}		
		var attrNum=cm.cm_exAttr.length;
		if (attrNum>15){
			attrNum=15;
		}
		for (i=0;i<attrNum;i++){
			if (cm.tid=="2"){
				Attval=prefix+(i+1);
			} else {
				Attval=prefix+"_a"+(i+1);
			}
			cm[Attval]=cm.cm_exAttr[i];
		}
		cm.cm_exAttr=null;
	}	
	if ((cm.pi == null) && (cm.pc == "Y")) {
		cm.pi = cmGetDefaultPageID();
	}
	
	try{
		if (parent.cm_ref != null) {
			cm.rf = parent.cm_ref;
			if (cm.pc == "Y") {
				parent.cm_ref = document.URL;
			}
		}
	
		// if parent had mmc variables and this is the first pageview, add mmc to this url
		if(parent.cm_set_mmc) {
			cm.ul = document.location.href + 
					((document.location.href.indexOf("?") < 0) ? "?" : "&") + 
					parent.cm_mmc_params; 
			if (cm.pc == "Y") {
				parent.cm_ref = cm.ul;
				parent.cm_set_mmc = false;
			}
		}
	}
	catch(err){}

	if (cm.ul == null) {
		cm.ul = window.location.href;
	}

	if (cm.ul.index)f("#">-1)
	{
		cm.ul=cm.ul.replace(/#/,"");
	}
	if (cm.rf==null) {
			cm.rf=window.referrer;
	}
	if (typeof(cm.rf)!="undefined") {
		if (cm.rf.index)f("#">-1)
		{
			cm.rf=cm.rf.replace(/#/,"");
		}
	}
	//check for zero price and zero quantity
	cmSafeZero(cm,["qt","bp","tr","sg"]);

	//check for manual_cm_mmc parameter;
	if (this.manual_cm_mmc != null && this.manual_cm_mmc != "") {
		cm.ul = cm.ul + ((cm.ul.indexOf("&") == -1) ? ((cm.ul.indexOf("?") == -1) ? "?" : "&") : "&") + "cm_mmc=" + this.manual_cm_mmc;
	}

	// convert MMC parameters to lowercase;
	cm.ul = cm.ul.replace(/cm_mmc/gi,"cm_mmc");
	cm.ul = cm.ul.replace(/cm_ven/gi,"cm_ven");
	cm.ul = cm.ul.replace(/cm_cat/gi,"cm_cat");
	cm.ul = cm.ul.replace(/cm_pla/gi,"cm_pla");
	cm.ul = cm.ul.replace(/cm_ite/gi,"cm_ite");
	if (cmCheckCMEMFlag){cmStartTagSet();}
    cm.writeImg();
	if (cmCheckCMEMFlag) {
		cmCheckCMEMFlag = false;	
		cmCheckCMEM();
		cmSendTagSet();		
	}
	
}

// HELPER FUNCTIONS -----------------------------------------------------------
/* These functions are used by the tag-generating functions and/or may be used
 * in in general as convenience functions
 */

/*
 * Creates an acceptable default Page ID value to use for Pageview tags.
 * The default Page ID is based on the URL, and consists of the path and
 * filename (without the protocol, domain and query string).
 * 
 * example:
 * returns "x/y/MyPage.asp" for the URL http://www.mysite.com/x/y/MyPage.asp
 */
function cmGetDefaultPageID() { 
	var pageName = window.location.pathname; 

	// eliminates everything after "?" (for Opera browswers)
	var tempIndex1 = pageName.indexOf("?");
	if (tempIndex1 != -1) {
		pageName = pageName.substr(0, tempIndex1);
	}
	// eliminates everything after "#" (for Opera browswers)
	var tempIndex2 = pageName.indexOf("#");
	if (tempIndex2 != -1) {
		pageName = pageName.substr(0, tempIndex2);
	}
	// eliminates everything after ";"
	var tempIndex3 = pageName.indexOf(";");
	if (tempIndex3 != -1) {
		pageName = pageName.substr(0, tempIndex3);
	}

	var slashPos = pageName.lastIndexOf("/");
	if (slashPos == pageName.length - 1) {
		pageName = pageName + "default.asp"; /****************** SET TO DEFAULT DOC NAME */
	}

	while (pageName.indexOf("/") == 0) {
		pageName = pageName.substr(1,pageName.length);
	}

	return(pageName); 
} 

function cmIndexOfParameter (parameter, inString) {
	return inString.indexOf(parameter);
}

function cmExtractParameter (parameter, inString) {
    if (cmIndexOfParameter(parameter, inString) == -1) {
        return null;
    }
	var s = inString;
	var begin = s.indexOf(parameter);
	var end = s.indexOf("&", begin);
	if (end == -1) {
		end = s.length;
	}
	var middle = s.indexOf("=", begin);
	return s.substring(middle + 1, end);
}

function cmRemoveParameter (parameter, inString) {
    if (cmIndexOfParameter(parameter, inString) == -1) {
        return inString;
    }
	var s = inString;
	var begin = s.indexOf(parameter);
	var start = (begin - 1);
	var end = s.indexOf("&", begin);
	if (end == -1) {
		end = s.length;
	}
	if (s.substring(start, begin) == "?") {    // retain leading "?"
		start = (start + 1);
		end = (end + 1);
	}
	return s.substring(0, start) + s.substring(end, s.length);
}

function cmCheckCMEM() {
	if (cmIndexOfParameter("cm_em",document.location.href) != -1){
		var emailAddress = cmExtractParameter("cm_em",document.location.href);
		if (emailAddress.indexOf(":")>-1){
			emailAddress=emailAddress.substring(emailAddress.indexOf(":")+1);
		}
		cmCreateRegistrationTag(emailAddress,emailAddress);
	}
	if (cmIndexOfParameter("cm_lm",document.location.href) != -1){
		var emailAddress = cmExtractParameter("cm_lm",document.location.href);
		if (emailAddress.indexOf(":")>-1){
			emailAddress=emailAddress.substring(emailAddress.indexOf(":")+1);
		}		
		cmCreateRegistrationTag(emailAddress,emailAddress);
	}
}

function cmSafeZero(cm, checkArray) {
	// put logic here to convert number 0 to string "0"
	for (var i = 0; i < checkArray.length; ++i) {
		if ((cm[checkArray[i]] != null) && (cm[checkArray[i]] == 0)) {
			cm[checkArray[i]] = "0";
		}
	}
}

if (defaultNormalize == null) { var defaultNormalize = null; }

function myNormalizeURL(url, isHref) {
    var newURL = url;

    if (isHref) {
		newURL=newURL.replace(/#/,"");
	    var blackList = ["#"];
	    var paramString;
	    var paramIndex = newURL.indexOf("?");
	    var params;
	    var keepParams = new Array();
	    var goodParam;
	
	    if (paramIndex > 0) {
		paramString = newURL.substring(paramIndex+1);
		newURL = newURL.substring(0, paramIndex);
		params = paramString.split("&");
	
		for(var i=0; i<params.length; i++) {
			goodParam = true;
			for(var j=0; j<blackList.length; j++) {
			//This match is case insensitive.  Remove .toLowerCase() to add case sensitivity
				if (params[i].toLowerCase().indexOf(blackList[j].toLowerCase()) == 0) {
					goodParam = false;
				}
			}
			if(goodParam == true) {
				keepParams[keepParams.length] = params[i];
			}
		}
		
		newURL += "?" + keepParams.join("&");
	
	    }
	 
	    if (defaultNormalize != null) {
	        newURL = defaultNormalize(newURL, isHref);
	    }
	}	
    return newURL;
}

// install normalization
if (document.cmTagCtl != null) {
    var func = "" + document.cmTagCtl.normalizeURL;
    if (func.indexOf('myNormalizeURL') == -1) {
        defaultNormalize = document.cmTagCtl.normalizeURL;
        document.cmTagCtl.normalizeURL = myNormalizeURL;
    }
}

/*  hash functions that support shop aggregation with attributes */
function cm_hex_sha1(s)    { return cm_rstr2hex(cm_rstr_sha1(cm_str2rstr_utf8(s))); }

function cm_rstr_sha1(s)
{
  return cm_binb2rstr(cm_binb_sha1(cm_rstr2binb(s), s.length * 8));
}

function cm_rstr2hex(input)
{
  var hex_tab = 0 ? "0123456789ABCDEF" : "0123456789abcdef";
  var output = "";
  var x;
  for(var i = 0; i < input.length; i++)
  {
    x = input.charCodeAt(i);
    output += hex_tab.charAt((x >>> 4) & 0x0F)
           +  hex_tab.charAt( x        & 0x0F);
  }
  return output;
}

function cm_str2rstr_utf8(input)
{
  var output = "";
  var i = -1;
  var x, y;

  while(++i < input.length)
  {
    /* Decode utf-16 surrogate pairs */
    x = input.charCodeAt(i);
    y = i + 1 < input.length ? input.charCodeAt(i + 1) : 0;
    if(0xD800 <= x && x <= 0xDBFF && 0xDC00 <= y && y <= 0xDFFF)
    {
      x = 0x10000 + ((x & 0x03FF) << 10) + (y & 0x03FF);
      i++;
    }

    /* Encode output as utf-8 */
    if(x <= 0x7F)
      output += String.fromCharCode(x);
    else if(x <= 0x7FF)
      output += String.fromCharCode(0xC0 | ((x >>> 6 ) & 0x1F),
                                    0x80 | ( x         & 0x3F));
    else if(x <= 0xFFFF)
      output += String.fromCharCode(0xE0 | ((x >>> 12) & 0x0F),
                                    0x80 | ((x >>> 6 ) & 0x3F),
                                    0x80 | ( x         & 0x3F));
    else if(x <= 0x1FFFFF)
      output += String.fromCharCode(0xF0 | ((x >>> 18) & 0x07),
                                    0x80 | ((x >>> 12) & 0x3F),
                                    0x80 | ((x >>> 6 ) & 0x3F),
                                    0x80 | ( x         & 0x3F));
  }
  return output;
}

function cm_rstr2binb(input)
{
  var output = Array(input.length >> 2);
  for(var i = 0; i < output.length; i++)
    output[i] = 0;
  for(var i = 0; i < input.length * 8; i += 8)
    output[i>>5] |= (input.charCodeAt(i / 8) & 0xFF) << (24 - i % 32);
  return output;
}

function cm_binb2rstr(input)
{
  var output = "";
  for(var i = 0; i < input.length * 32; i += 8)
    output += String.fromCharCode((input[i>>5] >>> (24 - i % 32)) & 0xFF);
  return output;
}

function cm_binb_sha1(x, len)
{
  /* append padding */
  x[len >> 5] |= 0x80 << (24 - len % 32);
  x[((len + 64 >> 9) << 4) + 15] = len;

  var w = Array(80);
  var a =  1732584193;
  var b = -271733879;
  var c = -1732584194;
  var d =  271733878;
  var e = -1009589776;

  for(var i = 0; i < x.length; i += 16)
  {
    var olda = a;
    var oldb = b;
    var oldc = c;
    var oldd = d;
    var olde = e;

    for(var j = 0; j < 80; j++)
    {
      if(j < 16) w[j] = x[i + j];
      else w[j] = cm_bit_rol(w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16], 1);
      var t = cm_safe_add(cm_safe_add(cm_bit_rol(a, 5), cm_sha1_ft(j, b, c, d)),
                       cm_safe_add(cm_safe_add(e, w[j]), cm_sha1_kt(j)));
      e = d;
      d = c;
      c = cm_bit_rol(b, 30);
      b = a;
      a = t;
    }

    a = cm_safe_add(a, olda);
    b = cm_safe_add(b, oldb);
    c = cm_safe_add(c, oldc);
    d = cm_safe_add(d, oldd);
    e = cm_safe_add(e, olde);
  }
  return Array(a, b, c, d, e);

}

function cm_sha1_ft(t, b, c, d)
{
  if(t < 20) return (b & c) | ((~b) & d);
  if(t < 40) return b ^ c ^ d;
  if(t < 60) return (b & c) | (b & d) | (c & d);
  return b ^ c ^ d;
}

function cm_sha1_kt(t)
{
  return (t < 20) ?  1518500249 : (t < 40) ?  1859775393 :
         (t < 60) ? -1894007588 : -899497514;
}

function cm_safe_add(x, y)
{
  var lsw = (x & 0xFFFF) + (y & 0xFFFF);
  var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
  return (msw << 16) | (lsw & 0xFFFF);
}

function cm_bit_rol(num, cnt)
{
  return (num << cnt) | (num >>> (32 - cnt));
}  

function cmSetCurrencyCode(currencyCode) {
	cm_currencyCode = currencyCode;
}
