// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

String.prototype.humanize = function() {
  return this.gsub(/_id$/, '').gsub(/_/, ' ').capitalize();
}

var Startforce = function() {
  privateMethod = function() {
  }
  return Class.create({
    _validationQueues: [],
    _passedValidations: [],
    
    initialize: function() {
      this.rsaService = new RSAKey();
      var parts = passwordPublicKey.split(":");
      this.rsaService.setPublic(parts[0], parts[1]);
    },
    
    willLogin: function(form) {
      var createCookie = function (name, value, seconds) {
        var expires = "";
        if (seconds) {
          var date = new Date();
          date.setTime(date.getTime() + (seconds * 1000));
          expires = "; expires=" + date.toGMTString();
        }
        document.cookie = name + "=" + value + expires;
      }
      var eraseCookie = function (name) {
        createCookie(name, "", -1);
      }
      if ($('optRemember').checked)
        createCookie("username", $("email").value, 2592000);
      else
        eraseCookie("username");
      var encryptedPass = this.rsaService.encrypt($F('password'));
      $(form).insert({bottom: '<input type="hidden" name="rsapass" id="rsapass" value="' + encryptedPass + '" />'});
      $('password').value = "";
      form.action = "https://" + window.location.host + "/os/";
      form.submit();
    },
    
    checkPriceChange: function() {
      if (!$F('#organization_storage')|| $F('organization_storage') < 10) {
        $('#organization_storage').value = 10;
      }
      if (!$F('organization_webtops')) {
        $('organization_webtops').value = 10;
      }
      var webtops = parseInt($F('organization_webtops'));
      var storage = parseInt($F('organization_storage'));
      var price = (webtops * 29.90) + ((Math.max(10, storage) - 10) * 2);
      
      $('total_price').value = '$' + price;
    },
    
    observePriceChanges: function() {
      $j('#organization_storage').add('#organization_webtops').change(function() {
        this.checkPriceChange();
      });
      this.checkPriceChange();
    },
    
    // Validations go here
    validatesPresenceOf: function(object, field, options, callback) {
      callback($F(object + '_' + field) != "", 'must be present');
    },
    
    validatesUniquenessOf: function(object, field, options, callback) {
      new Ajax.Request('/users/check_existence?field=' + field + '&value=' + $F(object + '_' + field), {
        method: 'get',
        onSuccess: callback.curry(false, 'already exists'),
        onFailure: callback.curry(true)
      })
    },
    
    validatesLengthOf: function(object, field, options, callback) {
      var field = $F(object + '_' + field);
      var min = options['within'] ? options['within']['minimum'] : options['minimum'];
      var max = options['within'] ? options['within']['maximum'] : options['maximum'];
      if (min && max) {
        callback(field.length >= min && field.length <= max, 'must be between ' + min + ' and ' + max + ' characters');
        return;
      } else if (min) {
        callback(field.length >= min, 'is too short');
        return;
      } else if (max) {
        callback(field.length <= max, 'is too long');
        return;
      } 
      callback(true);
    },
    
    validatesConfirmationOf: function(object, field, options, callback) {
      var firstField = $(object + '_' + field);
      var confirmationField = field.endsWith('_confirmation') ? $(object + '_' + field.gsub(/_confirmation$/, '')) : $(object + '_' + field + '_confirmation');
      if (confirmationField) {
        if (!field.endsWith('_confirmation')) {
          confirmationField.stopObserving('blur', this.validate.bind(this, object, field + '_confirmation', [{func: this.validatesConfirmationOf, opts: {}}]));
          confirmationField.observe('blur', this.validate.bind(this, object, field + '_confirmation', [{func: this.validatesConfirmationOf, opts: {}}]));
        }
        if (firstField.present() && confirmationField.present() && $F(firstField) != $F(confirmationField)) {
          callback(false, 'must match confirmation');
        }
      }
      callback(true);
    },
    
    validatesFormatOf: function(object, field, options, callback) {
      callback($F(object + '_' + field).match(options['with']), 'is not in the specified format');
    },
    
    validatesNumericalityOf: function(object, field, options, callback) {
      callback(true, 'must be a number');
    },
    
    validate: function(object, field, humanName, testMethods) {
      this._validationQueues[object + field] = testMethods.map((function(f) {
        return f.func.bind(this, object, field, f.opts, this.validationCallback.bind(this, object, field, humanName, f.opts));
      }).bind(this));
      this._passedValidations[object + field] = true;
      while (this._validationQueues[object + field] && this._validationQueues[object + field].length > 0) {
        this._validationQueues[object + field].pop()();
      }
    },
    
    validationCallback: function(object, field, humanName, options, result, message) {
      if (!result) {
        this._passedValidations[object + field] = false;
        this.validationsFinished(object, field, humanName, options['message'] || message);
        return;
      }
      if (this._validationQueues[object + field] && this._validationQueues[object + field].length == 0) {
        this.validationsFinished(object, field, humanName, options['message'] || message);
      }
    },
    
    validationsFinished: function(object, field, humanName, message) {
      fieldWithoutConfirmation = field.gsub(/_confirmation$/, '')
      var fieldName = object + '_' + fieldWithoutConfirmation;
      var confirmationField = $(fieldName + '_confirmation');
      if (this._passedValidations[object + field]) {
        $(fieldName).removeClassName('error');
        if (confirmationField) {
          confirmationField.removeClassName('error');
        }
        if ($(fieldName + '_error')) {
          $(fieldName + '_error').hide();
        }
      } else {
        $(fieldName).addClassName('error');
        if (confirmationField) {
          confirmationField.addClassName('error');
        }
        if ($(fieldName + '_error')) {
          $(fieldName + '_error').show().innerHTML = humanName + ' ' + message;
        }
      }
      delete this._passedValidations[object + field];
      delete this._validationQueues[object + field];
    }
  });
}();

var sf = new Startforce();