﻿$(document).ready(function() {
  var requiredTemplateMsg = $.validator.format("{0} is a required field.");
  var lessThanTemplateMsg = $.validator.format("{0} must be < than {1}.");
  var greaterThanTemplateMsg = $.validator.format("{0} must be > than {1}.");
  var rangeTemplateMsg = $.validator.format("The value for {0} must be between {1} and {2}.");
});

  function enforceType(type, className)
  {
    $(className).each(function() {

      $(this).keyup(function(e) {
      if ((e.keyCode != 37) && (e.keyCode != 39) && (e.keyCode != 46) && (e.keyCode != 8)) {
          if (type == 'integer') {
            $(this).val(getNumeric($(this).val()));
          }
          else if (type == 'decimal') {
            $(this).val(getFloat($(this).val()));
          }
        }
      });
    });
  }
  
  function addInputMask(type, className) {
    $.mask.definitions['~'] = '[0-9.]';

    if (type == 'decimal') {
      $(className).mask('?~~~~~~~~~~~', { placeholder: ' ' }).keydown(function(e) {
        if (e.keyCode == 190) {
          if ($(this).val().indexOf('.') > -1)
            e.preventDefault();
        }
        else if (e.keyCode == 32) e.preventDefault();
      });
    }

    else if (type == 'phone') {
      $(className).mask("(999) 999-9999");
    }

    else if (type == 'zip') {
      $(className).mask("99999?-9999").keydown(function(e) {
        if (e.keyCode == 32) e.preventDefault();
      });
    }

    else if (type == 'integer') {
      $(className).mask('?999999999', { placeholder: ' ' }).keydown(function(e) {
        if (e.keyCode == 32) e.preventDefault();
      });
    }
    
    else if (type == 'url') {
      $(className).blur(function() {
        var newVal = $.trim($(className).val().toLowerCase());
        if (newVal.length <= 7 || newVal.substring(0, 7) != 'http://') {
          $(className).val("");
          $(className).removeClass("error");
        }
      });
      $(className).focus(function() {
        var newVal = $.trim($(className).val().toLowerCase());
        if (newVal == "")
          $(className).val('http://');
      });
    }
  }

  function getNumeric(str) {   
    return str.replace(/[^0-9]/g,"");  
  }

  function getFloat(str) {
    if (str != null) {
      var mtch = str.match(/[.]/g);
      var pts = 0;
      if (mtch != null)
        pts = mtch.length;
      
      while (pts > 1) {
        var idx = str.indexOf('.');
        str = str.substring(0, idx) + str.substring(idx+1, 100);
        pts--;
      } 
    }      
    return str.replace(/[^0-9.]/g,"");  
  }


function initValidation() {
  // Initialize validation on the entire ASP.NET form.

  var theForm = $("form:first");
  if (theForm != null) {
    $(theForm).validate({
      onkeyup : false,
      errorPlacement: function(error, element) { },
      onsubmit: false
    });
  }

  // Search for controls marked with the causesValidation flag 
  //  that are contained anywhere within elements marked as 
  //  validationGroups, and wire their click event up.
  $('.validationGroup .causesValidation').click(Validate);

  // Select any input[type=text] elements within a validation group
  //  and attach keydown handlers to all of them.
  $('.validationGroup :text').keydown(function(evt) {
    // Only execute validation if the key pressed was enter.
    if (evt.keyCode == 13) {
      // Find and store the next input element that comes after the
      //  one in which the enter key was pressed.
      var $nextInput = $(this).nextAll(':input:first');
      // If the next input is a submit button, go into validation.
      //  Else, focus the next form element as if enter == tab.
      if ($nextInput.is(':submit')) {
        Validate(evt);
      }
      else {
        evt.preventDefault();
        $nextInput.focus();
      }
    }
  });
}

function Validate(evt) {
  // Ascend from the button or input element that triggered the 
  //  event until we find a container element flagged with 
  //  .validationGroup and store a reference to that element.
  var $group = $(this).parents('.validationGroup');
  var $nonRequiredGrp = $group.find(":text:enabled:not(.required)");
  var $requiredGrp = $group.find(":text.required");
  var isValid = true;

  // Descending from that .validationGroup element, find any input
  //  elements within it, iterate over them, and run validation on 
  //  each of them.
  $requiredGrp.each(function(i, item) {
    if (!$(item).valid()) {
      isValid = false;
    //  alert(item.id);
    }
  });

  $nonRequiredGrp.each(function(i, item) {
    if ($(item).val() != "" && !$(item).valid()) {
      isValid = false;
    }
  });

  // If any fields failed validation, prevent the button's click 
  //  event from triggering form submission.
  if (!isValid)
    evt.preventDefault();

  var toperror = $('input.error:first');
  if (toperror.length > 0)
    $(toperror).trigger('focus');  
}

