//Initialise the behaviour of the toggle elements, used in the regional availability checkers

Initialiser.modules.uiToggles = function(){

	/* ---------------------------------------
		Configuration of AJAX params: */
		
		var checkerOptions = {
			method: $('#availabilityCheck').attr('method'), //GET or POST the check request:
			url: $('#availabilityCheck').attr('action') //The URL to use to check availability for a product. Defaults to the 'action' of the form				
		}
		
	/* ---------------------------------------
		Configuration of the product lister elements */
	
			
		//Quick validation on zipCode entry forms:
		$('form.zipCodeCheck')
			.submit(function(){
				//Only validate when in 'filtered' mode:				
				if ($(this).attr('id') == 'listerViewMode') {					
					//Only validate when in filtered mode:
					if ($('#filterModeAll').attr('checked')) {
						return true; //We're showing all products, so we don't care about the zip
					} else {
						return validateZipCode($(this)); //Check that the zip looks OK
					}
				} else {
					//Always validate otherwise:
					return validateZipCode($(this));
				}
		});
			
		//Auto-submit select boxes that fire their form when changed:
		$('select.autoSubmit').change(function(){
			$(this).closest('form').submit();
		});
			
		/* ---------------------------------------
			Configuration of the product detail elements */

		//Initialise the overlay events:
	
		//Links that trigger the overlay
		$('#checkAvailability, #addToCartForm a.changeZip')
			.click(function(){
				$('#checkAvailabilityComponent').removeClass('success fail checkInProgress').addClass('availabilityCheck');
				setTimeout("$('#zipCodeEntry').focus();",200);
		});
		
		//Initialise close widgets
		//$('a.closeWidget')
			//.closeDOMWindow({eventType:'click'});
			
		//$('a.chatButton')
		//	.closeDOMWindow({eventType:'click'});	

		//The AJAX requests for the availability check:
		$('#checkAvailabilityComponent')
			.find('form')
				.submit(function(){
					
					var form = $(this)
					
				 	if (!validateZipCode(form)) {return false};
					
					var fieldset = $(this).find('fieldset')
					$('#checkAvailabilityComponent').addClass('checkInProgress');
					
					var zipCodeToCheck = $('#zipCodeEntry').attr('value');
					var catentryId  = $('#ajax_catentryId').attr('value');
					catentryId = getSkuId(document.OrderItemAddForm, catentryId);
					var storeId = $('#ajax_storeId').attr('value');
                    var command = $('#ajax_command').attr('value');
                    
						  $('p.noteError', '#OrderItemAddForm').slideUp(200);
                    $('span.zipCode').text(zipCodeToCheck);
															
					var checkData = {
						zipcode: zipCodeToCheck, 
						command: command,
						storeId: storeId,
						catentryId: catentryId					
					}; 
														
					//Insert the zip into the overlay wherever required:
					
					$.ajax({
						method: checkerOptions.method,
						url: checkerOptions.url,
						data:checkData,
						success: function(data, textStatus){
	  					$('#checkAvailabilityComponent').removeClass('checkInProgress');
						  showCheckSuccess(data, textStatus);
						},
						error: function(data, textStatus){
	  					$('#checkAvailabilityComponent').removeClass('checkInProgress');
						  showCheckError(data, textStatus);
						}
					});
					
					return false;
		})
		.end()
		.find('a.changeZip')
			.click(function(){
				$('#checkAvailabilityComponent').removeClass('success fail').addClass('availabilityCheck');
		});
	
	
	/* The handlers for the check results: */
	var showCheckSuccess = function(data, textStatus) {
	
		var zipCodeToCheck = $('#zipCodeEntry').attr('value');
		
		//$('body').append('<blockquote>' + data + '</blockquote>');
		
		var result = data.getElementsByTagName("result")[0].childNodes[0].nodeValue;	
		var status = data.getElementsByTagName("status")[0].childNodes[0].nodeValue;
		var message = data.getElementsByTagName("message")[0].childNodes[0].nodeValue;
						
		switch(status){
			case 'success' :				
				switch (result) {
					case 'available':
						//The product is available:
						$('#checkAvailabilityComponent').removeClass('availabilityCheck').addClass('success');
						if(!validateSelectedOptionsNoPopup(document.OrderItemAddForm, false)){
							$('#checkSuccess .buttonAddToCart').addClass('buttonHide');
							document.OrderItemAddForm.zipcode.value = zipCodeToCheck;
						}else{
							$('#checkSuccess .buttonAddToCart').removeClass('buttonHide');
						}
					break;		
					case 'unavailable':
						//The product is unavailable:
						$('#checkAvailabilityComponent').removeClass('availabilityCheck').addClass('fail');
					break;
				}								
			break;
			
			case 'failure':				
				document.getElementById('averror').innerHTML = message;
				$('#availabilityCheck').find('label.error[for*=zipCode]', $('#availabilityCheck')).slideDown(100);				
			break; 
		}
		
		
	}
	
	/* If the server doesn't respond correctly to a check: */
	var showCheckError = function(data, textStatus) {
		return false;
	}
	
	//Quick validation of a sensible looking zipCode:
	var validateZipCode = function(reference) {
				
		//Check that the zipcode isn't empty, and is all numbers:
		var zipValue = $('input.zipCode', reference),
			zipNumber;
			if (zipValue) {zipNumber = parseInt(zipValue.attr('value'))}
		
		if (!(isNaN(zipValue.val()) || zipValue.val().length != 5)) {
			reference
				.find('label.error[for*=zipCode]', reference)
				.slideUp(100);
								
				return true;
		} else {
			//Show the status message
			reference
				.find('label.error[for*=zipCode]', reference)
				.slideDown(100);
				
			zipValue.removeClass('valid').focus();

			return false; //prevent the submission
		}
	}
	
	/* When returning from a successful check: */
	// Change the 'check availability' button to
	$('#checkSuccess .goBack').click(function(){
											
		var zipCodeToCheck = $('#zipCodeEntry').attr('value');			
		var storeId = $('#ajax_storeId').attr('value');          
		
		$('span.zipCodeOnForm').text(zipCodeToCheck);		
														
		var checkData = {
			zipcode: zipCodeToCheck, 
			command: 'setzip',
			storeId: storeId,			
			prestatus: 'success'						
		}; 
		
		$.ajax({
			method: checkerOptions.method,
			url: checkerOptions.url,
			data:checkData,
			success: function(data, textStatus){showSetZipSuccess(data, textStatus)},
			error: function(data, textStatus){showSetZipError(data, textStatus)}
		});
				
		return false;
	});
			
	$('#checkFail .goBack').click(function(){
					
		var zipCodeToCheck = $('#zipCodeEntry').attr('value');			
		var storeId = $('#ajax_storeId').attr('value');   
		
		//$('span.zipCodeOnForm').text(zipCodeToCheck);	        
																				
		var checkData = {
			zipcode: zipCodeToCheck, 
			command: 'setzip',
			storeId: storeId,
			prestatus: 'failure'					
		}; 
																										
		$.ajax({
			method: checkerOptions.method,
			url: checkerOptions.url,
			data:checkData,
			success: function(data, textStatus){
			  showSetZipSuccess(data, textStatus);
			},
			error: function(data, textStatus){showSetZipError(data, textStatus)}
		});
		
		$('p.noteError', '#OrderItemAddForm').slideDown(200);
		$('#checkAvailabilityComponent').jqmHide();
		return true;
														
	});

	var showSetZipSuccess = function(data, textStatus) {	
	
		var prestatus = data.getElementsByTagName("prestatus")[0].childNodes[0].nodeValue;
		var status    = data.getElementsByTagName("status")[0].childNodes[0].nodeValue;
		var message   = data.getElementsByTagName("message")[0].childNodes[0].nodeValue;
		
		var zipCodeToCheck = $('#zipCodeEntry').attr('value');
					
		switch (prestatus) {
			case 'success':
				//The product is available:
				
				$('#refreshProduct_zipcode').val(zipCodeToCheck);
				
				//When the PDP has been loaded with 'regionalUnavailable', we need to refresh the page to retrieve the attributes:
				if ($('#OrderItemAddForm').is('.regionalUnavailable')) {
					document.refreshProduct.submit(); 	
				} else {
					$('#checkAvailabilityComponent a.closeWidget').click();
					$('#addToCartForm').fadeTo(200, 0.01, function(){
						$(this)
							.removeClass('unavailable')
							.addClass('available')
							.fadeTo(200, 1)
							.fadeTo(200, 1, function(){
								if (jQuery.browser.msie) this.style.removeAttribute('filter');
							});
					});
				}
				
			break;		
			case 'failure':
				switch (status) {
					case 'success':
						
						
						$('#refreshProduct_zipcode').val(zipCodeToCheck);
						
						//When the PDP has been loaded with 'regionalUnavailable', we need to refresh the page to retrieve the attributes:
						if ($('#OrderItemAddForm').is('.regionalUnavailable')) {
							document.refreshProduct.submit(); 
						} else {
							$('#checkAvailabilityComponent a.closeWidget').click();
							$('#addToCartForm').fadeTo(200, 0.01, function(){
								$(this)
									.removeClass('available')
									.addClass('unavailable')
									.fadeTo(200, 1, function(){
										if (jQuery.browser.msie) this.style.removeAttribute('filter');
									});
							});	
						}	
					
					break;
					case 'failure':
						$('#checkAvailabilityComponent a.closeWidget').click();
						
						$('#addToCartForm').fadeTo(200, 0.01, function(){
							$(this)
								.removeClass('available')
								.addClass('unavailable')
								.fadeTo(200, 1, function(){
									if (jQuery.browser.msie) this.style.removeAttribute('filter');
								});
						});						
					break;
				}				
			break;
		}
			
		return true;		
	}
	
	/* If the server doesn't respond correctly to a check: */
	var showSetZipError = function(data, textStatus) {	    	    				
		return false;
	}
	
	/* When the user has selected a valid zipcode, but on a page without attributes loaded, we need to update the URL and refresh the page: */
	$('#availableButNoAttributes').click(function(){
		var oldURL = window.location.href,
			newURL = oldURL.replace(/zipcode=\d{5}/, 'zipcode=' + document.OrderItemAddForm.zipcode.value);
			window.location = newURL;
			return false;
	});
	
	/*------------------------------------------------

		Functions for the PLP: add zip, set filter mode, etc.

	  ------------------------------------------------*/


		if ($('#prdSrchZipnAll').length) {

			var $resultsNavForm = $('#prdSrchZipnAll')
				$zipCodeEntry = $('#zipCode'),
				$productList = $('#productList'),
				$toggleModeZip = $('#toggleModeZip'),
				$toggleModeAll = $('#toggleModeAll');

				//When the zip is changed, invalidate it to stop it being passed to the PDP
				$zipCodeEntry.bind('change, keydown', function(){
					$(this).removeClass('valid');
				});

				//Check the settings object set in the JSPs
				if (window.regionConfig) {

						//Update the server with the new zip, and check the result of validation
						var setZip = function(){
							if ($zipCodeEntry.val()) {
								//Toggle the button 'clicked':
								$toggleModeZip.addClass('toggleSelected');
								$toggleModeAll.removeClass('toggleSelected');
								$productList.addClass('inProgress');

								//validate the zip entry
								if (!(isNaN($zipCodeEntry.val()) || $zipCodeEntry.val().length != 5)) {

									//Send the zip to the server
									$.get(regionConfig.zipCode.setZipURL($zipCodeEntry.val()), 
										function(response){

											var zipStatus = response.getElementsByTagName("status")[0].childNodes[0].nodeValue,
												message = response.getElementsByTagName("message")[0].childNodes[0].nodeValue;

											switch (zipStatus) {
												case 'success' : //If this is a valid zip
													window.location = regionConfig.zipCode.refreshURL + "&zipcode=" + $zipCodeEntry.val();
													return true;
												break;
												case 'failure' : //If the zip is invalid
													$toggleModeAll.addClass('toggleSelected');
													$toggleModeZip.removeClass('toggleSelected');
													$productList.removeClass('inProgress');

													document.getElementById("ziperror").innerHTML = message;
							    					$('form.zipCodeCheck').find('label.error[for*=zipCode]', $('#availabilityCheck')).slideDown(100);

													return false;
												break;
											}
										},
										function(response){
											//The server exploded.
											$toggleModeAll.addClass('toggleSelected');
											$toggleModeZip.removeClass('toggleSelected');
											$productList.removeClass('inProgress');

											document.getElementById("ziperror").innerHTML = 'Oops. Something went wrong and we couldn\'t set your zip. Please try again?';
											$resultsNavForm.find('label.error[for*=zipCode]', $('#availabilityCheck')).slideDown(100);
											return false;
										}
									, 'xml');
								} else {
									$toggleModeAll.addClass('toggleSelected');
									$toggleModeZip.removeClass('toggleSelected');
									$productList.removeClass('inProgress');

									document.getElementById("ziperror").innerHTML = 'Please enter a 5 digit US zip code.';
									$resultsNavForm.find('label.error[for*=zipCode]', $('#availabilityCheck')).slideDown(100);
								}
							} else {
								$toggleModeAll.addClass('toggleSelected');
								$toggleModeZip.removeClass('toggleSelected');
								$productList.removeClass('inProgress');

								document.getElementById("ziperror").innerHTML = 'Please enter a 5 digit US zip code.';
								$resultsNavForm.find('label.error[for*=zipCode]', $('#availabilityCheck')).slideDown(100);
							}

							return false;
						}

					//Hacky: Create the unfiltered mode URL by removing the 'fzip' param:
					window.regionConfig.zipCode.unfilteredURL = regionConfig.zipCode.refreshURL.replace('fzip=true', '');

					//Remove the active zipcode and reset the page:
					$('#filterModeAll').click(function(){
						//if ($zipCodeEntry.val()) {
							//Toggle the button 'clicked':
							$toggleModeAll.addClass('toggleSelected');
							$toggleModeZip.removeClass('toggleSelected');
							$productList.addClass('inProgress');

							//Refresh in the new mode:
							window.location = $zipCodeEntry.val() ? regionConfig.zipCode.unfilteredURL + "&zipcode=" + $zipCodeEntry.val() : regionConfig.zipCode.unfilteredURL;
						//}
					});

					//Set the page to 'filtered' mode with the latest zip.
					$('#filterModeZip').click(function(){
						setZip();
					});

					$resultsNavForm.submit(function(){
						return setZip();
					});

				}
				
				$productList.children('li.product')
					.click(function(e){
						if (!$(e.target).is('.quickLookTrigger, a')) {
							$(this).addClass('active').find('a:first').click();
						}
					});

				$productList.find('a').click(function(e){
					var href = $(this).attr('href');
					if ($('#zipCode.valid').val()) {
						if(href.indexOf("?") == -1){
							href += '?zipcode=' + $('#zipCode.valid').val();
						} else {
						 	href += '&zipcode=' + $('#zipCode.valid').val();
						}
					}
					window.location.href = href;
					e.preventDefault();
					e.stopPropagation();//Stop the link going up to the product again.
				});
		}
		
		//If the zipcode field is filled, do a client side validation:
		if ($('#zipCode').val()) {
			validateZipCode($('#zipCode').closest('form'));
		}
	
	
	//Clone the page navigation and put it at the bottom of the product lister:
	$('div.resultsNavigationLower', '#bodycontent').clone(true).addClass('bottomNavigation').appendTo('#bodycontent');
	
};



/* [BH] Creating functions like this pollutes the global namespace. DON'T DO IT. */
function validateSelectedOptionsNoPopup (aForm, multipleProducts) {

	var maxNoOfProducts = 1;
	var maxNoOfOptions = 10;
	if (multipleProducts) {
		maxNoOfProducts = 10;
	}
	
	for (prodIdx = 1; prodIdx <= maxNoOfProducts; prodIdx++) {

		var productPrefix = "";
		if (maxNoOfProducts > 1) {
			productPrefix = "p" + prodIdx;
		}

		var checkBoxId = productPrefix + "_selected";
		var bValidate=true;
		if (document.getElementById(checkBoxId)) {
			var includeProduct = document.getElementById(checkBoxId);
			if (!includeProduct.checked) {
				bValidate=false;
			}
		}

		if (bValidate) {
			for (i = 1; i <= maxNoOfOptions; i++) {
				var elementId = productPrefix + "attrValue" + (i);
				if (document.getElementById(elementId)) {
					var definingOption = document.getElementById(elementId);
					if (definingOption !== "undefined") {
						var selIndex = definingOption.selectedIndex;
						var errorText = definingOption.options[0].text + " " + definingOption.options[0].value;
						if (selIndex <= 0) {							
							return false;
						}
					}
				} else {
					i = maxNoOfOptions + 1;
				}		
			}		
		}
	}
	return true;

}

function getSkuId (aForm, productId) {

	var maxNoOfProducts = 1;
	var maxNoOfOptions = 10;
	var keyValue = "";
			
	for (i = 1; i <= maxNoOfOptions; i++) {
		var elementId = "attrValue" + (i);
		if (document.getElementById(elementId)) {
			var definingOption = document.getElementById(elementId);
			if (definingOption !== "undefined") {
				var selIndex = definingOption.selectedIndex;				
				if (selIndex <= 0) {							
					return productId;
				}else{
					var selValue = definingOption.options[selIndex].value;
					if(keyValue != "")
						keyValue = keyValue + "_";
					keyValue = keyValue + selValue.rtrim();		
				}
			}
		} else {
			i = maxNoOfOptions + 1;
		}		
	}		
	
	return skumap.get(keyValue);
			
}



