var idArray=new Array();
//var bookings=new Array();

// array to keep courtnames in bookings sheet
var courtnames=new Array();

// 2D array to keep selected cells in bookings sheet. initialised via php script according to size of grids
var selectedbookings = [];

// used to count active bookings - used to control enable/disable mode of make_bookings button
var active_bookings = 0;

var delete_bookings = new Array();


/* ------------------------------------------
 Used by ALL pages to control loading text banner:
 * Enabled (visible) when new page loaded (by main tab page).
 * Disabled (hidden) by content page after loaded.

 -ElementID is DIV object identifier where loading banner 
   initialised (main tab page).
 -State is new state to set banner: 'visible' or 'hidden'
 
 NB: change to set current page elements hidden when event buttons clicked.
     EG, in bookings sheet when update sheet clicked, hide grid until page reloaded...
 ------------------------------------------  */ 
function page_in_frameset(){
  if (window.top.location==window.self.location)  //not in a frame
   return false;
  else
   return true;
}


 
function set_club_bookings_visibility_loading_text(elementID, state) {	
  window.document.getElementById(elementID).style.visibility=state;
}
 
//This function toggles the visibility of the given elementID (eg loadingtext banner), states are: hidden/visible.
//This function will work for elements in a stand-alone page (elements created and toggled by same page), or elements in a 
//tabbed environment (elements created by the main (top-most) page and toggled by another local tabbed (child/embedded) page).
//
//NB: Function not meant to be used by club bookings page - here page can be embedded by external parent. this must be handled differently.
function set_visibility_loading_text(elementID, state) {	

  //need valid DOCUMENT object to call getElementById method on.
  var page;	
  if (window.top.location==window.self.location){  //caller page not embedded (ie, stand alone)
     page = document;    //use top-most document root, ie, self is TOP-most
  }
  else {                                          //page embedded, eg, caller is a tabbed page
     //get top-most doc root. we assume this function is being called by a tabbed/child page (eg, booking sheet) to hide 
	 //loadingbar created by parent (smiimain) page.
	 
	 //NB: dont use this for club bookings page. we cant assume club bookings page will be stand-alone, eg, might be called
	 // as an embedded page where we dont have access to top-most doc root.
	 page = window.top.document;
  }

  page.getElementById(elementID).style.visibility=state;
}

function toggle_page_elem_visibility(elementID, state) {	
  document.getElementById(elementID).style.visibility=state;
}

//returns local time of the browser. time format "2008 10 15 560" 
function getlocalPCtime() { 
  var nowtime = new Date();
  var localtime;

  localtime = nowtime.getFullYear() + ' ' + ((nowtime.getMonth()*1) + 1) + ' ' + nowtime.getDate() + ' ' + ((nowtime.getHours() * 60) + (nowtime.getMinutes()*1));

  return localtime;
}

//returns full timestamp : 2009 02 31 09:26:48
function getlocalPCtime_fullTimestamp(){
  var nowtime = new Date();
  var date = nowtime.getFullYear()+' '+ pad_num_zero((nowtime.getMonth()*1)+1)+' '+pad_num_zero(nowtime.getDate()); //2009 01 30
  
  
  var time = pad_num_zero(nowtime.getHours()) + ':' + pad_num_zero(nowtime.getMinutes())+':'+pad_num_zero(nowtime.getSeconds());
  var ts = date + " " + time;
  return ts;
}

//returns true if the given timestamp is within interval_secs (eg, 180) of the current browser time.
//otherwise, return false (the given timestamp is greater than interval_minutes in the past).
//webcheck_timestamp corresponds to DB timestamp, eg, 2008 09 29 16:07:07
function confirm_proceed_timecheck (webcheck_timestamp, interval_secs){
	
	  //if we couldnt get the time assume the timestamp is out of date
	  if (webcheck_timestamp==null || webcheck_timestamp==""){
	    return false;
	  }
	  
      //gets default interval mins if none provided
	  if (interval_secs==null || interval_secs==""){
		  interval_secs = get_remote_check_default_timout_sec();
	  }

      var interval_secs_int = parseInt(interval_secs);//forces to int to use in timestamp 
	  
      //parse and build new DATE object from timestamp. assumes format as above
	  //split using spaces to get yy mm dd time
	  var chck_ts = webcheck_timestamp.split(" "); //
	  var chck_yr = chck_ts[0]*1;
	  var chck_mm = chck_ts[1]*1;
	  var chck_dd = chck_ts[2]*1;	  
  	  //split timestring using ":" hr mm
	  var chck_tm = chck_ts[3].split(":"); //eg, "16:07:07"
	  var chck_hr = chck_tm[0]*1;	  
	  var chck_min= chck_tm[1]*1;
 	  var chck_sec= chck_tm[2]*1;
	  
	  //adds the allowed interval time to the sec component
	  chck_sec += interval_secs_int;	  	  
	  
	  var chck_date = new Date();
      chck_date.setFullYear(chck_yr,chck_mm-1,chck_dd);
	  chck_date.setHours(chck_hr,chck_min,chck_sec);
									  
	  var nowtime = new Date(); 	  
       //alert("ts ("+webcheck_timestamp+") plus "+interval_secs_int+"s interval ("+chck_date+ ") should be in the future (now "+nowtime+") if up to date");	      	  
	   
	  // if given time stamp + interval_mins is current, it will be in the future.
	  if (chck_date < nowtime) 
  	    return false;
	  else
	    return true;
}

//mins
function get_remote_check_default_timout_sec() {
	return "180";
}

function get_remote_check_timout_message() {
	var msg = "WARNING: Your Club computer has temporarily lost its connection. This booking cannot be confirmed until it is back online.\r\n\r\nClick OK to proceed anyway or CANCEL to cancel the booking and try again later.";	   
	return msg;
}

function get_remote_check_timout_message_update() {
	var msg = "WARNING: Your Club computer has temporarily lost its connection. This update cannot be confirmed until it is back online.\r\n\r\nClick OK to proceed anyway or CANCEL to cancel the update and try again later.";	   
	return msg;
}

//Navigates page to the given url string, ie, if called from within a frame, sets the top (main) url to the given url
function nav_to_url (url) {
	
	if (window.top.location == window.self.location) {  //not in a frame
   	   window.location=url;
	}
	else {        //in a frame
	    window.top.location=url;
	}
}

//sets the current page location to the given string, so if called from within a frame, only the frame url will be changed.
//useful for navigation within a tab, ie, main tab stays the same while page within tab changes location.
function load_page(url) {
  window.self.location = url;	
}

function refresh_pg(url, set_pending_changes){     
   //set_visibility_loading_text('loadingtxt','visible');  this is greyed out because when a reloads
   //alert(get_active_tab_main()); 
 
   if (set_pending_changes) url=url + "&pending_changes=1";
	
   var now_ts = getlocalPCtime_fullTimestamp();	
   url = url + "&local_ts=" + now_ts;   
   
   load_page(url);
}  

// ------------------------------------------------------------
//       used by smiimain.php 
// ------------------------------------------------------------

function prompt_close_window(){
 var check_close = confirm("Logging out of Internetbookings will close the current Window. Click OK to proceed or CANCEL to remain logged in.");
 if (check_close)
   window.close();
}

//old. unused??
function do_logout(){
  document.logout_form.submit();	
}

function broadcast_admin_logged_in(){
  var iframe_form = window.top.document.iframe_form;
  iframe_form.broadcast.value = 1;
//  iframe_form.local_ts.value = getlocalPCtime_fullTimestamp();
  iframe_form.submit();      
}

// -----------------------------------------
// used by the iframe (status progress)
// ------------------------------------------

function pad_num_zero(num_string){
	var padded_num;
	var num1 = num_string;	
	var num = num1+0;	
	if (num < 10)
	  padded_num = "0" + num_string;
	else   
	  padded_num = num_string;		  
	return padded_num;
}

function resubmit_page(show_loading_banner){    
   if (show_loading_banner) {
     toggle_page_elem_visibility("checkingtxt","visible");
   }
   var iframe = window.top.document.iframe_form;
//   iframe.local_ts.value = getlocalPCtime_fullTimestamp();   
   iframe.submit();    	  
}
function hide(){
   window.top.document.iframe_form.indexes.value = "";
   window.top.document.iframe_form.submit();    	  	  
}
//set visibility of iframe from main page
function toggle_update_inset_visibility (state) {
  //state should be "none" to hide page, or "block" to show page.	
  var fr = document.getElementById ("iframe_status");
  fr.style.display=state;
}

//sets a hidden form element in the main page (smiimain.php) with the given tab. 
//id_dest matches the tab name in main tab declaration. 
//caller is main tab controller (in smiimain.php) when tabs changed.
function set_active_tab_main (id_dest){
  var page;	 
  if (page_in_frameset())
	 page = window.top.document;  
  else
     page = document;

   page.main_refresh_form.active_tab.value = id_dest;	
}

function get_active_tab_main (){
  var page;	 
  if (page_in_frameset())
	 page = window.top.document;  
  else
     page = document;

  return page.main_refresh_form.active_tab.value;
}

function reload_main() {
  var page;	 
  if (page_in_frameset())
	 page = window.top.document;  
  else
     page = document;

//   page.main_refresh_form.lc_date.value = getlocalPCtime();	  
   page.main_refresh_form.submit(); 	
}


// Method submits the iframe form as a mechanism to notify the iframe that there has been a change which it must now check for completion.
// Method usually called when change is made. Note, all other iframe form variables left to their CURRENT setting, only new action flag is raised
function submit_iframe_action(action_id, iframe_params) {
   var iframe = window.top.document.iframe_form;
   
   //process ichange :: here the given list (ibookings_changes table rowsIDs) is added to the current list (iframe form variable "indexes"). 
   //                   called when a new row is added to ibookings_changes table, eg, player details updated, controller staus changed, etc.
   if (action_id==1){ 	
	var curr_ichanges =  iframe.indexes.value; //list of rowID's in ibookings_changes table to check 
	var new_val;  
  	if (!curr_ichanges) {     //the current list is empty
	  new_val = iframe_params;    //add new list
 	}
	else { 	//if list already exists  --> append to list
	  var index_array = curr_ichanges.split(","); //get current list
	  index_array.push(iframe_params);  //add to end of current list
	  new_val = index_array.join(","); // make new list
	}
    iframe.indexes.value = new_val;		
   }
   
   //process pending booking :: called when a new booking is made.
   else if (action_id==2){ 
      iframe.bookings_chk.value = 1;   
   }
   
   //process connectivity loss :: action is to notify iframe that admin connection is lost
   else if (action_id==3){
      iframe.conn_status.value = -1;   //-1 sets status as out-of-date
   }
   
   //leave ALL other iframe form variabled set to their CURRENT setting, only raise flag that the iframe has an updatye to check	   
   iframe.local_ts.value = getlocalPCtime_fullTimestamp();	   
   iframe.submit();  	
}

//initiates, ie, loads, the iframe. first two args are enabled/disable flags (1/0), third arg is status of admin connection (-1,1) and
//fourth arg is list of ibooking_changes IDs (null if no list)
function initiate_iframe(broadcast_admin_login, check_pending_bookings, admin_connectivity_status, ichange_id_list){
	var iframe_form = window.top.document.iframe_form;
	
	//set iframe to broadcast admin login
	if (broadcast_admin_login){
       iframe_form.broadcast.value = 1;
	}	

	//set iframe to check for pending bookings
    if (check_pending_bookings){
	    iframe_form.bookings_chk.value = 1;	
	}

	//set iframe to check ibooking_changes 
	if (ichange_id_list!=null && ichange_id_list!="" && ichange_id_list!=0){
	    iframe_form.indexes.value = ichange_id_list;	
	}

	//set iframe variable to current connection status
    iframe_form.conn_status.value = admin_connectivity_status;	

//    iframe_form.local_ts.value = getlocalPCtime_fullTimestamp();	
    iframe_form.submit();    
}

// ------------------------------------------
// used by smiilogin.php -- login functions  
// ------------------------------------------
function VerifyLoginPin(value){
  if (!value|| isNumeric(value)==false || value.length != 4)
    return false;
  else
    return true;	
}

function CheckFields(){
	   var userval = document.form0.user.value;
  	   var passval = document.form0.pass.value;

 	   if (!userval){
  		   alert("Please enter a Card Number."); return false;
	   }
	   else if (isNumeric(userval) == false){
  		   alert("Card numbers must be numeric. Please enter a valid card number."); return false;
	   }
	   else if(userval.length != 6) {		   
  		   alert("Card numbers must be 6 digits. Please enter a valid card number."); return false;
	   }

	   if (!passval){
   		   alert("Please enter Valid Password."); return false;
   	   }
       if (passval.length < 4 || passval.length > 6){		   
  		   alert("Passwords must be between 4 and 6 characters. Please enter a valid password."); return false;	   
   	   }

	   return true;		   
}

function isNumeric(elem){
  	   var numericExpression = /^[0-9]+$/;
   	   if(elem.match(numericExpression)){
		return true;
   	   }
  	   else {
//		elem.focus();
		return false;
	   }
}

//submits to caller page (login) to process login (ie, check password)
function do_login() {
		set_visibility_loading_text('loadingtxt','visible');
		
	 	if ( CheckFields() ){			 
			document.form0.submit();
		}
		else {
			set_visibility_loading_text('loadingtxt','hidden');
		}
}

function check_popup_blocked(){
  var newWin = window.open('','','width=1,height=1,left=0,top=0,scrollbars=no');
  var isblocked = false;
  if (newWin && newWin.top)
    newWin.close();
  else 
    isblocked = true;
	
  return isblocked;
}

function do_club_bookings_login(){
 
  if ( CheckFields() ){
	  
    var isblocked = check_popup_blocked();    
    if (isblocked) {
	   var msg = "Internetbookings needs to open a new window to log you in but your browser has Pop-up windows blocked. Please configure your browser to allow Pop-ups from this site first." 	 
       if (navigator.appName=="Microsoft Internet Explorer")  	   
		 msg += " To do this (1) click on the main 'Tools' menu, (2) select the 'Pop-up Blocker' option, and (3) click on the option for 'Always Allow Pop-ups from This Site'.\r\n\r\nAlternately, click the 'Login' button while holding down the 'Ctrl' button to temporarily allow Internetbookings to log you in.";
        alert (msg);
	    return;
    }	  
  
    document.form0.action = "smiilogin.php";	  
	document.form0.submit();	
  }	

}
	 
function do_demo_login(){	 
	document.form0.user.value = "800000";
	document.form0.pass.value = "1234";
	document.form0.submit();
}
	 
//take user to bookings page	
function load_logged_in(){
	set_visibility_loading_text("loadingtxt","visible");
    document.s_form.lc_date.value = getlocalPCtime();
	document.s_form.submit();
}

//returns the height, in terms of number of pixels, of the browser window. This only includes the html part, 
//ie, it doesnt include the applications window buttons
function get_page_height(){
	var pagedoc;
    if (window.top.location==window.self.location)  //not in a frame
      pagedoc = document;
    else                                           //in a frame
	  pagedoc = window.top.document;
	return pagedoc.body.clientHeight;	
}

//returns the browser window width (pixels).
function get_page_width(){
    if (window.top.location==window.self.location)  //not in a frame
      return document.body.clientWidth;	
    else { //in a frame
	  return window.top.document.body.clientWidth;
	}
}


function login_prob(prob){
	if (prob == -1)
		alert("Unable to locate Login/Password. Please contact your Club");
	if (prob == 2)
		alert("Login or Password Incorrect Please contact your Club");
	if (prob == 3)
		alert("Your card is Invalid. Please contact your Club.");
	if (prob == 4)
		alert("Your card has expired. Please contact your Club.");
	if (prob == 10)
		alert("You cannot delete a booking within xxhrs of the booking.");
	if (prob == 11)
		alert("Your booking cost will not be rufunded as it is within xxhrs of the booking.");
}

// ------------------------------------------------------------
//       used by bookings_sheet.php -- bookings functions  
// ------------------------------------------------------------

/*
function toggleview(view){
	
   if (view==0) //action is switch to std view
     document.bs_form.court_id.value = 0; //clear current court (no longer application)    		
   document.bs_form.view.value = view;
   document.bs_form.action = "booking_sheet.php";
   document.bs_form.submit();
}
*/
function refresh_booking_sheet_common(switch_to_calview) {
	  if (switch_to_calview)  
	      document.bs_form.calview.value = 1;	
	  else	  
	      document.bs_form.calview.value = 0;		  
	  toggle_page_elem_visibility('gridbox', 'hidden');
	  set_visibility_loading_text('loadingtxt','visible'); 
	  update_booking_sheet();
}


function update_booking_sheet(){
      document.bs_form.lc_date.value = getlocalPCtime();	  
//	  document.bs_form.action = "booking_sheet.php";
  	  document.bs_form.submit();
}

function nav_to_date_common(new_date){
      document.bs_form.lc_date.value=getlocalPCtime(); 	
      document.bs_form.date.value = new_date;
//      document.bs_form.action = "booking_sheet.php";
      refresh_booking_sheet_common(0);
}	
	
	
function init_add_courts(courtname){
	courtnames.push (courtname);
}
	 
//2D array to represent bookings grid, with each value initialised to -1
function init_create_bookingsgrid (num_rows, num_cols) {	
    for (var i=0; i<num_rows; i++){
	   var columnarray = new Array(num_cols);		   
	   for (var j=0; j<num_cols; j++){
		    columnarray[j] = -1;
	   }
	   selectedbookings[i] = columnarray;
	 }
		
	 //reset - used to count active bookings to enable/disable make_bookings button
	 active_bookings = 0;
}

/*
 This function checks submits the bookings to be confirmed if the remoteWebCheckTimestamp is up to date.
 If the up to date check fails, the user is warned that there is a connection problem and asked to proceed anyway.
 If so, the booking can proceed, otherwise the booking page is reloaded. 
*/
function make_booking_controlled (webcheck_timestamp, interval_sec) {

	if 	( confirm_proceed_timecheck (webcheck_timestamp, interval_sec) ) {
	   submit_make_booking();
	}
	else {
       var chk_confirm = confirm (get_remote_check_timout_message());		
	   if ( chk_confirm ) {
   	      submit_make_booking();		   
	   }
	   else	{
  	      update_booking_sheet();
	   }
	}
	
}

//collect all selected cells on booking grid (bookings), format them into suitable format and submit the form.
//formats bookings as a single comma separated string (each booking is a hyphen "-" separated pair of court_number and time_period)
function submit_make_booking(){	
	   var bookings = "";
       var delim = "";

/*   CODE BELOW USED TO COLLECT BOOKINGS IN ORDER OF TIME...
  	   for (var r=0; r<selectedbookings.length; r++){
	     for (var c=0; c<selectedbookings[r].length; c++){				
*/
      //COLLECT BOOKINGS IN COURT ORDER...
	   num_cols = selectedbookings[0].length;	   
  	   for (var c=0; c<num_cols; c++){	   
   	      for (var r=0; r<selectedbookings.length; r++){
		    //only add bookings if there's a valid entry in grid (see grid)			  
			if ( selectedbookings[r][c] != "-1"){				
				bookings = bookings + delim + selectedbookings[r][c];
				delim = ".";
			}			  
		  }
	   }
	   
	  //document.bs_form.local_fulltimestamp.value = getlocalPCtime_fullTimestamp();
   	  document.bs_form.bookings.value = bookings;
      //document.bs_form.lc_date.value = getlocalPCtime();	  
	  document.bs_form.action = "confirm.php";
  	  document.bs_form.submit();
}


	 
//onchange_action needs to be a function name for what to do when selectbox is changed. 
//eg can be "refresh_booking_sheet()" or "club_bookings refresh_club_bookings()" etc
//current date should be format: "6 10 2008"
function BuildDaysAhead(days, nowdate, currentdate, onchange_action, show_date_format){

	if (days == "")
	 daysadvance = 14;
	else
	 daysadvance = days;

    var split_date = nowdate.split(" ");//dd mm yyyy
	now = new Date()
    now.setDate(split_date[0]); //1-31
    now.setMonth(split_date[1] - 1);//0-11
    now.setFullYear(split_date[2]);	
	
	if (show_date_format == 1) {
    	d = new Array("Sun","Mon","Tues","Wed","Thurs","Fri","Sat");
     	m = new Array("Jan","Feb","Mar","Apr","May","June","July", "Aug","Sept","Oct","Nov","Dec");
    }
	else	{
    	d = new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
   	    m = new Array("January","February","March","April","May","June","July", "August","September","October","November","December");
	}

	aDay = 24*60*60*1000;
	then = new Date(now.getTime()-(daysadvance*aDay));
	until = new Date(now.getTime()+(daysadvance*aDay));
	
	text = '<select ID="selectdateID" name="date" ONCHANGE="'+onchange_action+'" >'; 
	//change_sport(this.options[this.selectedIndex].value);
	for (i=now.getTime();i <= until.getTime();i+=aDay) {
    	date = new Date(i);
    	year = date.getYear();
     	if (year < 1900) {
		  year += 1900;   
	    } 	
		
		display_date = d[date.getDay()]+' '+date.getDate()+' '+m[date.getMonth()]+' '+year;
		value_date   = date.getDate()+' '+(date.getMonth()+1)+' '+year;
		
		var selectedtext = "";
		if (currentdate == value_date){
 		  selectedtext = "selected";
		}
    	text += '\n<option value="'+value_date+'"'+selectedtext+'>'+ display_date+'</option>';
	}
 	text += '</select>';
	document.write(text);
} 



//these used to be used to control no right clicks in bookings sheet. see booking_sheet_orig.php
//copied from http://www.dynamicdrive.com/dynamicindex9/noright.htm

function clickIE4(){
  if (event.button==2)
    return false;  
  else	
   return true;  
}

function clickNS4(e){
  if (document.layers||document.getElementById&&!document.all){
   if (e.which==2||e.which==3) return false;
  }
}

// ------------------------------------------------------------
//       used by confirm.php -- button functions
// ------------------------------------------------------------

function finish_booking_controlled (webcheck_timestamp, interval_sec) {
    set_visibility_loading_text('loadingtxt','visible');		
	
	if 	( confirm_proceed_timecheck (webcheck_timestamp, interval_sec) ) {
	   finish_booking_confirm();
	}
	else {
       var chk_confirm = confirm (get_remote_check_timout_message());		
	   if ( chk_confirm ) {   
   	      finish_booking_confirm();		   
	   }
	   else	{
     	   set_visibility_loading_text('loadingtxt','hidden');
		 //note: could change to do either: do nothing (leave user to cancel out of confirm page) or cancel_booking_confirm()
		 
		 //reload booking sheet. 
//        document.confirm_form.action='booking_sheet.php';
//        document.confirm_form.lc_date.value = getlocalPCtime();	     
//        document.confirm_form.submit();	
   
         
	   }
	}
}

function finish_booking_confirm(){
	if (document.confirm_form.alt_email.value == "" && document.confirm_form.main_email.value == "")	{
		alert("Please enter an email address for the confirmation");
        set_visibility_loading_text('loadingtxt','hidden');				
		return false;
	}
	
	else {
        //alert( document.confirm_form.alt_email.value +" "+document.confirm_form.main_email.value);
//        document.confirm_form.lc_date.value = getlocalPCtime();	  
		document.confirm_form.action = 'smiifinish.php';
	    document.confirm_form.submit();
	}	
}

function cancel_booking_confirm() {
/*
	  var new_file = "smiilogin.php";	  
	  var new_url = modify_url_new_file(new_file);
	  
	  //as we're in a frame - must change the caller url location.
	 window.top.location = new_url;
*/	  
  	  set_visibility_loading_text('loadingtxt','visible');

//      document.confirm_form.lc_date.value = getlocalPCtime();	  
	  document.confirm_form.action = "booking_sheet.php";
  	  document.confirm_form.submit();

}

// Creates a new url string pointing to given filename.
// Uses current window's hostname, path etc. i.e., assumes new filename in current folder
function modify_url_new_file (filename){
     
	  var protocol = window.location.protocol;
      var hostname = window.location.hostname;
	  var pathstring = window.location.pathname;
	 
 	  //if path begins with "/" - remove it from path
	  if ( pathstring.charAt(0) == "/" ){
	  	pathstring = pathstring.substring(1);
	  }	

	  //split path into array - to handle cases where path has folder names like 'internetbookings/new/page.php'
      var path_array = pathstring.split("/");
	  var num_paths = path_array.length;
 
 	  // create new path exactly same as the current except change filename, which is last value 
	  // in path_array, to new file.
	  var newPath = "";
	  for (var i=0; i<num_paths; i++ ) {
	    newPath += "/";
		if (num_paths == (i+1)) {  //last string in array - as i starts from 0 (eg, "test/new/page.url" has length=3)
		   newPath += filename;
		 }
		 else {  
		   newPath += path_array[i];
		 }  
	  }
   
     var newURL = protocol + "//" + hostname + newPath;	//note: newPath starts with '/' (from above loop) so dont need it here.
     return newURL;
}



function make_another_booking(){
   set_visibility_loading_text('loadingtxt','visible'); 

   document.finish_form.action='booking_sheet.php';
//   document.finish_form.lc_date.value = getlocalPCtime();	     
   document.finish_form.submit();	
}

// ------------------------------------------------------------
//       used by player_bookings.php -
// ------------------------------------------------------------


//function prompts the user if they would like to proceed with deleting the selected bookings.
//if so, they are deleted, otherwise the action is cancelled.
//this function displays all the selected bookings to delete in the confirmation box.
function delete_booking(){	
  var num_bookings = delete_bookings.length; //number of rows in grid. 
  var bookings_inf = "";  
  var num_to_delete = 0;
  var eol = "";
  var single_booking_row_num;
  var refund_str;  

  var refund_data;
  var row_data;
  //collect booking info (date, time and court, and refund info) to display in confirm box if multiple bookings are selected.
  
  for (var num=1; num<=num_bookings; num++){ //num=1 as grid rows start at 1
 	 row_data = mygrid.getUserData(num, "inf");  	 
 	 refund_data = mygrid.getUserData(num, "ref");  	 	 //can be blank, or have refund text, ie, "this can/cannot be refunded..."
	 
     if ( delete_bookings[num] ){  //if booking marked as deleted
	     if (refund_data)   
		    refund_str = "  -  this cost " + refund_data;		   
		 else 		 
   		    refund_str = "  (no cost)";		   
		 bookings_inf += eol + " * " + row_data +  refund_str;  //* 10 Nov 2008 at 9:45pm for Squash1 - this can/cannot be refunded

		 eol = "\r\n";  //end line
		 num_to_delete ++;
		 single_booking_row_num = num;
	 }
  }

  var msg;
  if (num_to_delete == 1){
     msg = "Are you sure you want to delete your booking on the " + mygrid.getUserData(single_booking_row_num, "inf") + "?";
 	 var refund_data = mygrid.getUserData(single_booking_row_num, "ref");  	 	 
	 if (refund_data) msg += "\r\n\r\nThis cost " +  mygrid.getUserData(single_booking_row_num, "ref");//can/cannot be refunded
  }
  else
     msg = "Are you sure you want to delete the following bookings? \r\n\r\n" + bookings_inf; //list each booking

  var chk_confirm = confirm (msg);		
  if ( chk_confirm ) {
	 do_delete_booking();
  }
}


//1. collects booking_no's from array (added by grid event) to compress into single (comma separated) form value.
//2. sets another form value to indicate submitted page is an update
//3. submits the form to the same page
function do_delete_booking(){
   set_visibility_loading_text('loadingtxt','visible'); 	
	
   var delete_val = ""	
   var delim = "";
   
   var num_bookings = delete_bookings.length; //num rows in grid
   
   for (var num=1; num<=num_bookings; num++){ //num=1 as grid rows start at 1
	 if ( delete_bookings[num] ){             //if booking marked as deleted
		 delete_val = delete_val + delim + delete_bookings[num];
		 delim = ",";
	 }
   }
   document.viewbook.delete_booking_ids.value = delete_val;
   document.viewbook.update.value = "1";   
//   document.viewbook.lc_date.value = getlocalPCtime();	        
  
   document.viewbook.submit();	
}

function refresh_club_bookings(){
  	  set_club_bookings_visibility_loading_text('loadingtxt','visible'); 
	  
//      document.bs_form.lc_date.value = getlocalPCtime();	  
	  document.bs_form.action = "club_bookings.php";
  	  document.bs_form.submit(); 
}   

function show_your_bookings_records(load_group){
    set_visibility_loading_text('loadingtxt','visible');
		
	document.viewbook.show_res_next.value = load_group;
	document.viewbook.submit()	
}

// ------------------------------------------------------------
//    update member details functions 
// ------------------------------------------------------------

// Function submits member info page with warning message if admin remote check delayed.
// Only password input checked before form submitted, ie, passwords must be valid password fields (if entered).

function submit_player_info_update (webcheck_timestamp, interval_sec) {
 	set_visibility_loading_text('loadingtxt','visible'); 
    document.member_info.lc_date.value = getlocalPCtime();

    //Password fields can be blank if no change required. If there is at least one value in each of the 3
	//passwords fields, assume a password update is required and check all password fields valid.
    if ( document.member_info.current_password.value || 	    
	     document.member_info.new_password.value ||
		 document.member_info.new_password_cnfm.value ){

      //if password input invalid , return with error
      if (!validate_update_password_input()){
   	     set_visibility_loading_text('loadingtxt','hidden');	   	   		 
	     return false;
	  }
	}
	//Otherwise, no password change neccessary so continue...
	
    //submit page	
	if 	( confirm_proceed_timecheck (webcheck_timestamp, interval_sec) ) {
	   document.member_info.submit();
	}
	else {
       var chk_confirm = confirm (get_remote_check_timout_message_update());		
	   if ( chk_confirm ) {
   	      document.member_info.submit();	   
	   }
	   else {
   	      set_visibility_loading_text('loadingtxt','hidden');	   	   		 
       }
	}
}

//check all 3 fields valid when member updates password. Valid means:
// - there exists a value in each of the three input fields
// - the length of the new password is 4 digits (only) long
// - the new password matches the confirm new password value
function validate_update_password_input() {
	//check all input entered
    if ( !document.member_info.current_password.value ||	    
	     !document.member_info.new_password.value ||
		 !document.member_info.new_password_cnfm.value ){
		alert("Please enter a value for all three password fields first.");
		return false;
	}	
	
	//check new password is an integer 4 chars long
	if (document.member_info.new_password.value.length < 4 || document.member_info.new_password.value.length > 6){
		alert("Invalid password! Please ensure new password is between 4 and 6 characters.");
		return false;
   }		

	//check new passwords match
	if (document.member_info.new_password.value != document.member_info.new_password_cnfm.value){
		alert("New passwords to not match! Please ensure both new passwords are the same.");
		return false;
    }
		
	return true;
}

// ---------------------------admin functions ------------------------------------------

// ------------------------------------------------------------
// controller update functions
// ------------------------------------------------------------

function submit_controller_update(){
	set_visibility_loading_text('loadingtxt','visible'); 
	
    //get latest timestamps
//    document.controller_form.lc_date.value = getlocalPCtime();	  //timestamp format used by rest of site
//    document.controller_form.local_ts.value = getlocalPCtime_fullTimestamp(); //timestamp format used by admin area functions
	
    document.controller_form.update.value = 1;
 
     //submit to same page	
  	document.controller_form.submit();		
}




// ------------------------------------------------------------
// search member functions
// ------------------------------------------------------------

// submits the search member page with the member select-list value as the chosen search value
function submit_searchmember_memberlist(){
	set_visibility_loading_text('loadingtxt','visible'); 
//    document.search_form.lc_date.value = getlocalPCtime();	  
   
    //clear search terms first:
	document.search_form.member_srch_card.value = "";
    document.search_form.member_srch_fname.value = ""; 
	document.search_form.member_srch_sname.value = "";
    //submit to same page	
  	document.search_form.submit();		
}
  
// submits the form when the select-list ordering changes (search terms if any, will also be submitted)
function submit_searchmember_listorder(){
	set_visibility_loading_text('loadingtxt','visible'); 
    document.search_form.lc_date.value = getlocalPCtime();	 
  	document.search_form.submit(); //to same page		
}
  
// submits the search member page with the search terms as the chosen search value(s)
function submit_searchmember_search(){
    document.search_form.member_target.value = 0;
	set_visibility_loading_text('loadingtxt','visible'); 
//    document.search_form.lc_date.value = getlocalPCtime();	  
    document.search_form.action = "search_member.php";
  	document.search_form.submit();		
}

/*

These have been replaced by function below

function submit_member_receipt(){
	set_visibility_loading_text('loadingtxt','visible'); 
    document.search_form.lc_date.value = getlocalPCtime();	 
    document.search_form.action = "receipt_member.php";
  	document.search_form.submit(); //to same page		
}
function nav_to_searchmember(){
  	set_visibility_loading_text('loadingtxt','visible'); 
    document.receipt_fm.lc_date.value = getlocalPCtime();	 
    document.receipt_fm.action = "search_member.php";
  	document.receipt_fm.submit(); 
}
*/

function submit_form_action (source, target){
    set_visibility_loading_text('loadingtxt','visible'); 
    source.lc_date.value = getlocalPCtime();	 
    source.action = target;
  	source.submit(); //to same page		
}

// ------------------------------------------------------------
//reciept member functions
// ------------------------------------------------------------

  
// Large function which checks ALL input fields in receipt member form valid, and collects
// and pre-processes all user data into required format for database insert.
// IE, when form submitted - all data assumed to be database ready, so no checks needed after
// Checks are:
	//check all required fields have a value. 
	// 1. get cents value for amount. User input can either be in cents
	// 2. check date correct
	// 3. check "reciept by" max 3 chars
//
// Page throws warning if admin remote check delayed.
//
function submit_receipt_member_controlled (webcheck_timestamp, interval_sec) {
	set_visibility_loading_text('loadingtxt','visible'); 
    document.receipt_fm.lc_date.value = getlocalPCtime();	 

	
	//check all required fields have a value
    if (!reciept_member_all_fields_entered() ){
	  alert("Please ensure that you have completed all fields marked as *required first.");
   	  set_visibility_loading_text('loadingtxt','hidden');
	  return false;
    }  


    //get journal type radio button value
	var journal_type = reciept_member_get_journal_field();
	if (!journal_type){
	  alert("Please select a valid Payment type first. E.g., Cash.");
   	  set_visibility_loading_text('loadingtxt','hidden');
	  return false;
	}
	
	//assuming all required fields are entered, so check validity of each input...
	
	// 1. get cents value for amount. User input can either be in cents
    cents_value=get_valid_money_cents(document.receipt_fm.receipt_amt.value);
	if (!cents_value){
	   alert("The amount you have entered is invalid. Please enter another amount, for example\r\n\r\n - 10 for $10 only, or\r\n - 5.50 for $5.50.")  
   	   set_visibility_loading_text('loadingtxt','hidden');	   
	   return false;
	}	 
	//set cents value in feild
    document.receipt_fm.receipt_amt_ready.value = cents_value;
	
		
	// 2. check date correct
	var formatted_date_string = get_valid_formatted_input_date(document.receipt_fm.receipt_date.value);
	if ( formatted_date_string==0 ){ //cant match regular expression for date, must be invalid
	   alert('The date you have entered is invalid. Please enter a date in the format "dd\\mm\\yyyy"');
   	   set_visibility_loading_text('loadingtxt','hidden');	   	   
	   return false;	
	}
	else if ( formatted_date_string== -1 ){ //valid date string entered, but date cannot exist 
	                                        //return with no error as function throws error warning
     	   set_visibility_loading_text('loadingtxt','hidden');	   											
		   return false;	
	}
	document.receipt_fm.receipt_date_ready.value = formatted_date_string;
	
	
	// 3. check "reciept by" max 3 chars
	if (document.receipt_fm.receipt_by.value.length > 3){
	  alert("The \"Entered by\" value is too long. Please ensure this is 3 characters or less.");
  	   set_visibility_loading_text('loadingtxt','hidden');	   	  
	  return false;
	}      
		   
	//all input valid 

    //document.receipt_fm.submit(); 
    if 	( confirm_proceed_timecheck (webcheck_timestamp, interval_sec) ) {
	   //submit_receipt_member();
	   document.receipt_fm.submit();
	}
	else {
       var chk_confirm = confirm (get_remote_check_timout_message_update());		
	   if ( chk_confirm ) {
   	      document.receipt_fm.submit();	   
	   }
	   else	{
  	      nav_to_searchmember();
	   }
	}
}
  
function reciept_member_all_fields_entered(){
    if ( document.receipt_fm.receipt_date.value &&	    
	    document.receipt_fm.receipt_amt.value &&
		document.receipt_fm.receipt_by.value){
		return true;
	}	
	return false;	  
}

function reciept_member_get_journal_field(){
      var len = document.receipt_fm.journal.length;
	  
 	  for (var i=0; i<len; i++) {
        if (document.receipt_fm.journal[i].checked) {
		  return document.receipt_fm.journal[i].value;
		}
      }
	  return null;
}
  
function get_valid_formatted_input_date(date_string){
    var re = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/; //format dd/mm/yyyy
    var match = date_string.match(re);	
	
    if (match == null || !match){
	  return 0;
	}  
	else {
	  if (!match[1] || !match[2] || !match[3]){
	    return 0;
	  }	
	  //get each value in date string and convert into int
	  var d = match[1]*1;
	  var m = match[2]*1;
	  var y = match[3]*1;	
	  
	  if (d<=0 || m<=0 || y<=0) return 0;
	  //chech month < 12
	  if (m>12) {
	      alert("Invalid Month. Please enter a month between 1-12.");
		  return -1;
	  }
	  
	  //check feb month num days
	  if (m==2){
	    if (y % 4==0) {//leap year
		  if (d>29){ 
  	        alert("There are only 29 days in February! Please enter a valid date.");
   	        return -1;
		  }	
		}
		else { //non leap year
		  if (d>28){ 
  	        alert("There are only 28 days in February! Please enter a valid date.");
   	        return -1;
		  }			
		}  
	  }
	  //check apr,june,sept nov has 30 days. 
	  else if (m==4||m==6||m==9||m==11){
	    if (d>30) {
 	      alert("There are only 30 days in month! Please enter a valid date.");
   	      return -1;
		}
	  }
	  //check jan,mar,may,july,aug,oct,dec has 31
	  else {
	    if (d>31) {
 	      alert("There are only 31 days in month! Please enter a valid date.");
   	      return -1;
		}
	  }
	  
	  var datestamp = y + "-" + m + "-" + d + " 00:00:00"; 
	  return datestamp ;
	}  
}	

function get_valid_money_cents(amount_string){

    //first match dollar value, ie, any number of digits (no cents). Multiply by 100 to return value in cents
    var re = /^\d+$/;
    var match = amount_string.match(re);
	if (match != null){
	  amount_string = amount_string * 100;
	  return amount_string;
	}
	
	//if input does not match only dollar value, match any number of dollar digits and 2 digits (cents) separated by full stop (.)
    var re = /^\d+\.\d{1,2}$/; //eg, 100.21 or 1.2
    var match = amount_string.match(re);
	if (match != null){
	  var amount_array = amount_string.split(".");//split into dollar and cents
		
	  var dollars = amount_array[0]*100; //convert dollars into cents
	  if (amount_array[1].length == 1) 
	   var cents = dollars + (amount_array[1]*10);  //if cent value 1 digit, assume its in tens (eg 1.2=120 cents)
	  else 
	   var cents = dollars + (amount_array[1]*1);	//if cents value 2 digits, its single value (eg, 1.02=102 cents)  
      return cents;
	}	

	return 0;  
}	


/// --------------------- online payments page functions -------------------------------------------------------
function check_onlinepayment_amount(value){
  var verify = Number(value);  
  if (verify==0||isNaN(verify)){
     alert("Please enter a valid dollar and cents amount to topup your card first!");
	 return false;
  }	
  return true;		
}

function submit_online_payment(form){
  // if (!confirm ('You will be transferred to a secure online payments site to topup your card balance (you will leave InternetBookings).\r\n\r\nAre you sure you want to proceed?'))      return false;   
  toggle_page_elem_visibility ('form_btn', 'hidden'); 
  toggle_page_elem_visibility ('form_busy', 'visible');
  form.submit(); 
}

function clear_payment_form(){
	document.pg_form.paymentamt.value=0;
//	document.pg_form.paymentmode.value=0;	
	document.pg_form.submit();	 
}

function select_payment_mode(form){
 if (!check_onlinepayment_amount(form.paymentamt.value)){ 
   form.paymentmode.value = 0;
   return false; 
 }		  
 submit_form_action(form,"payment_online.php")
}

function check_online_payment_ok(form){
  //validation here
  //var t = document.getElementById("form_btn").style.visibility;
    
 // if (!confirm ("You will be transferred to a secure online payments site to topup your card balance (you will leave InternetBookings).\r\n\r\nAre you sure you want to proceed?"))
 //    return false;  

/*
  if (form_id == 1) { 
    //copy amount to variable expected by paypal
    form.amount.value = form.amt.value;
  }
  else if (form_id == 2) { 
    //copy amount to variable expected by authorize.net. needs decimal places...
    form.x_amount.value = form.amt.value;
    alert(form.x_amount.value);	
  }
*/

  //toggle_page_elem_visibility ("form_btn", "hidden");  
  //toggle_page_elem_visibility ("form_busy", "visible");  
} 


/* Checks if a date input (3 separate text feilds) is valid. Checks the following:
 - all feilds are numbers (greater than 0)
 - month range is between 1 and 12
 - day range valid (for given month, eg, 28 vs 30 vs 31 days)
 - date is 4 digits
*/
function verify_date_input(src_form){ 
  var mm=src_form.card_exp_mm.value;
  var dd=src_form.card_exp_dd.value;
  var yy=src_form.card_exp_yy.value;
  
  if ( dd || mm || yy ) { //one was entered...
    if (!dd || !isNumeric(dd) || !mm || !isNumeric(dd) || !yy || !isNumeric(yy) ) {
	   alert("Invalid Card Expiry Date! Please enter a valid date first.");
	   return false; 
	}
   
    //check size of yy string
	var yylen = yy.length;
    if (yylen!=4) {
   	   alert("The expiry date you've entered is invalid - a full 4-digit year is required.");
	   return false;
    }

    //convert to numbers
    dd=dd*1;
	mm=mm*1;
	yy=yy*1;

    if (dd<1 || mm<1 || yy<1) {
	   alert("Invalid Card Expiry Date! Please enter a valid date first.");
	   return false; 
	}

    var lyear = yy%4;  
	if (mm>12) {
   	   alert("The expiry date you've entered is invalid - the month value is incorrect! Please enter a valid date first.");
	   return false;
    }

    if (dd==31){
	  if (mm==2||mm==4||mm==6||mm==9||mm==11) {
   	   alert("The expiry date you've entered is invalid - there are too many days in the month! Please enter a valid date first.");
	   return false;
      }
    }
	
    if (mm==2){
	 if ( (lyear==0 && dd>29) || (lyear!=0 && dd>28)) {
   	  alert("The expiry date you've entered is invalid - there are too many days in the month! Please enter a valid date first.");
  	  return false;
	 }
    }
	
    src_form.card_exp_yy.value=yy*1;
    src_form.card_exp_dd.value=dd*1;
    src_form.card_exp_mm.value=mm*1;  
  }
  
  return true;
}


 function checkdelete(ad_list_to_check, form_elem_prefix_name){
	if (ad_list_to_check=='') {
		 num=0;
	}
	else {
      var tolist = ad_list_to_check.split(","); //split into array of numbers	
      var num = tolist.length; //array length
	}
	
   
	//first check if any checkboxes are selected to be deleted. 
	var numtodelete = 0;
    for (var i=0; i<num; i++){
	    var ad = tolist[i];
        delete_ad = document.getElementById(form_elem_prefix_name + ad);
		if(delete_ad.checked) numtodelete = numtodelete + 1;
    }

    //if there is at least one selected, need to show confirmation.
    if (numtodelete > 0){
	  var msg = "You have selected to clear " + numtodelete + " ad(s). \r\rAre you sure you want to proceed?\r\rNote that the image(s) will still remain on the server.";
	  //msg = msg + "\n\nDo you also want to completely remove these image from the server?\n\nIf yes, click OK. Otherwise, to keep these images stored on the server, click Cancel";
	  if (!confirm(msg))
		return;
	}
	
	//submit!
	document.ad_form.submit();   
 }
