/*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.
*/


/*
JSONstring v 1.01
copyright 2006 Thomas Frank
(small sanitizer added to the toObject-method, May 2008)

This EULA grants you the following rights:
Installation and Use. You may install and use an unlimited number of copies of the SOFTWARE PRODUCT.
Reproduction and Distribution. You may reproduce and distribute an unlimited number of copies of the SOFTWARE PRODUCT
either in whole or in part; each copy should include all copyright and trademark notices, and shall be accompanied by a copy of this EULA.
Copies of the SOFTWARE PRODUCT may be distributed as a standalone product or included with your own product.
Commercial Use. You may sell for profit and freely distribute scripts and/or compiled scripts that were created with the SOFTWARE PRODUCT.

Based on Steve Yen's implementation:
http://trimpath.com/project/wiki/JsonLibrary

Sanitizer regExp:
Andrea Giammarchi 2007

*/

JSONstring={
	compactOutput:true,
	includeProtos:false,
	includeFunctions: false,
	detectCirculars:false,
	restoreCirculars:true,
	make:function(arg,restore) {
		this.restore=restore;
		this.mem=[];this.pathMem=[];
		return this.toJsonStringArray(arg).join('');
	},
	escapeString: function(arg){
		var a=['\n','\\n','\r','\\r','"','\\"','\t', '\\t', '\f', '\\f', '\v', '\\v'];
		arg+=""; for(var i=0;i<a.length;i+=2){if(arg.indexOf(a[i]) == -1) continue; arg=arg.split(a[i]).join(a[i+1]);}
		return arg;
	},
	toObject:function(x){
		if(!this.cleaner){
			try{this.cleaner=new RegExp('^("(\\\\.|[^"\\\\\\n\\r])*?"|[,:{}\\[\\]0-9.\\-+Eaeflnr-u \\n\\r\\t])+?$');}
			catch(a){this.cleaner=/^(true|false|null|\[.*\]|\{.*\}|".*"|\d+|\d+\.\d+)$/;}
		}
		if(!this.cleaner.test(x)){return {};}
		eval("this.myObj="+x);
		if(!this.restoreCirculars || !alert){return this.myObj;}
		if(this.includeFunctions){
			var y=this.myObj;
			for(var i in y){if(typeof y[i]=="string" && !y[i].indexOf("JSONincludedFunc:")){
				y[i]=y[i].substring(17);
				eval("y[i]="+y[i]);
			}}
		}
		this.restoreCode=[];
		this.make(this.myObj,true);
		var r=this.restoreCode.join(";")+";";
		eval('r=r.replace(/\\W([0-9]{1,})(\\W)/g,"[$1]$2").replace(/\\.\\;/g,";")');
		eval(r);
		return this.myObj;
	},
	toJsonStringArray:function(arg, out) {
		if(!out){this.path=[];}
		out = out || [];
		var u; // undefined
		switch (typeof arg) {
		case 'object':
			if(arg && arg.constructor == Date){
				out.push("new Date('" + arg.toString() + "')");
				return out;
			}
			this.lastObj=arg;
			if(this.detectCirculars){
				var m=this.mem; var n=this.pathMem;
				for(var i=0;i<m.length;i++){
					if(arg===m[i]){
						out.push('"JSONcircRef:'+n[i]+'"');return out;
					}
				}
				m.push(arg); n.push(this.path.join("."));
			}
			if (arg) {
				if (arg.constructor == Array) {
					out.push('[');
					for (var i = 0; i < arg.length; ++i) {
						this.path.push(i);
						if (i > 0)
							out.push(',\n');
						this.toJsonStringArray(arg[i], out);
						this.path.pop();
					}
					out.push(']');
					return out;
				} else if (typeof arg.toString != 'undefined') {
					out.push('{');
					var first = true;
					for (var i in arg) {
						if(!this.includeProtos && arg[i]===arg.constructor.prototype[i]){continue;}
						this.path.push(i);
						var curr = out.length;
						if (!first)
							out.push(this.compactOutput?',':',\n');
						this.toJsonStringArray(i, out);
						out.push(':');
						this.toJsonStringArray(arg[i], out);
						if (out[out.length - 1] == u)
							out.splice(curr, out.length - curr);
						else
							first = false;
						this.path.pop();
					}
					out.push('}');
					return out;
				}
				return out;
			}
			out.push('null');
			return out;
		case 'unknown':
		case 'undefined':
		case 'function':
			if(!this.includeFunctions){out.push(u);return out;}
			arg="JSONincludedFunc:"+arg;
			out.push('"');
			out.push(this.escapeString(arg));
			out.push('"');
			return out;
		case 'string':
			if(this.restore && arg.indexOf("JSONcircRef:")==0){
				this.restoreCode.push('this.myObj.'+this.path.join(".")+"="+arg.split("JSONcircRef:").join("this.myObj."));
			}
			out.push('"');

			out.push(this.escapeString(arg));
			out.push('"');
			return out;
		default:
			out.push(String(arg));
			return out;
		}
	}
};

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){
		this.setShoppedWLCookiesList(getNewCookieValue(this.getShoppedWLCookiesList(), wlId));


		function getNewCookieValue(lists, wlId){
			for(var i = 0; i< lists.length; i++){ if(wlId == lists[i]) return  lists;}
			lists.push(wlId);
			return lists;
		}
	},

	setShoppedWLCookiesList: function(wls){
		this.setCookie('shoppedForWishLists', wls.join(","), 60);
	},

	getShoppedWLCookiesList: function(){
		var c = this.getCookie('shoppedForWishLists');
		if(!c) return [];
		return c.split(",");
	},

	findWishList: function(wlName, wlFoundCallback, wlFailedCallback){
		$.getJSON(WLC.findWishListURL + "&wlName=" + escape(wlName) + "&viewer=" + escape(this.custId) + "&jsoncallback=?", function(wlResponse){
				if(wlResponse.isFound){
					wlFoundCallback();
				} 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(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){
			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;

		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])];
		}
	},



	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

		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){
			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'].value = wlInternalId;

			// if has an amount then set that
			var itemPrice = $("#cartprice_" + compositeId).text();
			if(itemPrice && itemPrice.indexOf("$") === 0) itemPrice = itemPrice.substring(1);
			if(itemPrice){
				$("<input type='hidden' value='"+ itemPrice +"' name='amount' id='amount' class='addedOpts'>").appendTo(submitForm);
				$("#custcol_gft_wrp_web_q_"+compositeId+":checked").each(function(){
					var priceDetail = "$"+ $("#onlineprice_"+compositeId).val() +" / "+ $("#wrapcharge_"+compositeId).val();
					$("<input type='hidden' value='"+ priceDetail +"' name='custcol_gw_price_detail' id='custcol_gw_price_detail' class='addedOpts'>").appendTo(submitForm);
				});
			}

			// 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(){ $(WLC.printf("<input type='hidden' value='%x' name='%x' class='addedOpts'>", [this.value, this.id.replace(/(custcol.*)_q_.*/,"$1")])).appendTo(submitForm);});

			$("select").filter(function(){return RegExp('custcol.*_q_' + compositeId).test(this.getAttribute('id'));}).
				each(function(){ var optSel = this; $(optSel).find("option:selected").
					each(function(){ $(WLC.printf("<input type='hidden' value='%x' name='%x' class='addedOpts'>", [this.value, optSel.id.replace(/(custcol.*)_q_.*/,"$1")])).appendTo(submitForm);});});

			// 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 t = "";
			//for(var n in elems) t += n + ": " + elems[n].value + "\n";
			//alert(t);

			$(submitForm).submit(); // just in case we add some events to the form
	},

	finishedPendingOrder: function(target){

			var responseDoc = getResponseDoc(target);
			if(responseDoc.itemAdded){
				if(responseDoc.location.hash){
					var compositeId = responseDoc.location.hash.substring(1);
					compositeId = compositeId.indexOf("?") == -1 ? compositeId : compositeId.substring(0, compositeId.indexOf("?"));
					var addBtn = document.getElementById("addToCartBtn_" + compositeId);
					WLC.setElemText(addBtn, 'Item Added');
					$(addBtn).children().css("color", "black");
				}
				$("#cartResult").attr("src", "/site/wishList/emptyFrame.html");

				$.ajax({
				  url: '/site/wishList/cartContents.html',
				  cache: false,
				  success: function(html){
				    $('#qwl-cartContents', parent.document).empty().append(html.replace(/<script(.|\s)*?\/script>/ig, ""));
				  }
				});
			}


			//otherwise check the frame for an error message
			function getResponseDoc(target){
				var innerDoc = (target.contentDocument) ? target.contentDocument : target.contentWindow.document;
				if(innerDoc) return innerDoc;
				if(target.Document) return target.Document;
				return $(target).contents();

			}
	}


};
}();


