/* Plugin for subscriptions */
$.fn.subWidget = function (options) {

  var defaults = {
  }
  var opts = $.extend(defaults, options);


  return this.each(function () {


    var self = this;
    var $self = $(this);
    
    // Public Fields
    this.updateMode = null;
    
    // Private Fields
    var $customerFields, $subFieldMain, $subFieldPress, $subFieldSupplier, formBaseUrl, segment, isUnjoined;

    var $emvForm          = $('form.emv-sub', self);
    var $divLoading       = $('div.emv-loading', self);
    var $unjoinContainer  = $('div.unjoin-container', $emvForm);
    
    $emvForm.find('.button').button();
    
    var $refreshOnUpdate = $('input[name="refresh_on_update"]', $emvForm);

    this.activate = function() {

      // Form Base URL
      formBaseUrl     = $('input[name="FORM_BASE_URL"]', $emvForm).val();

      // Segment
      segment      = $('input[name="SEGMENT_FIELD"]', $emvForm).val();

      // Sub Fields
      $subFieldMain     = $('input[value="SUB_RB"]', $emvForm);
      $subFieldPress    = $('input[value="SUB_RB_PRESS_FIELD"]', $emvForm);
      $subFieldSupplier = $('input[value="SUB_RB_SUPPLIER_FIELD"]', $emvForm);
      
      
      // Customer Fields
      $customerFields   = $('select[name="COUNTRY_OF_RESIDENCE_FIELD"], input[name="FIRSTNAME_FIELD"], input[name="LASTNAME_FIELD"], select[name="TITLE_FIELD"]', $emvForm);

      $emvForm.bind('submit', function() {
        self.clearAlerts();
        self.setUpdateMode();
        if(self.validator.form())
        {
          self.requestUpdate();
        }
        return false;
      });
      
      // Define unjoin button event
      $('.unjoin-button', $emvForm).bind('click', function () {
        if (confirm('Are you sure you want to opt out of all marketing correspondence?')) {
          self.requestUnjoin();
        }
      });

      // Show sub checkboxes
      if (segment == 'P') {
        $subFieldPress.closest('tbody').show();
      } else if (segment == 'S') {
        $subFieldSupplier.closest('tbody').show();
      }
      $subFieldMain.closest('tbody').show();

      // Get member id
      var memberId = parseInt($('input[name="MID"]', $emvForm).val());

      // Load data
      if (isNaN(memberId)) {
        this.showForm(0);
      } else {
        $divLoading.show();
        self.requestLoad(memberId);
      }

    }

    this.requestLoad = function(memberId) {
      var url = '/newsletter/getdata/' + memberId + '?nocache=' + new Date().getTime();
      //alert(url);
      $.get(url, function (dataString) {
        self.actionLoad(dataString, memberId);
      }
           );
    }

    this.actionLoad = function(dataString, memberId) {

      //alert(dataString);
      var data = $.parseJSON(dataString);

      if (data==null) {
        //location.href = formBaseUrl;
        this.doError('There was a problem retrieving your details.');
        this.doAlert('If you wish to update your details including your subscriptions please ' +
                     '<a href="mailto:newsletter@railbookers.com?subject=Newsletter Preferences Update Request (E1: '+ memberId + ')">' +
                     'click here to email us</a>.<br />We apologise for any inconvenience.');
        // Hide form
        $('div.sub-form', $emvForm).hide();

      } else {

        $('input[type="text"],input[type="hidden"].settable', $emvForm).each(function () {
          if (typeof(data[$(this).attr('name')])!='undefined' && data[$(this).attr('name')] !=null) {
            $(this).val(data[$(this).attr('name')]);
          }
        });
        
        $('select[name="COUNTRY_OF_RESIDENCE_FIELD"] option', $emvForm).each(function() {
          this.selected = (typeof(data.COUNTRY_OF_RESIDENCE_FIELD)!='undefined' && data.COUNTRY_OF_RESIDENCE_FIELD == this.value);
        });
        
        $('select[name="TITLE_FIELD"] option', $emvForm).each(function() {
          this.selected = (typeof(data.TITLE_FIELD)!='undefined' && data.TITLE_FIELD == this.value);
        });
                                                                                          
        // Show unjoined message
        if(data.UNJOINED && !$refreshOnUpdate.length) {
          this.doAlert('You have opted to receive no marketing correspondence from us. If you wish you can always resubscribe below.');
        }
        
        // If customer set non editable fields
        if(data.CUSTOMER_ID_FIELD!=null) {
          $customerFields.filter('input').attr('readonly', true);
          $customerFields.filter('select').attr('disabled', true);
          $customerFields.addClass('readonly');
          $('tbody.existing-customer', $emvForm).show();
        }
        
        
        // Main Sub
        $subFieldMain.attr('checked', data.SUB_RB==1);

        // Press Sub
        $subFieldPress.attr('checked', data.SUB_RB_PRESS_FIELD==1);

        // Supplier Sub
        $subFieldSupplier.attr('checked', data.SUB_RB_SUPPLIER_FIELD==1);

        // Show Press and Supplier fields if necessary
        if (data.SUB_RB_PRESS_FIELD==1 || data.SEGMENT_FIELD == 'P') {
          $subFieldPress.closest('tbody').show();
        }
        if (data.SUB_RB_SUPPLIER_FIELD==1 || data.SEGMENT_FIELD == 'S') {
          $subFieldSupplier.closest('tbody').show();
        }

        if(!data.UNJOINED) {
          $unjoinContainer.show();
        }

      }

      this.showForm(500);
    }

    this.requestUnjoin = function() {
      self.clearAlerts();
      $self.block();
      var url = '/newsletter/member/UNJOIN/?'+$("input[name='ORIGINAL_EMAIL_FIELD'], input[name='csrf']", $emvForm).serialize() + '&nocache=' + new Date().getTime();
      //alert(url);
      $.get(url, {}, function (dataString) {
        self.actionUnjoin(dataString);
      }
           );
    }

    this.actionUnjoin = function(dataString) {
      var data = $.parseJSON(dataString);

      // display faults
      if (typeof(data.faults)=='object') {
      
        for (var i=0; i<data.faults.length; i++) {
          self.doError(data.faults[i]);
        }
        
      } else if (data.success==1) {
      
        this.doAlert('You will no longer receive any marketing correspondence from us. It can take up to 10 minutes to take effect. <br />If you wish you can always resubscribe below.');
        
        $subFieldMain.attr('checked', false);
        $subFieldPress.attr('checked', false);
        $subFieldSupplier.attr('checked', false);
        
        $unjoinContainer.hide();
      
      } else {
        self.doError('Save failed');
      }

      $self.unblock();
    }

    this.requestUpdate = function() {
      self.clearAlerts();
      $self.block();

      var url = '/newsletter/member/'+ self.updateMode + '/?' + $emvForm.serialize() + '&nocache=' + new Date().getTime();
      //alert(url); return;
      $.get(url, {}, function (dataString) {
        self.actionUpdate(dataString);
      });
    }
    
    
    this.actionUpdate = function(dataString) {
      var data = $.parseJSON(dataString);

      // display faults
      if (typeof(data.faults)=='object') {

        for (var errField in data.faults) {
          self.doError(data.faults[errField]);
        }

      } else if (data.success==1) {
        var msg;
        if (typeof(data.msg) == 'string') {
          msg = data.msg;
        } else {
          msg = 'Thank you. Your subscriptions have been updated.';
        }
        self.doAlert(msg);
        
        if(self.updateMode == 'UPDATE')
        // Preference Centre
        {
          $unjoinContainer.show();
        }
        else
        // SUBSCRIBE FORM OR EMAIL CHANGE
        {
          $emvForm.hide();
        }
        
        if($refreshOnUpdate.length)
        {
          setTimeout(function() {
            window.location.reload();
          }
          , 1000);
          return;
        }
        
      } else {
        self.doError('Save failed.');
      }

      $self.unblock();
    }

    this.doError = function (text) {
      $('.form-alerts', self).append('<div class="ui-widget" style="margin-top: 12px; margin-bottom: 12px;"><div style="padding: 0.8em 0.7em 0 0.7em;" class="ui-state-error ui-corner-all"><p><span style="margin-right: 0.3em; float: left;" class="ui-icon ui-icon-alert"></span> '+text+'</p></div></div>');
      $('.form-alerts', self).fadeIn('slow');
      //niceScroll('#page-top');
    }

    this.doAlert = function (text) {
      $('.form-alerts', self).append('<div class="ui-widget" style="margin-top: 12px; margin-bottom: 12px;"><div style="padding: 0.8em 0.7em 0 0.7em;" class="ui-state-highlight ui-corner-all"><p><span style="margin-right: 0.3em; float: left;" class="ui-icon ui-icon-info"></span> '+text+'</p></div></div>');
      $('.form-alerts', self).fadeIn('slow');
      //niceScroll('#page-top');
    }

    this.clearAlerts = function () {
      $('.form-alerts', self).hide().empty();
    }
    
    this.setUpdateMode = function()
    {
    
      var originalEmail = $("input[name='ORIGINAL_EMAIL_FIELD']", $emvForm).val();
      if(typeof(originalEmail) != 'undefined')
      {
        originalEmail = originalEmail.toLowerCase();
      }
      var newEmailA = $("input[name='EMAIL_FIELD']", $emvForm).val().toLowerCase();
      var newEmailB = $("input[name='EMAIL_FIELD_CONFIRM']", $emvForm).val().toLowerCase();
      var existingMember = (typeof(originalEmail) != 'undefined');
      
      self.updateMode = 'UPDATE';
      if (existingMember)
      // Existing member
      {
        // If new address entered
        if (originalEmail != newEmailA)
        {
          self.updateMode = 'UPDATEEMAIL';
        }
      }
      else
      // Non-member
      {
        self.updateMode = 'INSERT';
      }
      
    }
    
    
    /* NEW VALIDATE FUNCTION */
    
    var validateOptions = {

      onsubmit: false,
      
      //onfocusout: false,
      //onkeyup: false,
    
      focusInvalid: false,
      focusCleanup: true, // not recommended with focusInvalid
    
      errorClass: "form-error",
      //validClass: "form-valid",

      errorPlacement: function(error, element) {
        if(element.attr('errorboxid')) {
          error.appendTo('#'+element.attr('errorboxid'));
        } else {
          error.appendTo( element.next('.error-msg') );
        }
      },
      
      rules: {
        EMAIL_FIELD: {
          required: true,
          email: true
        },
        EMAIL_FIELD_CONFIRM: {
          required: function(element) {
            return (self.updateMode != 'UPDATE');
          },
          equalToIfExists: '#EMAIL_FIELD',
          email: true
        },
        COUNTRY_OF_RESIDENCE_FIELD: {
          required: true
        },
        'SUB_FIELDS[]': {
          minChecked: 1
        }
        
      },
      
      messages: {
        EMAIL_FIELD: {
          required: 'Please enter your email address.',
          email: 'Please enter a valid email address.'
        },
        EMAIL_FIELD_CONFIRM: {
          required: 'Please enter your email address again.',
          email: 'Please enter a valid email address.',
          equalToIfExists: 'Your email addresses do not match.'
        },
        COUNTRY_OF_RESIDENCE_FIELD: {
          required: 'Please select your country of residence.'
        },
        'SUB_FIELDS[]': {
          minChecked: 'Please select at least one newsletter to receive.'
        }
      }
    
    };
  
    var $evCor = $('input[name="ev_cor"]', $emvForm);
    if($evCor.length)
    {
      var $evCorRequiredOption  = $('select[name="COUNTRY_OF_RESIDENCE_FIELD"] option[value="' + $evCor.val() + '"]', $emvForm);
      if($evCorRequiredOption.length)
      {
        validateOptions.rules.COUNTRY_OF_RESIDENCE_FIELD.equalTo      = '#' + $evCor.attr('id');
        validateOptions.messages.COUNTRY_OF_RESIDENCE_FIELD.equalTo   = 'You must be a resident of ' + $evCorRequiredOption.text() + '.';
      }
      validateOptions.rules.TITLE_FIELD         = { required: true };
      validateOptions.rules.FIRSTNAME_FIELD     = { required: true };
      validateOptions.rules.LASTNAME_FIELD      = { required: true };
      validateOptions.messages.TITLE_FIELD      = { required: 'Please select your title.' };
      validateOptions.messages.FIRSTNAME_FIELD  = { required: 'Please enter your first name.' };
      validateOptions.messages.LASTNAME_FIELD   = { required: 'Please enter your last name.' };
    }
  
    this.validator = $emvForm.validate(validateOptions);
    
    /************************/
    
    
    

    this.showForm = function(delay) {
      setTimeout(function() {
        $divLoading.hide();
        $emvForm.show();
      }
      , delay);
    }


    self.activate();

  }
                  );

}
