/*jsl:option explicit*/

/*
Qicnet Wish List
� 2008 Brett Knights. All rights reserved. This material may not be reproduced,
displayed, modified or distributed without the express prior written
permission of the copyright holder.

For site customization please make all changes to WishListCatalogFunctions.js

Some portions of this work fall under other copyright terms and are so marked.
*/
if(!this.JSON){this.JSON={};}(function(){function f(n){return n<10?"0"+n:n;}if(typeof Date.prototype.toJSON!=="function"){Date.prototype.toJSON=function(key){return isFinite(this.valueOf())?this.getUTCFullYear()+"-"+f(this.getUTCMonth()+1)+"-"+f(this.getUTCDate())+"T"+f(this.getUTCHours())+":"+f(this.getUTCMinutes())+":"+f(this.getUTCSeconds())+"Z":null;};String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(key){return this.valueOf();};}var cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,meta={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},rep;function quote(string){escapable.lastIndex=0;return escapable.test(string)?'"'+string.replace(escapable,function(a){var c=meta[a];return typeof c==="string"?c:"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4);})+'"':'"'+string+'"';}function str(key,holder){var i,k,v,length,mind=gap,partial,value=holder[key];if(value&&typeof value==="object"&&typeof value.toJSON==="function"){value=value.toJSON(key);}if(typeof rep==="function"){value=rep.call(holder,key,value);}switch(typeof value){case"string":return quote(value);case"number":return isFinite(value)?String(value):"null";case"boolean":case"null":return String(value);case"object":if(!value){return"null";}gap+=indent;partial=[];if(Object.prototype.toString.apply(value)==="[object Array]"){length=value.length;for(i=0;i<length;i+=1){partial[i]=str(i,value)||"null";}v=partial.length===0?"[]":gap?"[\n"+gap+partial.join(",\n"+gap)+"\n"+mind+"]":"["+partial.join(",")+"]";gap=mind;return v;}if(rep&&typeof rep==="object"){length=rep.length;for(i=0;i<length;i+=1){k=rep[i];if(typeof k==="string"){v=str(k,value);if(v){partial.push(quote(k)+(gap?": ":":")+v);}}}}else{for(k in value){if(Object.hasOwnProperty.call(value,k)){v=str(k,value);if(v){partial.push(quote(k)+(gap?": ":":")+v);}}}}v=partial.length===0?"{}":gap?"{\n"+gap+partial.join(",\n"+gap)+"\n"+mind+"}":"{"+partial.join(",")+"}";gap=mind;return v;}}if(typeof JSON.stringify!=="function"){JSON.stringify=function(value,replacer,space){var i;gap="";indent="";if(typeof space==="number"){for(i=0;i<space;i+=1){indent+=" ";}}else{if(typeof space==="string"){indent=space;}}rep=replacer;if(replacer&&typeof replacer!=="function"&&(typeof replacer!=="object"||typeof replacer.length!=="number")){throw new Error("JSON.stringify");}return str("",{"":value});};}if(typeof JSON.parse!=="function"){JSON.parse=function(text,reviver){var j;function walk(holder,key){var k,v,value=holder[key];if(value&&typeof value==="object"){for(k in value){if(Object.hasOwnProperty.call(value,k)){v=walk(value,k);if(v!==undefined){value[k]=v;}else{delete value[k];}}}}return reviver.call(holder,key,value);}cx.lastIndex=0;if(cx.test(text)){text=text.replace(cx,function(a){return"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4);});}if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,""))){j=eval("("+text+")");return typeof reviver==="function"?walk({"":j},""):j;}throw new SyntaxError("JSON.parse");};}}()); //" balance quote
function tty(msg){ if(window.console && window.console.log) window.console.log(msg);}

var WLC = function(){

function xSplit(target, _regEx){
		 // Most browsers can do this properly, so let them -- they can do it faster
		if ("a~b".split(/(~)/).length === 3) { return target.split(_regEx); }

		 // IE (and any other browser that do not capture the delimiter)
		 // will, unfortunately, have to be slowed down

		 if (!_regEx.global)
				{ _regEx = new RegExp(_regEx.source, 'g' + (_regEx.ignoreCase ? 'i' : '')); }

			var start = 0, arr=[];
			var result;
			while((result = _regEx.exec(target)) != null){
					arr.push(target.slice(start, result.index));
					if(result.length > 1) arr.push(result[1]);
					start = _regEx.lastIndex;
			}
			if(start < target.length) arr.push(target.slice(start));
			if(start == target.length) arr.push(""); //delim at the end
			return arr;
	}

	function lPad(num){
		if(num < 10) return "0" + num.toString();
		return num.toString();
	}

	return {

	 setValueTitle: function(target){
			if(!target.value ) target.value = target.getAttribute("title");
		},


	setMyFrameHeight: function(){ // call whenever more nodes are added to this page
		if(parent && parent.resizeIFrame){
			parent.resizeIFrame($('#wishListFrame', parent.document ? parent.document : parent.contentDocument).get(0));
		}
	},

	setReturnURL:	function (){
		var target = window.parent ? window.parent : window;
		this.setCookie('intendedLocation', target.location.href);
	},

	addShoppedWishListCookie: function(wlId, wlName){
		function getNewCookieValue(lists, wlId, wlName){
			for(var i = 0; i< lists.length; i++){ if(wlId == lists[i].id) return  lists;}
			lists.push({id:wlId, name:wlName});
			return lists;
		}
		this.setShoppedWLCookiesList(getNewCookieValue(this.getShoppedWLCookiesList(), wlId, wlName));

	},

	setShoppedWLCookiesList: function(wls){
		this.setCookie('shoppedForWishLists', JSON.stringify(wls), 60);
	},

	getShoppedWLCookiesList: function(){
		var c = this.getCookie('shoppedForWishLists');
		if(!c) return [];
		if(/^[\d,]+$/.test(c)){
			this.clearCookie('shoppedForWishLists'); //just forget the old style ones;
			return [];
		}
		return JSON.parse(c);
	},

	findWishList: function(wlName, wlFoundCallback, wlFailedCallback){
		$.getJSON(WLC.findWishListURL + "&wlName=" + escape(wlName) + "&viewer=" + escape(this.custId) + "&jsoncallback=?", function(wlResponse){
				if(wlResponse.isFound){
					wlFoundCallback(wlResponse);
				} else {
					WLC.showError(wlResponse.message);
					if(wlFailedCallback) wlFailedCallback();
				}
		});
	},


	isLoggedIn: function(){
		return (this.custId && parseInt(this.custId, 10) > 0); // must be setup in client header
	},

/*jsl:ignore*/
	printf: function(sentence, reps){
		var calls = 0;
		var parts = sentence.split("%x");
		var a ="";
		for(var i = 0; i< parts.length; i++) a+= parts[i] + ((calls < reps.length) ? reps[calls++] : "" );
		return a;
	},

	mapPrintf: function(sentence, map){
		var parts = xSplit(sentence, /(%x\.|\.x%)/);
		if(parts.length == 1) return sentence; //but why call?
		var v = "";
		for(var i = 0; i< parts.length; i++){
			if(parts[i] != "%x.") v += parts[i];
			else if (parts[i] == "%x."){
				var key = parts[++i];
				if(typeof map[key] === 'undefined') throw Error (key + " is undefined in sentence:\n" + sentence);
				v += map[key];
				if(parts[++i] != ".x%") throw Error("imbalanced x%..%x delimiters");
			}
		}
		return v;
	},

/*jsl:end*/

	monthAbbrevs: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],

	formatDate: function(date){
			 // returns dd-M-yy formatted date
			 if(!date) return "";
			 return date.getDate() + "-" + this.monthAbbrevs[date.getMonth()] + "-" + date.getFullYear();

	},

	formatInputDate: function(date){
		if(!date) return "";
		return lPad(date.getUTCMonth() + 1) +"/" + lPad(date.getUTCDate()) + "/" + date.getUTCFullYear();
	},


	//Error responses can be updated on a page by page or situation by situation basis WLC.showMessage = function(){//my DOM manipulations here }
	showMessage:function(msg, msgId, data){
		if(document.getElementById(msgId)) $("#" + msgId).show(100);
		else if(document.getElementById("qwl-messageElem")) {
					$("#qwl-messageElem > div:not(:first)").remove();
					$("#qwl-messageElem").append("<div style='white-space:pre;'>" + (data ? this.printf(msg, data) : msg) + "</div>").show();
		} else alert (data ? this.printf(msg, data) : msg);
	},

	showError: function(msg,msgId, data){
		if(document.getElementById(msgId)) $("#" + msgId).show(100);
		else if(document.getElementById("qwl-messageElem")) {
					$("#qwl-messageElem > div:not(:first)").remove();
					$("#qwl-messageElem").append("<div style='color:red;white-space:pre-wrap;'>" + (data ? this.printf(msg, data) : msg) + "</div>").show(100);
		} else alert(data ? this.printf(msg, data) : msg);
	},


	getQueryParamList: function(targetWin){
		if(!targetWin) targetWin = window;
		if(!targetWin.queryParams){

			function addParam(h, nvPair){
				if(nvPair.length !== 2) return;
				var storedValue = h[nvPair[0]];
				if(!storedValue) h[nvPair[0]] = unescape(nvPair[1]);
				else if(storedValue.constructor == Array) storedValue.push(unescape(nvPair[1]));
				else h[nvPair[0]] = [storedValue, unescape(nvPair[1])];
			}

			targetWin.queryParams = {};
			if (targetWin.location.search){
				var qp = {};
				var pairs = targetWin.location.search.substring(1).split("&");
				for(var i = 0; i< pairs.length; i++){
					addParam(qp, pairs[i].split("="));
				}
				targetWin.queryParams = qp;
			}
		}
		return targetWin.queryParams;

	},



	getQueryParam: function(name, targetWin){
		var pList = this.getQueryParamList(targetWin);
		var pValue = pList[name];
		if(!pValue) return "";
		if(pValue.constructor == Array) return pValue[0];
		return pValue;
	},

	getQueryParamValues: function(name, targetWin){
				var pList = this.getQueryParamList(targetWin);
				var pValue = pList[name];
				if(!pValue) return [];
				if(pValue.constructor == Array) return pValue;
				return [pValue];
	},

	getCookie: function (name){
		var targetPatt = new RegExp(name + '=([^;]+);?', "i");
		var val = targetPatt.exec(document.cookie);
		if(val && val.length == 2){
			return unescape(val[1]);
		}
		return "";
	},

	setCookie: function (name, value, days, expires){
		var expDate = (expires ? expires.toGMTString()  : ( days ? new Date(new Date().getTime() + days * 86400000).toGMTString() : null ));
		if(expDate){
			document.cookie = name + '=' + escape(value) + '; path=/;expires=' + expDate + ";";
		} else 	document.cookie = name + '=' + escape(value) + '; path=/';
	},

	clearCookie: function (name){
		document.cookie = name + '=; path=/;expires=Thu, 01-Jan-1970 00:00:01 GMT';
	},

	setElemText: function(elem, value){ // only works for structures with a single nested text node

		if(!elem || !elem.normalize) return; //null or not a node

		elem.normalize(); // delete ignorable white space nodes
		var target = getTextNode(elem);
		if(target) {
			target.parentNode.replaceChild(document.createTextNode(value), target);
			return;
		}

		if(elem.getAttribute('value')) {
			elem.setAttribute('value', value);
		}


		function getTextNode(n){
			if(n.nodeType != 1) return null;
			var c = n.firstChild;
			while(c)	{
				if(c.nodeType == 3) return c;
				if(c.nodeType == 1){
					var x = getTextNode(c);
					if(x) return x;
				}
				c = c.nextSibling;
			}
			return null;
		}

	},

	addtoCart: function (compositeId, wlName){
			var itemId = compositeId.split("_")[0];
			var submitForm = document.getElementById('postItemForm');
			$(":hidden.addedOpts").remove();
			$(":hidden.optFor" + compositeId).clone().addClass("addedOpts").appendTo(submitForm);
			var elems = submitForm.elements;
			elems['buyid'].value = itemId;
			elems['qty'].value = $("#qty" + compositeId).val();
			elems['custcolqwl_assocwishlist_id'].value = wlName;

			// add a hash to the response for positive item response
			var redir = elems['redirect'].value;
			redir = redir.indexOf("#") == -1 ? redir : redir.substring(0, redir.indexOf("#"));
			elems['redirect'].value = redir + "#" + compositeId;

			var formFrag = $(submitForm).serialize();
			var custColFrags = null;

			// if has an amount then set that
			var itemPrice = $("#cartprice_" + compositeId).text();
			if(itemPrice && itemPrice.indexOf("$") === 0) itemPrice = itemPrice.substring(1);
			if(itemPrice){
				formFrag += '&amount='+ encodeURIComponent(itemPrice);
				$("#custcol_gft_wrp_web_q_"+compositeId+":checked").each(function(){
					var priceDetail = "$"+ $("#onlineprice_"+compositeId).val() +" / "+ $("#wrapcharge_"+compositeId).val();
					formFrag += '&custcol_gw_price_detail='+ encodeURIComponent(priceDetail);
				});
			}

			// e.g. <input type="checkbox" type="text" id="custcolgifwrap_q_1" value="T"/>  the _q_ helps avoid name conflicts with default option names

			$("input:text,input:checked").filter(function(){
						if((/\binternalTitle\b/).test(this.className) && this.getAttribute("title") == this.value) return false;
						return RegExp('custcol.*_q_' + compositeId).test(this.getAttribute('id'));
					}).
					each(function(){ formFrag += '&'+ this.id.replace(/(custcol.*)_q_.*/,"$1") +'='+ encodeURIComponent(this.value);});

			$("select").filter(function(){return RegExp('custcol.*_q_' + compositeId).test(this.getAttribute('id'));}).
				each(function(){ var optSel = this; $(optSel).find("option:selected").
					each(function(){ formFrag += '&'+ optSel.id.replace(/(custcol.*)_q_.*/,"$1") +'='+ encodeURIComponent(this.value);});});

			$.post(submitForm.action, formFrag, function(data, textStatus, jXR){
				WLC.finishedPendingOrder(compositeId, data, submitForm);
			});
	},

	finishedPendingOrder: function(compositeId, data, target){
					var addBtn = document.getElementById("addToCartBtn_" + compositeId);
		if(/^itemAdded\b/.test(data)){
					WLC.setElemText(addBtn, 'Item Added');
					$(addBtn).children().css("color", "black");
					$('#qwl-cartContents').load('/site/wishList/cartContents.html #qwl-replaceCartContents');
		}else{
			var msg = $(data).find("td").not(":has(td)").map(function(){ return $(this).text();}).get().join("\n");
			tty(msg);
			WLC.setElemText(addBtn, 'Add Failed');
			$(addBtn).children().css("color", "black");
			WLC.showError(msg || "Unable to add item to your shopping cart");
			tty(data);
			}
	},

	parseDate : function(dateSpec){ //parses JSON dates
		if(Date == dateSpec.constructor) return dateSpec;
		if(typeof dateSpec == 'object' && dateSpec.getTime) return dateSpec;

		var jsonDatePatt = /(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(\.\d{3})?Z/;
		var parts = jsonDatePatt.exec(dateSpec);
		if(parts && parts.length >6){
			function p(val){ return parseInt(val, 10);}
			return new Date(Date.UTC(p(parts[1]), p(parts[2])-1, p(parts[3]), p(parts[4]), p(parts[5]), p(parts[6])));
		}
		return dateSpec;
	}




};
}();



