/*~ worxvalidate.js.php
.---------------------------------------------------------------------------.
|  Software: Worx Form Validator/Submit                                     |
|   Version: 0.1                                                            |
|   Contact: codeworxtech@users.sourceforge.net                             |
|      Info: http://phpmailer.codeworxtech.com                              |
| ------------------------------------------------------------------------- |
|    Author: Andy Prevost andy.prevost@worxteam.com (admin)                 |
| Copyright (c) 2002-2009, Andy Prevost. All Rights Reserved.               |
| ------------------------------------------------------------------------- |
|   License: Proprietary license for use solely by codeworxtech.com         |
| This program is NOT distributed and WITHOUT ANY WARRANTY; without even    |
| the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR       |
| PURPOSE.                                                                  |
| ------------------------------------------------------------------------- |
| We offer a number of paid services:                                       |
| - Web Hosting on highly optimized fast and secure servers                 |
| - Technology Consulting                                                   |
| - Oursourcing (highly qualified programmers and graphic designers)        |
'---------------------------------------------------------------------------'
Last updated: May 31 2009 20:47 EST

/**
 * Worx Form Validator/Submit
 * @package Worx Form Validator/Submit
 * @author Andy Prevost
 * @copyright 2008 Andy Prevost
 *
 * Worx Form Validator/Submit is a multi-purpose javascript tool. In order
 * of processing, the features are (when the submit button is pressed):
 *   - checks the status of the class tag and if set to "required" makes
 *     the field required. If a required field is empty, the field will
 *     gain focus and form is not submitted
 *   - disables the Submit and Reset button (prevents multiple submissions)
 *   - submits the form
 * There is also functionality when leaving a field: the field can have
 * numeric based "masking". Good for phone numbers, social security numbers,
 * social insurance numbers, zip codes, dates, and other numeric inputs.
 *
 * Worx Form Validator/Submit is as unobtrusive as possible. When combined
 * with CSS, required fields are set with a unique background color. When
 * required fields are empty, the form is not submitted (and no data loss
 * occurs) and the empty field is set to focus.
 *
 * Please review the enclosed article for a complete explanation of the
 * strategy behind this script.
 */

// set the "action" of your form here - hides your form action and less like to get form hijacked
//var action = "phpmailer-fe.php"; // comment this after your complete your testing
var action = ''; // comment this after your complete your testing
// var action = "virtual/path/to/phpmailer-fe.php"; // uncomment this after you complete your testing

var requiredClassName = "required"; // first element of a class that triggers whether the field is required or not

/* FUNCTIONS */

function validateForm(wrxForm) {
  // you can insert any form validation here

  var e         = wrxForm.elements;
  var param     = '';
  var ptype     = 'jpg,jpeg,gif,png,txt,doc,pdf,rtf,zip,gz,rar,tar';
  var tequal    = '';
  var allPassed = true;
  var last_id   = 9999;

  var allTags   = document.getElementsByTagName("*");
  for ( var elem, i = 0; ( elem = e[i] ); i++ ) {
    talt   = '';
    tequal = '';
    if ( elem.id != '' && elem.type != 'hidden' ) {
      if ( param == '' ) {
        param = elem.id + ':';
      } else {
        param += ',' + elem.id + ':';
      }
      var mySplitResult = elem.className.split(' ');
      if (mySplitResult.length > 1) {
        talt = mySplitResult[mySplitResult.length - 1];
        talt = talt.replace(/\_/g,' ');
      }
      if ( talt != '' ) {
        var mySplitResult = talt.split('|=');
        if (mySplitResult.length > 1) {
          talt   = mySplitResult[0];
          tequal = mySplitResult[1];
        }
        param += talt + ':';
      } else {
        param += elem.id + ':' + 'NIL' + ':';
      }
      if ( elem.className.search(/required/i) >= 0 ) {
        param += '1';
      } else {
        param += '0';
      }
      if ( tequal != '' ) {
        param += ':' + tequal;
      }
    } else { //only valid if this is a type file
      var mySplitResult = elem.className.split(' ');
      if (mySplitResult.length > 1) {
        talt = mySplitResult[mySplitResult.length - 1];
        talt = talt.replace(/\_/g,' ');
      }
    }
  }

  // check for regexp support
  if (is_regex_supported()==false) {
    return true;
  }

  // split into fields
  field_params  = param.split(",");

  error_flag    = false;
  error_message = "";
  radioproc = -1;
  for(i=0; i<field_params.length; i++) {
    current_param = trim(field_params[i]);

    // get the individual parameters
    parameters     = current_param.split(":");
    param_id       = trim(parameters[0]);
    param_title    = trim(parameters[1]);
    param_title    = param_title.replace(/\_/g,' ');
    param_type     = trim(parameters[2]);
    param_required = '0';
    var tempSplitResult = document.getElementById(param_id).className.split(' ');
    param_class   = tempSplitResult[0];
    match_class   = trim(param_class.toLowerCase());
    match_text    = match_class.substring(0,8);
    if (match_text == "required") {
      param_required = '1';
    }
    if (parameters[4]) {
      param_equalto  = trim(parameters[4]);
    } else {
      param_equalto  = "";
    }
    //name_class    = document.getElementById(param_id).className;

    var tempSplitResult = document.getElementById(param_id).className.split(' ');
    param_class   = tempSplitResult[0];

    // get the type of the field
    current_obj = get_object(param_id);
    obj_type    = current_obj.type.toLowerCase();
    if ( obj_type != "checkbox" && obj_type != "radio" ) {
      obj_value   = get_value_of(param_id);
      obj_value   = obj_value.replace("\"", "``");
      obj_value   = obj_value.replace("\'", "`" );
      // input object value (text and textarea) security
      obj_value   = obj_value.replace(/</g, "&lt;").replace(/>/g, "&gt;");
      // END input object value (text and textarea) security
    } else if ( obj_type == "radio" ) {
      if (last_id != param_id) {
        obj_value = getRadioValue(wrxForm,param_id,last_id);
        last_id = param_id;
        radioproc = i;
      }
    } else if ( obj_type == "checkbox" ) {
      obj_value   = document.getElementById(param_id).checked;
    }

    // Error messages
    error_message_title     = "Form not submitted, errors:";
    error_message_hlink     = "\n- " + param_title + " (url not allowed)";
    error_message_invalid   = "\n- Invalid " + param_title;
    error_message_mismatch  = "\n- " + param_title + ", does not match";
    if (obj_type=="text" || obj_type=="textarea" || obj_type=="password" || obj_type=="hidden" || obj_type == "checkbox") {
      error_message_required = "\nRequired: " + param_title;
    } else {
      //if ( radioproc <= 0 ) {
        error_message_required = "\nRequired: " + param_title;
      //}
    }

    // validate the file extension if the object is type "file"
    if ( obj_type == "file" && document.getElementById(param_id).value != '') {
      allowSubmit = false;
      if ( trim(ptype) == '' ) {
        var extArray = new Array('zip','gz','rar','tar');
      } else {
        var extArray = ptype.split(',');
      }
      if (mySplitResult.length > 1) {
        talt   = mySplitResult[0];
        tequal = mySplitResult[1];
      }
      var filename = document.getElementById(param_id).value;
      var fileext  = filename.substring(filename.lastIndexOf('.')+1);
      var error_message_type = "\n- File type '" + fileext + "' not allowed";
      for(z=0; z < extArray.length; z++) {
        if ( extArray[z] == fileext ) {
          allowSubmit = true;
          break;
        }
      }
      if (!allowSubmit) {
        allPassed  = false;
        error_flag = true;
        error_message += error_message_type;
      }
    }

    // if the field is required
    if (param_required=="1" && obj_value=="") {
      allPassed  = false;
      error_flag = true;
      //if ( error_message.search(trim(param_title)) == -1 ) {
      if ( error_message.search(param_title) == -1 ) {
        error_message += error_message_required;
      }
    }

    /*
    if (param_type != nil)
      if (param_type != "url" && param_type != "password" && obj_value.length > 0) {
        badPos1 = obj_value.search(/http/i);
        badPos2 = obj_value.search(/www/i);
        badPos3 = obj_value.search(/href/i);
        badPos4 = obj_value.search(/<a/i);
        if ( badPos1 != -1 || badPos2 != -1 || badPos3 != -1 || badPos4 != -1 ) {
          allPassed  = false;
          error_flag     = true;
          error_message  = error_message_hlink;
        }
      }
    }
    */

    // type checking
    if (param_type!="NIL" && obj_value!="") {
      switch(param_type) {
        case 'numeric':
          func_str = 'numeric';
          break;
        case 'phone':
          func_str = 'phone';
          break;
        case 'string':
          func_str = 'string';
          break;
        case 'alphabet':
          func_str = 'alphabet';
          break;
        case 'email':
          func_str = 'email';
          break;
        case 'zip':
          func_str = 'zip';
          break;
        case 'postal':
          func_str = 'postal';
          break;
        case 'url':
          func_str = 'url';
          break;
        case 'DAT':
          func_str = 'date';
          break;
        case 'password':
          func_str = 'password';
          break;
        case 'text':
          func_str = 'text';
          break;
        default:
          func_str = 'text';
          break;
      }

      obj_value = obj_value.replace(/\n/g, '');
      obj_value = obj_value.replace(/\r/g, '');
      function_call_str = "validate_" + func_str + "(\"" + obj_value + "\")";
      validation_result = eval(function_call_str);
      if (validation_result==false) {
        allPassed  = false;
        error_flag     = true;
        error_message += error_message_invalid;
      }
    }

    // equality checking
    if (param_equalto!="" && obj_value!="") {
      value2 = get_value_of(param_equalto);
      if ( value2 != obj_value ) {
        allPassed  = false;
        error_flag     = true;
        error_message += error_message_mismatch;
      }
    }
  }

  if (error_flag) {
    alert(error_message_title + error_message + "\n");
  }

  for (var i=0; i<allTags.length; i++) {
    if (!validTag(allTags[i])) {
      allPassed = false;
    }
  }
  if ( allPassed === true ) {
    submitForm(wrxForm);
  } else {
    return allPassed;
  }

  function validTag(thisTag) {
    var outClass = "";
    var allClasses = thisTag.className.split(" ");

    for (var j=0; j<allClasses.length; j++) {
      outClass += validBasedOnClass(allClasses[j]) + " ";
    }

    thisTag.className = outClass;

    if (outClass.indexOf("invalid") > -1) {
      thisTag.focus();
      if (thisTag.nodeName == "INPUT") {
        thisTag.select();
      }
      return false;
    }
    return true;

    function validBasedOnClass(thisClass) {
      var classBack = "";

      switch(thisClass) {
        case "":
        case "invalid":
          break;
        case "required":
          if ( allPassed && ( thisTag.value == "" || thisTag.value == "Type your message here" ) ) {
            classBack = "invalid ";
          }
          classBack += thisClass;
          break;
        default:
          classBack += thisClass;
      }
      return classBack;
    }
  }
  // END

}

function validate_numeric(number) {
  /*
  if (isNaN(number)) {
    return false;
  } else {
    return true;
  }
  */
  pattern = '/^(|[0-9]+)$/';
  var regex = new RegExp(pattern);
  return regex.test(number);
}

function validate_phone(str) {
  var regex = new RegExp(/^(|([\(\). -]*[0-9]{1}[\(\). -]*){10,})$/);
  return regex.test(str);
}

function validate_string(str, pattern) {
  if (!pattern) {
    pattern = '^[a-zA-Z0-9\-\., ]*$';
  }
  var regex = new RegExp(pattern);
  return regex.test(str);
}

function validate_alphabet(str) {
  pattern = "/^(|[a-zA-Z]+)$/";
  var regex = new RegExp(pattern);
  return regex.test(str);
}

/*
function validate_text(str, pattern) {
  if (!pattern) {
    pattern = '^[a-zA-Z0-9\-\., ]*$';
    //
    pattern = "^[a-zA-Z0-9\-.; ]*$";
  }
  var regex = new RegExp(pattern);
  return regex.test(str);
}
*/

function validate_text(str) {
  //pattern = '^[a-zA-Z0-9\-\., ]*$';
  //pattern = '^[a-zA-Z0-9\-\., ]*$';
  pattern = '^[a-zA-Z0-9\-\_\.,:; ]*$';
  var regex = new RegExp(pattern);
  return regex.test(str);
}

function validate_zip(str) {
  regex = new RegExp(/(^\d{5}$)|(^\d{5}-\d{4}$)/);
  if (!regex.test(str)) {
    return false;
  } else {
    return true;
  }
}

function validate_postal(str) {
  //pattern   = "/^[a-zA-Z][0-9][a-zA-Z] ?[0-9][a-zA-Z][0-9]$/";
  //var regex = new RegExp(pattern);
  //return regex.test(str);
  regex = new RegExp(/^[a-zA-Z][0-9][a-zA-Z] ?[0-9][a-zA-Z][0-9]$/);
  if (!regex.test(str)) {
    return false;
  } else {
    return true;
  }
}

function validate_email(email) {
  var regex = new RegExp(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/);
  r =  regex.test(email);
  return r;
}

function validate_date(date) {
  date_parts = date.split("-");
  date_year  = parseInt(parseFloat(date_parts[0]));
  date_month = parseInt(parseFloat(date_parts[1]));
  date_day   = parseInt(parseFloat(date_parts[2]));
  if (isNaN(date_year) || isNaN(date_month) || isNaN(date_day) || date_year==0 || date_month==0 || date_day==0) {
    return false;
  }
  day_limits = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
  // if leap year
  if (date_year%4==0) {
    day_limits[1] = 29;
  }
  if (date_month>12) {
    return false;
  }
  if (date_day > day_limits[date_month-1]) {
    return false;
  }
  return true;
}

function validate_password(pass) {
  //pattern   = "/^(|[a-zA-Z0-9_].{4,})$/";
  //Tests if the input consists of 6 or more letters, digits, underscores and hyphens.
  //The input must contain at least one upper case letter, one lower case letter and one digit.
  //pattern   = '\A(?=[-_a-zA-Z0-9]*?[A-Z])(?=[-_a-zA-Z0-9]*?[a-z])(?=[-_a-zA-Z0-9]*?[0-9])[-_a-zA-Z0-9]{6,}\z';
  pattern   = '/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6}$/';
  var regex = new RegExp(pattern);
  r =  regex.test(pass);
  return r;
}

function validate_url(url) {
  pattern    = '^([a-zA-z0-9]{2,})(-([a-zA-Z0-9]+))*$';
  var regex = new RegExp(pattern);
  if ( regex.test(url) ) {
    return false;
  } else {
    return true;
  }
}

function is_regex_supported() {
  var supported = false;
  if (window.RegExp) {
    var tempStr = "a";
    var tempReg = new RegExp(tempStr);
    if (tempReg.test(tempStr)) supported = true;
  }
  return supported;
}

function get_value_of(id) {
  obj  = get_object(id);
  type = obj.type;
  val  = "";
  if (type=='text' || type=='textarea' || type=='password' || type=='hidden') {
    val = obj.value;
  } else if (type=='select-one') {
    val = obj.options[obj.selectedIndex].value;
  //} else if ( type=='radio' ) {
  //} else if ( type=="checkbox" ) {
    //val = document.getElementById(id).checked;
    //val = document.getElementById("Signature").checked;
  } else {
    if (obj.length) {
      for(j=0; j<obj.length; j++) {
        if (obj[j].checked) {
          val = obj[j].value;
        }
      }
    } else {
      if (obj.checked) {
        val = obj.value;
      }
    }
  }
  return trim(val);
}

function get_object(id) {
  if (document.getElementById(id)) {
    return document.getElementById(id);
  } else if (document.getElementsByName(id)) {
    objs = document.getElementsByName(id);
    if (objs.length) {
      return objs;
    } else {
      return objs[0];
    }
  }
}

function getRadioValue(obForm, radioObj,currid,lastid) {
  if (currid == lastid) {
    return;
  }
  var el = obForm.elements;
  for( var i = 0 ; i < el.length ; ++i ) {
    if( el[i].type == "radio" && el[i].name == radioObj ) {
      var radiogroup = el[el[i].name]; // get the whole set of radio buttons.
      var itemchecked = false;
      for( var j = 0 ; j < radiogroup.length ; ++j ) {
        if( radiogroup[j].checked ) {
          itemchecked = true;
          itemvalue   = radiogroup[j].value;
          break;
        }
      }
      if( !itemchecked ) {
        return false;
      } else {
        return itemvalue;
      }
    }
  }
}

function trim (str) {
  var str = str.replace(/^\s\s*/, ''),
      ws = /\s/,
      i = str.length;
  while (ws.test(str.charAt(--i)));
  return str.slice(0, i + 1);
}

/*
function trim(str) {
  if (str!='') {
    return str.replace(/^\s*|\s*$/g, '');
  } else {
    return str;
  }
}
*/

function disableForm(wrxForm) {
  if (document.all || document.getElementById) {
    for (i = 0; i < wrxForm.length; i++) {
      var tempobj = wrxForm.elements[i];
      if (tempobj.type.toLowerCase() == 'submit' || tempobj.type.toLowerCase() == 'reset') {
        tempobj.disabled = true;
      }
    }
  }
}

/*
 * [worxFilter] - A Numerical Input Mask for JavaScript
 * by Andy Prevost, http://www.codeworxtech.com/
 */

var worxFilterStep

function worxFilterStrip (worxFilterTemp, worxFilterMask) {
  worxFilterMask = replace(worxFilterMask,'#','');
  for (worxFilterStep = 0; worxFilterStep < worxFilterMask.length++; worxFilterStep++) {
    worxFilterTemp = replace(worxFilterTemp,worxFilterMask.substring(worxFilterStep,worxFilterStep+1),'');
  }
  return worxFilterTemp;
}

function worxFilterMax (worxFilterMask) {
  worxFilterTemp = worxFilterMask;
  for (worxFilterStep = 0; worxFilterStep < (worxFilterMask.length+1); worxFilterStep++) {
    if (worxFilterMask.charAt(worxFilterStep)!='#') {
      worxFilterTemp = replace(worxFilterTemp,worxFilterMask.charAt(worxFilterStep),'');
    }
  }
  return worxFilterTemp.length;
}

function worxFilter (key, textbox, worxFilterMask) {
  worxFilterNum = worxFilterStrip(textbox.value, worxFilterMask);
  if (key==9) { //tab
    return true;
  } else if (key==8 && worxFilterNum.length!=0) { //backspace
    worxFilterNum = worxFilterNum.substring(0,worxFilterNum.length-1);
  } else if ( ((key>47&&key<58)||(key>95&&key<106)) && worxFilterNum.length<worxFilterMax(worxFilterMask) ) { //numbers
    if (key>=96&&key<=105) { key = key - 48 ;}
    worxFilterNum=worxFilterNum+String.fromCharCode(key);
  }

  var worxFilterFinal='';
  for (worxFilterStep = 0; worxFilterStep < worxFilterMask.length; worxFilterStep++) {
    if (worxFilterMask.charAt(worxFilterStep)=='#') {
      if (worxFilterNum.length!=0) {
        worxFilterFinal = worxFilterFinal + worxFilterNum.charAt(0);
        worxFilterNum = worxFilterNum.substring(1,worxFilterNum.length);
      } else {
        worxFilterFinal = worxFilterFinal + "";
      }
    } else if (worxFilterMask.charAt(worxFilterStep)!='#') {
      worxFilterFinal = worxFilterFinal + worxFilterMask.charAt(worxFilterStep);
    }
  }
  textbox.value = worxFilterFinal;
  return false;
}

function replace(fullString,text,by) {
  var strLength = fullString.length, txtLength = text.length;
  if ((strLength == 0) || (txtLength == 0)) {
    return fullString;
  }
  var i = fullString.indexOf(text);
  if ((!i) && (text != fullString.substring(0,txtLength))) {
    return fullString;
  }
  if (i == -1) {
    return fullString;
  }
  var newstr = fullString.substring(0,i) + by;
  if (i+txtLength < strLength) {
    newstr += replace(fullString.substring(i+txtLength,strLength),text,by);
  }
  return newstr;
}

/*
 * support functions
 * by Andy Prevost, http://www.codeworxtech.com/
 */

function submitForm(wrxForm) {
  disableForm(wrxForm);    // disable submit and reset buttons
  /*
  wrxForm.action = action; // reset the action of the form
  */
  wrxForm.submit();        // submit the form
  return true;             // return true status
}

function initForms() {
  for (var i=0; i< document.forms.length; i++) {
    document.forms[i].onsubmit = function() { return validateForm(this); }
  }
}

function focusCursor() {
  for (var i = 0; i < document.forms.length; ++i) {
    var f = document.forms[i];
    for (var j = 0; j < f.elements.length; ++j) {
      if (f.elements[j].type == 'text' || f.elements[j].type == 'textarea') {
        f.elements[j].focus();
        return;
      }
    }
  }
}

function centerScreen() {
  var xMax = screen.width, yMax = self.screen.availHeight;
  if (document.body.clientWidth) {
    lnBodyClientWidth=document.body.clientWidth
    lnBodyClientHeight=document.body.clientHeight
  } else {
    lnBodyClientWidth=window.innerWidth
    lnBodyClientHeight=window.innerHeight
  }
  xOffset = (xMax - lnBodyClientWidth)/2, yOffset = (yMax -
  lnBodyClientHeight)/2;
  self.moveTo(xOffset,yOffset)
}

/*
 * LOAD WITH THE SCRIPT CALL - DO NOT REMOVE THIS
 *
 * This next code snippet is what displays the form, sets up the form to use
 * the checks for required fields. Once the required fields tests are met,
 * this will disable the submit and reset buttons, and submit the form.
 */

window.onload = function() {
  /*
  document.getElementById("worxFormDiv").style.display="block";
  centerScreen()
  */
  initForms();
  focusCursor();
}

