﻿	document.observe('dom:loaded', initPage);
	var frmEl;

	function validateEmail(sEmail) {
	  if (sEmail == null || sEmail.length == 0 ||
	      sEmail.indexOf('.') == -1 || sEmail.indexOf('@') == -1 ||
	      sEmail.indexOf(' ') != -1) { return false; }
	  var rx, _match, user, domain, valid;
	  // validate local part
	  rx = /(^\w{2,}\.?\w{2,})@/;
	  _match = rx.exec(sEmail); if (_match) { user = RegExp.$1; } else { return false; }
	  //validate domain part
	  rx = /@(\[\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\])$/; //checks domain literals
	  _match = rx.exec(sEmail);
	  if (_match) { domain = RegExp.$1; valid = true; } else {
	    rx = /@(\w{2,}\.(\w{2,}\.)?[a-zA-Z]{2,3})$/; //check domain names
	    _match = rx.exec(sEmail);
	    if (_match) { domain = RegExp.$1; valid = true; } else { valid = false; }
	  }
	  return valid;
	}
	
	function initPage() {
	  Ajax.Responders.register({ onCreate: function() {  }, onComplete: function() {  } });
	  frmEl = document.forms[0].name;
      document.forms[0].onsubmit = function() { return submitForm(); };
	}
	
	function ajaxOnException() {showMsg('Sorry but we couldn\'t process your request at this time. Please try again later. (AJAX_EXCEPTION)');}
	function ajaxOnFailure() {showMsg('Sorry but we couldn\'t process your request at this time. Please try again later. (AJAX_FAILURE)');}
	function ajaxOnComplete(transport) {
	  var resp = transport.responseText;
	  if (resp=='OK') {
  			$('divRequestMsg').innerHTML = 'We have received your request - please check your email inbox in a few minutes.';
			$('divRequestMsg').setStyle({color:'green'});
			
	  } else {
		  showMsg('Error Occurred: Sorry but we couldn\'t process your request at this time. Please try again later. ('+resp+')');
	  }
	}
	
	function submitForm() {
		var sEmail = $F('email');		
		if (validateEmail(sEmail)){
			$('divRequestMsg').innerHTML = 'Sending your request...';
			$('divRequestMsg').setStyle({color:'green'});
			$('cmdSubmit').disabled=true;
			var request = new Ajax.Request('/aspx/request-acceptor.aspx', { parameters: 'subject=' + encodeURIComponent($F('subject')) + '&email=' + encodeURIComponent($F('email')),
    		onComplete: ajaxOnComplete, onException: ajaxOnException, onFailure: ajaxOnFailure});
		} else {
		  	showMsg('Sorry but the email address entered does not appear to be correct. Please check and try again.');
		}
	   	return false;
	}

	function showMsg(sMsg) {
		$('divRequestMsg').innerHTML = sMsg;
		$('divRequestMsg').setStyle({color:'red'});
		$('cmdSubmit').disabled=false;
	}
	
