/* javaScript for torgersonforcongress.com in cooperation with mindformation.com

   written / maintained by Grace E. Morris and Tom Green - 07/30/2011

*/

function validate() {

  var status = true;

  var emailRegEx = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;

  var emailAddress = document.forms['volunteer'].elements['email'].value;

  state = emailAddress.match(emailRegEx);

  if ( emailAddress.match(emailRegEx) != emailAddress || false) {

    writeToDiv('Please enter a valid email address');

    status = false;

  }

  var firstName = document.forms['volunteer'].elements['firstName'].value;

  if ( firstName == '' || firstName == document.forms['volunteer'].elements['firstName'].defaultValue ) { status = false; }

  var lastName = document.forms['volunteer'].elements['lastName'].value;

  if ( lastName == '' || lastName == document.forms['volunteer'].elements['lastName'].defaultValue ) { status = false; }

  var smu = document.forms['volunteer'].elements['smu'].checked;

  var vhl = document.forms['volunteer'].elements['vhl'].checked;

  if (smu == false && vhl == false) {

    writeToDiv('Please select one or both options!');

    status = false;

  }

  if (status == true) {

    writeToDiv('&nbsp;');

    var theKey = encode_re(firstName + lastName + emailAddress);

    theKey = theKey.join('');

    theKey = theKey.replace(/,/g,"");

    sendToMailer(firstName, lastName, emailAddress, smu, vhl, theKey);

    writeToDiv('&nbsp;');

    if (serverSez == 'OKAY') {

      removeForm();

    } else {

      writeToDiv('Unable to verify data or contact mail server at this time. Please try again later...');

    }

  }

  return false;

}

function removeForm() {

  document.getElementById('formContent').innerHTML = '<h2>Thank you for participating in the Lynne Torgerson For Congress Campaign!</h2><p><br>Your information has been sent.</p>';

}
function writeToDiv(theText) {

  document.getElementById('webformErrors').innerHTML = theText;

}

function sendToMailer(firstName, lastName, email, smu, vhl, theKey) {

  var xmlHttp;

	try {

		xmlHttp = new XMLHttpRequest();

	} catch (e) {

		try {

			xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");

		} catch (e) {

		  try {

				xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");

			} catch (e) {

				alert("No AJAX!?");

				return false;

			}

		}

	}

	xmlHttp.onreadystatechange = function() {

		if ( xmlHttp.readyState == 4 ) {

      if ( xmlHttp.status == 200 ) {

        serverSez = xmlHttp.responseText;

        return serverSez;

  		} else {

  		  return 'ERROR';

  		}

		}

	}

  var url = 'http://www.mindformation.com/cgi-bin/torgersonWebmail.pl?' + 'fname=' + firstName + '&lname=' + lastName + '&email=' + email + '&smu=' + smu + '&vhl=' + vhl + '&theKey=' + theKey;

  writeToDiv('Waiting for response from mail server...');

	xmlHttp.open("GET", url, false);

	xmlHttp.send(null);

}

function encode_re(input) {

  var encoding = [];

  input.match(/(.)\1*/g).forEach(function(substr){ encoding.push([substr.length, substr[0]]) });

  return encoding;

}

function formField (field, maneuver) {

  fieldValue = document.forms['volunteer'].elements[field].value;

  fieldDefaultValue = document.forms['volunteer'].elements[field].defaultValue;

  var firstName = document.forms['volunteer'].elements['firstName'].value;

  var lastName = document.forms['volunteer'].elements['lastName'].value;

  var regEx = /^[a-zA-Z ]+$/;

  if ( firstName != '' && regEx.test(firstName) == false ) { writeToDiv('First Name may only contain alphabetic characters'); }

  if ( lastName != '' && regEx.test(lastName) == false ) { writeToDiv('Last Name may only contain alphabetic characters'); }

  if (maneuver == 'blur') {

    if ( fieldValue == '' || fieldValue.match(/^\s+/) ) {

      document.forms['volunteer'].elements[field].value = fieldDefaultValue;

      return;

    }

  }

  if (maneuver == 'focus') {

    writeToDiv('&nbsp;');

    if ( fieldValue == fieldDefaultValue ) { document.forms['volunteer'].elements[field].value = ''; }

  }

}

function decode(username, hostname, gTLD, item, code, subject) {

  var decoded_username = '';

  var decoded_hostname = '';

  var decoded_gTLD = '';

  element_id = document.getElementById('em_' + item);

  for (i = 1; i < username.length; i += 2) { decoded_username += username.charAt(i); }

  for (i = 1; i < hostname.length; i += 2) { decoded_hostname += hostname.charAt(i); }

  for (i = 1; i < gTLD.length; i += 2) { decoded_gTLD += gTLD.charAt(i); }

  decoded_username = strrev(rotTomg(decoded_username, code));

  decoded_hostname = strrev(rotTomg(decoded_hostname, code));

  decoded_gTLD = strrev(rotTomg(decoded_gTLD, code));

  emstring = decoded_username + String.fromCharCode(64) + decoded_hostname + String.fromCharCode(46) + decoded_gTLD;

  emlink = decoded_username + String.fromCharCode(64) + decoded_hostname + String.fromCharCode(46) + decoded_gTLD + '?subject=' + subject;

  element_id.innerHTML = '<' + String.fromCharCode(97) + ' hr'+ String.fromCharCode(101) + 'f="' + String.fromCharCode(109) + String.fromCharCode(97) + 'ilto' + String.fromCharCode(58) + emlink + '" id="ea_' + item + '">' + emstring +  '</' + String.fromCharCode(97) + '>';

  element_id.onclick = document.getElementById('em_' + item).onclick;

  element_id.onmouseover = document.getElementById('em_' + item).onmouseover;

}

function strrev(str) {

  return str.split("").reverse().join("");

}

function rotTomg (str, code) {

  var coded = '';

  var alpha   = 'abcdefghijklmnopqrstuvwxyz';

  var beta    = 'movutcyqphigbsfrnwkxjezald';

  var gamma   = 'plozhjbcrvwdgeafsykinxutmq';

  var delta   = 'iqtodavrwflepzyncmkusgbxhj';

  var epsilon = 'cghobjsztqermdyuxfawnivklp';

  var zeta    = 'ksgpxodlqijmfnvbrcztwuheay';

  for (i = 0; i < str.length; i++) {

    character = str.charAt(i);

    switch (code) {

      case 'beta':

        idx = beta.indexOf(character);

        break;

      case 'gamma':

        idx = gamma.indexOf(character);

        break;

      case 'delta':

        idx = delta.indexOf(character);

        break;

      case 'epsilon':

        idx = epsilon.indexOf(character);

        break;

      case 'zeta':

        idx = zeta.indexOf(character);

        break;

    }

    if (idx == -1) {

      coded += character;

    } else {

      coded += alpha.charAt(idx);

    }

  }

  return coded;

}

