/*
CVS Version : $Id: myaccount.js,v 1.13 2003/06/11 15:29:40 aankja Exp $

*/

function showlogoff(storeid,langid,logoffurl,linkname,confirmmsg){
if (storeid!="" && langid!="" && logoffurl!="" && linkname!="" && confirmmsg!="" && document.cookie.length > 0){
search="WCS_SESSION_ID";
offset = document.cookie.indexOf(search)
if (offset != -1) {
offset += search.length
end = document.cookie.indexOf(";", offset)
if (end == -1)
end = document.cookie.length
thevalue=unescape(document.cookie.substring(offset, end));
lastchar=thevalue.substring(thevalue.length-5,thevalue.length);
if (lastchar.indexOf(',,')==-1 && lastchar.indexOf('null')==-1 && thevalue.indexOf(storeid)!=-1 ){
document.writeln("<td>");
document.writeln("<div class=pipe>&nbsp;|&nbsp;</div>");
document.writeln("</td>");
document.writeln("<td>");
document.writeln("<script><a href=\"javascript:if(confirm('"+escape(confirmmsg)+"')){document.location='/webapp/wcs/stores/servlet/Logoff?langId="+langid+"&storeId="+storeid+"&URL="+logoffurl +"'};\" class=logout>"+linkname+"</a></" + "script>");
document.writeln("</td>");
}//write
} //offset
} //cookie
}

/**
	Enhanced version of the showlogoff function that doesn't ouput formatting
	@author KLSK
	@author BM26 (fixed bug between sites)
	@author KNBU (migrated to use WC5.6 cookie. Existing 5.4 is in a separate method OLD54haslogoffURL
	@author MTJO 2006-11-21  - (fixed problem with logout in firefox)
	@autho MAQT 2008-04-08 - Added check for cookie client_showlogoff_link
*/
function haslogoffURL(storeid){
	//document.write('<td>' + unescape(document.cookie) + '</td>');
	if (document.cookie == null) {
		// no cookie at all
		return false;
	}
	//change by maqt 080408
	//this should be the only check except for the first one. But we keep the famloggedin check becouse of the roll-out of 4.4.
	//there is also a internet explorer bug/feature that causes this cookie not to be set when logging in through the ecom flow. There's a redirect which kills the cookie.
	//therefore, we also have the old solution that check for the 12' position in one of the commerce cookies
	if (IRWreadCookie("client_showlogoff_link_" + storeid) && IRWreadCookie("client_showlogoff_link_" + storeid)=="true") {
		return true;
	}

/*

	//should be removed after fix of iebug with killed cookies in ecom redirects  /maqt
	// Split cookie
	var cookieArray = unescape(document.cookie).split(';');
	var wcauthstring = 'WC_USERSESSION_';
	var wcauthinfo = '';
	var wcstorestring = 'WC_ACTIVESTOREDATA';
	var wcstoreinfo = '';
	for (var i=0; i<cookieArray.length; i++) {
  	if (cookieArray[i].indexOf(wcauthstring) > -1) {
  		// Get authentication info
			wcauthinfo = cookieArray[i].substring(cookieArray[i].indexOf('=') + 1);
		}
		if (cookieArray[i].indexOf(wcstorestring) > -1) {
			// Get store info
			wcstoreinfo = cookieArray[i].substring(cookieArray[i].indexOf('=') + 1);
	  }
  }
	if (wcauthinfo == null || wcauthinfo == '') {
		return false;
	}

	var wcauthinfo_array = wcauthinfo.split(",");
	var wcstoreinfo_array = wcstoreinfo.split(",");

  var userId = wcauthinfo_array[0];

  var detailedInfo = wcauthinfo_array[12].substring(wcauthinfo_array[12].indexOf('[') + 1);
  var detailedInfo_array = detailedInfo.split("|");
  
var cookieStoreId = detailedInfo_array[0];


  // If 12th element is 'null' the user is not logged in
  if (wcauthinfo_array[11] == 'null') {
  	// Not logged in
  	return false;
  }

	// If the user changes store, kill the cookie
	
	if (storeid != cookieStoreId) {
 		var sDomain = document.domain;
 		
 		while (sDomain.indexOf('.') > -1) {
		  document.cookie = "WC_USERSESSION_" + userId + "=;domain=" + sDomain + ";path=/;expires=Wednesday, 09-Nov-99 23:12:40 GMT";
		  document.cookie = "WC_AUTHENTICATION_" + userId + "=;domain=" + sDomain + ";path=/;expires=Wednesday, 09-Nov-99 23:12:40 GMT";
		  sDomain = sDomain.substring(sDomain.indexOf('.') + 1);
		}
		//document.cookie = "WCS_ACTIVESTOREDATA=;path=/;expires=Wednesday, 09-Nov-99 23:12:40 GMT";
		//document.cookie = "WCS_UNIQUE_ID=;path=/;expires=Wednesday, 09-Nov-99 23:12:40 GMT";
		//document.cookie = "WCS_SSLCHECKCOOKIE=;path=/;expires=Wednesday, 09-Nov-99 23:12:40 GMT";
		//document.cookie = "WCS_PARORG=;path=/;expires=Wednesday, 09-Nov-99 23:12:40 GMT";
		//document.cookie = "WCS_CRNTCNTRCTS=;path=/;expires=Wednesday, 09-Nov-99 23:12:40 GMT";
		//document.cookie = "WCS_ELGBCNTRCTS=;path=/;expires=Wednesday, 09-Nov-99 23:12:40 GMT";
		//document.cookie = "WCS_SESSCNTRCTS=;path=/;expires=Wednesday, 09-Nov-99 23:12:40 GMT";
		//document.cookie = "JSESSIONID=;path=/;expires=Wednesday, 09-Nov-99 23:12:40 GMT";
		return false;
	}
*/
	// User is not logged in
	return false;

}

function setUserName() {
	var UserName=IRWreadCookie("displayname");
	if (UserName) {
		try {
			$('span_userName').update(UserName);
		} catch(e) {
		}
	}
}
function getCurrentURL(){
	var returnurl = document.location.pathname + document.location.search;
	// This is fixed in setupyouarehere.jsp..
	// var returnurl = document.location.pathname;
	return returnurl;
}

function logonLink() {
	var argForm;
	//netscape 6 && ie 5>
	if (document.getElementById){
	        argForm = document.getElementById("myAccount");
	}
	else if (document.all){ //Explorer 4
	        argForm = document.all['myAccount'];
	}
	else {
	        alert (js_fn_NOT_VALID_BROWSER);
	        return false;
	}
  argForm.submit();
}


function OLD54haslogoffURL(storeid){
	var wcssessionidcookie = getCookie("WCS_SESSION_ID");
	if (wcssessionidcookie == null) {
		//no cookie at all.
		return false;
	}

	//split variables in cookie.
	var wcssessionidcookie_array = wcssessionidcookie.split(",");

	//last String in array is the userid and if there is a user id, then user is logged in.

	var userId = wcssessionidcookie_array[wcssessionidcookie_array.length - 1];
	var loggedIn = userId != null && userId != "" && userId != "null";

	if (wcssessionidcookie_array[2] == storeid) {

		if (loggedIn) {
			//logged in customer, show logout.
			return true;
		}
		else {
			//not logged in but cookie for right country.
			return false;
		}
	}
	else {
		//User from wrong country, kill cookie.
		document.cookie = "WCS_SESSION_ID=;path=/;expires=Wednesday, 09-Nov-99 23:12:40 GMT";
		document.cookie = "WCS_SSLCHECKCOOKIE=;path=/;expires=Wednesday, 09-Nov-99 23:12:40 GMT";
		document.cookie = "WCS_AUTHENTICATION_ID=;path=/;expires=Wednesday, 09-Nov-99 23:12:40 GMT";
		document.cookie = "WCS_PARORG=;path=/;expires=Wednesday, 09-Nov-99 23:12:40 GMT";
		document.cookie = "WCS_CRNTCNTRCTS=;path=/;expires=Wednesday, 09-Nov-99 23:12:40 GMT";
		document.cookie = "WCS_ELGBCNTRCTS=;path=/;expires=Wednesday, 09-Nov-99 23:12:40 GMT";
		document.cookie = "WCS_SESSCNTRCTS=;path=/;expires=Wednesday, 09-Nov-99 23:12:40 GMT";
		document.cookie = "JSESSIONID=;path=/;expires=Wednesday, 09-Nov-99 23:12:40 GMT";
		return false;
	}
}


//helper for reading cookie values
//added 080408 by MAQT
function IRWreadCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

/*
 * START Base64 encode/decode from http://www.webtoolkit.info/javascript-base64.html
 */

var Base64 = {

	// private property
	_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

	// public method for encoding
	encode : function (input) {
		var output = "";
		var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
		var i = 0;

		input = Base64._utf8_encode(input);

		while (i < input.length) {

			chr1 = input.charCodeAt(i++);
			chr2 = input.charCodeAt(i++);
			chr3 = input.charCodeAt(i++);

			enc1 = chr1 >> 2;
			enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
			enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
			enc4 = chr3 & 63;

			if (isNaN(chr2)) {
				enc3 = enc4 = 64;
			} else if (isNaN(chr3)) {
				enc4 = 64;
			}

			output = output +
			this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
			this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

		}

		return output;
	},

	// public method for decoding
	decode : function (input) {
		var output = "";
		var chr1, chr2, chr3;
		var enc1, enc2, enc3, enc4;
		var i = 0;

		input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

		while (i < input.length) {

			enc1 = this._keyStr.indexOf(input.charAt(i++));
			enc2 = this._keyStr.indexOf(input.charAt(i++));
			enc3 = this._keyStr.indexOf(input.charAt(i++));
			enc4 = this._keyStr.indexOf(input.charAt(i++));

			chr1 = (enc1 << 2) | (enc2 >> 4);
			chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
			chr3 = ((enc3 & 3) << 6) | enc4;

			output = output + String.fromCharCode(chr1);

			if (enc3 != 64) {
				output = output + String.fromCharCode(chr2);
			}
			if (enc4 != 64) {
				output = output + String.fromCharCode(chr3);
			}

		}

		output = Base64._utf8_decode(output);

		return output;

	},

	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";

		for (var n = 0; n < string.length; n++) {

			var c = string.charCodeAt(n);

			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}

		}

		return utftext;
	},

	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;

		while ( i < utftext.length ) {

			c = utftext.charCodeAt(i);

			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}

		}

		return string;
	}

}
/*
 * END Base64 encode/decode from http://www.webtoolkit.info/javascript-base64.html
 */

/**
*
*  URL encode / decode
*  http://www.webtoolkit.info/
*
**/

var Url = {

	// public method for url encoding
	encode : function (string)
	{
		string=escape(this._utf8_encode(string));
		string=string.replace(new RegExp('\\+','g'),'%2B');
		return string.replace(new RegExp('%20','g'),'+');
	},

	// public method for url decoding
	decode : function (string)
	{
		string = string.replace(new RegExp('\\+','g'),' ');
		return this._utf8_decode(unescape(string));
	},

	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";

		for (var n = 0; n < string.length; n++) {

			var c = string.charCodeAt(n);

			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}

		}

		return utftext;
	},

	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;

		while ( i < utftext.length ) {

			c = utftext.charCodeAt(i);

			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}

		}

		return string;
	}

}
/**
	Populates the logon/logoff part of the header based on user authentication state
	@author Magnus Hjersing (MHJE)
	@since CR5.1
*/	
function getUserInfo(storeID,requestType) {
		requestType = typeof(requestType) != 'undefined' ? requestType : 'async';
		if (document.cookie == null) {
				// no cookie at all -> user has never logged or doesn't support cookies
				return null;
		}

		var cookieStr = new String(document.cookie);
			
		if (!cookieStr.include("WC_")) {
			// No Commerce cookie present which means there is no session against server
				return null;
		}

		var userInfo = null;
		var displayname = null;
	
		if (IRWreadCookie("user_info_" + storeID)) {
			// There is a display name set
			displayname = new String(IRWreadCookie("user_info_" + storeID)).strip();
			if (displayname != null && displayname != 'notloggedin' && !displayname.blank()) {
				// The cookie is base64 and URL encoded
				decodedStr = Url.decode(Base64.decode(displayname));
				// Ok there is a name set let's create a userinfo object to return to the header
				userInfo = new Object();
				var strArray = decodedStr.split(';');
				if (strArray.length > 0) {
					userInfo.firstName = unescape(strArray[0]);
				}
				if (strArray.length > 1) {
					userInfo.lastName = unescape(strArray[1]);
				}
				if (strArray.length > 2) {
					userInfo.title = unescape(strArray[2]);
				}
			}
		}
		if (userInfo != null) {
			// There is info for the user to return to the header
			return userInfo;
		}
		
		if (cookieStr.include("WC_") && displayname != 'notloggedin' && requestType == 'async') {
			// No	valid displayname cookie found but there is a session with the server	
			// If displayname is set to notloggedin it just means that we already asked 
			// the server in this session
			getUserInfoFromServer(storeID);
		}

		if (cookieStr.include("WC_AUTHENTICATION") && displayname == 'notloggedin' && requestType == 'async') {
			// The cookie says the user is not logged in but there is WC cookie saying differently
			getUserInfoFromServer(storeID);
		}

		return null;
}

/**
	Retrives the display name for a known user from the server through AJAX call and
	updates the displayname cookie. If the user is not known the cookie will be set to
	"notloggedin" to avoid fetching it on every request.
	@author Magnus Hjersing (MHJE)
	@since CR5.1
*/
function getUserInfoFromServer(storeID) {
		try {
			var requestURL = '/webapp/wcs/stores/servlet/GetUserInfo?storeId='+storeID;
			userRequest = new Ajax.Request(requestURL,{ 
				method: 'get', 
				onFailure: function () {
					//do nothing
				},
				onException: function (instance,object) {
					//do nothing
				},
				onInteractive: function () {
					//do nothing
				},
				onSuccess: function(transport){ 
					var requestXML = transport.responseXML;
					var _status = requestXML.getElementsByTagName('loggedIn')[0].firstChild.data;
					var _path = null;
					if (requestXML.getElementsByTagName('cookie_path')[0].firstChild != null) {
						_path = requestXML.getElementsByTagName('cookie_path')[0].firstChild.data;
					}
					var _domain = null;
					if (requestXML.getElementsByTagName('cookie_domain')[0].firstChild != null) {
						_domain = requestXML.getElementsByTagName('cookie_domain')[0].firstChild.data;
					}
					var _days = requestXML.getElementsByTagName('cookie_expiry_days')[0].firstChild.data;
					if (_status == 'Y' || _status == 'P') {
						var cookieContent = requestXML.getElementsByTagName('cookie_content')[0].firstChild.data;
						if (_status == 'P' && _days != '-1') {
							// We know this a user that wants to be remembered so we can safely use a
							// persistent cookie
							_expires = new Date(); 
							_expires.setDate(_expires.getDate() + _days);
							document.cookie = "user_info_" + storeID + "=" + unescape(cookieContent) + ";domain=" + _domain + ";path=" + _path + ";expires=" + _expires.toGMTString();
						} else {
							// Just use a session cookie
							document.cookie = "user_info_" + storeID + "=" + unescape(cookieContent) + ";domain=" + _domain + ";path=" + _path;
						}
						userInfo = getUserInfo(storeID);
					} else {
							document.cookie = "user_info_" + storeID + "=notloggedin;domain=" + _domain + ";path=" + _path;
					}
					updateWelcomeText();
				}
			});
		} catch (e) {
			//do nothing
		}
		return;
}

function showError(str) {
	alert('error:\n'+str);
}
