//The first line assigns the MatchIgnoreCase function as an equalsIgnoreCase method of the String object  
String.prototype.equalsIgnoreCase=MatchIgnoreCase;
function MatchIgnoreCase(strTerm){
  var strToSearch = this.toLowerCase();
  strTerm = strTerm.toLowerCase();
  return strToSearch == strTerm;
} //End Function

function trim(inputString) {
   // Removes leading and trailing spaces from the passed string. Also removes
   // consecutive spaces and replaces it with one space. If something besides
   // a string is passed in (null, custom object, etc.) then return the input.
   if (typeof inputString != "string") { return inputString; }
   var retValue = inputString;
   var ch = retValue.substring(0, 1);
   while (ch == " ") { // Check for spaces at the beginning of the string
      retValue = retValue.substring(1, retValue.length);
      ch = retValue.substring(0, 1);
   }
   ch = retValue.substring(retValue.length-1, retValue.length);
   while (ch == " ") { // Check for spaces at the end of the string
      retValue = retValue.substring(0, retValue.length-1);
      ch = retValue.substring(retValue.length-1, retValue.length);
   }
   while (retValue.indexOf("  ") != -1) { // Note that there are two spaces in the string - look for multiple spaces within the string
      retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, retValue.length); // Again, there are two spaces in each of the strings
   }
   return retValue; // Return the trimmed string back to the user
} // Ends the "trim" function


function checkLinkTitle(){
  var linkTextBox = document.getElementById('linkTitle');
  var linkText = linkTextBox.value;
  var linkTitleCheck = document.getElementById('linkTitleCheck');
  var linkTitleError = document.getElementById('linkTitleError');
  if (linkText == "" || linkText == undefined) {
    linkTitleCheck.innerHTML = "<img src='/images/exclamation.jpg' width='14' height='14' />";
    linkTitleError.innerHTML = "<span class='error'>Link title cannot be empty</span>";
    linkTextBox.className="errorBox";
    return false;
  }
  var words = linkText.split(" ");
  if(words.length > 8) {
    linkTitleCheck.innerHTML = "<img src='/images/exclamation.jpg' width='14' height='14' />";
    linkTitleError.innerHTML = "<span class='error'>The title cannot exceed 8 words</span>";
    linkTextBox.className="errorBox";
    return false;
  }
  var resultString = "";
  for (var i = 0, length = words.length; i < length; i++){
    var word = words[i];
    if (i != 0 && ( "and".equalsIgnoreCase(word) || "a".equalsIgnoreCase(word) || "the".equalsIgnoreCase(word))) {
      resultString += word;
    }
    else {
      resultString += word.substring(0, 1).toUpperCase() + word.substring(1, word.length).toLowerCase();
    }
    if (i + 1 < length) {
      resultString += " ";
    }
  }
  linkTextBox.value = resultString;
  linkTitleCheck.innerHTML = "<span class='success'>OK.</span>";
  linkTitleError.innerHTML = "&nbsp;";
  linkTextBox.className="forms";
  return true;
}

function changeLinkTypeText(radioButton, linkType) {
  var textBox = document.getElementById('linkTypeText');
  if (radioButton.value == "partner") {
    textBox.innerHTML = "Premium listings will appear in bold above all free listings (search engines give more weight to the links closer to the top). We allow linking to an individual page on your site. All premium submissions are reviewed within 12 hours. If your listing is not accepted into our directory you will be given a full refund. We are actively promoting Web Directory Y, so your listings would get exposure.";
  }
  if (radioButton.value == "regular") {
    if ( linkType == 0 ){
      textBox.innerHTML = "There is no guaranteed review time for free listings. We recommend that you place a premium listing, as sites placed for free in our directory could be moved down later on or broken down into pages. Premium listings will always appear at the top and won't be broken down into individual pages within a category. We are actively promoting our directory, so that your listings would get exposure.";
    }
    else {
      textBox.innerHTML = "Text for regular links goes here.";
    }
  }
  return;
}

function isValidProtocol(protocol) {
  if (protocol == undefined || protocol == "") {
    return false;
  }
  if(protocol == "http" || protocol == "https") {
    return true;
  }
  return false;
}


function checkValidUrl(url, urlError, urlTextErrorBox, required) {
  var urlTextCheck = document.getElementById(urlError);
  var urlTextError = document.getElementById(urlTextErrorBox);
  url.value = trim(url.value);
  
  if(required == false && (url.value.length == 0 || trim(url.value) == "http://")) {
    urlTextCheck.innerHTML = "<span>&nbsp;</span>";
    url.className = "forms";
    urlTextError.innerHTML = "&nbsp;";
    return true;
  }

  var urlStr = url.value;
  var checkTLD=1;
  var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
  var urlPat=/^(.+)\:\/\/(.+)$/;
  var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
  var validChars="\[^\\s" + specialChars + "\]";
  var quotedUser="(\"[^\"]*\")";
  var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
  var atom=validChars + '+';
  var word="(" + atom + "|" + quotedUser + ")";
  var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
  var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
  var matchArray = urlStr.match(urlPat);
  if (matchArray == null) {
    urlTextCheck.innerHTML = "<img src='/images/exclamation.jpg' width='14' height='14' />";
    url.className = "errorBox";
    urlTextError.innerHTML = "<span class='error'>You have entered an invalid url.</span>";
    return false;
  }
  var protocol = matchArray[1];
  var domain = matchArray[2];
  if (!isValidProtocol(protocol)) {
    urlTextCheck.innerHTML = "<img src='/images/exclamation.jpg' width='14' height='14' />";
    url.className = "errorBox";
    urlTextError.innerHTML = "<span class='error'>Unknown protocol.</span>";
    return false;
  }
  
  for (i=0; i<domain.length; i++) {
    if (domain.charCodeAt(i)>127) {
      urlTextCheck.innerHTML = "<img src='/images/exclamation.jpg' width='14' height='14' />";
      url.className = "errorBox";
      urlTextError.innerHTML = "<span class='error'>The domain name contains invalid characters.</span>";
      return false;
    }
  }
  
  var IPArray=domain.match(ipDomainPat);
    if (IPArray!=null) {
      for (var i=1;i<=4;i++) {
        if (IPArray[i]>255) {
          urlTextCheck.innerHTML = "<img src='/images/exclamation.jpg' width='14' height='14' />";
          url.className = "errorBox";
          urlTextError.innerHTML = "<span class='error'>Destination IP address is invalid!</span>";
          return false;
        }
      }
      urlTextCheck.innerHTML = "<span class='success'>OK.</span>";
      url.className = "forms";
      urlTextError.innerHTML = "&nbsp;";
      return true;
    }
  var atomPat=new RegExp("^" + atom + "$");
  var domArr=domain.split(".");
  var len=domArr.length;
  for (i=0;i<len;i++) {
    if (domArr[i].search(atomPat)==-1) {
      urlTextCheck.innerHTML = "<img src='/images/exclamation.jpg' width='14' height='14'/>";
      url.className = "errorBox";
      urlTextError.innerHTML = "<span class='error'>&nbsp;The domain name does not seem to be valid.</span>";
      return false;
    }
  }
  if (checkTLD && domArr[domArr.length-1].length!=2 && 
    domArr[domArr.length-1].search(knownDomsPat)==-1) {
      urlTextCheck.innerHTML = "<img src='/images/exclamation.jpg' width='14' height='14'/>";
      url.className = "errorBox";
      urlTextError.innerHTML = "<span class='error'>The url must end in a well-known domain or two letter country.</span>";
      return false;
  }
  if (len < 2) {
    urlTextCheck.innerHTML = "<img src='/images/exclamation.jpg' width='14' height='14' />";
    url.className = "errorBox";
    urlTextError.innerHTML = "<span class='error'>This url is missing a hostname!</span>";
    return false;
  }
  urlTextCheck.innerHTML = "<span class='success'>OK.</span>";
  url.className = "forms";
  urlTextError.innerHTML = "&nbsp;";
  return true;
}

function checkDescription(textAreaField) {
  var text = textAreaField.value;
  var descriptionCheck = document.getElementById('descriptionAreaCheck');
  var descriptionAreaError = document.getElementById('descriptionAreaError');
  
  if (text == undefined || text =="") {
    descriptionCheck.innerHTML = "<img src='/images/exclamation.jpg' width='14' height='14' />";
    descriptionAreaError.innerHTML = "<span class='error'>Description Field cannot be empty.</span>";
    textAreaField.className = "errorBox";
    return false;
  }
  if(text.length > 1000) {
    descriptionCheck.innerHTML = "<img src='/images/exclamation.jpg' width='14' height='14' />";
    descriptionAreaError.innerHTML = "<span class='error'>Your description has exceeded 1000 characters, please reduce the number of words in the description.</span>";
    textAreaField.className = "errorBox";
    return false;
  }
  descriptionCheck.innerHTML = "<span class='success'>OK.</span>";
  descriptionAreaError.innerHTML = "&nbsp;";
  textAreaField.className = "forms";
  return true;
}

function checkEmail() {
  var emailField = document.getElementById('emailText');
  var emailCheck = document.getElementById('emailCheck');
  var emailError = document.getElementById('emailError');

  return validateEmail(emailField, emailCheck, emailError);
}

function validateEmail(emailField, emailError, emailCheck) {
  var emailStr = emailField.value;
  var checkTLD=1;
  var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
  var emailPat=/^(.+)@(.+)$/;
  var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
  var validChars="\[^\\s" + specialChars + "\]";
  var quotedUser="(\"[^\"]*\")";
  var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
  var atom=validChars + '+';
  var word="(" + atom + "|" + quotedUser + ")";
  var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
  var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
  var matchArray=emailStr.match(emailPat);
  if (matchArray==null) {
    setErrorMessage(emailField, emailError, "You have entered an invalid email address.");
    emailCheck.innerHTML = exclamationImage;
    return false;
  }
  var user=matchArray[1];
  var domain=matchArray[2];
  for (i=0; i<user.length; i++) {
    if (user.charCodeAt(i)>127) {
      emailCheck.innerHTML = exclamationImage;
      setErrorMessage(emailField, emailError, "The username contains invalid characters.");
      return false;
    }
  }
  for (i=0; i<domain.length; i++) {
    if (domain.charCodeAt(i)>127) {
      emailCheck.innerHTML = exclamationImage;
      setErrorMessage(emailField, emailError, "The domain name contains invalid characters.");
      return false;
    }
  }
  if (user.match(userPat)==null) {
    emailCheck.innerHTML = exclamationImage;
    setErrorMessage(emailField, emailError, "The username doesn't seem to be valid.");
    return false;
  }
  var IPArray=domain.match(ipDomainPat);
    if (IPArray!=null) {
      for (var i=1;i<=4;i++) {
        if (IPArray[i]>255) {
          emailCheck.innerHTML = exclamationImage;
          setErrorMessage(emailField, emailError, "Destination IP address is invalid!");
          return false;
        }
      }
      setErrorMessage(emailField, emailError, "");
      setSuccessMessage(emailCheck, "OK");
      return true;
    }
  var atomPat=new RegExp("^" + atom + "$");
  var domArr=domain.split(".");
  var len=domArr.length;
  for (i=0;i<len;i++) {
    if (domArr[i].search(atomPat)==-1) {
      emailCheck.innerHTML = exclamationImage;
      setErrorMessage(emailField, emailError, "The domain name does not seem to be valid.");
      return false;
    }
  }
  if (checkTLD && domArr[domArr.length-1].length!=2 && 
    domArr[domArr.length-1].search(knownDomsPat)==-1) {
      emailCheck.innerHTML = exclamationImage;
      setErrorMessage(emailField, emailError, "The address must end in a well-known domain or two letter country.");
      return false;
  }
  if (len<2) {
    emailCheck.innerHTML = exclamationImage;
    setErrorMessage(emailField, emailError, "This address is missing a hostname!");
    return false;
  }
  setSuccessMessage(emailCheck, "OK");
  setErrorMessage(emailField, emailError, "");
  return true;
}

function checkImage() {
  var image = document.getElementById('imageTextBox');
  var imageCheck = document.getElementById('imageCheck');
  var imageError = document.getElementById('imageError');
  var imageStr = image.value;
  if ( imageStr == undefined || imageStr.length == 0) {
    image.className = "errorBox";
    imageCheck.innerHTML = "<img src='/images/exclamation.jpg' width='14' height='14' />";
    imageError.innerHTML = "<span class='error'>Incorrect code entered.</span>";
    return false;
  }
  var thisMd5 = hex_md5(imageStr);
  if (thisMd5 == md5){
    image.className = "forms";
    imageCheck.innerHTML = "<span class='success'>OK.</span>";
    imageError.innerHTML = "&nbsp;";
    return true;
  }
  else {
    image.className = "errorBox";
    imageCheck.innerHTML = "<img src='/images/exclamation.jpg' width='14' height='14' />";
    imageError.innerHTML = "<span class='error'>Incorrect code entered.</span>";
    return false;
  }
}

function validateForm() {
  var checkResult1 = checkEmail(); 
  var checkResult2 = checkDescription(document.getElementById('descriptionArea'));
  var checkResult3 = checkLinkTitle();
  var checkResult4 = checkValidUrl(document.getElementById('webSiteUrl'), 'urlTextCheck', 'urlTextError' ,true) ;
  var checkResult5 = checkValidUrl(document.getElementById('returnUrl'), 'returnUrlCheck','returnUrlError', false);
  var checkResult6 = checkImage(); 
  var result = checkResult1 && checkResult2 && checkResult3 && checkResult4 && checkResult5 && checkResult6;
  if (result == false) {
    alert("You have errors in form.");
  }
  return result;
}

