var LightBoxStockChecker = {};
$(document).ready(function(){
	
	/*************************************************************
	* do not run when on comparison page
	*************************************************************/
	var isComparisonPage = $("body").hasClass("productcompare");
	//if(isComparisonPage) return;
	
	
	var IE6 = ($.browser.msie && parseInt($.browser.version) == 6);
	var IE7 = ($.browser.msie && parseInt($.browser.version) == 7);
	var FF = ($.browser.mozilla); //needs work to not do it for FF3 etc
	var FF3 = ($.browser.mozilla && parseFloat($.browser.version).toFixed(1) >= 1.9);

	var dialogue = $("#lightBox")[0];
	var	overlay = $("#overlay")[0];	
	
	/*************************************************************
	* do not run when in gift mode section
	*************************************************************/	

	if(typeof inGiftMode !== "undefined" && inGiftMode === true) return;
	
	var postCodeFieldDefaultMessage = "Your postcode"
	
	LightBoxStockChecker = new (function(){  
		
		/*
		 * Product details init
		 */
		(function(){
			
		 	var deliveryDetails = $("#deliveryInformation ul")[0];
		 	if(deliveryDetails === undefined) return;		
			if(typeof isaltmServiceEnabled !== "boolean") return;
			if(typeof buyOrReservable !== "boolean") return;
			if(typeof outOfStockEmailable !== "boolean") return;
			
			
			
			var showPostCode;
			if(isaltmServiceEnabled && buyOrReservable) {
				showPostCode = true;
			}
			else if(outOfStockEmailable) {
				showPostCode = false;
			}
			else {
				// in the case that !buyOrReservable && !outOfStockEmailable
				return;
			}
		 	
		 	$(deliveryDetails).find("li.priceStockChecker").remove();
		 	var html = (function(){
		 				 		
		 		if(showPostCode) {
			 		var postCodeValue = getPostCodeFromCookie();			 		
			 		
			 		var postCodeFieldValue = postCodeValue;		
			 		var postCodeFieldClass = "";
			 		if(typeof postCodeValue == "undefined" || postCodeFieldValue == "undefined" || postCodeFieldValue ==""){
			 			postCodeFieldValue=postCodeFieldDefaultMessage;
			 			postCodeFieldClass = ' class="inputBkgrndText" ';
			 		}			 		
			 		var s ='';
			 		s += 	'<li class="stockChecker">';
			 		s +=		'<h2>Check stock in your area</h2>';
			 		s +=		'<input type="hidden" name="checkStock" value="true">';
			 		s +=		'<input type="hidden" name="backTo" value="product">';	 
			 		s +=		'<input type="text" id="postCode" '+postCodeFieldClass+' name="postCode" value="'+postCodeFieldValue+'"/>';
					s +=		'<input type="image" id="checkStockGo" src="/wcsstore/argos/en_US/images/p1/btn_go.gif" alt="Go" />';	     		
			 		s +=	'</li>';
			 	}
			 	// outOfStockEmailable
			 	else {
			 		var s ='';
			 		s += 	'<li class="emailMeBack">';
     				s +=		'<a class="emailMeBackInStock" href="#">Email me when<br/>back in stock</a>';
			 		s +=	'</li>';			 		
			 	}
		 		return s;
		 	}()); 	     	
		 	$(deliveryDetails).addClass("hasStockChecker");
		 	$(deliveryDetails).append(html);
		 	if(showPostCode) {
			 	$("input#checkStockGo").bind("click", checkStock_onClick);
			 	$("input#checkStockGo").bind("click", LightBoxStockCheckerTracking.trackAddToBasketPopup);
				$("input#postCode").keydown(function(event){
					if(event.keyCode === 13) {
						checkStock_onClick();
						
						return false;
					}
				});
				$("input#postCode").focus(function() {
					if( this.value == postCodeFieldDefaultMessage ) {
						this.value = "";
						$(this).removeClass("inputBkgrndText");
					}
				}).blur(function() {
					if( !jQuery.trim(this.value).length ) {
						this.value = postCodeFieldDefaultMessage;
						$(this).addClass("inputBkgrndText");
					}
				});				
			}
			else {
				$("li.emailMeBack a.emailMeBackInStock").bind("click", emailMeWhenBackInStock_onClick);
				$("li.emailMeBack a.emailMeBackInStock").bind("click", LightBoxStockCheckerTracking.trackAddToBasketPopup);
			}
			
			
					 	
		}());
	     
		/*
		 * Product search results
		 */
		(function(){
			if(typeof isaltmServiceEnabled !== "boolean") return;
			
			var actions = $("div#switchview li.product li.ordering li.action");
			var action;
			var URL;
			var identifier;
			for(var i = actions.length-1; i>=0;i--) {
				action = actions[i];
				var isOutOfStockEmailable = $(action).hasClass("outOfStockEmailable");
				var isBuyOrReservable = $(action).hasClass("buyOrReservable");
				$(action).find("p.priceStockChecker").remove();
				if(!isOutOfStockEmailable && !isBuyOrReservable) {
					continue;
				}
				
				// get href from product title link
				//href = $(action).parents("li.ordering").parents("ul").find("li.producttitle h4 a").attr("href");
				identifier = $(action).attr("id").split("action_")[1];
				URL = $("#href_"+identifier).attr("href");
				if(isBuyOrReservable && isaltmServiceEnabled) {
					$(action).prepend(
						(function getHTML(){
							var h = '';
							h +=	'<div class="stockChecker">';
							h +=		'<a class="checkStockActivator" href="/webapp/wcs/stores/servlet/ISALTMStockAvailability?';
							h += (function(){
								var h = '';
								h += "partNumber=" +getPartNumber( URL) || "";
								h += "&storeId=" + getStoreId() || "";
								h += "&langId=" +getLangId() || "";
								h += "&backTo=product+list" || "";
								return h;
							}());
							h +=		'">Check stock in your area</a>';
							h +=	'</div>';
							return h;
						}())
					);
					$("div#switchview div.stockChecker a.checkStockActivator").bind("click", checkStockActivator_onClick);
					$("div#switchview div.stockChecker a.checkStockActivator").bind("click", LightBoxStockCheckerTracking.trackAddToBasketPopup);
				}

				if(isOutOfStockEmailable) {
					$(action).html(
						(function getHTML(){
							var h = '';
							h +=	'<div class="emailMe">';
							h +=		'<a class="emailMe" href="/webapp/wcs/stores/servlet/ISALTMOutOfStockEmail?';
							h += (function(){
								var h = '';
								h += "partNumber=" + getPartNumber( URL) || "";
								h += "&storeId=" + getStoreId() || "";
								h += "&langId=" + getLangId() || "";
								h += "&viewTaskName=ISALTMAjaxResponseView";
								return h;
							}());
							h +=		'">Email me when<br/> back in stock</a>';
							h +=	'</div>';
							return h;
						}())
					)
					$("div#switchview div.emailMe a.emailMe").bind("click", listerEmailMe_onClick);
					$("div#switchview div.emailMe a.emailMe").bind("click", LightBoxStockCheckerTracking.trackAddToBasketPopup);
				}
			}
		}());	     
	    
		/*
		 * Product comparison
		 */

		(function(){
			
			if(typeof isaltmServiceEnabled !== "boolean") return;
			var cells = $("div#productcomparisonwrap table.compare td.buybutt");
			var cell;
			var URL;
			var identifier;
			for(var i = cells.length-1; i>=0;i--) {
				cell = cells[i];
				var isOutOfStockEmailable = $(cell).hasClass("outOfStockEmailable");
				var isBuyOrReservable = $(cell).hasClass("buyOrReservable");
				if(!isOutOfStockEmailable && !isBuyOrReservable) {
					continue;
				}

				identifier = $(cell).attr("id").split("product_")[1];
				URL = $("#href_"+identifier).attr("href");
				if(isBuyOrReservable && isaltmServiceEnabled) {
					$(cell).prepend(
						(function getHTML(){
							var h = '';
							h +=	'<div class="stockChecker">';
							h +=		'<a class="checkStockActivator" href="/webapp/wcs/stores/servlet/ISALTMStockAvailability?';
							h += (function(){
								var h = '';
								h += "partNumber=" + getPartNumber(URL) || "";
								h += "&storeId=" + getStoreId() || "";
								h += "&langId=" + getLangId() || "";
								h += "&backTo=product+list" || "";
								return h;
							}());
							h +=		'">Check stock in your area</a>';
							h +=	'</div>';
							return h;
						}())
					);
					$("div#productcomparisonwrap div.stockChecker a.checkStockActivator").bind("click", checkStockActivator_onClick);
				}

				if(isOutOfStockEmailable) {
					$(cell).prepend(
						(function getHTML(){
							var h = '';
							h +=	'<div class="emailMe">';
							h +=		'<a class="emailMe" href="/webapp/wcs/stores/servlet/ISALTMOutOfStockEmail?';
							h += (function(){
								var h = '';
								h += "partNumber=" + getPartNumber(URL) || "";
								h += "&storeId=" + getStoreId() || "";
								h += "&langId=" + getLangId() || "";
								h += "&viewTaskName=ISALTMAjaxResponseView";
								return h;
							}());
							h +=		'">Email me when back in stock</a>';
							h +=	'</div>';
							return h;
						}())
					)
					$("div#productcomparisonwrap div.emailMe a.emailMe").bind("click", listerEmailMe_onClick);
				}
			}
		}());

	    
	    function getPostCodeFromCookie() {
		    var postCode = Argos.Page.getCookie("PostCodeSessionCookie");
	    	//postCode = unescape( postCode );
	    	if( postCode == null )
	    		postCode = "";
	    	else if(typeof postCode === "undefined")
				postCode = "";
	    	return postCode;
	    }
	    
	    
	    function getPartNumber(productUrl){
 
			if(productUrl.indexOf("/static/")>-1){
				var partNumIndex = productUrl.indexOf("/partNumber/");
				if(partNumIndex>-1){ 
					var partNumOffset = (partNumIndex+"/partNumber/".length);
					// /partNumber/2553500/Trail...
					var partNumValueEndIdx = productUrl.indexOf("/", partNumOffset );
					if( partNumValueEndIdx == -1 )
						// /partNumber/2553500.htm
						partNumValueEndIdx = productUrl.indexOf(".", partNumOffset );
					// Defensive check!
					if( partNumValueEndIdx == -1 )
						partNumValueEndIdx = partNumOffset;
					var partNum = productUrl.substring(partNumOffset, partNumValueEndIdx );
					return partNum;
				}else{
					return "";
				}
			}else{
				return getQueryString("partNumber", productUrl);
			}
	    }
	    
	    function getStoreId(){
	    	return $("input[name=storeId]").val();
	    }
	    
	    function getLangId(){
	    	return $("input[name=langId]").val();	    
	    }
	    
		function checkStockActivator_onClick() {
			var data = this.href.split("?")[1];
			data += "&viewTaskName=ISALTMAjaxResponseView";
			checkStock(data);
			return false;
		}
		
		function listerEmailMe_onClick() {
			LightBox.showOverlay();
			LightBox.setHTML(LightBox.loadingHTML);
			LightBox.showLightBox();
			//reposition if required - false = not resizing window
			compTablePositioning(false);
			
			var ajax = $.ajax({
				url: this.href,
				dataType: "json",
				type: "get",
				success: displayEmailMe,
				error: showRequestError
			});
			return false;
		}		
	    
		function checkStock_onClick() {
							
			var postCode = $("input#postCode").val();
			if( postCode == postCodeFieldDefaultMessage ) {
				$("input#postCode").val( "" );
			}

			var data = $("form#pdpForm").serialize();
			data += "&viewTaskName=ISALTMAjaxResponseView";
			checkStock(data);

			if( postCode == postCodeFieldDefaultMessage ) {
				$("input#postCode").val( postCode );
			}
			return false;
		}	    
	    
	    function stockAvailability_onSubmit() {
	    	var data = $("form#stockAvailabilityForm").serialize();
	    	data += "&viewTaskName=ISALTMAjaxResponseView";
	    	checkStock(data);
	    	return false;
	    }
	    
	    function checkOtherStores_onClick() {
	    	var data = this.href.split("?")[1];
	    	data += "&viewTaskName=ISALTMAjaxResponseView";
	    	checkStock(data);
	    	return false;	    
	    }
	    
	    function backToStockCheck_onClick() {
	    	var data = this.href.split("?")[1];
	    	data += "&viewTaskName=ISALTMAjaxResponseView";
	    	checkStock(data);
	    	return false;
	   	}
	    
	    this.checkStock = checkStock;
	    function checkStock(data) {
	    	if(typeof data === "undefined") data = "";
			LightBox.showOverlay();
			LightBox.setHTML(LightBox.loadingHTML);
			LightBox.showLightBox();
			//reposition if required - false = not resizing window
			compTablePositioning(false);
			var ajax = $.ajax({
				url: "/webapp/wcs/stores/servlet/ISALTMStockAvailability",
				dataType: "json",
				type: "post",
				success: displayStockCheckLightBox,
				data: data,
				error: showRequestError
			});
			
			
	    }
	    
	    function dontAdd_onClick() {
	    	var linkID = this.id.split("_")[1];
	    	var hiddenPartNumber = document.getElementById("partNumber_"+linkID);
	    	var hiddenCatEntryId = document.getElementById("ISALTMcatEntryId_"+linkID);
	    	var tableRow = $(this).parents("tr")[0];
	    	
	    	if(hiddenPartNumber !== null) {
	    		$(hiddenPartNumber).remove();
	    	}
	    	if(hiddenCatEntryId !== null) {
	    		$(hiddenCatEntryId).remove();
	    	}	    	
			if(typeof tableRow !== "undefined") {
				$(tableRow).fadeOut(400, function() {
					$(this).remove();
				});
			}
			
			var partNumber = hiddenPartNumber.value;
			removeCheckedProduct(partNumber);
			return false;
	    }
	    
	    function removeCheckedProduct(partNumber) {
			// super defensive due to interfacing with other script
			try {
				var products = argos.product.details.add.productList.products;
				// loop through each product
				for (var props in products) {
					var product = products[props];
					var productCode = product.code.replace(/\//g,"");
					if(productCode === partNumber) {
						argos.product.details.add.removeEvent(product.key);
						break;
					}
				}
			} 
			catch(e){
				alert("catch");
			}
	    }
	    
	    
	    function emailMe_onClick() {
	    	LightBox.hideLightBox();
			LightBox.setHTML(LightBox.loadingHTML);
			LightBox.showLightBox();
			//reposition if required - false = not resizing window
			compTablePositioning(false);
			var ajax = $.ajax({
				url: this.href+"&viewTaskName=ISALTMAjaxResponseView",
				dataType: "json",
				type: "get",
				success: displayEmailMe,
				error: showRequestError
			});			
	    	return false;
	    }
	    
	    function selectPreferredStore_onClick() {
	    	LightBox.showOverlay();
			LightBox.setHTML(LightBox.loadingHTML);
			LightBox.showLightBox();
			//reposition if required - false = not resizing window
			compTablePositioning(false);
			var ajax = $.ajax({
				url: this.href+"&viewTaskName=ISALTMAjaxResponseView",
				dataType: "json",
				type: "get",
				success: LightBoxStoresAZ.init,
				error: showRequestError
			});
	    	return false;
	    }
	    
	    function emailMeWhenBackInStock_onClick() {
	    	var data = $("#pdpForm").serialize();
	    	data += "&viewTaskName=ISALTMAjaxResponseView";
	    	LightBox.showOverlay();
			LightBox.setHTML(LightBox.loadingHTML);
			LightBox.showLightBox();
			//reposition if required - false = not resizing window
			compTablePositioning(false);
			var ajax = $.ajax({
				url: "/webapp/wcs/stores/servlet/ISALTMOutOfStockEmail",
				dataType: "json",
				type: "get",
				data: data,
				success: displayEmailMe,
				error: showRequestError
			});			
	    	return false;
	    }	    
	    
	    this.displayStockCheckLightBox = displayStockCheckLightBox;
		function displayStockCheckLightBox(json) {
		
			var dialogue = $("#lightBox")[0];
			var overlay = $("#overlay")[0]
			
			LightBox.hideLightBox();
			LightBox.setHTML(json.html);
			LightBox.showLightBox();
			//reposition if required - false = not resizing window
			compTablePositioning(false);
			compTableTopMarginAdjust();
			prepareCheckStockLightBox();		
			LightBoxStockCheckerTracking.track(json.page, json.state);
	    	LightBoxStockCheckerTracking.init();
			
		}	 
	    
	    function prepareCheckStockLightBox() {
	    	$("form#stockAvailabilityForm").bind("submit", stockAvailability_onSubmit);
	    	$("div#lightBoxStockAvailability a.checkOtherStores").bind("click", checkOtherStores_onClick);
	    	$("div#lightBoxStockAvailability a.backToStockCheck").bind("click", backToStockCheck_onClick);
	    	$("div#lightBoxStockAvailability a.dontAdd").bind("click", dontAdd_onClick);
	    	$("div#lightBoxStockAvailability a.emailOutOfStock").bind("click", emailMe_onClick);
	    	$("div#lightBoxStockAvailability p.storeAZ a").bind("click", selectPreferredStore_onClick);	    	
	    	$("input#postCodeLightBox").focus();
	    	new ArgosDisableCheckboxes($("form#stockAvailabilityForm input.checkbox"), 2);
	    }	    
	    
	    function displayEmailMe(json) {
			LightBox.hideLightBox();
			LightBox.setHTML(json.html);
			LightBox.showLightBox();
			//reposition if required - false = not resizing window
			compTablePositioning(false);
			compTableTopMarginAdjust();
			prepareEmailForm(json);    	
	    }
	       
	    function prepareEmailForm(json) {
	    	$("form#outOfStockEmailForm").bind("submit", outOfStockEmailForm_onSubmit);
	   	 	LightBoxStockCheckerTracking.track(json.page, json.state);
	   	 	LightBoxStockCheckerTracking.init();
	    }
	    
	    function outOfStockEmailForm_onSubmit() {
	    	var data = $(this).serialize();
	    	data += "&viewTaskName=ISALTMAjaxResponseView";
	    	LightBox.hideLightBox();
			LightBox.setHTML(LightBox.loadingHTML);
			LightBox.showLightBox();
			//reposition if required - false = not resizing window
			compTablePositioning(false);	    	
			var ajax = $.ajax({
				url: "/webapp/wcs/stores/servlet/ISALTMOutOfStockEmail",
				dataType: "json",
				type: "post",
				success: displayEmailMe,
				data: data,
				error: showRequestError
			});
	    	return false;
	    }
	  
		//
		this.compTablePositioning = compTablePositioning;
	    function compTablePositioning(resized) {
	    	    	
    		if (isComparisonPage) {
    		  	//calculate diff between window and default outerwrap width and initial X positions
				var viewDiff = ($(window).width() - 896);
				var lightBoxX = argos.product.comparison.result.getPageX(document.getElementById("lightBox"));
				var overlayX = argos.product.comparison.result.getPageX(document.getElementById("outerwrap"));
				if (IE7) {
					if (!resized) {		
						if (viewDiff > 0) {
							lightBoxX = (lightBoxX - viewDiff/2);
							$(dialogue).css({left: lightBoxX + "px"});
						} 

					}	
				} else if (!FF) {	
					viewDiff = ($(window).width() - $("#outerwrap").width());
					if (viewDiff > 0) {
						overlayX -= (viewDiff/2);
						lightBoxX -= (viewDiff/2);
					} else {
						overlayX += (viewDiff/2);
					}				
					if (IE6) {					
						if (viewDiff > 0) {
							$(overlay).css({left: overlayX + "px"});
						} else {
							$(overlay).css({width: $(document).width() + "px"});
						} 
					}
					if (!resized) {
						$(dialogue).css({left: lightBoxX + "px"});
					} 
				}
			}
		}		
		
		this.compTableTopMarginAdjust = compTableTopMarginAdjust;
	    function compTableTopMarginAdjust() {
	    	if (isComparisonPage) {
	    		//spawn Y position
				var lightBoxY = argos.product.comparison.result.getPageY(document.getElementById("lightBox"));
				//browser adjustments
				if(!FF3) {
					lightBoxY -= 30; 
					if(IE7) {
						lightBoxY += 8; 
					}
					if(IE6) {
						lightBoxY +=12; 
					}
					if(FF) {
						lightBoxY +=25; 
					}
				} else {
					lightBoxY -= 6; 
				}				
				argos.product.comparison.result.setPageY(dialogue,lightBoxY);
			}
		}
	    
	    /*
	     * Shows an AJAX request error in a lightbox
	     * @param XMLHttpRequest as object
	     * @param textStatus as string
	     * @param errorThrown as string
	     * @return void
	     */
	    this.showRequestError = showRequestError;
	    function showRequestError(XMLHttpRequest, textStatus, errorThrown) {
	    	var html = '';
	    	html += '<div id="lightBoxError">';
	    	html +=		'<div class="heading"><h2>An error occured</h2><a href="#" class="closeLightBox">Close</a></div>'
	    	html +=		'<div class="details">';
	    	html +=			'<p>Request: '+XMLHttpRequest+'</p>';
	    	html +=			'<p>Status: '+textStatus+'</p>';
	    	html +=			'<p>Error: '+errorThrown+'</p>';
	    	html +=		'</div>';
	    	html += '</div>';
	    	LightBox.hideLightBox();
	    	LightBox.setHTML(html);
	    	LightBox.showLightBox();
	    	//reposition if required - false = not resizing window
			compTablePositioning(false);
			compTableTopMarginAdjust();
	    }
	    
		function getQueryString(key, str) {
			var queryString = null;
			if (key == null || key === "") return null;
			if (queryString == null) {
				queryString = {};
				var qs = (function(){
					var qs = str.split("?");
					if(qs.length > 0) {
						qs = qs[1];
					}
					else {
						qs = str;
					}
					qs = qs.split("&");
					return qs;
				}()) 
				var qsElements;
				for (var i = 0, j = qs.length; i<j; i++) {
					qsElements = qs[i].split("=");
					if (queryString[qsElements[0]]) {
						if (queryString[qsElements[0]] instanceof Array) {
							queryString[qsElements[0]].push(qsElements[1] || "")
						} else {
							queryString[qsElements[0]] = [queryString[qsElements[0]], qsElements[1]];
						}
					} else {
						queryString[qsElements[0]] = qsElements[1] || "";
					}
				}
			}
			return queryString[key];
		};	    
	    
	}); 
});

var LightBoxStoresAZ = new (function(){
	var container = null;
	this.init = init;
	function init(json) {
		LightBox.hideLightBox();
		LightBox.setHTML(json.html);
		LightBox.showLightBox();
		//reposition if required - false = not resizing window
		LightBoxStockChecker.compTablePositioning(false);
		LightBoxStockChecker.compTableTopMarginAdjust();
		container = document.getElementById("lightBoxStoresAZ");
		if(container === null) return;		
		$(container).find("a.backToStockCheck").bind("click", backToStockCheck_onClick);
	    $(container).find("div.letters a").bind("click", letter_onClick);
	    $(container).find("div.results a").bind("click", store_onClick);
	    LightBoxStockCheckerTracking.track(json.page, json.state);
	    LightBoxStockCheckerTracking.init();
	}
	
	function backToStockCheck_onClick() {
		var data = this.href.split("?")[1];
		data += "&viewTaskName=ISALTMAjaxResponseView";
	    LightBoxStockChecker.checkStock(data);
	    return false;
	}
	
	function letter_onClick() {
    	LightBox.showOverlay();
		LightBox.setHTML(LightBox.loadingHTML);
		LightBox.showLightBox();
		//reposition if required - false = not resizing window
		LightBoxStockChecker.compTablePositioning(false);
		var ajax = $.ajax({
			url: this.href+"&viewTaskName=ISALTMAjaxResponseView",
			dataType: "json",
			type: "get",
			success: LightBoxStoresAZ.init,
			error: LightBoxStockChecker.showRequestError
		});			
    	return false;
	}
	
	function store_onClick() {
		LightBox.showOverlay();
		LightBox.setHTML(LightBox.loadingHTML);
		LightBox.showLightBox();
		//reposition if required - false = not resizing window
		LightBoxStockChecker.compTablePositioning(false);
		var ajax = $.ajax({
			url: this.href+"&viewTaskName=ISALTMAjaxResponseView",
			dataType: "json",
			type: "get",
			success: LightBoxStockChecker.displayStockCheckLightBox,
			error: LightBoxStockChecker.showRequestError
		});			
    	return false;
	}
});

/************************************************************************************
* OMNITURE TAGS
*************************************************************************************/
var LightBoxStockCheckerTracking = new (function(){
	var event = "";	
	var elementClicked = null;
	var pageG = "";
	
	var state = {previous: "",current: ""};
	
	this.track = track;
	function track(page, nextState) {
		pageG = page;
		state.previous = (state.current === "") ? nextState : state.current;
		state.current = nextState;
		if(elementClicked === null || event === "") return;
		var codeState = page+":stock:"+state.previous+":"+event;
		trackBasketPopupChoice(elementClicked, codeState);
		event = "";
		elementClicked = null;
	}
	
	this.init = init;
	function init() {
		/**
		 * Called immediately
		 */
		$("div#lightBoxStockAvailability .closeTag, div#lightBoxEmailMe .closeTag").bind("click", function(){
			$(window).unbind("resize");
			event = "close";
			elementClicked = this;
			track(pageG, state.current);
		});
  	
		$("div#lightBoxStockAvailability input.buyOrReserve").bind("click", function(){
			event = "buyorreserve";
			elementClicked = this;
			track(pageG, state.current);
		});		
		
		$("div#lightBoxStockAvailability .backTo").bind("click", function(){
			event = "backtolist";
			elementClicked = this;
			track(pageG, state.current);
		});	
				
		/**
		 * Called with response
		 */
		var checkboxes = $("#stockAvailabilityForm input.checkbox");
		
    	$("form#stockAvailabilityForm").bind("submit", function(){
    		event = "checkstock";
    		elementClicked = this;
    		if(state.current === "storelist") {
    			if(checkboxes.length > 0) {
	    			var count = 0;
	    			for(var i = 0; i< checkboxes.length; i++) {
	    				if(checkboxes[i].checked) {
	    					count++
	    				}
	    			}
	    			if(count === 0) {
	    				event = "nostoreerror";
	    			}
	    		}
    		}
    	});

		$("div#lightBoxStockAvailability a.emailOutOfStock").bind("click",function(){
			event = "emailstock";
			elementClicked = this;
		});		
    	$("div#lightBoxStockAvailability a.checkOtherStores").bind("click",function(){
			event = "checkotherstores";
			elementClicked = this;
		});
		$("div#lightBoxEmailMe #emailMeSubmit").bind("click",function(){
			event = "go";
			elementClicked = this;
		});
		
		$(window).bind("resize", function(){
			//reposition if required - true =  resizing window
			LightBoxStockChecker.compTablePositioning(true);
		});
	}
	
	this.trackAddToBasketPopup = trackAddToBasketPopup;
	function trackAddToBasketPopup() {
		var s=s_gi(s_account);
		s.tl(this,'o','Add to basket pop-up');
	}

	function trackBasketPopupChoice(obj, tag) {
		var s=s_gi(s_account);                
		s.linkTrackVars="events,products,eVar29";
		s.linkTrackEvents="event3";
		s.events="event3";
		s.eVar29=tag;
		s.tl(obj,'o','Add to basket pop-up:yes selected');	
	}
});
