// JavaScript Document
var xmlHttp;
var url = "http://www.stormwatchalert.com/data/checkRegistration.php?action=test";

// This guy is what determines which type of obejct we're using based on the browser
function createXMLHttpRequest() {
	if (window.ActiveXObject) {
		xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
	}
	else if (window.XMLHttpRequest) {
		xmlHttp = new XMLHttpRequest();
	}
}

// This is a prototype of a function that gets called from the webpage
function startRequest() {
	createXMLHttpRequest();
	url = "http://www.stormwatchalert.com/data/checkRegistration.php?action=test";
	xmlHttp.onreadystatechange = handleStateChange;
	xmlHttp.open("GET", url, true);
	xmlHttp.send(null);
}

// This is a prototype of a fuction to handle the response initiated from the function above
function handleStateChange() {
	if(xmlHttp.readyState == 4) {
		if(xmlHttp.status == 200) {
			outText = parseResponse();
			alert("The server replied with: " + outText);
		}
	}
}

// This will take our XML response formed like "<response>text</response>" and pump out the text in between
function parseResponse(){
	var xmlDoc = xmlHttp.responseXML;
	var responseNode = xmlDoc.getElementsByTagName("response")[0];
	return responseNode.childNodes[0].nodeValue;
}

//------------------------------------------
//Production functions
//------------------------------------------

function compareEmails(){
	// grab the email values from the form
	var email1 = document.getElementById("email").value;
	var email2 = document.getElementById("email2").value;
	
	// if the two entries are the same, we'll process to see if they're already in the database
	if (email1 > "" && email2 > "" && email1 == email2) {
		emailCheck = valid(email1);
		//alert(emailCheck);
		if (emailCheck == true) {
			//if (email1 == email2) {
				createXMLHttpRequest();
				pieces = "&email1=" + email1;
				url = "http://www.stormwatchalert.com/data/checkRegistration.php?action=checkEmail" + pieces;
				xmlHttp.onreadystatechange = checkEmails;
				xmlHttp.open("GET", url, true);
				xmlHttp.send(null);
			//}
		}
		else {
			document.getElementById("emailMsg").innerHTML = "The email address provided is not valid.";
			document.getElementById("email").focus();
			document.getElementById("email").select();
			document.getElementById("email2").value = "";
		}
	}
	// if they're not the same, let's make them re-enter it
	else {
		document.getElementById("emailMsg").innerHTML = "The email addresses do not match.";
		document.getElementById("email2").focus();
		document.getElementById("email2").select();
	}
}

// This function makes the server call to determine if the address is already in the database
function checkEmails() {
	if(xmlHttp.readyState == 4) {
		if(xmlHttp.status == 200) {
			outText = parseResponse();
			if (outText == "new") {
				document.getElementById("emailMsg").innerHTML = "<font color=blue><strong>OK</strong></font>";
				// go to the next page of the registration process
				window.location = "register.php?step=2&email="+document.getElementById("email").value;
			}
			else if (outText == "registered"){
				toPage = "<font color=blue><strong>You have already registered for StormWatchAlert.com<br>Click <a href=password.php?email="+document.getElementById("email").value+">here</a>";
				toPage += " to have your password emailed to your account.</strong></font>"
				document.getElementById("emailMsg").innerHTML = toPage;
				document.getElementById("inputButton").innerHTML = "";
				}
			else if (outText == "exists"){
				toPage = "<font color=blue>This email address has already been registered with your local Sheriff's Office.";
				toPage += " A confirmation email has been sent to the email address you provided.  Please click the link provided within the email to finish your account creation.  If you do not receive your confirmation email, please check your SPAM filter and / or add the following email:";
				toPage += " <strong>account@stormwatchalert.com</strong> to your contacts list and begin the registration process again.";
				toPage += "</font>";
				document.getElementById("emailMsg").innerHTML = toPage;
				document.getElementById("inputButton").innerHTML = "";
			}
		}
	}
}

// Validates the structure of the email address
function valid(email) {
  var str = email;
  if (window.RegExp) {
    var reg1str = "(@.*@)|(\\.\\.)|(@\\.)|(\\.@)|(^\\.)";
    var reg2str = "^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$";
    var reg1 = new RegExp(reg1str);
    var reg2 = new RegExp(reg2str);
    if (!reg1.test(str) && reg2.test(str)) {
      return true;
    }
    return false;
  } else {
    if(str.indexOf("@") >= 0)
      return true;
    return false;
  }
}


function comparePasswords(){
	// grab the password values from the form
	var pass = document.getElementById("password").value;
	var pass2 = document.getElementById("password2").value;
	
	if (pass > ""){
		if (pass != pass2) {
			document.getElementById("loginMsg").innerHTML = "The passwords do not match.";
			disableStep2();
			//document.getElementById("password2").focus();
			//document.getElementById("password2").select();
		}
		else {
			document.getElementById("loginMsg").innerHTML = "<font color=blue><strong>OK</strong></font>";
			document.getElementById("SubmitStep2").disabled = false;
			document.getElementById("SubmitStep2").className = 'formbutton';
		}
	}
}

function disableStep2(){
	document.getElementById("SubmitStep2").disabled = true;
	document.getElementById("SubmitStep2").className = 'formbuttondisabled';
}

// This is a prototype of a function that gets called from the webpage
function loadStates() {
	createXMLHttpRequest();
	url = "http://www.stormwatchalert.com/data/general.php?action=getstatelist";
	xmlHttp.onreadystatechange = loadStatesRequest;
	xmlHttp.open("GET", url, true);
	xmlHttp.send(null);
}

// This is a prototype of a fuction to handle the response initiated from the function above
function loadStatesRequest() {
	if(xmlHttp.readyState == 4) {
		if(xmlHttp.status == 200) {
			outText = parseStates();
			//alert("The server replied with: " + outText);
		}
	}
}

// This will take our XML response formed like "<response>text</response>" and pump out the text in between
function parseStates(){
	var xmlDoc = xmlHttp.responseXML;
	var nodes = xmlDoc.getElementsByTagName("name");
	
	wheretostop = nodes.length;
	
	document.getElementById("pickstate").options.length = 0
	document.getElementById("pickstate").options[0]=new Option("Choose a state", '', true, false)
	
	for(i=0;i<nodes.length;i++){
		//alert(nodes[i].childNodes[0].nodeValue);
		document.getElementById("pickstate").options[i+1] = new Option(nodes[i].childNodes[0].nodeValue,nodes[i].childNodes[0].nodeValue,false,false);
	}
	//var responseNode = xmlDoc.getElementsByTagName("response")[0];
	return wheretostop;
}

function loadCounties(state) {
	createXMLHttpRequest();
	url = "http://www.stormwatchalert.com/data/general.php?action=getcountylist&state="+state;
	xmlHttp.onreadystatechange = loadCountiesRequest;
	xmlHttp.open("GET", url, true);
	xmlHttp.send(null);
}

// This is a prototype of a fuction to handle the response initiated from the function above
function loadCountiesRequest() {
	if(xmlHttp.readyState == 4) {
		if(xmlHttp.status == 200) {
			outText = parseCounties();
			//alert("The server replied with: " + outText);
		}
	}
}

function parseCounties(){
	var xmlDoc = xmlHttp.responseXML;
	var nodes = xmlDoc.getElementsByTagName("name");
	
	wheretostop = nodes.length;
	
	document.getElementById("pickcounty").options.length = 0
	
	for(i=0;i<nodes.length;i++){
		//alert(nodes[i].childNodes[0].nodeValue);
		document.getElementById("pickcounty").options[i] = new Option(nodes[i].childNodes[0].nodeValue,nodes[i].childNodes[0].nodeValue,false,false);
	}
	//var responseNode = xmlDoc.getElementsByTagName("response")[0];
	return wheretostop;
}

function disableComplete(){
	document.getElementById("complete").disabled = true;
	document.getElementById("complete").className = 'formbuttondisabled';
}

function enableComplete(){
	if (document.getElementById("terms").checked == true){
		document.getElementById("complete").disabled = false;
		document.getElementById("complete").className = 'formbutton';
	}
	if (document.getElementById("terms").checked == false){
		document.getElementById("complete").disabled = true;
		document.getElementById("complete").className = 'formbuttondisabled';
	}
}

function addRowHTML (tableID, html) {
  if (document.getElementById && !document.all) {
    var table = document.getElementById(tableID);
    var tbody = table.tBodies[table.tBodies.length - 1];
    var range = document.createRange();
    range.setStartAfter(tbody.lastChild);
    var docFrag = range.createContextualFragment(html);
    tbody.appendChild(docFrag);
  }
}

var thisCountyDropdown = "";

function loadCountyList(state,countyDrop) {
	thisCountyDropdown = countyDrop;
	if(state != "All"){
		createXMLHttpRequest();
		url = "http://www.stormwatchalert.com/data/general.php?action=getcountylist&state="+state;
		xmlHttp.onreadystatechange = loadCountiesRequest2;
		xmlHttp.open("GET", url, true);
		xmlHttp.send(null);
	}
	if(state == "None" || state == "All"){
		document.getElementById(thisCountyDropdown).options.length = 0
	}
}

// This is a prototype of a fuction to handle the response initiated from the function above
function loadCountiesRequest2() {
	if(xmlHttp.readyState == 4) {
		if(xmlHttp.status == 200) {
			outText = parseCounties2();
			//alert("The server replied with: " + outText);
		}
	}
}

function parseCounties2(){
	var xmlDoc = xmlHttp.responseXML;
	var nodes = xmlDoc.getElementsByTagName("name");
	
	wheretostop = nodes.length;
	
	document.getElementById(thisCountyDropdown).options.length = 0
	document.getElementById(thisCountyDropdown).options[0] = new Option("All","All",false,false);
	for(i=1;i<=nodes.length;i++){
		//alert(nodes[i].childNodes[0].nodeValue);
		document.getElementById(thisCountyDropdown).options[i] = new Option(nodes[i-1].childNodes[0].nodeValue,nodes[i-1].childNodes[0].nodeValue,false,false);
	}
	//var responseNode = xmlDoc.getElementsByTagName("response")[0];
	return wheretostop;
}

var isNN = (navigator.appName.indexOf("Netscape")!=-1);
function autoTab(input,len, e) {
	var keyCode = (isNN) ? e.which : e.keyCode; 
	var filter = (isNN) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46];
	if(input.value.length >= len && !containsElement(filter,keyCode)) {
	input.value = input.value.slice(0, len);
	input.form[(getIndex(input)+1) % input.form.length].focus();
}
function containsElement(arr, ele) {
	var found = false, index = 0;
	while(!found && index < arr.length)
	if(arr[index] == ele)
	found = true;
	else
	index++;
	return found;
}
function getIndex(input) {
	var index = -1, i = 0, found = false;
	while (i < input.form.length && index == -1)
	if (input.form[i] == input)index = i;
	else i++;
	return index;
	}
	return true;
}