/****************************************
 * Numeric Analytics tagging framework
 * v 2.0  Feb 15th 2010 
****************************************/
function getRandomNumber(range) {
      return Math.floor(Math.random() * range);
}
function getRandomChar() {
      var chars = "0123456789abcdefghijklmnopqurstuvwxyzABCDEFGHIJKLMNOPQURSTUVWXYZ";
      return chars.substr( getRandomNumber(62), 1 );
}
function randomID(size) {
      var str = "";
      for(var i=0; i<size; i++) {
            str += getRandomChar();
      }
      return str;
}
function initToken() {
	/*
      var tokenId = randomID(40);
      document.getElementById('token').value = tokenId;
      naf.omni.sendToken(tokenId);
      */
}




/******BEGIN:	*************	dynamic tagging	**********************************/

$(document).ready( function(){
	
	var url_page_name = document.location.href;
	var pageSection = url_page_name.substring(url_page_name.indexOf('.com/')+5, url_page_name.lastIndexOf('/'));
	page_name = url_page_name.substring(url_page_name.lastIndexOf('/')+1, url_page_name.indexOf('.html'));

	
	switch(pageSection.toLowerCase()){			
		case 'aboutrei':
			createPageTags('aboutrei:'+url_page_name, 'aboutrei', 'aboutrei', 'aboutrei', '', 'rei'); 
			break;
			
		case 'adventures/resources':
			createPageTags('adventures:'+url_page_name, 'adventures', 'adventures', 'adventures', 'resources', 'adventures');
			break;
			
		case 'adventures/activity':
			createPageTags('adventures:'+url_page_name, 'adventures', 'adventures', 'adventures', 'activity', "adventures");
			break;
	}
	//Dynamically creates omniture page tags for specific pages.
	function createPageTags(dPage, site_section, template_type, content_type, subsection1, siteId){
		var alreadyTagged = false;		
		if(typeof(naf) == 'object'){ alreadyTagged = true; }
		
		setTimeout(function(){
			if(!alreadyTagged){
				var naf = new Object();
				naf['page_name'] = dPage;
				naf['site_section'] = site_section;
				naf['subsection1'] = subsection1;
				naf['template_type'] = template_type;
				naf['content_type'] = content_type;
				naf['site_id'] =  siteId;
			}
			else{
				//alert('already tagged');
			}
		}, 1000);
	}
	
	$('#hunt2 a#membershipLink').click(function(){
	    naf.omni.sendMembershipEvent('mem_header_tab');
	});
});


/*******END: 	************	dynamic tagging	**********************************/




// NAF
if(!naf){var naf = new nafTemplateObj();
}else{
	naf.setProperty = function(pName,pValue){
		this[pName] = pValue;
	}
	naf.getProperty = function(pName){
		if(this[pName]){return this[pName];}else{return "";}
	}
}

function nafTemplateObj(){//default template object that all objects are instantiated from
	this.setProperty = function(pName,pValue){
		this[pName] = pValue;
	}
	this.getProperty = function(pName){
		if(this[pName]){return this[pName];}else{return "";}
	}
}


//A private object that is used for configuration of the framework.  All properties should be set by code, not programatically so that proper framework functioning is assured
naf._config = new Object();
//Utilities object to hold the tools needed to transverse the DOM, set events, get elements etc.
naf.utils = new Object();
//Web Analytics Object for anything related to WA
naf.wa = new Object();


// ****************** START CONFIG *********************************
naf._config.getLocationtoSelf = function(){
	var myName = /(^|[\/\\])numericAnalyticsFramework\.js(\?|$)/;
	var scripts = document.getElementsByTagName("script");
	for (var i = 0; i < scripts.length; i++) {
	    var src1;
	    if (src1 = scripts[i].getAttribute("src")) {
	      if (src1.match(myName)) {
	        src1 = src1.substring(0, src1.lastIndexOf("/")+1);
	        return src1; 
	      }
	    }
	}
}
naf._config.openScrpt = '<scr' + 'ipt language="JavaScript" type="text/javascript" src="';
naf._config.closeScrpt = '"></scr' + 'ipt>';
naf._config.baseUrl = naf._config.getLocationtoSelf();


// ****************** END CONFIG *********************************

// ****************** START UTILS *********************************
naf.utils.sanitizeUntrusted = function(s) {
	return s.replace(/(;)|(')|(<)|(>)|(=)|(\))|(\()/igm,'!');
}
naf.utils.getQueryParam = function(name)
{
  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 naf.utils.sanitizeUntrusted(results[1]);
}
naf.utils.isIE = (window.navigator.userAgent.indexOf("MSIE") > 0);
if (!  naf.utils.isIE ) {
  HTMLElement.prototype.__defineGetter__("innerText",
              function () { return(this.textContent); });
  HTMLElement.prototype.__defineSetter__("innerText",
              function (txt) { this.textContent = txt; });
}
// ****************** END REQUIRED *****************************
// ******************  START PLUGINS *********************************
	

/*	Start Cookie Code   */ 
// Chip Cookie Object	
	naf.utils.cookieIngredients=function(){
	  //Constants
	  this.chip_cookie_name = "BIGNUMERIC";
		this.name_value_delim = "~";
    this.cookie_delim = "|";
   // this.length = -1;
    // Example: this.chips = { "cookiename1":cookievalue1, "cookiename2": cookievalue2 };
    this.chips = {};
    // Adds a name/value pair to the cookie's value array params: n = name, v = value
		this.add = function(n,val){
			this.chips[n]=val;
		}
		// Remove the cookie named cname and its value from the chips.
		this.eat = function(cname){
			for(var key in this.chips){ 
				if(key.indexOf(cname) >= 0){
					delete this.chips[key];
				 	break;
				}
			} 
		}
		// Return the value of the cookie requested (cname). Loop through the hash and if the cookie name is one of the hash keys return it's value.
		this.read = function(cname){
			var tmp = "";
			for(var key in this.chips){ 
				if(key.indexOf(cname) >= 0){
				 	tmp = this.chips[key];
				 	return naf.utils.sanitizeUntrusted(tmp);
				 	break;
				} 
			}
			return null;

		}
		// Takes the values of an existing chip cookie and populates the chipCookie object
		this.fill = function(str){
			var strArray = str.split(this.cookie_delim);
			for ( var i=0; i<strArray.length; ++i ){
				var namevalpair = strArray[i].split(this.name_value_delim);
				this.add(namevalpair[0],namevalpair[1]);
			}
			
		}
		// Returns name value pairs separated by the defined delimiters
		this.bake = function(){
			var tmpArray = new Array();
			 for(var key in this.chips){ 
			 		tmpArray.push(key + this.name_value_delim + this.chips[key]);
			 } 
			tmp = tmpArray.join(this.cookie_delim);
			return tmp;
		}
		// Returns how many chips are there?
		this.size = function(){
  		var len =  0;
			    for (var k in this.chips)
			      len++;
  		return len;
		}

		
};

// 	setChip(cookiename, cookievalue) : adds a name/value to the MEGA cookie. If the name already exists in the MEGA cookie it will overwrite its value.
naf.utils.setChip=function(cname, cval)
{ 
    var theChips = new naf.utils.cookieIngredients();
		var tmp = "";
		//The cookie already exists. Add a new value to it.
		if (naf.utils.getCookie(theChips.chip_cookie_name)){
					//Get the contents of the chip cookie
					tmp = naf.utils.getCookie(theChips.chip_cookie_name);
					theChips.fill(tmp);
					// add a new chip
					theChips.add(cname,cval);
					//Write the new cookie
		 			naf.utils.setCookie(theChips.chip_cookie_name, theChips.bake());
			}else{
					// add the first chip
					theChips.add(cname,cval);
					//Write the new cookie
		 			naf.utils.setCookie(theChips.chip_cookie_name, theChips.bake());
			}		
}

// getChip(cookiename) : returns the value of a chip
naf.utils.getChip=function(cname){
	var theChips = new naf.utils.cookieIngredients();
	var tmp = "";
		//The cookie already exists. Add a new value to it.
			if (naf.utils.getCookie(theChips.chip_cookie_name)){
					//Get the contents of the chip cookie
					tmp = naf.utils.getCookie(theChips.chip_cookie_name);
					theChips.fill(tmp);
					// add a new chip
					return theChips.read(cname);
			}else{
					return null
			}		
}

// deleteChip(cookiename) : deletes a chip from the MEGA cookie. It does not delete the MEGA cookie
naf.utils.deleteChip=function(cname) {
		var theChips = new naf.utils.cookieIngredients();
		var tmp = "";
		// The big cookie exists
		if (naf.utils.getCookie(theChips.chip_cookie_name)){
			//Get the contents of the chip cookie
			tmp = naf.utils.getCookie(theChips.chip_cookie_name);
			theChips.fill(tmp);
			//Remove the chip from the cookie
			theChips.eat(cname);
			//Write the new cookie
		 	naf.utils.setCookie(theChips.chip_cookie_name, theChips.bake());
		}
}
/*	End Chip Code   */ 
/*	Start Cookie Code   */ 
naf.utils.setCookie=function(name, value, expires){
var path = "/";

domain = document.domain;
dparts = domain.split(".");
if (dparts.length == 3) {
   rootDomain = dparts[1]+"."+dparts[2];
} else {
   rootDomain = domain;
}

var secure = false;
var cookie = name + "=" + unescape(value) +
((expires == null) ? "" : ("; expires=" + expires.toGMTString())) + ((path == null) ? "" : ("; path=" + path)) +
((rootDomain == null) ? "" : ("; domain=" + rootDomain)) +
((secure == true) ? "; secure" : "");

document.cookie = cookie;
}

naf.utils.getCookie = function(name){
try{
    var cookieValue = null;
    if (document.cookie && document.cookie != '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = cookies[i].replace(/^\s\s*/, '').replace(/\s\s*$/, '');
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) == (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return naf.utils.sanitizeUntrusted(cookieValue);
 
}catch(e){}
}
/*	End Cookie Code   */ 


naf.utils.getEventTarget = function(e){
	try {
		var targ = null;
		if (!e) {
			var e = window.event;
		}
		if (e.target) {
			targ = e.target;
		} 
		else if (e.srcElement) {
			targ = e.srcElement;
		}
		if (targ.nodeType == 3) {
			targ = targ.parentNode;
		}
		return targ;
	} catch(e) {return null;}
}
naf.utils.addEvent = function(func, El, evt){
	try{
		if(El.attachEvent){		
			El.attachEvent("on"+evt.toLowerCase(),func);
		}
		 if(El.addEventListener){

				El.addEventListener(evt.toLowerCase(),func,false);
				
		} 
		return this;
	}catch(e){}
}
naf.utils.returnFalse = function(){return false;}
naf.utils.decode = function( $str ){
	try{
		var $entities = [ ['%f8','%20'], ['%a0', '%20'],  ['%3e','%20'], ['%3c','%20'],  ['%26','%20'],  ['%22','%20'] ];
		var $ii = 0;
		var $estr = escape( $str );
		$estr = $estr.toLowerCase();
			while ($ii < $entities.length){
				$estr = $estr.replace(new RegExp($entities[$ii][0], "g"), $entities[$ii][1] );
				$ii++;
			}
		return unescape($estr);
	}catch(e){return $str;}
}
naf.utils.getText = function(nodeOrig){
	try{
	 var rtn= "";
	 var t=0;
	 var fcn = function(node){
	 	if(t < 100){
		 	for(var c=0;c<node.childNodes.length;c++){
				var childnode=node.childNodes[c];
				switch(childnode.nodeType){
					case 3: 
						rtn += naf.utils.decode(childnode.nodeValue);
						break;
					case 1:
						t++;
						fcn(childnode);
						break;
					};
				}
	 		}
		 }
		 fcn(nodeOrig);
			return rtn;
	}catch(e){return "";}
}
// ******************  END UTILS *********************************
naf.loadScriptLibrary = function(src, targetElement, olFunction) {
	var library = document.createElement('script');
	library.type = 'text/javascript'; 
	library.src = src;
	if(typeof olFunction == 'function') {
		if(library.addEventListener) {
		library.addEventListener("load",olFunction,false);
		} else {
			olFunIE = olFunction.toString();
			var from = olFunIE.indexOf('{') + 1;
			var length = olFunIE.length - 1 - from;
			olFunIE = olFunIE.substr(from, length);
			library.onreadystatechange = function () {
				if (library.readyState == 'complete' || library.readyState == 'loaded') {
					library.onreadystatechange = null;
					eval(olFunIE);
				}
			}
		}
	}
	document.getElementsByTagName('head')[0].appendChild(library);
}


naf.analyticsCallBack = function() {
	try{
		//load vendor widgets
		//Omniture

		naf.loadScriptLibrary(naf._config.baseUrl +"omniWidget.js",  document.getElementsByTagName('head')[0]);
		//Google Analytics
		//naf.loadScriptLibrary(naf._config.baseUrl + "gaWidget.js",  document.getElementsByTagName('head')[0]);

	}catch(e){}
}

//Call vender code
//Omniture
naf.loadScriptLibrary(naf._config.baseUrl +"s_code.js",  document.getElementsByTagName('head')[0], naf.metricTranslation);

//Google Analytics
//naf.utils.loadScriptLibrary(naf._config.baseUrl +"ga.js",  document.getElementsByTagName('head')[0]);


