
/**
 * Author: Fernando Mladineo
 * Date: 5 Jun 2008
 * Version: 0.1
 * Terms: you may freely distribute this as long as you keep this copyright notice intact.
 */

var http_request = false;
var divId = ""; // name of div ID that will stores the results of the AJAX call
var whichCb = "1"; // determines when to make 2nd AJAX call (refresh the CAPTCHA)

// Nice little graphic to let the user know we've made an AJAX call
var loading = new Image(220,19);
loading.src = "images/ajax-loader-bar.gif";

// Send email to the pre-determined recipient
function sendMail(form_id) {
	
	if (!validate(document.getElementById(form_id))) {
		return false;
	} else {
	 
		divId = "results";
		var str = "";
		var elem = document.getElementById(form_id).elements;
		for (var i = 0; i < elem.length; i++) {						
			if ((elem[i].type == "hidden") || (elem[i].type == "text") || (elem[i].type == "textarea")) { // Text field
			   str += elem[i].id + "=" + escape(encodeURI(trimField(elem[i].id))) + "&";
			} else if (elem[i].type == "checkbox") { // Check box
			   if (elem[i].checked) {
				  str += elem[i].id + "=on&";
			   } else {
				  str += elem[i].id + "=off&";
			   }
			} else if (elem[i].type == "select-one") { // Drop-down menu (SELECT)
				var sel = elem[i];
				str += sel.id + "=" + sel.options[sel.selectedIndex].value + "&";
			}
		}
		
		str = str.substring(0, str.length-1); 
		str = str.replace(/%250A/g,"%253Cbr%2520/%253E"); // Make sure that line breaks get transmitted properly
		if (form_id == "contact_us") {
			form_page = "scripts/contactusemail/sendMail.php";
		}
		AjaxRequest(form_page, str, "post");
	}
}

// Make the AJAX request
function AjaxRequest(url, parameters, type) {
	http_request = false;
	if (window.XMLHttpRequest) { // Mozilla, Safari,...
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) {
			// set type accordingly to anticipated content type
			//http_request.overrideMimeType('text/xml');
			http_request.overrideMimeType('text/html');
		}
	} else if (window.ActiveXObject) { // IE
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}
	if (!http_request) {
		alert("Cannot create XMLHTTP instance");
		return false;
	}
	
	if (type == "post") {
		// POST
		http_request.open('POST', url, true);
		http_request.onreadystatechange = AjaxRequestCb;
		http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		http_request.setRequestHeader("Content-length", parameters.length);
		http_request.setRequestHeader("Connection", "close");
		http_request.send(parameters);
	} else if (type == "get") {
		// GET
		http_request.open('GET', url + parameters, true);
		http_request.onreadystatechange = AjaxRequestCb;
		http_request.send(null);
	} // if...else
}

// AJAX Callback
function AjaxRequestCb() {
	if (http_request.readyState == 1 || http_request.readyState == 2 || http_request.readyState == 3) {
		result = "<p>&nbsp;</p><div style=\"text-align: center; margin: 0 auto;\"><img src=\"" + loading.src + "\" width=\"220\" height=\"19\" alt=\"\" title=\"Sending...\" /><br />Sending...</div>";
		document.getElementById(divId).innerHTML = result;
	} else if (http_request.readyState == 4) {
		if (http_request.status == 200) {
			result = http_request.responseText;
			document.getElementById(divId).innerHTML = result;
			
			// If CAPTCHA failed, then repopulate it
			if (result.indexOf("CAPTCHA") > -1) {
				Recaptcha.reload();
			} else {
				// Clear form after email has been sent
				document.forms["contact_us"].reset(); // Not robust, I know (will modify later)
				Recaptcha.reload(); // Display a new CAPTCHA
			}
		} else {
			alert("Callback failed. There was a problem with the request.");
		}
	}
}

// Remove any unneccessary whitespace
function trimField(field) {
	re = /(^\s*)([^\b]*\S)(\s*$)/;
	if (re.test(document.getElementById(field).value)) {
		document.getElementById(field).value = document.getElementById(field).value.replace (re, "$2");
		return document.getElementById(field).value;
	} else {
		document.getElementById(field).value = "";
		return "";		
	}
}



// form validation function //

function validate(form) {

		var name = form.name.value;
		var email = form.email.value;
		var phone = form.phone.value;
		var message = form.message.value;
		var regarding = form.regarding.value;
		var occupation = form.occupation.value;
		var recaptcha = form.recaptcha_response_field.value;
		var nameRegex = /^[a-zA-Z]+(([\'\,\.\- ][a-zA-Z ])?[a-zA-Z]*)*$/;
		var phoneRegex = /^\([1-9]\d{2}\)\s?\d{3}\-\d{4}$/;
		var emailRegex = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/;
		var messageRegex = new RegExp(/<\/?\w+((\s+\w+(\s*=\s*(?:".*?"|'.*?'|[^'">\s]+))?)+\s*|\s*)\/?>/gim);
		
		if(regarding == "" || regarding == null) {
			inlineMsg('regarding','<strong>Error</strong><br />You must select what this is regarding.',3);
			return false;
		}
		if(name == "") {
			inlineMsg('name','You must enter your name.',3);
			return false;
		}
		if(!name.match(nameRegex)) {
			inlineMsg('name','You have entered an invalid name.',3);
			return false;
		}
		if(email == "") {
			inlineMsg('email','<strong>Error</strong><br />You must enter your email.',3);
			return false;
		}
		if(!email.match(emailRegex)) {
			inlineMsg('email','<strong>Error</strong><br />You have entered an invalid email.',3);
			return false;
		}
		if(phone == "") {
			inlineMsg('phone','<strong>Error</strong><br />You must enter your phone number.',3);
			return false;
		}
		if(!phone.match(phoneRegex)) {
			inlineMsg('phone','<strong>Error</strong><br />You have entered an invalid phone number.<br />(###)###-####.',3);
			return false;
		}
		if(occupation == "" || occupation == null) {
			inlineMsg('occupation','<strong>Error</strong><br />You must select your occupation.',3);
			return false;
		}
		if(message == "") {
			inlineMsg('message','You must enter a message.',3);
			return false;
		}
		if(message.match(messageRegex)) {
			inlineMsg('message','You have entered an invalid message.',3);
			return false;
		}
		if(recaptcha == "") {
			inlineMsg('recaptcha_response_field','<strong>Error</strong><br />Please fill type what you see in the above image.',3);
			return false;
		}
		
		return true;
	
}

// START OF MESSAGE SCRIPT //

var MSGTIMER = 40;
var MSGSPEED = 5;
var MSGOFFSET = 3;
var MSGHIDE = 3;

// build out the divs, set attributes and call the fade function //
function inlineMsg(target,string,autohide) {
  var msg;
  var msgcontent;
  if(!document.getElementById('msg')) {
    msg = document.createElement('div');
    msg.id = 'msg';
    msgcontent = document.createElement('div');
    msgcontent.id = 'msgcontent';
    document.body.appendChild(msg);
    msg.appendChild(msgcontent);
    msg.style.filter = 'alpha(opacity=0)';
    msg.style.opacity = 0;
    msg.alpha = 0;
  } else {
    msg = document.getElementById('msg');
    msgcontent = document.getElementById('msgcontent');
  }
  msgcontent.innerHTML = string;
  msg.style.display = 'block';
  var msgheight = msg.offsetHeight;
  var targetdiv = document.getElementById(target);
  targetdiv.focus();
  var targetheight = targetdiv.offsetHeight;
  var targetwidth = targetdiv.offsetWidth;
  var topposition = topPosition(targetdiv) - ((msgheight - targetheight) / 2);
  var leftposition = leftPosition(targetdiv) + targetwidth + MSGOFFSET;
  msg.style.top = topposition + 'px';
  msg.style.left = leftposition + 'px';
  clearInterval(msg.timer);
  msg.timer = setInterval("fadeMsg(1)", MSGTIMER);
  if(!autohide) {
    autohide = MSGHIDE;  
  }
  window.setTimeout("hideMsg()", (autohide * 1000));
}

// hide the form alert //
function hideMsg(msg) {
  var msg = document.getElementById('msg');
  if(!msg.timer) {
    msg.timer = setInterval("fadeMsg(0)", MSGTIMER);
  }
}

// face the message box //
function fadeMsg(flag) {
  if(flag == null) {
    flag = 1;
  }
  var msg = document.getElementById('msg');
  var value;
  if(flag == 1) {
    value = msg.alpha + MSGSPEED;
  } else {
    value = msg.alpha - MSGSPEED;
  }
  msg.alpha = value;
  msg.style.opacity = (value / 100);
  msg.style.filter = 'alpha(opacity=' + value + ')';
  if(value >= 99) {
    clearInterval(msg.timer);
    msg.timer = null;
  } else if(value <= 1) {
    msg.style.display = "none";
    clearInterval(msg.timer);
  }
}

// calculate the position of the element in relation to the left of the browser //
function leftPosition(target) {
  var left = 0;
  if(target.offsetParent) {
    while(1) {
      left += target.offsetLeft;
      if(!target.offsetParent) {
        break;
      }
      target = target.offsetParent;
    }
  } else if(target.x) {
    left += target.x;
  }
  return left;
}

// calculate the position of the element in relation to the top of the browser window //
function topPosition(target) {
  var top = 0;
  if(target.offsetParent) {
    while(1) {
      top += target.offsetTop;
      if(!target.offsetParent) {
        break;
      }
      target = target.offsetParent;
    }
  } else if(target.y) {
    top += target.y;
  }
  return top;
}

// preload the arrow //
if(document.images) {
  arrow = new Image(7,80); 
  arrow.src = "images/msg_arrow.gif"; 
}