var IZIFindNearMeBackEnd = new Class({
  translations: new Hash({}),

  initialize: function ()
  {
    document.getElements('form[name=findnearme-form]').each( function ( form ) {
      form.addEvent('submit', function ( event ) {
        if( $('FindNearMeResult') ) {
          return this.search( form, event );
        }
      }.bind(this));
    }.bind(this));

    document.getElements('a.findnearme-search').each( function ( element ) {
      element.addEvent('click', function ( event ) {
        if( $('FindNearMeResult') ) {
          return this.search( element, event );
        }
        element.getParent('form').submit();
      }.bind(this));
    }.bind(this));
  },

  addTranslation: function ( translation )
  {
    this.translations.combine( translation );
  },

  search: function ( element, event )
  { 
    if( event ) {
      event = new Event( event );
      event.stop();
    }

    var myFx = new Fx.Scroll( window ).toElement('FindNearMeResult');

    element = $( element );
    if( element.match('form') ) {
      var form = element;
    } else {
      var form = element.getParent('form');
    }

    var zipcode = form.getElement('input[name*=zipcode]').get('value');
    var radius = 15;
    var absolute = false;

    var zipcode_regex = /^\d{4}/;
    if( !zipcode_regex.test( zipcode ) ) {
      $('FindNearMeResult').set('html', '<p class="error">' + this.translations.IZI_FINDNEARME_MODULE_FRONTEND_LOCATION_SEARCH_INVALID_ZIPCODE + '</p>' );
      return false;
    }

    $('FindNearMeResult').set('html', '<img src="/modules/FindNearMe/templates/default/icons/ajax-loader.gif" class="icon" /> ' + this.translations.IZI_FINDNEARME_MODULE_FRONTEND_LOCATION_SEARCH_LOADING );

    new Request.JSON({ 'url': '/service/FindNearMe/service-location-search',
      'method': 'post',
      onSuccess: function( response ) {
        $('FindNearMeResult').empty();

        if( !response.success ) {
          $('FindNearMeResult').set('html', '<p class="error">' + response.message + '</p>' );
          return false;
        }

        $('FindNearMeResult').set('html', response.data );
      },
      onFailure: function() {
        $('FindNearMeResult').set('html', '<p class="error">' + this.translations.IZI_FINDNEARME_MODULE_FRONTEND_LOCATION_SEARCH_FAILED + '</p>' );
      }
    }).send('zipcode=' + zipcode + '&radius=' + radius + '&absolute=' + absolute );
  }
});
