/**
 * jQuery plugin to accompany addess finder plugin
 * Siteclick Ltd
 */

jQuery.fn.addressfinder = function(opts) {

  var opts = jQuery.extend({
    address_1 : 'input[name=address_1]',
    address_2 : 'input[name=address_2]',
    town      : 'input[name=town]',
    county    : 'input[name=county]',
    postcode  : 'input[name=postcode]'
    }, opts);

  // The base URL for ajax requests
  var ajaxBase = $('base').attr('href') + ((location.href.match('index.php') != -1) ? 'index.php/' : '') + 'ajax/';

  // Local object reference
  var _this = this;

  // Update the address form via AJAX lookup, close Fancybox
  function updateAddressForm() {
    // Get the address ID we need to look up from the anchor
    var addressId = $(this).data('addressId');

    // Get the DIV with the full address form that needs updating
    var div = $($('#postcodelookup').get(0).addressFormDiv);

    // Load the address detail
    $.get(ajaxBase + 'addressfinder/detail', 'id=' + addressId, function(data) {

      var row = $(data).find('Row');

      if($(row).length > 0) {
        var line1     = $(row).attr('Line1');
        var line2     = $(row).attr('Line2');
        var town      = $(row).attr('PostTown');
        var county    = $(row).attr('County');
        var postcode  = $(row).attr('Postcode');

        // Fill in county if blank
        if(county == '')
          county = town;

        $(opts.address_1).val(line1);
        $(opts.address_2).val(line2);
        $(opts.town).val(town);
        $(opts.county).val(county);
        $(opts.postcode).val(postcode);
      }
      else {
        alert('Address not found');
      }
      
      // Close fancybox
      $.fancybox.close();
    }, 'xml');

    return false;
  }


  // Add postcode form to page
  function addPostcodeForm() {
    
    // Check flag to see if form already present
    if($('div#postcodelookup').length > 0) {
      return;
    }

    // Add div to page to hold postcode lookup form
    var div = $('<div id="postcodelookup" style="width: 400px; height: 400px"><h1>Find address</h1></div>');
    var inp = $('<input id="postcodelookupfield" name="postcode" value="" />');
    $(div).append('<p>Type your full postcode, then click your address in the list</p>');
    $(div).append('<label for="postcodelookupfield">Postcode</label>');
    $(div).append(inp);
  
    // Add space for search results
    var res = $('<ul id="postcoderesults"></ul>');
    $(div).append(res);
  
    $('body').append(div);
    $(div).hide();

    // Auto-capitalise postcode
    $('#postcodelookupfield').keyup(function() {
      var postcode = $(this).val().toUpperCase();
      $(this).val(postcode);

      // if postcode matches, do AJAX lookup
      var R = new RegExp('GIR 0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))|[0-9][A-HJKPS-UW]) [0-9][ABD-HJLNP-UW-Z]{2}');
      if(R.test(postcode)) {

        $('#postcoderesults').html('<li>Searching...</li>');
  
        $.get(ajaxBase + 'addressfinder', 'postcode=' + encodeURIComponent(postcode), function(data) {

          // Check data returned
          if($(data).find('Row').length < 1) {
            $('#postcoderesults').html('<li>Postcode not found.</li>');
            return false;
          }

          // Add links to postcode results
          $('#postcoderesults').empty();
          $(data).find('Row').each(function() {
            
            // Create link and store address ID to it
            var a = $('<a href="#">' + $(this).attr('StreetAddress') + '</a>');
            $(a).data('addressId', $(this).attr('Id'));
            $(a).click(updateAddressForm);
  
            // Add LI and add to list of results
            var li = $('<li></li>');
            $(li).append(a);
            $('#postcoderesults').append(li);
  
          })
        }, 'xml');
      }
      else {
        $('#postcoderesults').html('<li>Please type a valid postcode, eg W12 7RJ</li>');
      }
    })
    
    _this.formAdded = true;
  }


  return this.each(function(i, inputField){

    // Add the postcode form
    addPostcodeForm();

    jQuery(inputField).focus(function(ev, preventPopup) {

      ev.stopPropagation();

      if( ($(this).val() == '') && (preventPopup != true) ) {

        // Show the postcode search form
        $('#postcodelookup').show();
        $.fancybox($('#postcodelookup'), {
          onComplete  : function() {

            // Focus postcode field
            $('#postcodelookupfield').trigger('focus');
          },
          onCleanup : function() {
            $(inputField).trigger('focus', [true]);
          },
          onClosed : function() {

            // Hide form
            $('#postcodelookup').hide();

          }
        });
      }



    });
  })
  
}





