//<?
var currentTable = -1;
var currentRow = -1;
var doAJAXcall = false; //initally set AJAX call to false
var timeOutFunc;
var selectedFieldID;
var course_id;
var teeDate;
var teeTime;

//////////////////////////////////////////////////////////////////////////
//AJAX
//////////////////////////////////////////////////////////////////////////

// stores the reference to the XMLHttpRequest object
var xmlHttp = createXmlHttpRequestObject(); 

var dayOfWeek = ["Su","Mo","Tu","We","Th","Fr","Sa","Su"];
var month = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug", "Sep", "Oct", "Nov", "Dec"];

// creates an XMLHttpRequest instance
function createXmlHttpRequestObject() 
{
  // will store the reference to the XMLHttpRequest object
  var xmlHttp;
  // this should work for all browsers except IE6 and older
  try
  {
    // try to create XMLHttpRequest object
    xmlHttp = new XMLHttpRequest();
  }
  catch(e)
  {
    // assume IE6 or older
    var XmlHttpVersions = new Array('MSXML2.XMLHTTP.6.0',
                                    'MSXML2.XMLHTTP.5.0',
                                    'MSXML2.XMLHTTP.4.0',
                                    'MSXML2.XMLHTTP.3.0',
                                    'MSXML2.XMLHTTP',
                                    'Microsoft.XMLHTTP');
    // try every prog id until one works
    for (var i=0; i<XmlHttpVersions.length && !xmlHttp; i++) 
    {
      try 
 
      { 
        // try to create XMLHttpRequest object
        xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
      } 
      catch (e) {}
    }
  }
  // return the created object or display an error message
  if (!xmlHttp)
    alert("Error creating the XMLHttpRequest object.");
  else 
    return xmlHttp;
}

// make asynchronous HTTP request using the XMLHttpRequest object 

function getAddInfo(BookingStatus, SummaryOSBalance, SummaryTotalPrice, PaymentTotal, custID, tourOp) {
	//wait half a second
	doAJAXcall = true;
    setTimeout('getAddInfoMain("' + BookingStatus + '", "' + SummaryOSBalance + '", "' + SummaryTotalPrice + '", "' + PaymentTotal + '", "' + custID + '", "' + tourOp + '")', 1000);
}

function getAddInfoMain(BookingStatus, SummaryOSBalance, SummaryTotalPrice, PaymentTotal, custID, tourOp) {
  // proceed only if the xmlHttp object isn't busy and our call hasn't been cancelled
  if (doAJAXcall && (xmlHttp.readyState == 4 || xmlHttp.readyState == 0))
  {
	    // execute 
	    url = "ajax_get_add_info.php?bs=" + BookingStatus + "&osb=" + SummaryOSBalance + "&tp=" + SummaryTotalPrice + "&pt=" + PaymentTotal + "&custID=" + custID + "&tourOp=" + tourOp;
	    //alert(url);
	    xmlHttp.open("GET", url, true);  
	    // define the method to handle server responses
	    xmlHttp.onreadystatechange = handleServerResponse;
	    // make the server request
	    xmlHttp.send(null);
  }
  else
    // if the connection is busy, try again after so many miliseconds
    //setTimeout('getAddInfo("' + BookingStatus + '", "' + SummaryOSBalance + '", "' + SummaryTotalPrice + '", "' + PaymentTotal + '", "' + custID + '", "' + tourOp + '")', 100);
    ;
}

// executed automatically when a message is received from the server
function handleServerResponse() 
{
  // move forward only if the transaction has completed
  if (xmlHttp.readyState == 4) 
  {
    // status of 200 indicates the transaction completed successfully
    if (xmlHttp.status == 200) 
    {
      // extract the XML retrieved from the server
      xmlResponse = xmlHttp.responseXML;
      // obtain the document element (the root element) of the XML structure
      xmlDocumentElement = xmlResponse.documentElement;
      
      //the first obejct is the response object
      respNode = xmlDocumentElement.firstChild;

      html = "";
      osb = "";
      tp = "";
      bs = "";
      pt = "";

		osbList = xmlDocumentElement.getElementsByTagName("osb");      
		if (osbList.length > 0) {
			osb = getFirstItemDataValue(osbList);
			html = "<b><span style=color:red>Outstanding Balance " + osb + "</span></b><br>";
		}
	
		tpList = xmlDocumentElement.getElementsByTagName("tp");      
		if (tpList.length > 0) {
			tp = getFirstItemDataValue(tpList);
			//if osb zero then show "Paid Up"
			if (osb == "") html += "<b><span style=color:green>Fully Paid Up</span></b><br>";
		}
				      
      
		ptList = xmlDocumentElement.getElementsByTagName("pt");      
		if (ptList.length > 0) {
			pt = getFirstItemDataValue(ptList);
		}
		
		//add other additional info
		html += "<table class='olFontClass'>";

		bsList = xmlDocumentElement.getElementsByTagName("bs");      
		if (bsList.length > 0) {
			bs = getFirstItemDataValue(bsList);
			html += "<tr><td><b>Booking Status:</b></td><td>" + bs + "</td></tr>";
		}
		
		if (tp != "") html += "<tr><td><b>Total Cost:</b></td><td>" + tp + "</td></tr>";
		if (pt != "") html += "<tr><td><b>Paid:</b></td><td>"       + pt + "</td></tr>";

		companyList = xmlDocumentElement.getElementsByTagName("company");      
		if (companyList.length > 0) {
			company = getFirstItemDataValue(companyList);
			html += "<tr><td><b>Company:</b></td><td>" + company + "</td></tr>";
		}
		nameList = xmlDocumentElement.getElementsByTagName("name");      
		if (nameList.length > 0) {
			name = getFirstItemDataValue(nameList);
			html += "<tr><td><b>Contact:</b></td><td>" + name + "</td></tr>";
		}
		phoneList = xmlDocumentElement.getElementsByTagName("phone");      
		if (phoneList.length > 0) {
			phone = getFirstItemDataValue(phoneList);
			html += "<tr><td><b>Phone:</b></td><td>" + phone + "</td></tr>";
		}
		emailList = xmlDocumentElement.getElementsByTagName("email");      
		if (emailList.length > 0) {
			email = getFirstItemDataValue(emailList);
			html += "<tr><td><b>Email:</b></td><td><a href='mailto:" + email + "'>" +  email + "</td></tr>";
		}
		countryList = xmlDocumentElement.getElementsByTagName("country");      
		if (countryList.length > 0) {
			country = getFirstItemDataValue(countryList);
			html += "<tr><td><b>Country:</b></td><td>" +  country + "</td></tr>";
		}
		touropList = xmlDocumentElement.getElementsByTagName("tourop");      
		if (touropList.length > 0) {
			tourop = getFirstItemDataValue(touropList);
			html += "<tr><td><b>Tour Operator:</b></td><td>" +  tourop + "</td></tr>";
		}
		
		html += "</table>";

      //display popup
      olib(html, 'Additional Details');
    } 
    // a HTTP status different than 200 signals an error
    else 
    {
      alert("There was a problem accessing the server: " + xmlHttp.statusText);
    }
  }
}

// Member selection

function selectName(fieldID, e, d_date) {
	clearTimeout(timeOutFunc);
	prevEnteredName = '';    //force refresh when we chane something
	
	if(window.event) {  // IE
	  keynum = e.keyCode;
    } else if(e.which) {// Netscape/Firefox/Opera
	  keynum = e.which;
  	}
  	//alert(keynum);
  	if (keynum == 39 || keynum == 40) highlightTableRow(currentTable, currentRow + 1, 'up');
  	else if (keynum == 37 || keynum == 38) highlightTableRow(currentTable, currentRow - 1, 'down');
  	else if (keynum == 13) selectRow(); 
 	else {
	    timeOutFunc = setTimeout("selectNameMain('" + fieldID + "', '" + d_date + "')", 400);
 	}
    return false;
}	

var prevEnteredName;
var prevfieldID;

function selectNameMain(fieldID, d_date) {
	field = document.getElementById(fieldID);
	enteredName = trim(field.value);

	if (prevEnteredName == enteredName && prevfieldID == fieldID) {
		return false;
	}
	
	prevEnteredName = enteredName;
	prevfieldID = fieldID;

	clearHiddenValues(fieldID);

	//check for words guest of/with
	checkLength = 3;
	enteredName = enteredName.toUpperCase();
	words = enteredName.split(" ");
	if (words[0] == "GUEST") {
		checkLength += 6;    //GUEST <plus space>

		if (words[1] == "OF")   checkLength += 3;
		if (words[1] == "WITH") checkLength += 5;
	}

	if (enteredName.length < checkLength) {
		cClick();
	} else {
		
		if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
		    url = "ajax_search_members.php?name=" + encodeURIComponent(enteredName) + "&fieldID=" + fieldID + "&d_date=" + d_date;
		    //alert(url);
		    xmlHttp.open("GET", url, true);  
		    xmlHttp.onreadystatechange = gotNames;
		    xmlHttp.send(null);
		} else {
		    timeOutFunc = setTimeout("selectNameMain('" + fieldID + "', '" + d_date + "')", 100);
		}
	}
}		

var tableCount = 0;
var topCaption = '';

function gotNames() {
  if (xmlHttp.readyState == 4) {  // move forward only if the transaction has completed
   if (xmlHttp.status == 200) {   // status of 200 indicates the transaction completed successfully
   	
		xmlResponse = xmlHttp.responseXML;
		xmlDocumentElement = xmlResponse.documentElement;
		
		fieldID = xmlDocumentElement.getElementsByTagName("fieldID").item(0).firstChild.nodeValue;
   		field = document.getElementById(fieldID);
		x = findPosX(field);
		y = findPosY(field) +  17;
		
		tableCount = 0;
		selectedFieldID = fieldID;
		currentTable = 1;
		currentRow = -1;

		html = getHtmlTable('competition', 'Select Competition');
		    
		html += getHtmlTable('member', 'Select Member');
		    
		html += getHtmlTable('contact', 'Select Contact');
		
		if (tableCount > 0) {
		    olib2(html, topCaption, x, y);
		} else { 
		    olib2('', 'no matching names', x, y);
		}
	}
  }
}

function getHtmlTable(entName, caption) {
	html = '';
	contacts = 0;
	members  = 0;
	category = '';
	prevCategory = 'x';
	entities = xmlDocumentElement.getElementsByTagName(entName);
	numEnt = entities.length;
	
	if (numEnt > 0) {

		//get first category for contacts
		if (caption == 'Select Contact') {
			contacts = 1;
			
		//check guestof Flag for members
		} else if (caption == 'Select Member') {
			members = 1;
		}
		
		for (var i=0; i<numEnt; i++) {
			entity = entities.item(i);
			len = entity.childNodes.length;
			
			if (contacts == 1) {
				category = getHtmlChildDataValue(entity, 0);
				if (category == '') category = 'Contact';
				caption = 'Select ' + category;
			}
			
			if (category != prevCategory) {
				if (tableCount > 0) {
					
					//finish other table
					if (i>0) {
						html += "</table>";
						html += "</div>";
					}		
					
					html += "<table class='olCloseFontClass' border='0' cellpadding='2' cellspacing='0' width='100%'>" +
							"<tr bgcolor='#B0CBE2'><td><div class='olCapFontClass'><div style='float: left;'>" + caption + "</div></div></td></tr></table>";
				} else {
					topCaption = caption;
				}
			
				tableCount++;
				ii = 0;
	
				//for ie, height style also required
				var heightIE;
				if (olIe4) heightIE = 'height: 100px;';
				html += "<div style='max-height: 100px;  overflow: auto; " + heightIE + "'>";
				html += "<table id='" + entName + "_table' class='olFontClass' style='cursor:pointer'>";
			}
			prevCategory = category;
			
			html += "<tr onmouseover=\"highlightTableRow(" + tableCount + ", " + ii + ", '')\" onclick=\"selectRow()\">";
			hidden = '';
			ii++;
					
			for ( j=0; j<len ; j++) {
				valueString = getHtmlChildDataValue(entity, j);			
				//hide contact id and details after pos postcode (7)
				if (contacts && (j==0 || j == 4 || j > 6)) hidden = "style='display:none'";
				else 									   hidden = "";
				
				//for members hide the guest of flag at pos 0 
				if (members && j==0) {
					if (valueString == '0') {
						hidden = "style='display:none'";
					} else {
						hidden = "";
						valueString = 'Guest&nbsp;with'
					}
				}

				html += "<td " + hidden + "> " + valueString + "</td>";
			}		
			html += "</tr>";
		}	
		html += "</table>";
		html += "</div>";
	}	
	return html;
}

 
function highlightTableRow(t, n, scroll) {
	tables = over.getElementsByTagName('table');
	if (tables.length < 4) return;
	
	oldTable = tables[currentTable * 2 + 1];
	oldRows  = oldTable.getElementsByTagName('tr');
	 
	newTable = tables[t * 2 + 1];
	newRows  = newTable.getElementsByTagName('tr');

	if (n < 0) {
		if (t > 1) {
			t--;
			newTable = tables[t * 2 + 1];
			newRows  = newTable.getElementsByTagName('tr');
			n = newRows.length - 1;
		} else {
			n = 0;
		}
	}
	
	if (n >= newRows.length) {
		if (t < tableCount) {
			t++;
			newTable = tables[t * 2 + 1];
			newRows  = newTable.getElementsByTagName('tr');
			n = 0;
		} else {
			n = newRows.length - 1;
		}
	}
	
	if (currentRow >= 0) oldRows[currentRow].style.backgroundColor='#FFFFFF';
	newRows[n].style.backgroundColor='#D5D5D5';
	
	//scroll containing div window
	if (scroll != '') {
		divWindow = newTable.parentNode;
		divWindow.scrollTop = newRows[n].offsetTop;
	}

	
	currentTable = t;
	currentRow = n;
}

function selectRow() {
	if (over == null) return;
	tables = over.getElementsByTagName('table');
	if (tables.length < 4) return;
	
  	table = tables[currentTable * 2 + 1];
	rows  = table.getElementsByTagName('tr');

	if (rows.length > 0) {
		row = rows[currentRow];
		
		if (table.id == 'member_table') {
			guestFlag  	= getTextChildDataValue(row, 0);
			surname 	= getTextChildDataValue(row, 1);
			firstName 	= getTextChildDataValue(row, 2);
			initials 	= getTextChildDataValue(row, 3);
			username 	= getTextChildDataValue(row, 4);
			memType 	= getTextChildDataValue(row, 5);
			
			fullName = firstName;
			if (initials.length > 0) {
				if (fullName.length > 0) fullName += ' ';
				fullName += initials;
			}
			if (surname.length > 0) {
				if (fullName.length > 0) fullName += ' ';
				fullName += surname;
			}
			
			if (guestFlag != '0') {
				fullName = 'Guest with';
				if (firstName.length > 0) fullName += ' ' + firstName;
				if (surname.length   > 0) fullName += ' ' + surname;
			} 
			
			field = document.getElementById(selectedFieldID);
			field.value = fullName;
				
			// set username field for guest of, or GUINo field for member
			if (guestFlag != '0') {
				field = document.getElementById(selectedFieldID + "Username");
				if (field != null) field.value = username;

				field = document.getElementById(selectedFieldID + "GUINo");
				if (field != null) field.value = '';

				field = document.getElementById(selectedFieldID + "MemType");
				if (field != null) field.innerHTML = '';
			} else {
				field = document.getElementById(selectedFieldID + "Username");
				if (field != null) field.value = '';

				field = document.getElementById(selectedFieldID + "GUINo");
				if (field != null) field.value = username;
				
				field = document.getElementById(selectedFieldID + "MemType");
				if (field != null) field.innerHTML = memType;
			}
			
			//competition purse
			if (selectedFieldID == 'compPurseTopUp') {
				// get comp purse balance by submitting the form
				document.getElementById('topup').value = 0; // set hidden topup to zero, so we don't try to do a topup
				document.topupForm.submit();
			}
			
			
		} else if (table.id == 'contact_table') {
			category 	= getTextChildDataValue(row, 0);
			company 	= getTextChildDataValue(row, 1);
			surname 	= getTextChildDataValue(row, 2);
			firstname 	= getTextChildDataValue(row, 3);
			id 			= getTextChildDataValue(row, 4);
			
			fullName = company;
			if (fullName.length == 0) {
				fullName = firstname;
				if (surname.length > 0) {
					if (fullName.length > 0) fullName += ' ';
					fullName += surname;
				}
			}
			
			field = document.getElementById(selectedFieldID);
			field.value = fullName;
			
			field = document.getElementById(selectedFieldID + "_id");
			if (field != null) field.value = id;
			
			//other customer fields
			if (selectedFieldID == 'customer') {
				document.getElementById("Category").value 			= getTextChildDataValue(row, 0);
				document.getElementById("CompanyName").value 		= getTextChildDataValue(row, 1);
				document.getElementById("Surname1").value 			= getTextChildDataValue(row, 2);
				document.getElementById("Firstname1").value 		= getTextChildDataValue(row, 3);
				document.getElementById("customer_id").value 		= getTextChildDataValue(row, 4);
				document.getElementById("Address1").value 			= getTextChildDataValue(row, 5);
				document.getElementById("PostcodeZip").value 		= getTextChildDataValue(row, 6);
				document.getElementById("Title1").value 			= getTextChildDataValue(row, 7);
				document.getElementById("Position1").value 			= getTextChildDataValue(row, 8);
				document.getElementById("TelephoneHome1").value 	= getTextChildDataValue(row, 9);
				document.getElementById("TelephoneWork1").value 	= getTextChildDataValue(row, 10);
				document.getElementById("Mobile1").value 			= getTextChildDataValue(row, 11);
				document.getElementById("Email1").value 			= getTextChildDataValue(row, 12);
				document.getElementById("Fax").value 				= getTextChildDataValue(row, 13);
				document.getElementById("Address2").value 			= getTextChildDataValue(row, 14);
				document.getElementById("TownCity").value			= getTextChildDataValue(row, 15);
				document.getElementById("County").value 			= getTextChildDataValue(row, 16);
				document.getElementById("Country").value 			= getTextChildDataValue(row, 17);
				document.getElementById("RecieveMarketingEmails").value = getTextChildDataValue(row, 18);
				
				setCustomerFields(false, true);

			}
			
			//tour op
			if (selectedFieldID == 'tour_operator') {
				setField('tour_operator', false, true);
			}
			
			
		} else if (table.id == 'competition_table') {
			resName 	= getTextChildDataValue(row, 0);

			field = document.getElementById(selectedFieldID);
			field.value = resName;
		}
		
		cClick();
	}
}

// Clear any form hidden values that were previously set by selecting a row

function clearHiddenValues(fieldID) {
	field = document.getElementById(fieldID + "Username");
	if (field != null) field.value = '';

	field = document.getElementById(fieldID + "GUINo");
	if (field != null) field.value = '';

	field = document.getElementById(fieldID + "MemType");
	if (field != null) field.innerHTML = '';	
}

function findPosY(obj){
	var curtop = 0;
	if (document.getElementById || document.all) {
		while (obj.offsetParent) {
			curtop += obj.offsetTop;
			if (typeof(obj.scrollTop) == 'number') curtop -= obj.scrollTop;
			obj = obj.offsetParent;
		}
	}
	else if (document.layers)
		curtop += obj.y;

	ScrollTop = document.body.scrollTop;
	if (ScrollTop == 0)  {
	    if (window.pageYOffset)	
	        ScrollTop = window.pageYOffset;
	    else
	        ScrollTop = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;	
	}
			
	return curtop - ScrollTop;
}

function findPosX (obj) {
	var curleft = 0;
	if (document.getElementById || document.all) {
		while (obj.offsetParent) {
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (document.layers)
		curleft += obj.x;
		
	return curleft;
}

function clearField(fieldID) {
	setField(fieldID, true, false);
	
	if (fieldID == "tour_operator") {
		 document.getElementById("tour_operator_id").value = '';
	} else if (fieldID == "customer") {
		setCustomerFields(true, false);
	}

	document.getElementById(fieldID).focus();
}

function editCustomer() {
	setCustomerFields(false, false);
}

customerFields = new Array("customer_id", "CompanyName", "TelephoneWork1", "Category", "TelephoneHome1", 
						"Title1", "Mobile1", "Firstname1", "Fax", "Surname1", "Position1", "Email1", 
						"Address1", "Address2", "TownCity", "County", "Country", "PostcodeZip", "RecieveMarketingEmails");
						
function setCustomerFields(clear, readonly) {
	for (fieldID in customerFields) {
		setField(customerFields[fieldID], clear, readonly);
	}
	
}

function setField(fieldID, clear, readonly) {
	field = document.getElementById(fieldID);
	
	if (clear) field.value = '';
	
	if (field.type == 'select-one') field.disabled = readonly;
	else 							field.readOnly = readonly;
	
	field.style.backgroundColor = (readonly) ? ('#cde') :('#ffffff');
}

// if form submitted with fields disabled, combo box values are not sent
// so need to enable before submit
function submitStt() {
	setCustomerFields(false, false);
	document.form.submit();
	return true;
}

//?>

