/**
 * FILENAME: findAddress.js
 * AUTHOR: Ashley Barrett (ashley.barret@rgroup.co.uk)
 * CREATED: 29/01/2010
 * COMMENTS: A javascript file to deal with find address through the postcode
 * */

$(function(){
	if($("#findAddressIntro").length > 0){
		$("#findAddressIntro").append("<p>To make it easier for you simply enter your postcode and click the Find Address link. We will then present you with a list of addresses in that postcode region. Select yours and it will pre-fill the form for you.</p>");
		
		$(".selectHide").hide();
		
		$("#addressLink").append("<a href=\"/ajax/address/index.php\" id=\"findAddress\">Find Address</a>");
		
		$("#findAddress").click(function(){
			var postcode = $("input[name=postCode]").val();
		
			if($("#selectAddress")){
				$("#addressSearchResults").slideUp("slow");
				$("#selectAddress").remove();
			}
			
			if(postcode.length != 0){
				$.ajax({
					url : "/ajax/address/index.php",
					data : "postcode="+postcode,
					type : "POST",
					dataType : "json",
					cache : false,
					success : function(obj){
						
						if(obj.length == 1){
							alert("Sorry we could not find any matches for post code "+postcode+". Please revise or enter manually.");
						}else{
							
							var select = '<select id="selectAddress"><option selected="selected" value="0">- Select -</option>';
							$.each(obj, function(i, val) {
								var value = val;
								value = value.replace(postcode.toUpperCase(),"");
								select += '<option value="'+i+'">'+$.trim(value)+'</option>';
							});
							select += '</select>';
							
							$(select).appendTo("#addressSearchResults");
							
							$("#selectAddress").change(function(){
								
								if($("#selectAddress").val() == 0){
									return;
								}else{
								
									var value = $("#selectAddress :selected").text();
									var address = value.split(",");
									
									if(address[3]){
										$("input[name=address1]").val($.trim(address[0]+' '+address[1]));
										$("input[name=address2]").val($.trim(address[2]));
										$("input[name=town]").val($.trim(address[3]));
									}
									else if(address[2]){
										$("input[name=address1]").val($.trim(address[0]));
										$("input[name=address2]").val($.trim(address[1]));
										$("input[name=town]").val($.trim(address[2]));
									}else{
										$("input[name=address1]").val($.trim(address[0]));
										$("input[name=address2]").val('');
										$("input[name=town]").val($.trim(address[1]));
									}
									
									$(".selectHide").slideDown("slow");
								}	
							});
							
							$("#addressSearchResults").slideDown("slow");
						}
					}
				});
			}
			
			return false;
		});
	}
});
