/*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.

This file may be modified for purpose of site customization. Modifications may
not be displayed or distributed without the express prior written permission
of the copyright holder. For permission, contact brett@knightsofthenet.com

Some portions of this work fall under other copyright terms and are so marked.
*/

// check if user used custom login link then send them back to the referring page.
var intendedLocation = WLC.getCookie('intendedLocation');
if(intendedLocation){
	WLC.clearCookie('intendedLocation');
	document.location = unescape(intendedLocation);
}

var addingWishList = WLC.getCookie('addingForWishList');
var shoppingForWishList = WLC.getCookie('shoppingForWishList');
var itemsAdded = [];

$('document').ready(function(){

	checkMatrixOptions();

	if(WLC.isLoggedIn()){
		$("div.qwl-loggedIn,span.qwl-loggedIn").show(100);
	}else{
		$("div.qwl-notLoggedIn,span.qwl-notLoggedIn").show(100);
	}

	if(inWisherMode()){
				$("#qwl-wisherPane").show();
				$("#qwl-shopperPane").hide();
				loadCustomerWishLists(function(){
				$('#qwl-wishListList').change(function(){
					if(this.selectedIndex > 0){
						WLC.setCookie( "addingForWishList", (addingWishList = this.options[this.selectedIndex].value));
						itemsAdded = [];
						$("button.wlItemAdded").each(function(){WLC.setElemText(this, "Add to Wish List");}).contents().andSelf().removeClass('wlItemAdded');
					}
				});
			});

	}else {

		var shopWL = /\bshopWL=([^&]+)/.exec(location.search || '?'); // query param overrides older cookie method
		if(shopWL){
			$("input[name='custcolqwl_assocwishlist_id'],input[name='custcolqwl_assocwishlist']").val(shopWL[1]);
		}else if(shoppingForWishList){
			$("input[name='custcolqwl_assocwishlist_id'],input[name='custcolqwl_assocwishlist']").val(shoppingForWishList);
		}

		if(document.getElementById('qwl-shopperWishListList')){
			loadShopperWishLists(function(){
				var shopperWishList = document.getElementById('qwl-shopperWishListList');
				if(shopperWishList.options.length > 1){
					$("#qwl-shopperActive").css("visibility", "visible");
					$(shopperWishList).change(function(){
							var opt;
							if(this.selectedIndex > 0){
								opt = this.options[this.selectedIndex];
								WLC.setCookie( "shoppingForWishList", (shoppingForWishList = WLC.shopperListNames[opt.value]));
								$("input[name='custcolqwl_assocwishlist_id']").val(shoppingForWishList);
							}
							if(this.selectedIndex != -1){
								opt = this.options[this.selectedIndex];
								if(/\bqwl-itemNotOnList\b/.test(opt.className))	$(this).addClass('qwl-itemNotOnList');
								else $(this).removeClass('qwl-itemNotOnList');
								this.setAttribute("title", opt.getAttribute("title"));
							}
					});
				}
			});
		}
	}

	$("div.messageCloser *").bind("click", WLC.hideParent);

	function inWisherMode(){
		return addingWishList &&
				WLC.isLoggedIn() &&
				document.getElementById('qwl-wishListList');
	}

});

function checkMatrixOptions(){
	var paramList = WLC.getQueryParamList();
	for(var pName in paramList){
		var elem = document.getElementById(pName);
		if(!elem || elem.type != "select-one")continue;
		var pValue = WLC.getQueryParam(pName);
		for(var i = 0; i< elem.length;i++){
			if(elem.options[i].value == pValue) {
				elem.selectedIndex = i;
				break;
			}
		}

	}
}

function goToWishList(){
	var listIdSel = document.getElementById('qwl-wishListList');
	if(!listIdSel) return;


	if(!WLC.wishListHomeURL){
		WLC.ShowError("Missing parameter for WLC.wishListHomeURL", 'qwl-missingWishListHome');
		return;
	}

	if(listIdSel.options.length === 1 || listIdSel.selectedIndex < 1) {
		document.location=WLC.wishListHomeURL;
		return;
	}

	document.location=WLC.wishListHomeURL + "?wlId=" + listIdSel.options[listIdSel.selectedIndex].value;
}

function shopWishList(){
		var listIdSel = document.getElementById('qwl-shopperWishListList');
		if(!listIdSel) return;

		if(listIdSel.options.length < 2 || listIdSel.selectedIndex < 1) {
			WLC.showError("please select a wish list from the drop down", "qwl-noShopperWishListSelected");
		}

		document.location = WLC.sharedListHome + "#shopWL=" + WLC.shopperListNames[listIdSel.options[listIdSel.selectedIndex].value];
}


function openAboutWishLists(){
	$("#qwl-aboutWishLists").show(300);
}

function closeAboutWishLists(){
	$("#qwl-aboutWishLists").hide();
}


function findWishList(){
	var wlName = document.getElementById('qwl-wlName');
	if(wlName){
		WLC.findWishList(wlName.value, function(){ document.location = WLC.sharedListHomeURL + "#shopWL=" +escape(wlName.value);});
	}
}


function loadCustomerWishLists(afterLoad, listHandler){
		// get existing wish lists
	$.getJSON(WLC.getCustomersWishListsURL + "&noExp=T&jsoncallback=?", function(wlResponse){
			if(listHandler) listHandler(wlResponse);
			else{
				var list = document.getElementById('qwl-wishListList');
				list.options.length = 0;
				if(wlResponse.isSuccess){
					list.options[list.options.length] = new Option("select wish list");
					$.each(wlResponse.wishLists, function(idx, wishList){
						var opt = new Option(wishList.label, wishList.internalId);
						if( wishList.internalId == addingWishList) opt.selected = true;
						list.options[list.options.length] = opt;
					});
				}
			}
			if(afterLoad) afterLoad();
		});
	}

	function loadShopperWishLists(afterLoad){
		var listSpecs = WLC.getShoppedWLCookiesList();
		var buyElem = document.getElementById("buyid");
		var buyQuery = (!buyElem) ? "" : "&itemId=" + escape(buyElem.value);
		WLC.shopperListNames = {}; // object not array; ensure sparse
		$.getJSON(
			WLC.getShopperWishListsURL +"&"+
			$.param({viewer:WLC.custId, wlId:$.map(listSpecs, function(wl){return wl.id;})}) +
			((!buyElem) ? "" : "&itemId=" + escape(buyElem.value)) + "&jsoncallback=?",
				function(wlResponse){
				var list = document.getElementById('qwl-shopperWishListList');
				list.options.length = 0;
				if(wlResponse.isSuccess){
					list.options[list.options.length] = new Option("select wish list");
					list.options[0].className="qwl-shopWishListOption";
					$.each(wlResponse.wishLists, function(idx, wishList){
						WLC.shopperListNames[wishList.internalId] = wishList.listName;
						var opt = new Option(wishList.label, wishList.internalId);
						opt.className="qwl-shopWishListOption";
							if( wishList.listName == shoppingForWishList || wishList.internalId == shoppingForWishList){
								if(/^[0-9]$/.test(shoppingForWishList)){ // fix legacy where id was used
									shoppingForWishList = wishList.listName;
									WLC.setCookie( "shoppingForWishList", shoppingForWishList);
								}
								opt.selected = true;
							}
						if(buyElem && !wishList.hasPageItem){
							$(opt).addClass('qwl-itemNotOnList').attr("title", "item not on this list");
							if(opt.selected) $(list).addClass(opt.className).attr('title', opt.title);
						}
						list.options[list.options.length] = opt;
					});

				}
			if(afterLoad) afterLoad();
		});
	}

WLC.hideParent = function(event){ // button in a div in a div
	event.stopPropagation();
	$(event.target.parentNode.parentNode).hide();
};



function addToWishList(buyId, addingWishList){
	// if ! logged in then log them in

	// cookie the current location in lastWishListItem
	if(!WLC.isLoggedIn()){
		WLC.showMessage("You must be logged in and select a wish list to use this button. Please log in and select a wish list to proceed", "qwl-mustLogIn");
		return;
	}
	if(!addingWishList){ //override default behaviour
		if(!hasAnyList()){
			WLC.showMessage("You must first create a wish list to use this button. Please go to the wish list page and created a wish list to proceed", "qwl-mustHaveList");
			return;
		}

		if(!hasSelectedList()){
			WLC.showMessage("You must select a wish list to use this button. Please select a wish list to proceed", "qwl-mustSelectList");
			return;
		}

		var wishListSel = document.getElementById('qwl-wishListList');
		addingWishList = wishListSel.options[wishListSel.selectedIndex].value;
	}


	if(itemsAdded[buyId]){
		if(itemsAdded[buyId] == "pending") return; // debounce double click/mouse stutter
//		if(itemsAdded[buyId] == "added") {
//			WLC.showMessage("You have already added this item. \nThe wish list only allows one of each item.", 'qwl-onlyOneOfEach');
//			return;
//		}
	}
	var theForm = $("#form" + buyId).get(0);

	var qty = parseInt(theForm.elements['qty'].value, 10);
	if(isNaN(qty) || qty === 0) {
			WLC.showMessage("Please set a quantity for this item", 'qwl-quantityMissing');
			return;
	}

	bindSelects(theForm);
	if(!checkSelects(theForm)){
			WLC.showMessage("You must set the drop down options before adding the item", 'qwl-dropdownsMissing');
			return;
	}

		itemsAdded[buyId] = "pending";
		WLC.setElemText(document.getElementById('qwl-addToWishList_' + buyId), "adding...");

	var params = {wlId: addingWishList, buyId: buyId, qty: theForm.elements['qty'].value, custcols: getCustCols(theForm) };

	$.getJSON(WLC.addItemSuiteletURL  +'&'+ $.param(params) +'&jsoncallback=?', function(addResponse){
			if(!addResponse.isSuccess){
				itemsAdded[buyId] = "errored";
				WLC.showError(addResponse.error, 'qwl-addToWishListFailed');
				return;
			}
			itemsAdded[buyId] = "added";
			WLC.showMessage("Item Added To Wish List");

		});

	function bindSelects(theForm){
		var elems = theForm.elements;
		for(var i = 0; i< elems.length; i++){
			var elem = elems[i];
			if(elem.type != 'select-one') continue;
			if(!elem.name || elem.name.indexOf('custcol') !== 0) continue;
			$(elem).unbind('change.itemsAdded').bind('change.itemsAdded', function(){
				itemsAdded = [];
				$("button.wlItemAdded").each(function(){WLC.setElemText(this, "Add to Wish List");}).contents().andSelf().removeClass('wlItemAdded');
			});
		}
	}


	function checkSelects(theForm){
		var elems = theForm.elements;
		for(var i = 0; i< elems.length; i++){
			var elem = elems[i];
			if(elem.type != 'select-one') continue;
			if(!elem.name || elem.name == 'custcolqwl_assocwishlist_id' || elem.name.indexOf('custcol') !== 0) continue;
			if(elem.options.length < 2) continue;
			if(elem.selectedIndex <= 0 ) return false;  // assumes first element is name or "-select-"
		}
		return true;
	}

	function getCustCols(theForm){
		var cols =[];
		$.each(theForm.elements, function(){
			if(this.type != 'select-one') return;
			if(!this.name || this.name.indexOf('custcol') !== 0) return;
			cols.push(WLC.printf("{selLabel: '%x', selId:'%x', optValue:'%x', optId:'%x'}", [
				this.options[0].text,
				this.name,
				this.options[this.selectedIndex].text,
				this.options[this.selectedIndex].value]));
		});
		if(cols.length === 0) return "";
		return "[" + cols.join(",\n") + "]";

	}

	function hasAnyList(){
		var list = document.getElementById('qwl-wishListList');
		return (list && list.options && list.options.length > 0);
	}

	function hasSelectedList(){
		var list = document.getElementById('qwl-wishListList');
		return (list && list.options && list.selectedIndex > 0);
	}
}





function resizeIFrame(target){
	var getFFVersion=navigator.userAgent.substring(navigator.userAgent.indexOf("Firefox")).split("/")[1];
	var FFextraHeight=parseFloat(getFFVersion)>=0.1? 32 : 0; //extra height in px to add to iframe in FireFox 1.0+ browsers

	function getMinHeight(ht){
		if(!jQuery.browser.safari) return ht;
		var minHeight = parseInt(target.style.height,10);
		if(!isFinite(minHeight) || !(minHeight > 0)) return ht;

		return ht < (minHeight + 0) ? minHeight : ht;
	}

	if (target && !jQuery.browser.opera){
			target.style.display="block";

			var innerDoc = (target.contentDocument) ? target.contentDocument : target.contentWindow.document;
			if (innerDoc.body.offsetHeight){ //ns6 syntax
				target.height = getMinHeight(innerDoc.body.offsetHeight + FFextraHeight);
			}else if (target.Document && target.Document.body.scrollHeight){ //ie5+ syntax
				target.height = getMinHeight(target.Document.body.scrollHeight);
			}else {
				try{
					var ht = parseInt(innerDoc.defaultView.getComputedStyle(innerDoc.body,"").getPropertyValue("height"), 10);
					if(isFinite(ht)) target.height = getMinHeight(ht);
				}catch(e){}
			}

			//safari bug
			if(jQuery.browser.safari){
				target.style.overflow = "scroll";
			}
	}
}



