// GENERAL VALIDATION

var errorcount = 0;

function validate() {  
  errorcount = 0;

  $(".file").each(function() {
    if(this.value != ""); {
      x = this.value.substr(this.value.lastIndexOf("."),4).toLowerCase();
      if ((x != ".gif") && (x != ".jpg") && (x != ".pdf")) {
	$("#error").html("Uploaded files must be a in GIF, JPG or PDF format.");
	$("#error").show();
	errorcount++;
      }
    }
  });

  $(".required.phone").each(function() {
    if(!checkPhone(this.value)) {
       $("#error").html("Please enter a valid phone number.");
       $("#error").show();
       errorcount++;
    } 
  });

  $(".required.email").each(function() {
    if(!echeck(this.value)) {
       $("#error").html("Please enter a valid e-mail address.");
       $("#error").show();
       errorcount++;
    } 
  });

  $("select.required").each(function() {
    if (this.selectedIndex == "0") {
      $("#error").html("Please select an item from the drop-down list.");
      $("#error").show();
      errorcount++;    
    }
  });

  $("input.required").each(function() {
    if (this.value == "") {
      $("#error").html("Please fill out all required fields.");
      $("#error").show();
      errorcount++;    
    }
  });

  if (errorcount == 0) {
    return true;
  }  else { 
    return false;
  }
}

// TELEPHONE VALIDATION

var digits = "0123456789";
var phoneNumberDelimiters = "()- ";
var minDigitsInIPhoneNumber = 10;

function isInteger(s) {   var i;
  for (i = 0; i < s.length; i++) {   
    var c = s.charAt(i);
      if (((c < "0") || (c > "9"))) return false;
  }
  return true;
}

function trim(s) {
  var i;
  var returnString = "";
  for (i = 0; i < s.length; i++) {   
    var c = s.charAt(i);
    if (c != " ") returnString += c;
  }
  return returnString;
}

function stripCharsInBag(s, bag) {
  var i;
  var returnString = "";
  for (i = 0; i < s.length; i++) {   
    var c = s.charAt(i);
    if (bag.indexOf(c) == -1) returnString += c;
  }
  return returnString;
}

function checkPhone(strPhone){
  var bracket=3
  strPhone=trim(strPhone)
  s=stripCharsInBag(strPhone,phoneNumberDelimiters);
  return (isInteger(s) && s.length >= minDigitsInIPhoneNumber);
}

//EMAIL VALIDATION

function echeck(str) {
  var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
  if (filter.test(str)) {
    return true;
  } else {
    return false;
  }
}

$(document).ready(function(){  
  $('#contact').bind('submit', validate)
});
