var strHref = '';

var mainSendData = function(strVPN) {
	if (document.location.href.indexOf('rockymountaineer.com/staging/') != -1) {
		var strDomainName = "rockymountaineer.com";
		var strWebPropertyId = 'UA-442998-5';	// Staging account
	}	
		// Internal VKI Testing
	else if (document.location.href.indexOf('rockymountaineer.com') != -1) {
		var strDomainName = "rockymountaineer.com";
		var strWebPropertyId = 'UA-442998-1';
	}	
		// Internal VKI Testing
	else if(document.location.href.indexOf('vkistudios.net') != -1) {	
		strDomainName = 'vkistudios.net';
		strWebPropertyId = 'UA-981819-16';
	}	
		// for other QA domains/IP address hostnames, etc - filters exclude  non-rockymountaineer.com traffic from live profiles
	else  {																
		strDomainName = 'auto';			// just don't know
		strWebPropertyId = 'UA-442998-1';
	}	

	var pageTracker = _gat._getTracker(strWebPropertyId); 	
		pageTracker._setDomainName(strDomainName);

		// Determine what the page name will be based on whether 
		//	a Virtual Page Name was provided in document.strTrackPageView
		//  or in checkGetSearchURL() or in checkGetBrochureThankyouURL()
	if (strVPN) {
		strHref = strVPN;
	} else {
		if (document.strTrackPageView)
			strHref = document.strTrackPageView;
		else
			strHref = document.location.pathname + document.location.search;
	}
	

		// functions will stop executing when one returns true
	checkGetSearchURL(strHref) ||
	checkGetBrochureThankyouURL(strHref) ||
	checkGetVirtualBrochure(strHref) ||
	checkGetUSagentBrochureURL(strHref) ||
	checkGetNewsLetterThankyouURL(strHref) ||
	checkContactThankyouURL(strHref) ||
	checkGenericConversionPage(strHref) ;

	strHref = normalizeHref(strHref);
	
		// if document.strVisitorSegment is set, process it.  before, segmentVisitor() 
		// 		was called but required that top-stats.js be called first.
		// With CustomVar being sent with _trackPageview(), the value must be set before top-stats.js is loaded 
		// so this can run all the way through to _trackPageView( ...)
	if (document.strVisitorSegment) {
			// Call segmentHelperObj function to set a value if one must be set
		segmentHelperObj.segmentVisitor(document.strVisitorSegment)
		segmentHelperObj.setCustomVar(pageTracker, 1, 1);
	}

	pageTracker._trackPageview(strHref);
	// debugging: divResults.innerHTML += strVPN + '<br><br>' + strHref+'<hr>';

	return true;
};

	// replaces old version of this function for backward compatability with the ecommerce code
segmentVisitor = function(inputSegmentationLvl) {
	document.strVisitorSegment = inputSegmentationLvl;
	// call an event to send the custom var 
}


	// VKI - Erik Vold, Brian Katz 080319
	// Required to segment visitors for Google Analytics
	// Called from GA script blocks on all pages.
	// Removing this file will cause Javascript errors on all pages that call the segmentVisitor() function

//List the custom levels for this application here:
	// Levels may NOT:
	// 	be an empty string
	//	be duplicated
	//	contain dots
var segmentHelperObj = {};
segmentHelperObj.visitorSegmentationLvls = new Array(
'No Action',	
'No Action-Travel Agents',	// Has logged in but not performed a "Lead" action
'No Action-Wholesalers',		// Has arrived at their page and returned to the rest of the site or has 
							// logged in but not performed a "Lead" action
'Leads',
'Leads-Newsletter',	// Distinguishes between those who have merely clicked the download pdf link
							// where true Leads have made some commitment and divulged at least an email address.
'Leads-Requested Brochure',	// Distinguishes between those who have merely clicked the download pdf link
							// where true Leads have made some commitment and divulged at least an email address.
'Leads-Travel Agents Requested Brochure',	// Travel Agent requested brochure/s
'Lead-Travel Agents',		// Logged in and performed a "Lead" action
'Lead-Wholesalers',			// Logged in and performed a "Lead" action
'Conversions', 
'Conversion-Travel Agents',
'Conversion-Wholesalers'
);

	// Must be set to false once development is completed and before the changes go live or
	// 	an alert box will display to the client.
segmentHelperObj.debuggingMode = false;
	
segmentHelperObj.getCookie = function(cookie_name){
  	var results = document.cookie.match( '(^|;) ?'+cookie_name+'=([^;]*)(;|$)' );
	
  	if (results)
    	return ( unescape(results[2]) );
  	else
    	return null;
};

segmentHelperObj.cleanGoogle_utmvCookie = function(){
  	var results = segmentHelperObj.getCookie('__utmv');

	if (results)
	{
		return results.replace(/^\.?(([A-Za-z]|[0-9])*\.)*/,"");
	}
	else
	{
		return null;
	}
	
};
	
segmentHelperObj.trimStr = function(str){
		var whitespace=' \n\r\t\f\x0b\xa0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000';
		for(var i=0;i<str.length;i++){
			if(whitespace.indexOf(str.charAt(i)) === -1){
				str = str.substring(i);
				break;
			}
		}
		for(i=str.length-1;i>=0;i--){
			if(whitespace.indexOf(str.charAt(i)) === -1){
				str = str.substring(0, i + 1);
				break;
			}
		}
		return whitespace.indexOf(str.charAt(0)) === -1 ? str : '';
};
segmentHelperObj.segmentationLvlToSet = '';

segmentHelperObj.setCustomVar = function (obj, intSlot, intScope) {
	if (segmentHelperObj.segmentationLvlToSet) {
		obj._setCustomVar(intSlot, 'Visitor Commitment', segmentHelperObj.segmentationLvlToSet, intScope);		
	}
}


segmentHelperObj.segmentVisitor = function(inputSegmentationLvl)
{
	// grab the GA cookie var that stores the custom visitors segment type, and trim whitespace
	var currentSegmentationLvl = segmentHelperObj.cleanGoogle_utmvCookie(); //'__utmv'

	// COMMENT OUT WHEN  TESTING IS DONE
//if (segmentHelperObj.debuggingMode && (inputSegmentationLvl != 'No Action' || inputSegmentationLvl != 'null'))
//	alert("__utmv segmentVisitor=" + segmentHelperObj.cleanGoogle_utmvCookie() + ". Trying to set it to:" + inputSegmentationLvl); 
	
		// if the current value is null (ie: not found) then stop and do nothing.
	if(currentSegmentationLvl==null) currentSegmentationLvl = "";

	var numOfLevels = segmentHelperObj.visitorSegmentationLvls.length;
	var currentSegmentationIndex = numOfLevels;
	var newSegmentationIndex = numOfLevels;

	var tempSegmentationLvlLabel = "";
	
		//trim whitespace and covert to all upper case
	currentSegmentationLvl = (segmentHelperObj.trimStr(currentSegmentationLvl)).toUpperCase();
	var newSegmentationLvl = (segmentHelperObj.trimStr(inputSegmentationLvl)).toUpperCase();
	
		// loop through the segmentation lvls from lowest to highest
	for(var i=0;i<numOfLevels;i++){
		tempSegmentationLvlLabel = (segmentHelperObj.visitorSegmentationLvls[i]).toUpperCase();
		
			// is the current lvl equal to this lvl?
		if(currentSegmentationLvl === tempSegmentationLvlLabel){
			currentSegmentationIndex = i;
		}
		
			// is the new lvl equal to this lvl?
		if(newSegmentationLvl === tempSegmentationLvlLabel){
			newSegmentationIndex = i;
		}
		
			// are we done yet?
		if(currentSegmentationIndex < numOfLevels && newSegmentationIndex < numOfLevels){
			break;
		}
	}
	
	if(newSegmentationIndex == numOfLevels)
	{
		// check if we are in debugging mode
		if(segmentHelperObj.debuggingMode){
			alert('Segment Error: requested visitor level not in list of levels!. Please continue');
		}
		
		segmentHelperObj.segmentationLvlToSet ='ERROR';
		// setCustomVar(pageTracker, 'ERROR');
	}
		// if the new lvl is greater than the current lvl OR the new level was found but the current level 
		// could not be found, then call _setVar()
	else if(newSegmentationIndex < numOfLevels && (newSegmentationIndex > currentSegmentationIndex || currentSegmentationIndex == numOfLevels))
	{
		segmentHelperObj.segmentationLvlToSet = inputSegmentationLvl
			//setCustomVar(pageTracker, inputSegmentationLvl);
	}

//if (segmentHelperObj.debuggingMode && (segmentHelperObj.cleanGoogle_utmvCookie() != 'No Action' || segmentHelperObj.cleanGoogle_utmvCookie() != 'null') 
//		alert("__utmv segmentVisitor cookie is now:" + segmentHelperObj.cleanGoogle_utmvCookie()); 
};


function fGooAnTagPdfs() {
	if (document.getElementsByTagName) {
				// Initialize external link handlers
			var hrefs = document.getElementsByTagName("a");
			for (var l = 0; l < hrefs.length; l++) {
					// try {} catch{} block added by erik VKI for tags that have no href
				try{
							//protocol, host, hostname, port, pathname, search, hash
						if (hrefs[l].protocol == "mailto:") {
								startListening(hrefs[l],"click",trackMailto);
						} else if (hrefs[l].host == location.host) {
								var path = hrefs[l].pathname + hrefs[l].search;

								var isDoc = path.match(/\.(?:pdf)($|\&|\?)/);
								if (isDoc) {
										startListening(hrefs[l],"click",trackExternalLinks);
								}
						} else {
								startListening(hrefs[l],"click",trackExternalLinks);
						}
				}
				catch(e){
						continue;
				}
			}
	}
} 


function fSafeAddOnload(func) {
    v = 'v3.1.0 2006-11-22; like:; req:;';
    if (!window.__load_events) {
        var init = function () {
            if (arguments.callee.done) return;
            arguments.callee.done = true;
            if (window.__load_timer) {
                clearInterval(window.__load_timer);
                window.__load_timer = null;
            }
            for (var i = 0; i < window.__load_events.length; i++) {
                window.__load_events[i]()
            }
            window.__load_events = null
        };
        if (document.addEventListener) {
            document.addEventListener("DOMContentLoaded", init, false)
        }
        if (/WebKit/i.test(navigator.userAgent)) {
            window.__load_timer = setInterval(function () {
                if (/loaded|complete/.test(document.readyState)) {
                    init()
                }
            },
            10)
        }
        window.onload = init;
        window.__load_events = []
    }
    window.__load_events.push(func)
}


function startListening (obj,evnt,func) {
        if (obj.addEventListener) {
                obj.addEventListener(evnt,func,false);
        } else if (obj.attachEvent) {
                obj.attachEvent("on" + evnt,func);
        }
}

function trackMailto (evnt) {
        var href = (evnt.srcElement) ? evnt.srcElement.href : this.href;
        var mailto = "/mailto/" + href.substring(7);
        mainSendData(mailto);
//        if (typeof(pageTracker) == "object") pageTracker._trackPageview(mailto);
}

function trackExternalLinks (evnt) {
        var e = (evnt.srcElement) ? evnt.srcElement : this;
        while (e.tagName != "A") {
                e = e.parentNode;
        }
        var lnk = (e.pathname.charAt(0) == "/") ? e.pathname : "/" + e.pathname;
        if (e.search && e.pathname.indexOf(e.search) == -1) lnk += e.search;
        if (e.host != location.host) lnk = "/external/" + e.host + lnk;
        mainSendData(lnk);
//        if (typeof(pageTracker) == "object") pageTracker._trackPageview(lnk); 
} 

/*
      var isDoc = path.match(/\.(?:doc|eps|jpg|png|svg|xls|ppt|pdf|xls|zip|txt|vsd|vxd|rar|exe|wma|mov|avi|wmv|mp3)($|\&)/);
*/

function sendPageView(strTrackPageView, strSegmentationLvl) {
	if (strSegmentationLvl)
		segmentHelperObj.segmentVisitor(strSegmentationLvl);

	if (strTrackPageView)
		pageTracker._trackPageview(strTrackPageView);
	else
		pageTracker._trackPageview();

	// if (strSegmentationLvl)
		// segmentHelperObj.segmentVisitor(strSegmentationLvl);
}

function  normalizeHref(strHref) {
	var ptnIsLocale = /^\/(([a-z]{2}(_[a-z]{2}){1,2})|([a-z]{2}))(\/|$)(.*)/;

	strHref = strHref.toLowerCase();
	
		// remove protocol and hostname in case passed in as VPN
	var ptnHTTPs = new RegExp("^https?://" + document.location.hostname, '');
	strHref = strHref.replace(ptnHTTPs, '');

		// add locale folder in case VPN does not have it or not in pathname
	var isLocale = strHref.search(ptnIsLocale) !== -1;
	
	if (isLocale) {
		var strLocale = strHref.substring(0, 3) + '/';
		var strAfterLocale = strHref.match(ptnIsLocale)[6];
		strHref = strLocale + strAfterLocale;
	} 
	
	// strHref = strHref.replace(ptnLocale, '/$1$3');
	strHref = strHref.replace(/\/$/, '');
	
	return strHref;
}

function checkGetSearchURL(strURI) {
	var ptnStartingCity=/(StartingCity=)[^&]+rmv-(\d+)/i;	
	var ptnDuration=/Duration=[^&]+/i; 						
	var ptnMonth=/StartingDate=[^&]+/i; 							
	var aryCities = new Array();
	
	aryCities[2048] = 'Toronto';
	aryCities[2063] = 'Halifax';
	aryCities[893] = 'Whistler';
	aryCities[896] = 'Victoria';
	aryCities[890] = 'Vancouver';
	aryCities[670] = 'Banff';
	aryCities[668] = 'Jasper';
	aryCities[887] = 'Calgary';
	aryCities[3732] = 'Tofino';
	aryCities[9] = 'Montreal';
	aryCities[8] = 'Kamloops';
	aryCities[7] = 'Quesnel';
	aryCities[6] = 'Lake Louise';
	
		// expected URI for the search results page before the search parameters
	var strURL = '/routes_and_packages/package_search/?action=form';
	var ptnURL = /\/routes_and_packages\/package_search\/?\?action=form/i;
	if (strURI.search(ptnURL) == -1) return false; //return that no changes made to strHref and other functions need to run

	var strStartingCity = strURI.match(ptnStartingCity);
	if (strStartingCity) {
		var strCityName = aryCities[strStartingCity[2]] ? aryCities[strStartingCity[2]] : 'rmv-' + strStartingCity[2] + '-city missing from list';
		strStartingCity = /*strStartingCity[1] +*/ strCityName;
	} else {
		strStartingCity = '';
	}	

	var strDuration = strURI.match(ptnDuration);
	if (strDuration) {
		strDuration = strDuration[0];
	} else {
		strDuration = '';
	}	

	var strnMonth = strURI.match(ptnMonth);
	if (strnMonth) {
		strnMonth = strnMonth[0];
	} else {
		strnMonth = '';
	}	

	var strQuery = '';
	strQuery += strStartingCity ? strStartingCity + ' ' : '';
	strQuery += strDuration ? strDuration.toLowerCase()  + ' ' : '';
	strQuery += strnMonth ? strnMonth.toLowerCase() : '';
	
	strQuery = strQuery.replace(/\+$/, '');
	
	strURL += strQuery ? '&search=' + strQuery : '';
	strHref = strURL;

	return (strURI !== strHref);

}


// https://www.google.com/analytics/reporting/top_content?id=17185106&pdr=20100621-20100916&cmp=average&trows=10&gdfmt=nth_day&rpt=TopContentReport&segkey=request_uri&kf={%22filters%22%3A[{%22keyName%22%3A%22request_uri%22%2C%22filterString%22%3A%22request_a_brochure.*confirmation%22%2C%22filterType%22%3A1%2C%22exclude_match_type%22%3Afalse}%2C{%22keyName%22%3A%22request_uri%22%2C%22filterString%22%3A%22.*%28guest|true|international%29.*%22%2C%22filterType%22%3A1%2C%22exclude_match_type%22%3Atrue}]}&tab=0&tchcol=0&tst=0&tscol=v0&tsdir=0&mdet=WORLD&midx=0&gidx=0&glcnt=1#lts=1284760792207

function checkGetBrochureThankyouURL(strURI) {

		// BK 100916 WAS: var ptnBrochureConfirmation=/\/request_a_brochure\/?\?.*page=confirmation/;	
	var ptnBrochureGuest = /^\/.*request.*brochure.*(page=)?confirmation.*(guest|true|international).*/;	

		// BK 100916 WAS: var ptnBrochureThankyouType=/\/request_a_brochure\/?\?.*type=(canada-agent|international)/;
		// href = /en_CA_BC/request_a_brochure?page=confirmation&sent=true&type=canada-agent
		// BK 100916 Cannot use the regex directly from the goal config because it matches the changed href below  ^/.*request_a_brochure/confirmation/canada-agent;	
	var ptnBrochureAgent = /^\/.*request.*brochure.*(page=)?confirmation.*canada-agent.*/;	

	var agentMatch = strURI.match(ptnBrochureAgent);	// do agent match first because ptnBrochureGuest will match both (until change in strHref below)
	var guestType;
	if (!agentMatch) guestType = strURI.match(ptnBrochureGuest);
	
	if (guestType) {
		try {guestType = strURI.match(ptnBrochureGuest)[2]} catch (e) {};
		guestType = (guestType == 'true') ? 'guest' : guestType;
		if (!document.strVisitorSegment) document.strVisitorSegment = 'Leads-Requested Brochure';
		strHref = '/request_a_brochure/confirmation/' + guestType;
	} else if (agentMatch) {
		if (!document.strVisitorSegment) document.strVisitorSegment = 'Leads-Travel Agents Requested Brochure'; 
		strHref = '/request_a_brochure/confirmation/canada-agent';	// now ptnBrochureGuest (in GA Goal Settings) will only match guest/international
	}
	
	if (guestType || agentMatch) {
		sendAdWordsConversionCode();
		return true;
	}
}

function checkGetVirtualBrochure(strURI) {
	if (strURI.search(/\/external\/www\.nxtbook\.com\/dawson\/rockymountaineer/) !== -1) {
		sendAdWordsConversionCode(true);
		return true;
	}
	
}

function checkGetUSagentBrochureURL(strURI) {
	var ptnBrochureThankyouType=/\/external\/www\.orderrockymountainrail.com/;		// BK 100916 checked - was correct
	if (strURI.search(ptnBrochureThankyouType)!== -1) {
		if (!document.strVisitorSegment) {
			document.strVisitorSegment = 'Leads-Travel Agents Requested Brochure';
		}
		strHref = strURI;
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@			
		sendAdWordsConversionCode(true); // BK 100916 TESTING // msn.com goes into a loop when being called upon next being clicked
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@			
		return true;
	} 	
	return false;
}

function checkContactThankyouURL(strURI) {
		// BK 100916 was var ptnContactThankyou=/\/contact_us\/?\?page=confirmation/;
	var ptnContactThankyou=/.*\/contact_us[?&].*(confirmation|true)/;			// BK 100916 New version
	if (strURI.search(ptnContactThankyou) !== -1) {
		if (!document.strVisitorSegment) {
			document.strVisitorSegment = 'Leads';
		}
		sendAdWordsConversionCode();
		return true;
	} 	
	return false;
}

function checkGenericConversionPage(strURI) {
	var ptnGenericConversion=/(conv=true).*&(segvis=)*([^&]*)/;
	var strGenericConversion = strURI.match(ptnGenericConversion)
	if (strGenericConversion) {
		strGenericConversion = strGenericConversion[3]; 
		
		if (!document.strVisitorSegment && strGenericConversion) {
			document.strVisitorSegment = strGenericConversion;
		}
		sendAdWordsConversionCode();
		return true;
	}
	return false;
}

function checkGetNewsLetterThankyouURL(strURI) {
	var ptnNewsLetterThankyou=/\/newsletter_complete/;	// BK 100916 checked - was correct
	if (strURI.search(ptnNewsLetterThankyou) !== -1) {
		if (!document.strVisitorSegment) {
			document.strVisitorSegment = 'Leads';
		}
		sendAdWordsConversionCode();
		return true;
	} 	
	return false;
}

function sendAdWordsConversionCode(useTimeOut) {
	//console.log('In sendAdWordsConversionCode(useTimeOut) with ' + (useTimeOut || ''));
	
	var convFrame = document.createElement('iframe'); 
	convFrame.style.display = "none";
	convFrame.src = "/resources/rmvIframe.html";
	(document.getElementsByTagName('body')[0]).appendChild(convFrame);
	//console.log('iframe appended and done with google and msn from sendAdWordsConversionCode()');

	// document.write(unescape("%3Cscript src='http://www.googleadservices.com/pagead/conversion.js' type='text/javascript'%3E%3C/script%3E"));
	// window.googleConversion = function (){};
/*	
	var callConversion = function () {googleConversion();  };// googleConversion(); msnConversion()
	if (useTimeOut) {
		setTimeout( callConversion, 15000);
	} else {
		callConversion();
	}
*/	
	//console.log('Leaving sendAdWordsConversionCode');
	
}

fSafeAddOnload(mainSendData);
fSafeAddOnload(fGooAnTagPdfs);
	
