$(document).ready(function(){

	
	if ( $.browser.msie && $.browser.version == '6.0' ) {
		//fix PNGs in IE6
		$(".error-wrap").pngFix();
	}	

	// clear search example.
	$("#search").click(function() {
		$(this).attr("value", "");
	});
	
	
	// clear a form.
	$(".reset-form").click(function() {
		$("form")[1].reset();
		
	});
	
	
	// simple status message appear and disappear.
	function statusMessage( msg ) {
		$("#status-message").text(msg).show("slow",function() {
			setTimeout( function() {
				$("#status-message").hide("slow");
			}, 300000 );
		});
	}
	
	
	// auto disappear for static status message.
	setTimeout(function() {
		$("#status-message-static").hide("slow");
	},3000);

	
	// rename home link in nav.
	$("#nav-home").text("Home"); 
	
	
	
	
	// hides shipping details if checkbox checked.
	$("#shipping-check").click(function() {
		if( $(this).attr("checked") ){
			$("#shipping-wrap").hide();
		} else {
			$("#shipping-wrap").show();
		}
	});
	
	
	// full product images/thumbs switch.
	$("#photo-list li img").click(function() {
		var source = $(this).attr("src");
		$("#default-photo").attr("src", source.replace("small", "large") );
		$(".thickbox").attr("href", source.replace("_small", "") );
		
		// call preload function from preload.js.
		preload_full();
	});
	
	
	// show zoom icon when user hovers over main photo.
	$("#zoom").hover(function() {
		$(this).animate({
			opacity: '1'},
			{"duration":200
		});
	}, function() {
		$(this).animate({
			opacity: 0},
			{"duration":200
		});
	});
	
			
	// function to get around strict doctype - target _blank.
	$(".target-blank").click(function() {
		window.open( $(this).attr("href") );
		return false;
	});
	
	
	// check if quantity user adds to cart is more than stock level.
	$("#add-to-cart").click(function(){
		
		// references to quantity and product from form.
		var quantity = $("#quantity").val();
		var pid = $("#pid").val();
		
		$.ajax({
			type: "POST",
			url: "/product/stock_level_check.php",
			data: "pid=" + pid,
			success: function( stock_level ){
				
				// convert to integer.
				stock_level = parseInt( stock_level );
			
				// check if amount user is trying to add to cart is more than available stock.
				if ( quantity > stock_level ) {
					
					// show message to user. 
					$("#stock-message").text("Sorry, there are " + stock_level + " left in stock.");
				}
				else {
					// there is enough stock available to proceed to cart.
					$("#product-form").submit();
				}
				
			}
		
		});
		
		// prevents auto submission of form, due to submit button being clicked.
		return false;
				
	});
	
	
	
	// update price based on options selected.
	$(".option").click(function(){
		
		// get form values.
		var query_string = $(".option").serialize();
		var product_price = $("#product-price").val();
		var grant = parseFloat( $(".grant").text() ).toFixed(2);
		
		// difference between product price and grant.
		var deficit = parseFloat( product_price - grant ).toFixed(2);
		
		$.ajax({
			type: "POST",
			url: "/product/price_option.php",
			data: query_string,
			success: function( option_total ){
				
				var option_total = parseFloat(option_total).toFixed(2);
				
				// * 1 to ensure JS knows to add, not concatenate. parseFloat didn't work.
				var price = ( product_price * 1 + option_total * 1 ).toFixed(2);
				
				$("#price").text( "£" + price );
				
				$(".total").text( price );
				
				var personal = option_total;
				
				// if there is a deficit between laptop price and grant, then add amount to total price of options.
				if ( deficit > 0 ) {
					personal = ( option_total * 1 + deficit * 1 ).toFixed(2); 		
				}
				
				$(".personal").text( personal );
			}
		
		});
						
	});
	
	
	
	// store locator homepage.
	$("#locate").click(function() {
		$("#store-locator-form").submit();
	});
	
	
	// set noe ajax.
	// update price based on noe selected.
	$("#noe-set").change(function(){
		
		var boo = false;
		
		// check if there is anything in the cart yet. if so dont let them change.
		$.ajax({
			type: "POST",
			url: "/category/cart_contents.ajax.php",
			success: function( msg ){
			
				if (msg == 1) {
					alert("Please remove product from the cart before changing your NOE.");
					boo = true;
					return;
				}
				
			}
		
		});
		
		if ( boo ) {
			return;
		}
		
		// if user selects CO noe, go to CO packages. 
		if ( $(this).val() == '3' && $("#category-id").val() != '33' ) {
			location.href = "/connectivity-only/";
			return;
		}
		
		var qs1 = $(this).serialize();
		var qs2 = $("#category-id").serialize();
		
		
		$.ajax({
			type: "POST",
			url: "/category/update_price.php",
			data: qs1 + "&" + qs2,
			success: function( grant ){
				
				
				$(".grant").text( grant );
				
				$(".breakdown").each(function() {
					
					var total = $(this).find(".total").text();	
					var grant = $(this).find(".grant").text();
					
					var personal = (total - grant).toFixed(2);
					
					// cant be minus, so set to zero.
					if ( personal < 0 ) {
						personal = "0.00";
					}
					
					$(this).find(".personal").text( personal );
				});
				
				
			}
		
		});
	
						
	});
	
	// perform above if onload noe session set.
	if ( $("#noe-set").val() != '' ) {
		$("#noe-set").trigger('change');				
	}
	
	
	// only allow user to proceed to the product page from the category page if they have selected a noe.
	$(".noe-required").click(function() {
		if ( $("#noe-set").val() == '' ) {
			alert("Please select a NoE code from the drop down list.");
			return false;
		}
	});
	
	
	$('input#personal-yes').click(function() {
		$('dl#personal-billing').css( 'display', 'none' );
	    return true;
	});

	$('input#personal-no').click(function() {
		$('dl#personal-billing').css( 'display', 'block' );
	    return true;
	});

	
	
	
	
	
	// POSTCODE LOOKUP AJAX.
	$("#postcode-lookup-submit").click(function() {
		
		// Check if input field is empty.
		if ( $("#postcode-lookup").val() == '' ) {
			return;
		}
		
		// Show spinner.
		$("#postcode-lookup-loading").css("display","inline");
		
		// Create query string from form field.
		var query_string = $("#postcode-lookup").serialize();
		
		// Do Ajax magic, but note expects a JSON object to be returned, so use json_encode($array) in your PHP.
		$.ajax({
			type: "POST",
			url: "/checkout/postcode_lookup.php",
			data: query_string,
			dataType: "json", 
			success: function( address ){
				
				// Check if an address was found.
				if ( address == false ) {
					alert("Address could not be found.");
				}
				else {
					// First clear all fields.
					$("#billing-address-line1,#billing-address-line2,#billing-address-line3,#billing-county,#billing-postcode").val("");

					// Prefill relevant fields based on available data.
					$("#billing-address-line2").val( address.address1 );
					
					if ( address.address3 ) {
						$("#billing-address-line3").val( address.address3 );
					}
					else {
						$("#billing-address-line3").val( address.address4 );
					}
					
					$("#billing-county").val( address.county );
					$("#billing-postcode").val( address.postcode );
				}	
				
				// Done, so hide spinner.
				$("#postcode-lookup-loading").css("display","none");	
					
			}
			
		});
	
	});
	
	
	
	
	
	// Store Locator Show/Hide.
	$(".store-info").toggle(
		function(){
			$( "#storeid-" + $(this).attr("id") ).show();
			$(this).text("hide details");
		},
		function(){
			$( "#storeid-" + $(this).attr("id") ).hide();
			$(this).text("show details");
		}	
	);
	
	
	// check grant details match.
	$("#billing-shipping").submit(function(){
		if ( ! $("#confirm").attr("checked") ) {
			alert("You must check proof of ID matches grant card details");
			return false;
		}
	});
	
	
	
	// Store Locator - Show Cities in County.
	$("#select-county").change(function(){
		
		// Grey out the city drop down.
		$("#select-city").attr("disabled", true);
		
		// If the county is blank, truncate all cities.
		if ( $(this).val() == '' ) {
			$("#select-city option").remove();
			return;
		}
		
		// Gets value from the county select.
		var query_string = $(this).serialize();
		
		// Do the Ajax magic. Note that a JSON object is returned.
		$.ajax({
			type: "POST",
			url: "/store-locator/cities_in_county.ajax.php",
			data: query_string,
			dataType: "json", 
			success: function( cities ){
				
				// Count the number of properties in the JSON object.
				var count = 0;
				var prop;
				for ( prop in cities ) {
					count++;
				}

				// Check if any cities were found.
				if ( cities == false ) {
					return;
				}
				else {
					// Truncate any exising options in the city drop down.
					$("#select-city option").remove();
					
					// Loop through JSON object, appending the options.
					for( var i = 0; i <= count - 1; i++ ) {
						$("#select-city").append( '<option value="' + cities[i].city + '">' + cities[i].city + '</option>' );
					}
					
					// Ready to show to the user, so re-enable.
					$("#select-city").removeAttr("disabled");
					
				}
	
			}
			
		});
		
	});
	
	
	
	
	
	
	
	// payment confirm button.
	$("form#confirm").submit(function() {
		$('#process').attr("src", '/images/buttons/please-wait.png');
		$('#process').attr("disabled", true);
		$('#process').css("cursor", "default");
		$('#loading').css("display", "block");
	});
	
	
	
	
	
});

function popup( url ) {
	newwindow = window.open( url, 'CVV', 'width=300, height=200' );
	if ( window.focus ) {
		newwindow.focus()
	}
	return false;
}