
var allies_info = null;
var allies_button = null;
var allies_popup = null;

/**
 *
 *  inits the Allies form using the following info...
 *
 *  info = {
 *    houseNumberField: '',
 *    postcodeField: '',
 *    addressFields: new Array()
 * }
 *
 */

function allies_initForm( info ) {

    var defaultCss = {
        position: 'absolute',
        top: '100px',
        left: '100px',
        height: '200px',
        width: 'auto',
        backgroundColor: '#eee',
        border: '1px #aaa solid',
        overflow: 'auto',
        padding: '5px'
    };

    allies_info = info;

    if ( allies_popup == null ) {
        allies_popup = jQuery( '<div></div>' )
                        .attr({
                            id: 'allies_addressPopup'
                        })
                        .css( defaultCss )                        
                        .blur(function(){ allies_popup.fadeOut() })
        jQuery(document.body).append( allies_popup );
        allies_popup.hide();
    }

}

/**
 *  Reads the postcode and makes a query to the Allies
 *  script to get houses for a postcode.  You can optionally
 *  pass in a button that will act as the source for the query,
 *  the results will then be position relative to this.  
 *
 *  @param button the button originating the action
 * 
 */

function allies_postcodeQuery( button ) {

    if ( button.id != undefined )
        allies_button = jQuery( button );

    aErrors = new Array();

    var oPostcode = jQuery( '#' +allies_info['postcodeField'] );

    // Get the postcode
    postcode = oPostcode.val().replace(/\s/, '');
    if ( !postcode.length ) {
        aErrors.push("You must enter the postcode");
    }
    
    // Make sure it's a valid postcode
    // Regex taken from http://regexlib.com/REDetails.aspx?regexp_id=260 and adjusted to exclude spaces from the match
    else if (!postcode.toUpperCase().match(/^([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]?[0-9][ABD-HJLN-UW-Z]{2}|GIR 0AA)$/)) {
        aErrors.push("You must enter a valid postcode");
    }

    // Did any errors occur?
    if ( aErrors.length ) {
        alert( aErrors.join("\n") );
        return;
    }

    // add loading feedback and show popup
    allies_positionPopup();
    allies_popup
        .html( 'Loading, please wait...' )
        .fadeIn();

	var url = '/custom/homeform/sharps/allies.php';

    jQuery.post(
        url, 
        {postcode: encodeURIComponent(postcode)},       
        allies_handlePostcodeQuery        
    );

}


/**
 *  handles the return of the query to fetch the users address from
 *  their postcode
 *
 *  @param xml the xml soap document from qas
 *  
 */

function allies_handlePostcodeQuery( xml ) {           
    var matchItem = xml.getElementsByTagName( 'item' );
    var eAddresses = jQuery( '#allies_addresses' );
    var hasAddresses = false;

    var street = '',
        town = '',
        locality = '',
        county = '',
        postcode = '';
    
    allies_popup.empty();

    jQuery.each( matchItem, function(i,item) {

        switch(item.getAttribute('xsi:type'))
        {
            case 'tns:PremiseListAddress':
                try { street = item.getElementsByTagName( 'street' )[ 0 ].firstChild.nodeValue; } catch(err){} 
                try { locality = item.getElementsByTagName( 'dependent_locality' )[ 0 ].firstChild.nodeValue; } catch(err){} 
                try { town = item.getElementsByTagName( 'post_town' )[ 0 ].firstChild.nodeValue; } catch(err){} 
                try { county = item.getElementsByTagName( 'county' )[ 0 ].firstChild.nodeValue; } catch(err){} 
                try { postcode = item.getElementsByTagName( 'postcode' )[ 0 ].firstChild.nodeValue; } catch(err){}  
                break; 
                 
            case 'tns:PremiseList':                                                          
                var name = '',
                    number='',
                    organisation= '';      
                
                try{ number = item.getElementsByTagName( 'premise' )[ 0 ].firstChild.nodeValue; } catch(err){}
                try{ organisation = item.getElementsByTagName( 'organisation' )[ 0 ].firstChild.nodeValue; } catch(err){}
                                
                var address1 = '';
                if(organisation.length > 0) { address1 += organisation + " "; }
                if(number.length > 0) { address1 += number + " "; }
                if(street.length > 0) { address1 += street; }
                
                var address2 = ''; 
                if(locality.length > 0) { address2 += locality + " "; }  
                
                name = address1 + ", " + town + ", " + county + ". " + postcode;                            

                var eLink = jQuery( '<a></a>' )
                .attr({
                href: "javascript:allies_setAddressFields('" + address1 + "','" + address2 + "','" + town + "','" + postcode + "');"
                })
                .css({
                display: 'block'                
                })
                .html( name );
                
                allies_popup.append( eLink );
                
                break;  
        }

        hasAddresses = true;

    });

    if ( !hasAddresses ) {
        allies_popup.html( 'Nothing found...' );
        setTimeout( 'allies_popup.fadeOut()', 1000 );
    }

    allies_positionPopup();
    allies_popup.fadeIn();
}

/**
 *  positions the popup element next to the  find button
 *
 */
function allies_positionPopup() {

    allies_popup.css({
        top: allies_button.offset().top,
        left: allies_button.offset().left + allies_button.width() + 15
    });

}


function allies_setAddressFields( address1, address2, town, postcode ) {    
    
    document.getElementById('address_fields').style.display = 'block';
    
    var element = document.getElementById(allies_info[ 'addressOneField' ]);
    element.value = address1;  
        
    element = document.getElementById(allies_info[ 'addressTwoField' ]);
    element.value = address2;  
    
    element = document.getElementById(allies_info[ 'postcodeField' ]);
    element.value = postcode; 
    
    element = document.getElementById(allies_info[ 'cityField' ]);
    element.value = town;
    
    allies_popup.fadeOut()             
}
