/*
		>>>>>>>>>>>>>> SET UP ERROR HANDLING AND DEBUGGING <<<<<<<<<<<<<<
*/
onerror=handleErr;
function handleErr(msg,url,l)
{
	// handle JavaScript Errors
	var txt="Error: " + msg + "\n";
	txt+="URL: " + url + "\n";
	txt+="Line: " + l + "\n\n";
	if(debug) alert(txt);
	return true;
}
var debug=false;    // if you set debug=true, we send alert messages to a popup window for improved debugging
var debugTxt="";
var dbgWin;
var startTime = (new Date()).getTime(); // now in milliseconds
function newAlert(str){
    if (!debug) return;
    timeStr = ( (new Date()).getTime() - startTime ).toString();
    debugTxt += timeStr + ": ";
    debugTxt+=str+"<br />";
    if(typeof(dbgWin)!="object"){
        dbgWin = window.open('','_debug','toolbar=0,scrollbars=1,location=0,statusbar=1,menubar=0,resizable=1,width=800,height=350');
    }
    dbgWin.document.open();
    dbgWin.document.write(debugTxt);
    dbgWin.document.write("\nTitle: " + window.document.title);
    dbgWin.document.close();
}
function noAlert(str){
    // do nothing
}
if(debug){
    window.alert = newAlert;
} else {
    window.alert = noAlert;
    // disable alert function
}


/*
*******************************************************************************
*******************************************************************************

		>>>>>>>>>>>>>>>>> UTILITY FUNCTIONS <<<<<<<<<<<<<<
		addLoadEvent and URL manipulation helper functions
		cookie functions

*******************************************************************************
*/

function addLoadEvent(func) {
// utility function to allow multiple onload events
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

function stripURL(u){
// removes hash and querystring from a url
    var hashind=u.indexOf("#");
    var v=u;
    if(hashind>0) v=v.substring(0,hashind);
    var qind=v.indexOf("?");
    if(qind>0) v=v.substring(0,qind);
    return v;
}

function pageName(u){
// returns just the page name from a url
    var v=u;
    v=stripURL(v);
    startind=v.lastIndexOf("/");
    v=v.substring(startind+1);
    return v;
}

function basePath(u){
// returns just the path info, minus the page, query and hash, from a url
    var v=u;
    v=stripURL(v);
    endind=v.lastIndexOf("/");
    v=v.substr(0,endind);
    return v;
}

function stripExt(f){
// strips extension from a filename
    ind=f.lastIndexOf(".");
    f=f.substr(0,ind);
    return f;
}

// tests whether the user accepts cookies.
var acceptsCookies = false;
if(document.cookie == '') {
    document.cookie = 'acceptsCookies=yes'; // Try to set a cookie.
    if(document.cookie.indexOf('acceptsCookies=yes') != -1) {
		acceptsCookies = true;
    }// If it succeeds, set variable
} else { // there was already a cookie
    acceptsCookies = true;
}
//alert("acceptsCookies: "+acceptsCookies);

function setCookie (name, value, hours, path, domain, secure) {
    if (acceptsCookies) { // Don't waste your time if the browser doesn't accept cookies.
		if(hours) {
			if ( (typeof(hours) == 'string') && Date.parse(hours) ) { // already a Date string
				var numHours = hours;
			} else if (typeof(hours) == 'number') { // calculate Date from number of hours
				var numHours = (new Date((new Date()).getTime() + hours*3600000)).toGMTString();
			}
		}
		document.cookie = name + '=' + escape(value) + ((numHours)?(';expires=' + numHours):'') + ((path)?';path=' + path:'') + ((domain)?';domain=' + domain:'') + ((secure && (secure == true))?'; secure':''); // Set the cookie, adding any parameters that were specified.
    }
} // setCookie


function getCookie(name) {
    if(document.cookie == '') { // there's no cookie, so go no further
		return false;
    } else { // there is a cookie
		var firstChar, lastChar;
		var theBigCookie = document.cookie;
		firstChar = theBigCookie.indexOf(name);	// find the start of 'name'
		var NN2Hack = firstChar + name.length;
		if((firstChar != -1) && (theBigCookie.charAt(NN2Hack) == '=')) { // if you found the cookie
			firstChar += name.length + 1; // skip 'name' and '='
			lastChar = theBigCookie.indexOf(';', firstChar); // Find the end of the value string (i.e. the next ';').
			if(lastChar == -1) lastChar = theBigCookie.length;
			return unescape(theBigCookie.substring(firstChar, lastChar));
		} else { // If there was no cookie of that name, return false.
			return false;
		}
    }
} // getCookie

function killCookie(name, path, domain) {
  var theValue = getCookie(name); // We need the value to kill the cookie
  if(theValue) {
      document.cookie = name + '=' + theValue + '; expires=Fri, 13-Apr-1970 00:00:00 GMT' + ((path)?';path=' + path:'') + ((domain)?';domain=' + domain:''); // set an already-expired cookie
  }
} // killCookie

// MODIFY STRING TO ADD <TRIM, LTRIM AND RTRIM FUNCTIONS>:
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}
// </TRIM FUNCTIONS>

/*
           >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> COREMETRICS FUNCTIONS <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
           >>>>>>>>>>>>>>>>>>>>>>>>>>>>> FLASH WINDOW/LINK FUNCTIONS <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
           					techprops, page view, and conversion events
*/

var cmTrack_whichPage="first";
function cmTrack(sid) {
    //alert("util.js cmTrack: " + sid);
// takes a stateID such as rewards_0, converts it to the correct CoreMetrics manual impression code and fires the event
// run from StateManager _dispatchEvents function
// if there isn't a case for a specific sid, it defaults to appending '.aspx' to the sid itself
// this way new codes can be added without updating this function
//
// Home
//   email signup
// TrendWatch
//   watch video
//   mobile alerts
//   browse featured fashions
// Bank
//   Policy Details
//       accept terms
//       proceed to application form
//       printable version of terms & conditions
//   Manage your Account
//       links within manage your account
//
    var first = cmTrack_whichPage;  // the first time only, this will be 'first';
    switch (sid)
    {
	    case "defaultState":
	      cmTrack_whichPage="Home.aspx";
	      break;
	    case "rewards_0":
	      cmTrack_whichPage="Rewards.aspx";
	      break;
	    case "rewards_1":
	      cmTrack_whichPage="Rewards_Level_1.aspx";
	      break;
	    case "rewards_2":
	      cmTrack_whichPage="Rewards_Level_2.aspx";
	      break;
	    case "rewards_3":
	      cmTrack_whichPage="Rewards_Level_3.aspx";
	      break;
	    case "rewards_4":
	      cmTrack_whichPage="Rewards_Level_4.aspx";
	      break;
	    case "rewards_5":
	      cmTrack_whichPage="Rewards_HowItWorks.aspx";
	      break;
	    case "stayInKnow_0":
	      cmTrack_whichPage="Know.aspx";
	      break;
	    case "stayInKnow_1":
	      cmTrack_whichPage="Know_InsideStory.aspx";
	      break;
	    case "stayInKnow_2":
	      cmTrack_whichPage="Know_ExcitingEvents.aspx";
	      break;
	    case "stayInKnow_3":
	      cmTrack_whichPage="Know_Newsletter.aspx";
	      break;
	    case "trend_0":
	      cmTrack_whichPage="TrendWatch.aspx";
	      break;
	    case "bank_0":
	      cmTrack_whichPage="Bank.aspx";
	      break;
	    case "bank_1":
	      cmTrack_whichPage="Bank_Compare.aspx";
	      break;
	    case "bank_1_1":
	      cmTrack_whichPage="Bank_LearnMore_Card_VisaSignature.aspx";
	      break;
	    case "bank_1_2":
	      cmTrack_whichPage="Bank_LearnMore_Card_PlatinumVisa.aspx";
	      break;
	    case "bank_1_3":
	      cmTrack_whichPage="Bank_LearnMore_Card_Retail.aspx";
	      break;
	    case "bank_1_4":
	      cmTrack_whichPage="Bank_LearnMore_Card_MOD.aspx";
	      break;
	    case "bank_1_5":
	      cmTrack_whichPage="Bank_LearnMore_Card_VisaCheckCard.aspx";
	      break;
	    case "bank_2":
	      cmTrack_whichPage="Bank_ManageAccount.aspx";
	      break;
	    case "bank_3":
	      cmTrack_whichPage="Bank_PolicyDetails.aspx";
	      break;
	    case "nfrTerms":
	      cmTrack_whichPage="Terms_and_Conditions.aspx";
	      break;
	    default:
	      cmTrack_whichPage=sid+".aspx";
	}
    if(first=="first"){return;} // don't run this the very first time.  Tech props tag on index handles it instead.
    if(cmTrack_whichPage==undefined){return;}
    if( (cmTrack_whichPage!="no")&&(cmTrack_whichPage!=null) ) {
        //alert("cmTrack function:\n     "+sid+" : "+cmTrack_whichPage);
        // will only send recognized id's to the create page view tag
	    cmSetProduction();  // uncomment to switch from test to production
        window.setTimeout(function(){
            cmCreatePageviewTag(cmTrack_whichPage, null, "0~2377475~6015353");
        },150);
    }
}

function flashLink(strUrl, strTarget) {
    // called from asfunction:newLink or asfunction:newWin in flash html href's
    // need to pop a new window or take over current window depending on which, and check for links we need to send through cmTrack or cmConversion
    //alert("flashLink: *"+strUrl+"*, "+strTarget);
	strUrl=strUrl.trim();
    switch (strUrl)
    {
        case "https://www.nordstrommobile.com/alerts.asp?source=1":
        	//alert("match with BP Mobile Sign Up");
            cmConversion("BP Mobile Sign Up", 1, "Email Sign Up", "0");
            break;
        case "https://secure.nordstrom.com/services/emailupdates.asp":
        	//alert("match wtih Email Updates Sign Up");
            cmConversion("Email Updates Sign Up", 1, "Email Sign Up", "0");
            break;
        default:
            // do nothing
    }
    if (strTarget == "_self") {
		//alert("target self, replacing...");
        window.location.href = strUrl;
    }
    if (strTarget == "_blank") {
        flashLinkWin = window.open(strUrl, "flashLinkWin", "toolbar=yes,location=yes,status=yes,menubar=yes,scrollbars=yes,resizable=yes");
        window.setTimeout("flashLinkWin.focus();", 1750);
    }


}


function cmConversion(whichEvent,startEnd,evtCategory,points) {
    // create a coreMetrics conversion event.  Received from certain Flash events
    //alert("coremetrics conversion event :" + whichEvent + ", start or finish: " + startEnd + ", Category: " + evtCategory + ", points: " + points);
    cmCreateConversionEventTag(whichEvent, startEnd, evtCategory, points);
}
