
var qas_info = null;
var qas_button = null;
var qas_popup = null;

/**
 *
 *  inits the QAS form using the following info...
 *
 *  info = {
 *    houseNumberField: '',
 *    postcodeField: '',
 *    addressFields: new Array()
 * }
 *
 */

function qas_initForm( info ) {

    var defaultCss = {
        position: 'absolute',
        top: '100px',
        left: '100px',
        height: '200px',
        width: 'auto',
        backgroundColor: '#eee',
        border: '1px #aaa solid',
        overflow: 'auto',
        padding: '5px'
    };

    qas_info = info;

    if ( qas_popup == null ) {
        qas_popup = $( '<div></div>' )
                        .attr({
                            id: 'QAS_addressPopup'
                        })
                        .css( defaultCss )
                        .blur(function(){ qas_popup.fadeOut() })
        $(document.body).append( qas_popup );
        qas_popup.hide();
    }

}

/**
 *  takes a ConForm field id, and tries to fetch the elements
 *  real id attribute.  if nothing it found then returns -1
 *
 *  @param name the conform id for the field
 *
 *  @return String field id, or -1 if not found
 *
 */

function qas_getConFormFieldId( name ) {

    var items = $( "*[@name='sendField[" +name+ "]']" );

    return items.length == 1 ? $(items[0]).attr('id') : '-1';

}

/**
 *  adjusts ConForms for using QAS integration.  the only argument is the
 *  QAS info that will need to be modified with to change the ConForm field
 *  id's to real element ID's before we pass the info to the real init func.
 *
 *  @param info was info to modify
 *
 */

function qas_initConFormForQas( info ) {

    // need to modify the info we receive because the data is the NAMEs of
    // the fields on the form, and we need it to be the ID's
    var postcodeId = qas_getConFormFieldId( info[ 'postcodeField' ] );
    var houseNumberId = qas_getConFormFieldId( info[ 'houseNumberField' ] );
    var addressNames = info[ 'addressFields' ];
    var addressIds = '';

    // work out id's for address fields
    $.each( addressNames.split(','), function(i,name) {
        var modifier = '';
        // split off a modifier?
        if ( name.substring(0,1) == '+' ) {
            modifier = '+';
            name = name.substring( 1 );
        }
        addressIds += ',' +modifier + qas_getConFormFieldId( name );
    });
    addressIds = addressIds.substring( 1 ); // trim off leading commer?

    // now we have all field id's we can init the QAS stuff
    qas_initForm({
        postcodeField: postcodeId,
        houseNumberField: houseNumberId,
        addressFields: addressIds
    });

    // finally add a button to the form
    var postcodeRow = $( '#'+postcodeId ).parent().parent().parent();

    $( '<div class="formRow"><div class="fieldLeft">&#160;</div><div class="fieldRight">' +
       '<input type="button" value="Find my address" onclick="qas_postcodeQuery(this)" /></div></div>' )
        .insertAfter( postcodeRow );

}

/**
 *  This adjusts the XForm to insert QAS functionality
 * 
 */

function qas_initXFormForQas() {

    // Find the row containing the first line of the address
    var oAddressDiv = jQuery( 'div[@class=aformrow]:has(#'+qas_info['houseNumberField']+')' );
    // Find the row containing the postcode value
    var oPostCodeDiv = jQuery( 'div[@class=aformrow]:has(#'+qas_info['postcodeField']+')' );

    // Move the postcode div below the address div
    oPostCodeDiv.remove();
    oPostCodeDiv.insertAfter( oAddressDiv );

    // Add functionality to the button
    // NB!!  this assumes there's only gonna be 1 QAS form on a page
    qas_button = $( '<input type="button" />' )
        .val( 'Find my address' )
        .click( qas_postcodeQuery );

    // Add a button for the ajax
    // Note: Do not create <input>-Elements without a type-attribute,
    // due to Microsofts read/write-once-rule for the type-attribute of <input>-elements
    // See this official statement for details: http://msdn2.microsoft.com/en-us/library/ms534700.aspx
    //
    oButtonDiv = jQuery('<div class="aformrow"><span class="aformlabel">&#160;</span></div>')
        .append( qas_button );

    // Insert the button after the postcode
    oButtonDiv.insertAfter( oPostCodeDiv );

}

/**
 *  Reads the address and postcode and makes a query to the QAS
 *  script to get houses for a postcode/number.  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.  (on XForms
 *  the button is set in the qas_initXFormForQas() method)
 *
 *  @param button the button originating the action
 * 
 */

function qas_postcodeQuery( button ) {

    if ( button.id != undefined )
        qas_button = $( button );

    aErrors = new Array();

    var oAddress1 = $( '#' +qas_info['houseNumberField'] );
    var oPostcode = $( '#' +qas_info['postcodeField'] );

    // Get the address line
    var address1 = oAddress1.val();
    if ( address1 == undefined )
        address1 = '';

    // 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
    qas_positionPopup();
    qas_popup
        .html( 'Loading...' )
        .fadeIn();

	var url = '/qas.php?postcode=' +encodeURIComponent(postcode)+ '&address1=' +encodeURIComponent(address1);

    jQuery.ajax({
        type: 'GET',
        url: url,
        success: qas_handlePostcodeQuery
    });

}

/**
 *  handles the return of the query to fetch the users address from
 *  their postcode
 *
 *  @param xml the xml soap document from qas
 *  
 */

function qas_handlePostcodeQuery( xml ) {

    var msie = (((navigator.userAgent.indexOf("Firefox") != -1)||(navigator.appVersion.indexOf("MSIE")!= -1))&&!window.opera)? true : false;
    var prefix = msie ? 'qas:' : '';
    var items = xml.getElementsByTagName( prefix + 'PicklistEntry' );
    var eAddresses = jQuery( '#QAS_addresses' );
    var hasAddresses = false;

    qas_popup.empty();

    jQuery.each( items, function(i,item) {

        var moniker = item.getElementsByTagName( prefix + 'Moniker' )[ 0 ].firstChild.nodeValue;
        var name = item.getElementsByTagName( prefix + 'Picklist' )[ 0 ].firstChild.nodeValue;
        var eLink = jQuery( '<a></a>' )
            .attr({
                href: 'javascript:;'
            })
            .css({
                display: 'block'
            })
            .html( name )
            .click(function(){
                qas_popup.fadeOut();
                jQuery.ajax({
                    type: 'GET',
                    url: '/qas.php?action=GetAddress&moniker=' +encodeURIComponent(moniker),
                    success: qas_handleGetAddressQuery
                });
            });

        qas_popup.append( eLink );

        hasAddresses = true;

    });

    if ( !hasAddresses ) {
        qas_popup.html( 'Nothing found...' );
        setTimeout( 'qas_popup.fadeOut()', 1000 );
    }

    qas_positionPopup();
    qas_popup.fadeIn();
    qas_popup.focus();

}

/**
 *  positions the popup element next to the qas find button
 *
 */

function qas_positionPopup() {

    qas_popup.css({
        top: qas_button.offset().top,
        left: qas_button.offset().left + qas_button.width() + 15
    });

}

/**
 *  handles the return of the query to get full information about a
 *  specific address.
 *
 *  @param xml the xml from the query
 *
 */

function qas_handleGetAddressQuery( xml ) {

    var msie = (((navigator.userAgent.indexOf("Firefox") != -1)||(navigator.appVersion.indexOf("MSIE")!= -1))&&!window.opera)? true : false;
    var prefix = msie ? 'qas:' : '';
    var lines = xml.getElementsByTagName( prefix + 'AddressLine' );
    var addressFields = qas_info[ 'addressFields' ].split( ',' );

    jQuery.each( lines, function(i,line) {

        if ( elem = line.getElementsByTagName(prefix+'Line')[ 0 ].firstChild ) {

            var value = elem.nodeValue;
            var field = addressFields[ i ];

            // check for append (+) modifier to the field
            if ( field.match(/^\+/) ) {
                field = field.substring( 1 );
                value = $('#'+field).val() + "\n" + value;
            }

            $( '#'+field ).val( value );

        }
    });

}
