$(document).ready(getCreditUser);

function getCreditUser() {

	var sURLPrmCreditUser = parseURLfor("cdu"); // Is there an id in the URL string?
	var sCookieCreditUser = getCookie("cdu"); // Do we have a cookie set already?
	var sCookieCountdownExpired = getCookie("cdck"); // Should we holding off on checking for the id cookies?  Presence of this cookie says, "yes."
	var sID = "";
	
	// If we're not on the FashionCents domain, don't replace any id's (to handle previewing on blogger's servers)
	if (window.location.href.indexOf("myfashioncents.com") == -1) return;
	
	// Check to see if we've grabbed an ID before; if so, use it.  If not, redirect to cookieTracker to get an ID.
	if (isValidCreditUser(sURLPrmCreditUser) && (sURLPrmCreditUser != "disabled")) { // If there's an ID in the URL parameter, save it - this supercedes the cookie
		sID = sURLPrmCreditUser;
		setCookie("cdu", sID, 3, "/", ".myfashioncents.com", false, "yr");
		_NeedCookie = true;
	} else if (!isValidCreditUser(sCookieCreditUser) && (sURLPrmCreditUser != "disabled")) {
  // We have no cookie, no URL param ID, URL param doesn't indicate that we've tried before + cookies are disabled.  Thus, we should redirect to cookieTracker and try to get a cookie.
  if (sCookieCountdownExpired ==-1) { // Countdown to try for an id cookie has expired?  Yes, if this cookie is expired from cache.
			// Re-set the countdown cookie.  It will expire in 15 seconds.
			setCookie("cdck", "true", 15, "/", ".myfashioncents.com", false, "sec");
			doCookieRedirect();
		}
		// Still waiting to check for id?  Do nothing.
		return;
	} else if (sURLPrmCreditUser != "disabled") {
		sID = sCookieCreditUser; // We have a cookie!  Yay!
	}
	
	// If we get here, we have a valid ID
	replaceDefaultCreditUserWith("MF" + sID);
	
	// If we didn't get an id cookie and the countdown cookie hasn't expired, prevent the cookie redirect until the next page load by adding "cdu" url param
	// to ALL hrefs in the dom.  If the cdu url param is ABSENT on page load, the id cookie check will be performed.  So by setting it here, we're effectively
	// saying, "we won't check cookies for 15 seconds or the next non-current page load, whichever comes last."  Of course, if the current page is reloaded
	// and the cdck cookie has expired, the cookie check will still be performed.  This is by design, since if a dist forgets to log in, visits the site, sees the
	// missing cdu, logs into the portal, then reloads, we want to populate the correct credit information.
	if ((sID == "") && (sCookieCountdownExpired !=-1)) {
		addGlobalURLParam("cdu", ((sID == "") ? "disabled" : sID) );
	}
	
	// Done!
}

function addGlobalURLParam(sParam, sValue) {
 var sDelim;
	var aReplace = new Array();

	aReplace = $("a").each(function(a) {
	 sDelim = ((this.href.indexOf('?') != -1) ? "&" : "?");
		this.href = (this.href + sDelim + sParam + "=" + sValue);
	});

}

function parseURLfor(name) {
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regex = new RegExp("[\\?&]"+name+"=([^&#]*)");
	var results = regex.exec(window.location.href);
	if (results == null)
		return "";
	else
		return results[1];
}

function removeParamFromString(sURL, sParam) {

	sURL = sURL.replace(sParam+"=", "~~~", "gi");

	// Replace params either followed by an ampersand or an end-of-line
	sURL = sURL.replace(/~~~.*&/, "", "gi");	
	sURL = sURL.replace(/~~~.*$/, "", "gi");

	// If the URL ends in a question mark, we've stripped off the last param - go ahead and remove that
	if (sURL.indexOf("?") == (sURL.length - 1)) {
		sURL = sURL.replace(/\?/, "", "gi");
	}
	
	return sURL;
}

function isValidCreditUser(sID) {
	if ((sID != undefined) && (sID != null) && (sID != "") && (sID != "-1") && (sID != "MF")) {
		return true;
	}
	
	return false;
}

function doCookieRedirect(sID) {
	var sCurLoc = window.location.href;
	//sCurLoc = sCurLoc.replace(/images\.myfashioncents/, "", "www.myfashioncents");	
	var sRedirect = ("http://cookietracker.marketamerica.com/cookieSvr_creditUser.html?redirect="+escape(removeParamFromString(sCurLoc, "cdu")));

 window.location = sRedirect;

}

function replaceDefaultCreditUserWith(sCreditUser) {
	var aDefCreditUsers = new Array("MFC9169563","C9169563");
	var i;

	if (isValidCreditUser(sCreditUser)) {
	
		for (i = 0; i < aDefCreditUsers.length; i++) {
			var aReplace = new Array();
	
			aReplace = $("a").each(function(a) {
				this.href = this.href.replace(aDefCreditUsers[i], sCreditUser);
			});
  }
  
 }
	
}

function getCookie(sName){ 
 var dc = document.cookie;
	var sPrefix = sName + "="; 
	var iBegin = dc.indexOf("; " + sPrefix); 

	if (iBegin == -1) {
		iBegin = dc.indexOf(sPrefix); 

		if (iBegin != 0){ 
			return -1; 
		} 
	} else {
		iBegin += 2; 
	}

	var iEnd = dc.indexOf(";", iBegin);

	if (iEnd == -1) {
		iEnd = dc.length; 
	} 

	return unescape(dc.substring(iBegin + sPrefix.length, iEnd));
}

function setCookie(sName, sValue, sExpiry, sPath, sDomain, sSecure, sUnit) {
	// Set time in milliseconds
	var dateToday = new Date();
	var sCookieString;
	
	dateToday.setTime(dateToday.getTime());
	
	if (sExpiry) {
	 switch(sUnit) {
	  case "ms":
  		sExpiry = sExpiry;
	   break;
	  case "sec":
  		sExpiry = sExpiry * 1000;
	   break;
	  case "min":
  		sExpiry = sExpiry * 1000 * 60;
	   break;
	  case "hr":
  		sExpiry = sExpiry * 1000 * 60 * 60;
	   break;
	  case "day":
  		sExpiry = sExpiry * 1000 * 60 * 60 * 24;
	   break;
	  case "wk":
  		sExpiry = sExpiry * 1000 * 60 * 60 * 24 * 7;
	   break;
	  case "mo":
  		sExpiry = sExpiry * 1000 * 60 * 60 * 24 * 7 * 4;
	   break;
	  case "yr":
  		sExpiry = sExpiry * 1000 * 60 * 60 * 24 * 7 * 52;
	   break;
	  default: // days
  		sExpiry = sExpiry * 1000 * 60 * 60 * 24;
	   break;
	 }
	}
	
	
	var dateExpiry = new Date(dateToday.getTime() + (sExpiry) );
	
	sCookieString = sName + "=" + escape(sValue) +
	( (sExpiry) ? ";expires=" + dateExpiry.toGMTString() : "" ) +
	( (sPath) ? ";path=" + sPath : "") +
	( (sDomain) ? ";domain=" + sDomain : "") +
	( (sSecure) ? ";secure" : "");
	
	document.cookie = sCookieString;
}