
$(document).ready(function() {

		//alert('billing-delivery-same-yes value: '+$('#billing-delivery-same-yes:checked').val());

		//if billing + delivery same, hide checkbox for delivery same as billing by default
		if($('#billing-delivery-same-yes:checked').val())
		{
			$("#postcode-pop-address-hide-delivery").hide();
			$('.postcode-pop-address-hide').hide();
		}

		//hide 'searching text'
			//$('.postcode-searching').hide();

	 	//get the data on click
		$('.postcode-getaddress').click( function(e)
		{
			//get params. fieldset - where the postcode is to be used, ie billing address, delivery address etc
			var fieldset = $(this).attr('id');
			var userpostcode = $('#'+fieldset+'_postcode').val();
			var building = ''; // $('#'+fieldset+'_address_line_1').val().split(' ');
			//call the function that actually does something
			address(fieldset, userpostcode, building, false);
			//stop defualt
			e.preventDefault();
			//unbind so it can't be clicked lots

			//show/hide searching text and button

		});

		//Coremetrics - tracking catalogue download
		$('#ord-cata-img, a[title=click here to download our catalogue]').click( function(){
			cmCreateConversionEventTag("Catalogue Download pdf", "2", "Catalogue", "10","Free Catalogue-_-INFORMATION-_--_--_--_--_--_--_--_--_--_-{if $getPartner}{$getPartner}{else}Standard{/if}-_--_--_-");
		});
		//Coremetrics - tracking order form download
		$('a[title=click here to download our order form]').click( function(){
			cmCreateConversionEventTag("Order form Download pdf", "2", "Order form", "10","Order form-_-INFORMATION-_--_--_--_--_--_--_--_--_--_-{if $getPartner}{$getPartner}{else}Standard{/if}-_--_--_-");
		});
});

function address(fieldset, userpostcode, building, action)
		{
			//show or hide address list on page load if needed
			if(action=='load')
			{
				$("#postcode-pop-address-hide-delivery").show();
			};

			//make sure postcode enetered, else don't bother
			if(userpostcode==''||userpostcode==undefined)
			{
				$('.postcode-getaddress').show();
				$('#'+fieldset+'-postcode-searching').hide();alert('Error: You must enter a postcode');


				return false;
			};

			//show it
			//empty any results from past search(es)
			$('#address-list-'+fieldset).html('');
			$('#address-list-'+fieldset).append('<optgroup label="Please select your address:"></optgroup>');
			//slide it out
			$("#address-list-box-"+fieldset).slideDown("slow");$("#address-list-box-"+fieldset).css({visibility: "visible", display: "block"});
			//Setting parameters for json load
			var parameters =
			{
				type: 'json',
				params:
				{
					postcode: userpostcode,
					building: building
				}
			};
			//replace button with searching text whilst ajax active
			$('.postcode-getaddress')
				.ajaxStart( function() {
					$(this).hide();
					$('.postcode-searching').show();
				})
				.ajaxComplete( function() {

					$(this).show();
					$('.postcode-searching').hide();
				});
			//send params and api call, '' for null loading icon
			getData.withMethod('/ajax/', 'website' ,'addressCapture', parameters, false,
				function(msg)
				{
					if (msg.errors)
					{
						$('#address-list-box-delivery p').show();
						//output error msg
						$('#address-list-box-'+fieldset+' p').html('<strong>'+msg.errors[0]+'</strong>').css({color: 'red'});

					}
					else //got expected results - show output etc
					{
						//hide error
						$('#address-list-box-delivery p').hide();

						//call function to show and populate list.
						populateAddressList(fieldset, msg);

					};

					//sets address into address fields based on selection from postcode lookup
					$("#use-this-address-"+fieldset).click( function(e)
					{
						e.preventDefault();
						populateAddress(fieldset);
					});
					$('.postcode-pop-opts').dblclick( function(e)
					  {
						  e.preventDefault();
						  populateAddress(fieldset);
					  });


					//to close a postcode pop up
					$(".postcode-pop-close").click( function(e)
					{
						e.preventDefault();
						//which one to close
						var fieldsetClose = $(this).attr('name');
						$("#postcode-pop-"+fieldsetClose).slideUp("medium");
					});
					//not found so closed popup and open up list
					//to close a postcode pop up
					$(".postcode-pop-close-nf").click( function(e)
					{
						e.preventDefault();
						var fieldsetClose = $(this).attr('name');
						alert('close this one '+fieldsetClose);
						$("#postcode-pop-address-hide-"+fieldsetClose).show();
						//which one to close

						$("#postcode-pop-"+fieldsetClose).slideUp("medium");
					});

			}); //end if msg successful function
		};
function populateAddressList(fieldset, msg)
{
	//vars to store elements of each returned address
	var adCompany;
	var adAddress1;
	var adAddress2;
	var adAddress3;
	var adTown;
	var adCounty;
	var adPostCode;
	var id = 0; //used to count ads
	//output msg showing user's search term
	$('#address-list-box-billing-'+fieldset+' p').html('<strong>Couldn\'t see your address? <a href="#" name="'+fieldset+'" class="postcode-pop-close-nf">Click here to enter it manually</a></strong><br />').css({color:'green'});
	//for all results, loop through and create vars/make selectable li
	for (var addr in msg.addresses)
	{
		//assign values to vars. values come from json object. some may be empty, but this is fine
		adCompany = msg.addresses[addr]['company'];					//includes housename/number
		adAddress1 = msg.addresses[addr]['address1'];

		adAddress2 = msg.addresses[addr]['address2'];
		adAddress3 = msg.addresses[addr]['address3'];
		adTown = msg.addresses[addr]['town'];
		adCounty = msg.addresses[addr]['county'];
		adPostCode = msg.addresses[addr]['postcode'];
		//out put html as a new li in results ul. clicking them selects and calls function below.

		$('#address-list-'+fieldset+' optgroup').append('<option id="postcode-pop-data-'+fieldset+'-'+id+'" class="postcode-pop-opts" value="'+
			adCompany+'-'+
			adAddress1+'-'+
			adAddress2+'-'+
			adAddress3+'-'+
			adTown+'-'+
			adCounty+'-'+
			adPostCode+'-'+
			'">'+
			adCompany+', '+adAddress1+', '+adAddress2+', '+adAddress3+', '+adTown+' '+adCounty+'. '+adPostCode+
			'</option>');
		id++; //increment adCounter
	};
};


function populateAddress(fieldset)
{
	//get value of selected one
	var selectedAddress = $('#address-list-'+fieldset).val();
	//if it's null, warn user
	if(!selectedAddress)
	{
		$('#address-list-box-'+fieldset+' p').html('<strong>Please select your address from the list:</strong>').css({color: 'red'});
	}
	else
	{
		//break it apart into array
		var addressParts = selectedAddress.split('-');
		//have a peep
		//alert('address is '+addressParts[0]+', '+addressParts[1]+', '+addressParts[2]+', '+addressParts[3]+','+addressParts[4]+', '+addressParts[5]);

		//set vars based on text between spans of outputted list...
		var adCompany = addressParts[0]; // $('#'+selectedAddress+'-adCompany').text();
		var adAddress1 =addressParts[1]; //$('#'+selectedAddress+'-adAddress1').text();
		var adAddress2 = addressParts[2]; //$('#'+selectedAddress+'-adAddress2').text();
		var adAddress3 = addressParts[3]; //$('#'+selectedAddress+'-adAddress3').text();
		var adTown =	addressParts[4]; //$('#'+selectedAddress+'-adTown').text();
		var adCounty = 	addressParts[5]; //= $('#'+selectedAddress+'-adCounty').text();
		var adPostCode = addressParts[6]; //$('#'+selectedAddress+'-adPostCode').text();
		//put vars into input fields on form
		$("#"+fieldset+"_address_line_1").val(adCompany);

		$("#"+fieldset+"_address_line_2").val(adAddress1+' '+adAddress2+' '+adAddress3);
		$("#"+fieldset+"_town").val(adTown);
		$("#"+fieldset+"_county").val(adCounty);
		$("#"+fieldset+"_postcode").val(adPostCode);

		var deliverySame = $('#address-delivery-checkbox .radio:checked').val();

		//also put values into delivery address - we assume that the 2 addresses are the same to begin with.
		if (deliverySame=='yes')
		{
			$("#delivery_address_line_1").val($('#billing_address_line_1').val());
			$("#delivery_address_line_2").val($("#billing_address_line_2").val());
			$("#delivery_town").val($("#billing_town").val());
			$("#delivery_county").val($("#billing_county").val());
			$("#delivery_country_code").val($("#billing_country_code").val());
			$("#delivery_postcode").val($("#billing_postcode").val());
			$('#delivery_addr label.error').css('display', 'none');
		}
		else
		{
		//reveal the address fields, completed with data
			$("#postcode-pop-address-hide-delivery").show();

		}

		$("#postcode-pop-address-hide-delivery-inner").show();
		//close the options list
		$("#address-list-box-"+fieldset).slideUp("medium");
		//reveal the address fields, completed with data
		$("#postcode-pop-address-hide-"+fieldset).show();
		//show the checkbox saying delivery is same as billing
		$("#address-delivery-checkbox").show();
	}
};