function pressEnter(e,nameForm,nextField,validateBy)
{
	var keynum;
	var keychar;
	
	if (window.event) // IE
	{
		keynum = e.keyCode;
	}
	else if (e.which) // Netscape/Firefox/Opera
	{
		keynum = e.which;
	}
	//keychar = String.fromCharCode(keynum);
	if (keynum == 13)
	{
		if (nextField != "")
		{
			eval('document.forms["' + nameForm + '"]["' + nextField + '"].focus();');
		}
		else
		{
			if (validateBy == "")
			{
				eval('document.forms["' + nameForm + '"].submit();');
			}
			else
			{
				eval(validateBy);
			}
		}
	}
}

function addMemberToDropdown(id, name) {
	displayLayer('composeMsg',true);
	appendOptionLast('recipient',id,name);

}

function appendOptionLast(select, id, value)
{
  var elOptNew = document.createElement('option');
  elOptNew.text = value;
  elOptNew.value = id;
  var elSel = document.getElementById(select);

  try {
    elSel.add(elOptNew, null); // standards compliant; doesn't work in IE
  }
  catch(ex) {
    elSel.add(elOptNew); // IE only
  }
  elSel.selectedIndex = elSel.options.length-1;
  
}

function changeClassName(name, className){
	var obj = document.getElementById(name);
	obj.className = className;
}


function writeLayer(name, txt){
	var layer = document.getElementById(name);
	layer.innerHTML = txt;
}

function toggleLayer(name){
	var foc = document.getElementById(name);
	if (foc) {
		if (foc.style.display == 'none') {
			foc.style.display='block';
		} else {
			foc.style.display='none';
		}
	}
}

function displayLayer(name, visible){
	var foc = document.getElementById(name);
	if (foc) {
		if (visible) {
			foc.style.display='block';
		} else {
			foc.style.display='none';
		}
	}
}

function setStyle(name, property, value){
	var foc = document.getElementById(name);
	if (foc) {
		foc.style[property] = value;
	}
}

function checkResponse() {
	var errors = "";
	
	if (document.forms["formblog"]["response_title"].value == "") {
		errors += "Title\n";
	}
	if (document.forms["formblog"]["response_text"].value == "") {
		errors += "Message\n";
	}
	
	if (errors == "") {
		//return true;
		document.forms["formblog"].submit();
	} else {
		alert("Please review the following information:\n\n" + errors);
		//return false;
	}
}

function checkPost() {
	var errors = "";
	
	if (document.forms["formblog"]["blog_title"].value == "") {
		errors += "Title\n";
	}
	if (document.forms["formblog"]["blog_text"].value == "") {
		errors += "Message\n";
	}
	
	if (errors == "") {
		//return true;
		document.forms["formblog"].submit();
	} else {
		alert("Please review the following information:\n\n" + errors);
		//return false;
	}
}

function checkAccount() {
	// do form validation here
	var password = document.forms.formaccount.member_password.value;
	var confirm = document.forms.formaccount.confirm.value;
	var surname = document.forms.formaccount.member_lastname.value;
	var email = document.forms.formaccount.member_email.value;
	var telephone = document.forms.formaccount.member_phone.value;
	var dob = document.forms.formaccount.member_dob.value;
	
	var errors = "";
	
	if (password != "") {
		if (!isValidUsernamePassword(password)) {
			errors += "Password (must be alphanumeric with no spaces)\n";
		}
		if (password != confirm) {
			errors += "Password confirmation\n";
		}
	}
	if (surname == "") {
		errors += "Surname\n";
	}
	if (!isValidEmail(email)) {
		errors += "Email address\n";
	}
	/*if (telephone == "") {
		errors += "Telephone\n";
	}*/
	if (!isValidDate(dob,"DMY")) {
		errors += "DOB\n";
	}
	
	if (errors == "") {
		document.forms.formaccount.submit();
	} else {
		alert("Please review the following information:\n\n" + errors);
	}
}

function checkReminder() {
	var errors = "";
	
	if (document.forms["formreminder"]["member_warrant"].value == "") {
		errors += "Warrant Number\n";
	}
	if (document.forms["formreminder"]["member_lastname"].value == "") {
		errors += "Surname\n";
	}
	
	if (errors == "") {
		//return true;
		document.forms["formreminder"].submit();
	} else {
		alert("Please review the following information:\n\n" + errors);
		//return false;
	}
}

function checkLogin() {
	var errors = "";
	
	if (document.forms["formlogin"]["member_warrant"].value == "") {
		errors += "Warrant Number\n";
	}
	if (document.forms["formlogin"]["member_lastname"].value == "") {
		errors += "Surname\n";
	}
	if (document.forms["formlogin"]["member_password"].value == "") {
		errors += "Password\n";
	}
	
	if (errors == "") {
		//return true;
		document.forms["formlogin"].submit();
	} else {
		alert("Please review the following information:\n\n" + errors);
		//return false;
	}
}

function checkContact()
{
	var errors = "";
		
	if (document.forms["formcontact"]["firstname"].value == "") {
		errors += "First name\n";
	}
	if (document.forms["formcontact"]["surname"].value == "") {
		errors += "Surname\n";
	}
	if (!isValidEmail(document.forms["formcontact"]["email"].value)) {
		errors += "Email\n";
	}
	if (document.forms["formcontact"]["comments"].value == "") {
		errors += "Comments,Feedback,Questions\n";
	}
	
	if (errors == "") {
		//return true;
		document.forms["formcontact"].submit();
	} else {
		alert("Please review the following information:\n\n" + errors);
		//return false;
	}
	
}

function popup(w,h,t,l,url,winName,status,toolBar,scrollBars,resizable) {
	if (scrollBars == undefined) scrollBars = "auto";
	if (resizable == undefined) resizable = "no";
  	var sWid = screen.width;
  	var sHi = screen.height;
	var wid = w;
	var hi = h;
	if ((t == 0) && (l == 0)) {
		var tp = (sHi/2)-(hi/2);
		var lft = (sWid/2)-(wid/2);
	} else {
		var tp = t;
		var lft = l;	
	}
	if (scroll && document.all && (navigator.userAgent.indexOf("Mac") > -1)) wid = wid+17;
	newwin=window.open(url,winName,"width=" + wid + ",height=" + hi + ",status=" + status + ",scrollbars=" + scrollBars + ",toolbar=" + toolBar + ",resizable=" + resizable + ", top = "+ tp +", left ="+ lft + ", screenX=" + lft +", screenY= "+tp);
	newwin.focus();
}

function checkRegister(validate) {
	// do form validation here
	var warrant = document.forms.formregister.member_warrant.value;
	//var username = document.forms.formregister.member_username.value;
	var password = document.forms.formregister.member_password.value;
	var confirm = document.forms.formregister.confirm.value;
	var surname = document.forms.formregister.member_lastname.value;
	var email = document.forms.formregister.member_email.value;
	var email_confirm = document.forms.formregister.email_confirm.value;
	var telephone = document.forms.formregister.member_phone.value;
	var dob = document.forms.formregister.member_dob.value;
	
	if (validate == "warrant") {
		if ((warrant != "") && (!isNaN(warrant))) {
			existWarrantNumber(warrant);
		} else {
			alert("Please enter a correct Warrant Number");
		} 
	} else if ((validate == "validwarrant") && (surname != "") && (dob != "")) {
		if (!isValidDate(dob,"DMY")) {
			alert("Please enter a correct DOB");
		} else {
			validWarrantNumber(warrant,surname,dob);
		}
		
	/*
	} else if (validate == "username") {
		if ((username != "") && (isValidUsernamePassword(username))) {
			existUsername(username);
		} else {
			alert("Please enter a correct Username (must be alphanumeric with no spaces)");
		} 
	*/
	} else {
		var errors = "";
		
		if (password != "") {
			if (!isValidUsernamePassword(password)) {
				errors += "Password (must be alphanumeric with no spaces)\n";
			}
			if (password != confirm) {
				errors += "Password confirmation\n";
			}
		} else {
			errors += "Password\n";
		}
		if (surname == "") {
			errors += "Surname\n";
		}
		if (!isValidEmail(email)) {
			errors += "Email address\n";
		} else if (email != email_confirm) {
			errors += "Email confirmation\n";
		}
		
		/*
		if (telephone == "") {
			errors += "Telephone\n";
		}
		*/
		
		if (!isValidDate(dob,"DMY")) {
			errors += "DOB\n";
		}
		
		if (errors == "") {
			document.forms.formregister.submit();
		} else {
			alert("Please review the following information:\n\n" + errors);
		}
	}
}

function existUsername(username) {
	var xmlhttp = InstanceXMLHttpRequest();
	xmlhttp.open('POST', '/ajax?method=existusername', true);

	xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

	xmlhttp.onreadystatechange = function() {		
		if (xmlhttp.readyState == 4) {
			//alert(xmlhttp.responseText);
			var result = parseInt(xmlhttp.responseText);
			if (!isNaN(result) && (result > 0)) {
				alert("Username already exists in the database, please try a different one.");
			} else {
				checkRegister("");
			}			
		}
	}
	xmlhttp.send('username=' + username);
}

function existWarrantNumber(warrant) {
	var xmlhttp = InstanceXMLHttpRequest();
	xmlhttp.open('POST', '/ajax?method=existwarrantnumber', true);

	xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

	xmlhttp.onreadystatechange = function() {		
		if (xmlhttp.readyState == 4) {
			//alert(xmlhttp.responseText);
			var result = parseInt(xmlhttp.responseText);
			if (!isNaN(result) && (result > 0)) {
				alert("Warrant Number already exists in the database, please try a different one.");
			} else {
				//checkRegister("username");
				checkRegister("validwarrant");
			}			
		}
	}
	xmlhttp.send('warrant=' + warrant);
}

function validWarrantNumber(warrant,surname,dob) {
	var xmlhttp = InstanceXMLHttpRequest();
	xmlhttp.open('POST', '/ajax?method=validwarrantnumber', true);

	xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

	xmlhttp.onreadystatechange = function() {		
		if (xmlhttp.readyState == 4) {
			//alert(xmlhttp.responseText);
			var result = xmlhttp.responseText;
			if (result != "") {
				document.forms.formregister.constable_dob.value = result;
				checkRegister("");
			} else {
				alert("Warrant Number not found.");
			}			
		}
	}
	xmlhttp.send('warrant=' + warrant + '&surname=' + surname + '&dob=' + dob);
}

function InstanceXMLHttpRequest() {
	if(window.XMLHttpRequest) {
		try {
			req = new XMLHttpRequest();
		} catch(e) {
			req = false;
		}
		// branch for IE/Windows ActiveX version
	} else if(window.ActiveXObject) {
		try {
			req = new ActiveXObject("Msxml2.XMLHTTP");
		} catch(e) {
			try {
				req = new ActiveXObject("Microsoft.XMLHTTP");
			} catch(e) {
				req = false;
			}
		}
	}
	return req;
}

function isValidEmail(email) {
	//var re = /^ *([a-z0-9_-]+\.)*[a-z0-9_-]+@(([a-z0-9-]+\.)+(com|net|org|mil|edu|gov|arpa|info|biz|inc|name|[a-z]{2})|[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}) *$/;
	var re = /^[\w\+\\'\.-]+@[\w\\'\.-]+\.[a-zA-Z]{2,}$/;
	return (re.test(email.toLowerCase()));
}

function isValidUsernamePassword(value) {
	re = /^\w+$/;
	return (re.test(value.toLowerCase()));
}

String.prototype.trim = function (){
	return this.replace(/(^\s+)/g, "").replace(/(\s+$)/g, "");
}

function isValidDate(dateStr, format) {
   if (format == null) { format = "MDY"; }
   format = format.toUpperCase();
   if (format.length != 3) { format = "MDY"; }
   if ( (format.indexOf("M") == -1) || (format.indexOf("D") == -1) || (format.indexOf("Y") == -1) ) { format = "MDY"; }
   if (format.substring(0, 1) == "Y") { // If the year is first
      var reg1 = /^\d{4}(\-)\d{1,2}\1\d{1,2}$/

   } else if (format.substring(1, 2) == "Y") { // If the year is second
      var reg1 = /^\d{1,2}(\-)\d{4}\1\d{1,2}$/

   } else { // The year must be third
      var reg1 = /^\d{1,2}(\-)\d{1,2}\1\d{4}$/

   }
   if ( reg1.test(dateStr) == false ) { return false; }
   var parts = dateStr.split(RegExp.$1); // Split into 3 parts based on what the divider was
   // Check to see if the 3 parts end up making a valid date
   if (format.substring(0, 1) == "M") { var mm = parts[0]; } else 
      if (format.substring(1, 2) == "M") { var mm = parts[1]; } else { var mm = parts[2]; }
   if (format.substring(0, 1) == "D") { var dd = parts[0]; } else
      if (format.substring(1, 2) == "D") { var dd = parts[1]; } else { var dd = parts[2]; }
   if (format.substring(0, 1) == "Y") { var yy = parts[0]; } else
      if (format.substring(1, 2) == "Y") { var yy = parts[1]; } else { var yy = parts[2]; }
   if (parseFloat(yy) <= 50) { yy = (parseFloat(yy) + 2000).toString(); }
   if (parseFloat(yy) <= 99) { yy = (parseFloat(yy) + 1900).toString(); }
   var dt = new Date(parseFloat(yy), parseFloat(mm)-1, parseFloat(dd), 0, 0, 0, 0);
   if (parseFloat(dd) != dt.getDate()) { return false; }
   if (parseFloat(mm)-1 != dt.getMonth()) { return false; }
   return true;
}