﻿String.prototype.trim = function() {
  return this.replace(/^\s+|\s+$/g, "");
};

Array.prototype.findIndex = function(value) {
  for (var i = 0; i < this.length; i++) {
    if (this[i] == value) { return i; }
  }
  return -1;
};

function StrRepeat(str, count) {
  return new Array(count + 1).join(str);  
}

function RemoveBreaks(field) {
  v = field.value;
  v = v.replace(/\r/, ' ').replace(/\n/, '');
  if (v!=field.value) { field.value = v; }
}

function HtmlEncode(str) {
  return str.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\"/g,"&quot;").replace(/\'/g,"&#39;").replace(/\r\n/g,"<br/>").replace(/\s+/g," ");
}

function Format_UpperCase(field) {
  var value = field.val().toUpperCase();
  if (value != field.val()) {
    var cp = field.caret();
    field.val(value);
    field.caret(cp.begin, cp.end);
  }
}

function Format_MaxLength(field) {
  maxlength = parseInt(field.attr("length"), 10);
  if (field.val().length > maxlength) { field.val(field.val().substring(0, maxlength)); }
  if (field.attr("count")) { $("#" + field.attr("count")).html(field.val().length); }
}

function FormatNumber(num, dec, zero) { 
  if (isNaN(parseFloat(num))) { return ""; }
  if (zero === false && num == 0) { return ""; }

  var neg = (num < 0);
  
  var tmpNum = parseFloat(num);
  tmpNum *= Math.pow(10, dec);
  tmpNum = Math.round(Math.abs(tmpNum));
  tmpNum /= Math.pow(10, dec);
  
  if (neg) { tmpNum *= -1; }
  
  var tmpNumStr = tmpNum.toString();
  if (dec > 0) {
    var pos = tmpNumStr.lastIndexOf(".");
    if (pos == -1) {
      tmpNumStr += "." + StrRepeat("0", dec);
    } else {
      pos = tmpNumStr.length - pos;
      if (pos < dec + 1) { tmpNumStr += StrRepeat("0", dec + 1 - pos); }
    }
  }
  
  return tmpNumStr;
}

function Input_DateConfig(field) {
  if (field.attr("mindate")) {
    field.datepicker("option", "minDate", field.attr("mindate"));
  }
  if (field.attr("maxdate")) {
    field.datepicker("option", "maxDate", field.attr("maxdate"));
  }
  field.datepicker("option", "changeMonth", true);
  field.datepicker("option", "changeYear", true);
  if (field.attr("yearrange")) {
    field.datepicker("option", "yearRange", field.attr("yearrange"));
  } else {
    field.datepicker("option", "yearRange", "-10:+0");
  }
}

function Input_Filter(e, input) {
  var key = e.keyCode;
  
  if (document.all) {
    shift = e.shiftKey;
    ctrl = e.ctrlKey;
  } else {
    shift = e.modifiers & Event.SHIFT_MASK;
    ctrl = e.modifiers & Event.CONTROL_MASK;
  }

  switch (key) {
    // navigation keys (tab, enter, esc, cursor, etc.)
    case 8: // backspace
    case 9: // tab
    case 13: // enter
    case 27: // esc
    case 33: case 34: // page up, page down
    case 35: case 36: // end, home
    case 37: case 38: case 39: case 40: // cursor keys
    case 45: case 46: // insert, delete
      return true;
      
    // editing keys (ctrl-c, v, x, z)
    case 67: case 86: case 88: case 90: 
      if (ctrl) { return true; }
  }
  
  
  switch (key) {
    // comma	
    case 188:			
      if (input == "float") { return true; }
      break;
    
    // period
    case 110: case 190:
      switch (input) { case "float": case "ip": return true; }
      break;

    // hyphen
    case 109: case 189:
      if (input == "zip") { return true; }
      break;
      
    // forward-slash
    case 111: case 191:
      if (input == "date") { return true; }
      break;

    // numerals
    case 48: case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: case 96: case 97: case 98: case 99: case 100: case 101: case 102: case 103: case 104: case 105: 
      if (shift) { return false; }
      switch (input) { case "digit": case "float": case "zip": case "date": case "ip": case "hex": case "vin": return true; }
      break;

    // alpha (a, b, c, d, e, f)
    case 65: case 66: case 67: case 68: case 69: case 70:
      switch (input) { case "alpha": case "vin": case "hex": case "zip": return true; }
      break;

    // alpha (i, o)
    case 73:  case 79:
      switch (input) { case "alpha": case "zip": return true; }
      break;
    
    // alpha (else)
    case 71: case 72: case 74: case 75: case 76: case 77: case 78: case 80: case 81: case 82: case 83: case 84: case 85: case 86: case 87: case 88: case 89: case 90:
      switch (input) { case "alpha": case "vin": case "zip": return true; }
      break;
      
    // space
    case 32:
      switch (input) { case "alpha": case "zip": return true; }
      break;
  }

  return false;
}

function Input_RestoreDefault(field) {
  if (field.value == "") field.value = field.defaultValue;
}

//========================================================================================================================
// Document Ready
//========================================================================================================================

$(function(){
  $("input:checked").addClass("checked");

  $("input[type='text'].default-value").focus(function(e){
    if (this.value == this.defaultValue) this.value = "";
  });

  $("input[type='text'].default-value").blur(function(e){
    var field = this;
    if ($(field).is(".input-year,.input-zip,.input-postal,.input-phone,.input-phoneext,.input-ssn")) {
      setTimeout(function(){ Input_RestoreDefault(field); }, 10);
    } else {
      Input_RestoreDefault(field);
    }
  });

  $("input[type='text'].input-digit").keydown(function(e){
    return Input_Filter(e, "digit");
  });
  
  $("input[type='text'].input-year").mask("9999");

  $("input[type='text'].input-float").keydown(function(e){
    return Input_Filter(e, "float");
  });

  $("input[type='text'].input-money").keydown(function(e){
    return Input_Filter(e, "float");
  });

  $("input[type='text'].input-pct").keydown(function(e){
    return Input_Filter(e, "float");
  });

  $("input[type='text'].input-zip").mask("99999?-9999");

  $("input[type='text'].input-postal").mask("a9a 9a9");

  $("input[type='text'].input-zippostal").keydown(function(e){
    return Input_Filter(e, "zip");
  });

  $("input[type='text'].input-date").keydown(function(e){
    return Input_Filter(e, "date");
  });

  $("input[type='text'].input-ip").keydown(function(e){
    return Input_Filter(e, "ip");
  });

  $("input[type='text'].input-phone").mask("(999) 999-9999");
  $("input[type='text'].input-phoneext").mask("(999) 999-9999? x99999");

  $("input[type='text'].input-ssn").mask("999-99-9999");

  $("input[type='text'].input-hex").keydown(function(e){
    return Input_Filter(e, "hex");
  });

  $("input[type='text'].input-rgb").keydown(function(e){
    return Input_Filter(e, "hex");
  });

  $("input[type='text'].input-alpha").keydown(function(e){
    return Input_Filter(e, "alpha");
  });

  $("input[type='text'].input-vin").keydown(function(e){
    return Input_Filter(e, "vin");
  });

  $("input[type='text'].input-vin").keydown(function(){
    Format_UpperCase($(this));
  }).keyup(function(){
    Format_UpperCase($(this));
  }).change(function(){
    Format_UpperCase($(this));
  }).blur(function(){
    Format_UpperCase($(this));
  });

  $("textarea[length]").each(function(){
    Format_MaxLength($(this));
  }).keydown(function(){
    Format_MaxLength($(this));
  }).keyup(function(){
    Format_MaxLength($(this));
  }).change(function(){
    Format_MaxLength($(this));
  }).blur(function(){
    Format_MaxLength($(this));
  });

  $("input[type=password]").focus(function(){
    if ($(this).val() == "[password]") { $(this).val(""); }
  });
  
  $("input[type='text'].input-date").datepicker({
    dateFormat :          "m/d/yy",
    showAnim :            ""
  }).each(function(){
    Input_DateConfig($(this));
  });

  $("input:input:checkbox").click(function(){
    $(this).toggleClass("checked");
  });

  $("input:radio").click(function(){
    gn = $(this).attr("name");
    $("input:radio[name='" + gn + "']").each(function(){
      $(this).toggleClass("checked", ($(this).attr("checked")));
    });
  });


  // Focus first field.  
  var highlight = true;
  if (_AppName == "Live") {
    highlight = (NoEdit === false);
  } else {
    highlight = (_NoEdit === false);
  }
  
  if (highlight) {
    if (gm("xClientSite") === undefined) {
      var inputs = null;
      if (gm("divContentFrame")) {
        inputs = $("#divContentFrame :input:not(button)");
      } else {
        inputs = $(":input:not(button)[id]");
      }

      for (i = 0; i < inputs.length; i++) {
        var input = inputs.eq(i);
        if (input.attr("type") != "hidden" && input.attr("readonly") !== true && !input.hasClass("read-only") && !input.hasClass("input-data")) {
          FieldFocus_Start(input);    
          break;
        }
      }
    }
  }
});
