// JavaScript Document

/*
	general purpose AJAX post function for entry module
*/
function entry_AJAXPost(action, opt_params){
	
	xmlHttp=GetXmlHttpObject();
	if (xmlHttp==null)
 	{
 		alert ("Browser does not support HTTP Request");
 		return;
 	}

	var url=CFG_SWSHOME + "/entry/entry_AJAX.php";
	var full_params = "action="+action + opt_params

	xmlHttp.onreadystatechange=function(){
		entry_AJAXReceive(action);
	};
	xmlHttp.open("POST",url,true);
	
	//Send the proper header information along with the request
	xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

	// REMOVED 7th Jan 2010 - fix for AJAX slowness with SAMX
	//xmlHttp.setRequestHeader("Content-length", params.length);
	//xmlHttp.setRequestHeader("Connection", "close");

	xmlHttp.send(full_params);
	//alert("AJAX:"+full_params);
	
}

function entry_AJAXReceive(action){
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
	 { 
	 	var response = xmlHttp.responseText;
		popDown("msgbox");
		switch(action){
		case "STATUS":
			document.getElementById("list").innerHTML=response; 
			break;
		case "ENTRY_STEP2":			
			entry_PopulateEntryDetails(response);
			break;
		case "ENTRY_BUILD_SELECT_CLASS":
			document.getElementById("classSelectHTML").innerHTML=response; 
			gotoStep("step1", "step2");
			break;
		case "ENTRY_BUILD_SELECT_EVENT":
			document.getElementById("eventSelectHTML").innerHTML=response;
			break;
		case "ENTRY_BUILD_FORM_SAORC":
			document.getElementById("submitHTML").innerHTML=response;
			entry_AJAXPost("ENTRY_BUILD_FORM_PAYPAL", "");
			break;
		case "ENTRY_BUILD_FORM_PAYPAL":
			document.getElementById("paypalHTML").innerHTML=response;			
			gotoStep("step4", "step5");			
			break;
		case "ENTRY_BUILD_FORM_PAYPAL_OTHER":
			document.getElementById("paypalHTML").innerHTML=response;						
			entry_TransfertoPaypal();
			break;
		}
	 } 
	document.body.style.cursor = "default";
}

/*
	Display status of all entries for a given licnumber
*/
function entry_DisplayEntryStatus(licnum, seriesCMB){
	var form = document.round_select;
	var sid = form.series.options[form.series.selectedIndex].value;
	document.getElementById("list").innerHTML="Please wait....";
	
	var params = "&sid="+sid+"&licnum="+licnum;
	entry_AJAXPost("STATUS", params);
}

function gotoStep(currStep, nextStep){
	var currStepDiv;
	var nextStepDiv;
	var canContinue;
	
	// validate step before moving forward (but not if they are going back)

		currStepDiv = document.getElementById(currStep);
		currStepDiv.style.visibility = "hidden";
		currStepDiv.style.height = "0";
		
		nextStepDiv = document.getElementById(nextStep);
		nextStepDiv.style.visibility = "visible";
		nextStepDiv.style.height = "400px";

}


// --------------------------------------------------------------
// update saorc database and then begin paypal process
// call entry_process.php

function processEntry()
{
	var params;
	var entry = document.entry;
	var series = document.entry.series.options[document.entry.series.selectedIndex].value;
	var eventid = document.entry.event.options[document.entry.event.selectedIndex].value;
	var lname = document.entry.lname.value;
	var fname = document.entry.fname.value;
	var malic = document.entry.licnum.value;
	var licexp = document.entry.licexp_date.value;
	var numb = document.entry.number.value;
	var rclass = document.entry.classcode.options[document.entry.classcode.selectedIndex].value;
	
	params="event="+eventid+"&number="+numb+"&licnum="+malic+"&fname="+fname+"&lname="+lname+"&series="+series+"&classcode="+rclass;
	
	var mmake = entry.machmake.options[entry.machmake.selectedIndex].value;
	var mmodel = entry.machmodel.value;
	var entlic = entry.entlic.value;
	var entname = entry.entname.value;
	var sponsors = entry.sponsor.value;
	var club = entry.club.value;
	
	params=params+"&mmake="+mmake+"&mmodel="+mmodel+"&entlic="+entlic+"&entname="+entname+"&sponsors="+ sponsors+"&club="+club;
	
	var age = entry.age.value;
	var dob = entry.dob.value;
	var hphone = entry.hphone.value;
	var mphone = entry.mphone.value;
	var paddr = entry.postaddr.value;
	var emailaddr = entry.emailaddr.value;
	var econtname = entry.emergContactName.value;
	var econtphone = entry.emergContactPhone.value;
	var econtaddr = entry.emergContactAddr.value;
	
	params=params+"&age="+age+"&dob="+dob+"&hphone="+hphone+"&mphone="+mphone+"&paddr="+ paddr;
	params=params+"&emailaddr="+emailaddr+"&econtname="+econtname+"&econtphone="+econtphone+"&econtaddr=" + econtaddr + "&licexp=" + licexp;
	
	xmlHttp=GetXmlHttpObject();
	if (xmlHttp==null)
 	{
 		alert ("Browser does not support HTTP Request");
 		return;
 	}
	var url="entry_process.php";
	
	COM_MsgBox("Submitting Entry. Please Wait...");
	
	//url=url+"?q="+str
	xmlHttp.onreadystatechange=stateChangedProcessEntry ;
	xmlHttp.open("POST",url,true);
	//Send the proper header information along with the request
	xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

	// REMOVED 7th Jan 2010 - fix for AJAX slowness with SAMX
	//xmlHttp.setRequestHeader("Content-length", params.length);
	//xmlHttp.setRequestHeader("Connection", "close");

	xmlHttp.send(params);
	
}

function stateChangedProcessEntry() 
{ 
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
	 { 
	 	var response = xmlHttp.responseText;
		var msg = ' ';
		
		popDown("msgbox");
		//alert("statechanged <"+response+">");
		// if no error
		if (response.indexOf("ERROR")< 0 && response.indexOf("error")< 0)
		{
			// if db success then submit paypal form
			// get amount and bus value from response
			
			var eventinfo = response.split("^");
			// extra ^ in front to skip junk in front of data
			var eid = trim(eventinfo[1]);
			var eventname = trim(eventinfo[2]);
			var cost = trim(eventinfo[3]);
			var puser = trim(eventinfo[4]);
			var sname = trim(eventinfo[5]);
			var sid = trim(eventinfo[6]);						
			var cc = document.entry.classcode.options[document.entry.classcode.selectedIndex].value;

			
			document.paypal.item_name.value = "Entry to " + eventname + " of " + sname + " for " + document.entry.fname.value + " " + document.entry.lname.value + ", #" + document.entry.number.value;
			document.paypal.item_number.value = sid +"."+ eid + "." + cc; // seriesid.eventid
			document.paypal.amount.value = cost;
			document.paypal.business.value = puser;
			document.paypal.custom.value =  cc;
			document.paypal.invoice.value = document.entry.licnum.value+"."+document.paypal.item_number.value;  // must be unique
		
			//msg = "item number=" + document.paypal.item_number.value + " item name=" + document.paypal.item_name.value;
			//msg = msg + " amount=" + document.paypal.amount.value + " business=" + document.paypal.business.value;
			//alert(msg);

			alert("Your request for entry has been successfully recorded in the " + g_webSiteName + " database.\n\n You will now be directed to paypal for immediate payment.");
			document.paypal.submit();
	
		} else 
		{
			// else display error message to user
			// alert(response);
			alert(response); 
	 	}
		
		//messageWindow("Thankyou", "Thankyou for testing SA ORC online entry. Please note this is a prototype only.  Online entry is NOT yet available.");

	 } 
	 document.body.style.cursor = "default";
	 document.entry.submitbutton.style.cursor = "default";
}

function entry_changeEvent(evSelType)
{
	//alert("SAORC DEBUG: Please ignore. ["+evSelType+","+evSelType.length+"]");
	var form;

	if (evSelType == 1)
	{	
		form = document.entry;
	} else
	{
		form = document.round_select;
	}
	
	var sel = form.event.selectedIndex;
	
	if (form.event.options[0].value < 0 && form.event.options[sel].value > 0)
	{
			// remove the please select a round option
			
			form.event.remove(0);
			//alert(evSelType);
			// if entry
			if (evSelType == "1")
			{			
				form.stepOneCont.disabled=false;
			}
	}
}



function entry_BuildEventSelect(evSelType)
{ 
	var form;

	if (evSelType == 1)
	{	
		form = document.entry;
	} else
	{
		form = document.round_select;
	}
	
	document.body.style.cursor = "wait";
	//form.series.style.cursor = "wait";

	var sel = form.series.selectedIndex;

	if (form.series.options[0].value < 0 && form.series.options[sel].value > 0)
	{
			// remove the please select a series option
			form.series.remove(0);
	}

	COM_MsgBox("Retrieving Event Details...");
	
	var params = "&sid="+entry_GetSID(form)+"&es_type="+evSelType;
	entry_AJAXPost("ENTRY_BUILD_SELECT_EVENT", params);
	
}

function changenonumber()
{

	if (document.entry.nonumber.checked){
		document.entry.number.value="TBD";
		document.entry.number.disabled=true;
	} else
	{
		document.entry.number.value="";
		document.entry.number.disabled=false;
	}
}


function entry_ChangeClass()
{
	var sel = document.entry.classcode.selectedIndex;

	if (document.entry.classcode.options[0].value < 0 && document.entry.classcode.options[sel].value != -1)
	{
			// remove the please select a round option
			document.entry.classcode.remove(0);
	}
	entry_CheckEnableStep3Cont();
}

function entry_BuildClassSelect(form)
{ 
	var params = "&sid="+entry_GetSID(form);
	entry_AJAXPost("ENTRY_BUILD_SELECT_CLASS", params);
}

function entry_BuildSubmit()
{
	var form=document.entry;
	var event=form.event;
	
	var sn=form.series.options[form.series.selectedIndex].text;
	var en=event.options[event.selectedIndex].text;
	var cn=form.fname.value+' '+form.lname.value;
	var ln=form.licnum.value;
	var numb=form.number.value;
	var cl=form.classcode[form.classcode.selectedIndex].text;
	var em=form.emailaddr.value;
	
	var params = "&sn="+sn+"&en="+en+"&cn="+cn+"&licnum="+ln+"&numb="+numb+"&cl="+cl+"&em="+em;
	entry_AJAXPost("ENTRY_BUILD_FORM_SAORC", params);
}

function checkStepOne()
{
	var sel = document.entry.event.selectedIndex;
	var eventid = document.entry.event.options[sel].value;
		
	sel = document.entry.series.selectedIndex;
	var seriesid = document.entry.series.options[sel].value;
		//alert("in echck step 1");
	// if event and series selected		
	if (eventid > 0 && seriesid > 0)
	{
		entry_BuildClassSelect(document.entry);		
		
	}else
	{
		alert("You must select a Series and a Round to continue.");
	}	
}

function entry_CheckStepTwo()
{
	var form = document.entry;
	var eventid = form.event.options[form.event.selectedIndex].value;
	//var sid = document.entry.series.options[document.entry.series.selectedIndex].value;
	var sid = entry_GetSID(form);
	var licnum = form.licnum.value;
	var numb = form.number.value;
	var newNumber = form.nonumber.value;
	var msg = "Cannot Continue to Next Step\n\n";
	var stepValid = "TRUE";
	
	//alert(seriesid);
	if (licnum.length < 5){
		msg = msg + "MA Licence number must be more than 4 digits.\n";
		stepValid = "FALSE";
	}
	if (numb.length == 0 && !form.nonumber.checked == 1){
		msg = msg + 'Enter a Series Number or check "Request Series Number".\n';
		stepValid = "FALSE";
	} else if(form.nonumber.checked == 1){
		numb="TBD";
		form.number.value = numb;
	}

	var c_ind = document.entry.classcode.selectedIndex;
	var cc = "";
	if (c_ind < 0) c_ind = 0;
	cc = document.entry.classcode.options[c_ind].value;
	
	// if both class and make have been selected then enable continue
	if (cc == -1)
	{
		msg = msg + 'Please select a class before continuing.\n';
		stepValid = "FALSE";
	}

	//alert(stepValid);
	if (stepValid == "TRUE"){
		// now need to check if details are unique		
		var params = "&sid="+sid+"&licnum="+licnum+"&eventid="+eventid+"&numb="+numb+"&cl="+cc;
		entry_AJAXPost("ENTRY_STEP2", params);
	} else {
		alert(msg);		
	}
}

function entry_PopulateEntryDetails(details) 
{ 
	var resp = details;
	var eventinfo;
	var mesg ;
	eventinfo = details.split("^");
	mesg = eventinfo[0];
	
	// if anything but SUCCESS
	if (mesg.indexOf("WARNING")>-1){
		alert(mesg);
	}
	if (mesg.indexOf("ERROR")>-1){
		alert(mesg);
	}
	// if anything but ERROR
	if (mesg.indexOf("ERROR")<0)
	{
		// need to remove entry fields from end of message
		//var s = resp.indexOf("^");
		//var tmp = resp.substr(s + 1, resp.length - s); // skip first ^
		//resp = resp.substr(0, s);
		//eventinfo = tmp.split("^");
		//alert(resp +">"+s+"<" + tmp);	
		//g_defClass = eventinfo[0];
		document.entry.machmake.selectedIndex = 0;
		document.entry.stepThreeCont.disabled = true;
		
		document.entry.machmake.value = eventinfo[2];
		document.entry.machmodel.value = eventinfo[3];
		document.entry.entlic.value = eventinfo[4];
		document.entry.entname.value = eventinfo[5];
		document.entry.sponsor.value = eventinfo[6];
		document.entry.club.value = eventinfo[7];
		document.entry.age.value = eventinfo[8];
		document.entry.dob.value = eventinfo[9];
		document.entry.hphone.value = eventinfo[10];
		document.entry.mphone.value = eventinfo[11];
			
		document.entry.emailaddr.value = eventinfo[12];
		document.entry.emergContactName.value = eventinfo[13];
		document.entry.emergContactPhone.value = eventinfo[14];			
		document.entry.lname.value = eventinfo[15];
		document.entry.fname.value = eventinfo[16];
		// 17 - number
		//document.entry.licexp_date.value = eventinfo[18];				
		//alert(details);		
		// no longer take class from previous entry
		//document.entry.class_code.value = eventinfo[1];

	 	gotoStep("step2", "step3");
		entry_CheckEnableStep3Cont();
	}
	
}

function entry_ChangeMake()
{

	var lb = document.entry.machmake;
	if (lb.options[0].value < 0 && lb.options[lb.selectedIndex].value != -1)
	{
			// remove the please select a ... option
			lb.remove(0);
	}
	entry_CheckEnableStep3Cont();
}

function entry_CheckEnableStep3Cont()
{
	var m_ind = document.entry.machmake.selectedIndex;			
	var c_ind = document.entry.classcode.selectedIndex;
	
	if (m_ind < 0) m_ind = 0;
	if (c_ind < 0) c_ind = 0;
	
	// if both class and make have been selected then enable continue
	if (document.entry.machmake.options[m_ind].value != -1 && document.entry.classcode.options[c_ind].value != -1)
	{
		document.entry.stepThreeCont.disabled=false;
	}
	
}


function entry_CheckStepThree()
{
	// internal checking because cont not enabled until make and class selected
	// all other fields are optional
	var lname = document.entry.lname.value;
	var fname = document.entry.fname.value;
	var msg = "Cannot Continue to Next Step\n\n";
	stepValid = "TRUE";
	
	if (lname.length <3) {
		msg = msg + "Last name is a required field and must be more than 2 characters.\n";
		stepValid = "FALSE";
	}
	
	if (fname.length <3){
		msg = msg +"First name is a required field and must be more than 2 characters.\n";
		stepValid = "FALSE";
	}
	
	if (stepValid.match("TRUE")){
		gotoStep("step3", "step4");
	} else {
		alert (msg);
	}
	
	return("TRUE");
	
}

function checkStepFour()
{
	// need to check that all fields are completed
	var msg = "Cannot Continue to Next Step\n\n";
	var stepValid = "TRUE";
	var age = document.entry.age.value;
	var hphone = document.entry.hphone.value;
	var mphone = document.entry.mphone.value;
	var paddr = document.entry.postaddr.value;
	var eaddr = document.entry.emailaddr.value;
	var eContName = document.entry.emergContactName.value;
	var eContPhone = document.entry.emergContactPhone.value;
	var eContAddr = document.entry.emergContactAddr.value;
	
	if (age.length <1) {
		msg = msg + "Age is a required field and must be more than 1 characters.\n";
		stepValid = "FALSE";
	}
	if (hphone.length <8 && mphone.length <8) {
		msg = msg + "Either a valid Home or Mobile Phone Number is required (must be more than 7 digits).\n";
		stepValid = "FALSE";
	}
	if (paddr.length <10) {
		msg = msg + "A valid Postal Address is required (must be more than 10 letters).\n";
		stepValid = "FALSE";
	}
	if (eaddr.length <10) {
		msg = msg + "A valid Email Address is required (must be more than 10 letters.\n";
		stepValid = "FALSE";
	}
	if (eContName.length <2) {
		msg = msg + "A valid Emergency Contact Name is required (must be more than 2 letters).\n";
		stepValid = "FALSE";
	}
	
	if (eContPhone.length <2) {
		msg = msg + "A valid Emergency Contact Hone number is required (must be more than 2 letters).\n";
		stepValid = "FALSE";
	}
	if (eContAddr.length <10) {
		msg = msg + "A valid Emergency Contact Hone Address is required (must be more than 10 letters).\n";
		stepValid = "FALSE";
	}
	
	if (stepValid == "TRUE"){
		entry_BuildSubmit();
	} else
	{
	alert(msg);
	}
	
}


function ent_ShowEntryHelp(stepNum)
{
	COM_ShowHelp(CFG_HELP_ENTRY);
	//var helpDiv = document.getElementById("helpHTML");
	//helpDiv.innerHTML = "test help";
	//helpDiv.style.visibilty = "visible";
	//helpDiv.style.height = "200px";
	//alert("mouseover");
	//alert(stepNum);
	/*
	var msg;
	msg = "<h2>SAORC Online Entry Help</h2>";
	msg = msg + '<p>For general SAORC entry process information click <a target="_blank" href="../information.php#entry">here.</a></p>';

	if (stepNum == "step1")
	{
		msg = msg + '<ul><li>It is assumed that all competitors have read the Supplementary Regulations available from your series home page</a>.</li>';
		msg = msg + '<li>To enter online all entrants must have a valid MA Racing Licence.</li><li>SAORC recommends that all competitors register with <a target="_blank" href="http://www.paypal.com.au">paypal</a> before planning to enter online.</li>';
		msg = msg + '<li>To enter online all entrants must have an allocated Series Riding Number.</li>';
		msg = msg + '<li>Competitors under the age of 18 will need to display a completed entry form signed by their guardian on the day of the event at registration.</li>';		
		msg = msg + '<li>Opening dates for each round are set by the event promoter (club).</li><li>Closing dates for online entries are available from your series home page.</li><li>Online entries qualify for the cheaper early bird fee.</li></ul>';

	} else if (stepNum == "step2") 
	{
		msg = msg + '<ul><li>Series numbers are available <a href="../information.php#numbers" target="_blank">here</a>.</li>.<li>If you do not have a series riding number, check "Request Series Number" and the website will automatically send an email requesting a number to the series results coordinator.</li></ul>';
	} else if (stepNum == "step3") 
	{
		msg = msg + '<ul><li>Sorry. No help available for this step.</li></ul>';
	} else if (stepNum == "step4") 
	{
		msg = msg + '<ul><li>As a security measure address will not be auto populated. It will need to be re-entered each time.</li></ul>';
	} else if (stepNum == "step5")
	{
		msg = msg + "<ul><li>Check your details. If they are incorrect then go back to the corresponding step and correct them.</li><li>Upon submitting your entry you will be redirected to paypal for immediate payment.</li></ul>";

	}

	msg = msg + '<p>Further assistance can be obtained by emailing the web site administrator <a href="mailto:info@saoffroadchampionships.com?subject=SAORC%20Online%20Entry%20Help">info@saoffroadchampionships.com </a></p>';
	//messageWindow("Online Entry Help", msg);
	
	COM_MsgBox(msg);
	*/
}



function ENT_ShowEntryStatusHelp(){
	COM_ShowHelp(CFG_HELP_ENTRYSTATUS);
}

function submitEntry()
{	
	document.body.style.cursor = "wait";
	document.entry.submitbutton.style.cursor = "wait";

	// process entry at database
	processEntry();
	
}

function entry_GetSID(form){
	return form.series.options[form.series.selectedIndex].value;
}

function entry_PlaceOrder(){
	var emsg = "";
	var order = document.order;
	var p_name = COM_StripHTML(trim(order.payer_name.value));
	var p_phone = COM_StripHTML(trim(order.payer_phone.value));
	var p_email = COM_StripHTML(trim(order.payer_email.value));
	
	if (p_name.length < 8 ){
		emsg = "Name (> 7 chars)\n";
	}
	if (p_phone.length < 7){
		emsg = emsg + "Phone (> 6 digits)\n";
	}
	if (p_email.length < 8){
		emsg = emsg + "Email (> 7 chars)\n";
	}
	if (emsg.length > 0 ){
		alert("Please enter valid values for the following fields:\n" + emsg);
	} else {
		msgBox("Your request to place an order of tickets is being processed. Please wait...");
		entry_AJAXPost("ENTRY_BUILD_FORM_PAYPAL_OTHER", "");			
	}
}

function entry_TransfertoPaypal(){
	
	var order = document.order;
	//var nt_adult = order.numtickets_adult.options[order.numtickets_adult.selectedIndex].value;
	//var nt_child = order.numtickets_child.options[order.numtickets_child.selectedIndex].value;
	var p_name = COM_StripHTML(order.payer_name.value);	
	var p_phone = COM_StripHTML(order.payer_phone.value);	
	var p_email = COM_StripHTML(order.payer_email.value);
	var p_misca = COM_StripHTML(order.payer_misca.value);
	//var p_miscb = COM_StripHTML(order.payer_miscb.value);
	var num_adults = order.numtickets_adult.options[order.numtickets_adult.selectedIndex].value;
	var num_child =  order.numtickets_child.options[order.numtickets_child.selectedIndex].value;
	var p_miscb = num_adults + " adult, " + num_child + " child.";
	var cost = order.totalcost.value;
	
	document.paypal.item_name.value = "SAORC_PRES2011: " + p_name + ": " + p_phone + ": " + p_email + ": " + p_misca + ": " + p_miscb;
	document.paypal.item_number.value = "2011.8"; // seriesid.eventid
	document.paypal.amount.value = cost;
	document.paypal.business.value = "juventusmcc@saoffroadchampionships.com";
	document.paypal.custom.value = p_email;
	document.paypal.invoice.value = "2011.8." + p_phone;  // must be unique
	//alert (document.paypal.image_url.value);
	msgBox("You are now being directed to paypal for immediate payment. Please Wait...");
	document.paypal.submit();
}
;


