﻿/* Provides functionality for address lookup form, requires jQuery 1.2.6 or later */

jQuery(document).ready(function() {
    addressForm.init();
});

function hide(el)
{
    if(jQuery(el))
        jQuery(el).style.display = 'none';
}

function show(el)
{
    if(jQuery(el))
	    jQuery(el).style.display = '';
}

function isHidden(el)
{
    if(jQuery(el) && jQuery(el).css('display') == 'none')
        return true;
        
    return false;
}

var addressForm = {

    addressCollection: null,

    init: function() 
    {
        addressForm.UI.setupForm();
              
        jQuery('#selectAddress').change(addressForm.events.selectAddressOptionChange);
        jQuery('#btnSearchAgain').click(addressForm.searchAgain);
    },
    
    /* method called when find address button clicked */
    search: function()
    {      
        if(jQuery('input.PostcodeSearch').get(0).value < 5)
        {
            alert("Please supply a full and valid UK postcode");
        }
        else
        {        	
            // transfer postcode from postcodesearch input to postcode input
            addressForm.ajax.search(jQuery('input.PostcodeSearch').get(0).value);      
        }
    },
    
    searchAgainFromForm: function()
    {
        if(jQuery('input.Postcode').val() != "")
            jQuery('input.PostcodeSearch').val(jQuery('input.Postcode').val());
        
        addressForm.searchAgain();
    },
    
    searchAgain: function()
    {
        if(jQuery('input.Postcode').val() != "")
            jQuery('input.PostcodeSearch').val(jQuery('input.Postcode').val());
        
        jQuery('#btnSearch').show();
        jQuery('#btnSearch').text("Find Address");    
        
        jQuery('#tb_lookup').show();
        jQuery('#tb_selectaddress').hide();
        jQuery('#tb_form').hide();
        
        //if(canResize != undefined && canResize && parent.setIframeHeight)
        //    parent.setIframeHeight('ifEnquiry');  
    },
    
    /* method called from containing form */
    validate: function()
    {
        if(isHidden('#tb_form'))
        {        
            if(isHidden('#tb_lookup'))
            {                         
                if(jQuery('selectAddress').value == "")
                {
                    alert("You must select your address from the address dropdown box, or complete your address manually by selecting the 'Enter Address Manually' option.");
                    return false;
                }
                else
                {
                    // populate address from select box
                    this.resolveAddressFields();   
                    return true;    
                }    
            }
            else
            {
                alert("Please supply a full and valid UK postcode and click 'Find address'");
                return false;
            }     
        }
        else
        {
            // address form completed manually therefore validate fields
            return this.validateAddressFields();
        }        
    },

    validateAddressFields: function()
    {
        bHasError = false;
        errorString = "";
        
        if(jQuery('input.Address1').val() == "")
        {
            errorString += "Please supply your address...\r\n";
            bHasError = true;
        }
        
        if(jQuery('input.Town').val()== "")
        {
            errorString += "Please supply your town...\r\n";
            bHasError = true;
        }
        
        if(bHasError)
            alert(errorString);
                
        return !bHasError;
    },
    
    /* method populates address fields from selected address item */
    resolveAddressFields: function()
    {
        var addressId = jQuery('#selectAddress').val();
        var addressItem = this.addressCollection[addressId];
        
        var Organisation = addressForm.data.getAddressItem(addressItem, "Organisation");
        var Addr1 = addressForm.data.getAddressItem(addressItem, "Addr1");
        var Addr2 = addressForm.data.getAddressItem(addressItem, "Addr2");
        var Town = addressForm.data.getAddressItem(addressItem, "Town");
        var County = addressForm.data.getAddressItem(addressItem, "County");
        
        this.clearAddressFields();
                
        if(Organisation != "")
	    {
		    if(Addr2 == "")
		    {
			    jQuery('input.Address1').val(Organisation);
			    jQuery('input.Address2').val(Addr1);
		    }
		    else
		    {
			    jQuery('input.Address1').val(Organisation + ", " + Addr1);
			    jQuery('input.Address2').val(Addr2);
		    }				
	    }
	    else
	    {				
		    jQuery('input.Address1').val(Addr1);
		    jQuery('input.Address2').val(Addr2);
	    }
    				
		jQuery('input.Town').val(Town);
		jQuery('input.County').val(County);	
		
		jQuery('input.Postcode').val(jQuery('input.PostcodeSearch').val());		
    },
    
    /* method clears address fields */
    clearAddressFields: function()
    {
        jQuery('input.Address1').val("");
        jQuery('input.Address2').val("");
        jQuery('input.Town').val("");
        jQuery('input.County').val("");
        jQuery('input.Postcode').val("");
    }
}
 
addressForm.UI = {

    setupForm: function()
    {
        // html is configured initially for users with js disabled
        // therefore show and hide necessary elements
        
        jQuery('#tb_form').hide();
        jQuery('#btnSearchAgain').show();
        jQuery('#tb_lookup').show();
        
        jQuery('#btnSearch').click(addressForm.search);
        
    },
    
    showForm: function()
    {
        jQuery('#tb_lookup').hide();
        jQuery('#tb_selectaddress').hide();
        jQuery('#tb_form').show();

	jQuery('#btnSearchAgainFromForm').show();
        
        //if(canResize != undefined && canResize && parent.setIframeHeight)
        //    parent.setIframeHeight('ifEnquiry');
    },
    
    showSearching: function()
    {
        jQuery('#btnSearch').hide();
        jQuery('#loader').show();
    },
    
    lookupFailure: function()
    {
        jQuery('#loader').hide();
        
        alert("There was a problem, please complete your address manually.");
        jQuery('#btnSearchAgain').hide();
        addressForm.UI.showForm();
    }
}

addressForm.ajax = {

    lookupservice: "/XMLAddresses.aspx",
     
    search: function(postcode)
    {
        jQuery.ajax({
            type: "GET",
            url: this.lookupservice + "?pc=" + postcode,
            dataType: "xml",
            success: addressForm.ajax.lookupResult,
            error: addressForm.UI.lookupFailure
        });
        
        addressForm.UI.showSearching(); 
    },
    
    lookupResult: function(data)
    {   
        jQuery('#loader').hide();
        
        addressForm.addressCollection = jQuery("Address",data);
        
        jQuery('#selectAddress').removeOption(/./);
        jQuery('#selectAddress').addOption("", "Select your address...");
        
        if(addressForm.addressCollection.length != 0)
        {   
            i = 0;
            
            addressForm.addressCollection.each(function(i, address) {

                jQuery('#selectAddress').addOption(i, addressForm.data.buildAddress(address));

            });
            
            
            jQuery('#selectAddress').addOption(-1, "<< Enter address manually >>");    
            jQuery('#selectAddress').selectOptions("");
            
            jQuery('#tb_lookup').hide();
            jQuery('#tb_selectaddress').show();            
        }
        else
        {
            alert("Sorry, no addresses were found for the postcode you supplied.\nPlease try your search again, or complete your address manually."); 
                        
            addressForm.UI.showForm();
        }
        
    }  
  
}

addressForm.data = {

    buildAddress: function(el)
    {
        address = "";
        
        if(jQuery("Organisation", el).text() != "")
        {
            address += (address != "" ? ", " : "") + jQuery("Organisation", el).text();
        }
        
        if(jQuery("Addr1", el).text() != "")
        {
            address += (address != "" ? ", " : "") + jQuery("Addr1", el).text();
        }
        
        if(jQuery("Addr2", el).text() != "")
        {
            address += (address != "" ? ", " : "") + jQuery("Addr2", el).text();
        }
        
        if(jQuery("Town", el).text() != "")
        {
            address += (address != "" ? ", " : "") + jQuery("Town", el).text();
        }
        
        if(jQuery("County", el).text() != "")
        {
            address += (address != "" ? ", " : "") + jQuery("County", el).text();
        }
	    
        return address;
    },

    getAddressItem: function(addrnode, nodename) 
    {
	    if(addrnode.getElementsByTagName(nodename)) 
	    {
		    var el = addrnode.getElementsByTagName(nodename);
    		
		    if(el.item(0).childNodes.item(0)) 
			    return el.item(0).childNodes.item(0).data;
	    }
    	
	    return "";
    }  
}

 
addressForm.events = {

    selectAddressOptionChange: function()
    {
        if(jQuery('#selectAddress').val() == -1)
        {
            jQuery('input.Postcode').value = jQuery('input.PostcodeSearch').val();
            addressForm.UI.showForm();
        }    
    }
}
