//REGISTRATION JAVASCRIPT CODE FOR HOUSING STATISTICS NETWORK

function clearInput(id){
//only clear if focussing for first time, check existing text
var idObj = document.getElementById(id);
var text = idObj.value;

text = text.substr(0,5);
//alert(text);
if(text == "Enter" || text == "First" || text == "Last " || text == "Your ")
{
	
	//Clears contents on focus and changes text color to black
	idObj.value = "";
	idObj.style.color = "black";


}
//Otherwise nothing happens old text remains for editing

}

function activeColor(id){
document.getElementById(id).style.color = "black";

}


function checkInput(id){

//Check characters are not more that limit set. Different for each one.
var idObj = document.getElementById(id);

var chqBlank = checkBlank(id);
//	alert(chqBlank);
changeStarColor(id, chqBlank);

//Check to see if all are ready, ie green
//setRequestButton();

}

function checkEmail(id){
//make sure not blank, then validate email format exists
var idObj = document.getElementById(id);

var chqBlank = checkBlank(id);
//alert("check email called, and chqBlank is" + chqBlank);

//if blank, no point in continuing this check exit and make sure star is red
if(chqBlank == false)
{
	changeStarColor(id, chqBlank);
	exit;
}

var chqFormat = checkFormat(id);
//alert(chqFormat);
changeStarColor(id, chqFormat);
//setRequestButton();

}

function checkBlank(id){
	//Check input not blank. Return true if not blank, false if blank

	var idValue = document.getElementById(id).value;
	//alert(idValue);

	if(idValue != "")
	{
		//alert(idValue);
		return true;
	}
	else
	{
		return false;
	}
}


function changeStarColor(id, bool){
//alert(id);
var strCheck = id.indexOf("star");
//alert(strCheck);
//adds "star" to id, make sure not including star
if(strCheck == -1){
	//alert(id);
	var starId = id + "star";
}
else
{
	//default
	starId = id;
	//alert(starId);
}
//some calls will include star in id, others are relying on id of related elements, hence adding star
//sorry, messy  i know

//alert(starId);

var starObj = document.getElementById(starId);

if(bool)
{

	//Replace red * with green *
	starObj.style.color = "forestgreen";
	
	//alert(starColor);
	//Check all other essential info stars, 
	
}
else
{
	//nothing happens, but make sure color remains or returns to tomato(not red)
	starObj.style.color = "tomato";


}
//go through set request button procedure
setRequestButton();

}


function checkFormat(id){
//Check format fits the data. 
var idObj = document.getElementById(id);
var dataEntry = idObj.value;

switch(id)
{
case "firstname": case "lastname": 
	
	break;
case "guestemail": 

	//make sure text input is in format of email, ie text@mailprovider.wotsitcalled.xx.xx
	//Using regular expression, first time here, seems to work, catch @ and one dot
	var regex = /^[\w\-._+]+@[\w\-.]+\.[\w\-.]+$/;
	//alert(dataEntry);

	if(!regex.test(dataEntry))
	{
	return false;
	//alert("Please check to make sure you have entered your email correctly.");
	}
	else
	{
	//nothing happens
	//alert("Looking goooood");
	return true;
	}
	break;

}

}


function checkDodgyChars(id){

//Check characters are not dodgy.

}


function setRequestButton(){
//Check all requirements are met before enabling request button for activation.
var starArray = new Array("firstname", "lastname", "guestemail", "guestorg");

var i;
for(i=0;i<=3;i++){
	var starId = starArray[i] + "star";
	var starColor = document.getElementById(starId).style.color;

	//!!!!!!!!Don't use alert here, constantly calls itself!!!

	if(starColor != "forestgreen" && starColor != "rgb(34, 139, 34)" && starColor != "#228b22")
	{
		//exit function to prevent button being prematurely enabled
		document.getElementById("regbutton").disabled = true;

		return;
	}

}
		document.getElementById("regbutton").disabled = false;
		//alert("Set Request");

}


function checkMaxChars(id){
//give alert based on id of input text box
var idObj = document.getElementById(id);
var charLength = idObj.value.length;
//alert(charLength);

switch(id)
{
case "firstname":
	if(charLength == 20){
	alert("Please enter a first name with 20 characters or less. \n" +
	"If this is a problem please contact me.");
	}
	break;

case "lastname":
	if(charLength == 30){
	alert("Please enter a last name with 30 characters or less. \n" +
	"If this is a problem please contact me.");
	}

	break;

case "guestemail":
	if(charLength == 60){
	alert("Please enter an email address with 60 characters or less. \n" +
	"If this is a problem please contact me.");
	}
	break;

case "guestphone":
	if(charLength == 20){
	alert("Please enter a phone number with 20 characters or less. \n" +
	"If this is a problem please contact me.");
	}
	break;

case "guestorg":
	if(charLength == 60){
	alert("Please enter an organisation name with 60 characters or less. \n" +
	"If this is a problem please contact me.");
	}
	break;

}
}



function resetRegForm(){
//returns the registration form to its original appearance, colour and text
var titleEle = document.getElementById("guesttitle");
titleEle.style.color = "silver";
titleEle.selectedIndex = 0;

var firstEle = document.getElementById("firstname");
firstEle.style.color = "silver";
firstEle.value = "First Name";

var lastEle = document.getElementById("lastname");
lastEle.style.color = "silver";
lastEle.value = "Last Name";

var guestEle = document.getElementById("guestemail");
guestEle.style.color = "silver";
guestEle.value = "Enter e-mail address";

var phoneEle = document.getElementById("guestphone");
phoneEle.style.color = "silver";
phoneEle.value = "Enter phone number";

var orgEle = document.getElementById("guestorg");
orgEle.style.color = "silver";
orgEle.value = "Your organisation..";

//clear radio check boxes
document.getElementById("listonly").checked = false;


//return essential star colours to tomato
document.getElementById("firstnamestar").style.color = "tomato";
document.getElementById("lastnamestar").style.color = "tomato";
document.getElementById("guestemailstar").style.color = "tomato";
document.getElementById("guestorgstar").style.color = "tomato";

//disable the register button
document.getElementById("regbutton").disabled = true;


}


//CODE FOR SERVER SIDE AJAX 
function createRequest() {
	var request = null;

	try {
		request = new XMLHttpRequest();
	} catch(trymicrosoft){
		try{
			request = new ActiveXObject("Msxm12.XMLHTTP");
		}catch(othermicrosoft){
			try{
				request = new ActiveXObject("Microsoft.XMLHTTP");
			}catch(failed){
				request = null;
			}
		}
	}
	if (request==null){
		alert("Error creating request object!");
	}
	else{
		return request;
	}
}

var request = createRequest();


function collectGuestInfo(task){
//Grab all the data from the form

var sel = document.getElementById("guesttitle");

var title = sel.options[sel.selectedIndex].value;
//alert("calling server side");

var firstName = document.getElementById("firstname").value;
var lastName = document.getElementById("lastname").value;
var guestEmail = document.getElementById('guestemail').value;
var guestPhone = document.getElementById('guestphone').value;
var guestOrg = document.getElementById('guestorg').value;
var contactListOnly = document.getElementById('listonly').checked;

//One for the future - Parse first and last names to capitalise first letters
//plenty of banana skins tho, hyphens, apostrophes and mc's and van's etc
//not worth it, let user enter their names properly.
//can edit later, manually, if further correspondence occurs

//alert(contactListOnly);
/*

if(contactListOnly == true)
{
contactListOnly = "Yes";
}
else
{
contactListOnly = "No";
}


 
 
if(document.getElementById('chqjoin').checked == true)
{
clChoice = "Yes";
}
else {
clChoice = "No";
}
*/

//alert("Name is " + title);
//alert("Name is " + title + ". " + firstName + " " + lastName);

//alert("Name is " + title + ". " + firstName + " " + lastName + "\n Email: " + guestEmail + "\n Phone: " + guestPhone);
//alert("Email: " + guestEmail + "\n\n Name: " + title + ". " + firstName + " " + lastName + "\n Phone: " + guestPhone + //"\n Organisation: " + guestOrg + "\n Steer Group: " + sgChoice + "\n  Seminar: " + regChoice + "\n Newsletters: " + //upChoice);

//create url for request
var urlApp = "gtitle=" + title + "&fname=" + firstName + "&lname=" + lastName + "&gmail=" + guestEmail + "&gphone=" + guestPhone + "&gorg=" + guestOrg + "&listonly=" + contactListOnly;

//+ "&sgchoice=" + sgChoice + "&clchoice=" + clChoice;

if(task == "confirm"){requestCheck(urlApp)};
if(task == "send"){requestConfirmation(urlApp)};

}



function requestCheck(urlApp){
	//alert("checking details");
	//sends all info to php ajax script which then actually creates and sends emails
	var url = "hsn-reg-ajax.php?task=confirm&" + urlApp;
	request.open("GET", url, true);
	request.onreadystatechange = confirmDetails;
	request.send(null);

}
function confirmDetails(){
//alert(request.readyState);
//alert(request.status);

if(request.readyState==4)
{
	if(request.status==200)

	{
		//alert("conf recieved");

		res = request.responseText;

		if(confirm(res))	
		{
			collectGuestInfo("send");
		}

		//if cancel, alert closes and user can amend details or just leave it.


	}
}

}

function requestConfirmation(urlApp){
	//alert("request to send made");
	//sends all info to php ajax script which then actually creates and sends emails
	var url = "hsn-reg-ajax.php?task=send&" + urlApp;
	request.open("GET", url, true);
	request.onreadystatechange = confirmReg;
	request.send(null);

}

function confirmReg(){
//alert(request.readyState);
//alert(request.status);

if(request.readyState==4)
{
	if(request.status==200)

	{
	//Confirm registration with message in form, clear the form, or return to default text and colours.
	var confMessage = request.responseText;
	//alert("confirming registration by email " + confMessage);

	//remove previous message, just in case
	//Thank user and inform about email.
	var pObj = document.getElementById("regconf");

	removeDomChilds(pObj);

	//Add message
	var pTextNode = document.createTextNode(confMessage);
	pObj.appendChild(pTextNode);

	//alert(confMessage.substring(0,1));
	//reset the form only if mail was successful, read the message to confirm success.
	//Leave details in boxes, don't reset if unsuccessful
	if(confMessage.substring(0,8) == "Thankyou")
	{
		resetRegForm();
	}
	//Message if email process failed


	
	}
}

}


