function surf_away(club_id) {
  if (confirm("Your teetime will be returned for sale if you leave this screen.\n\nClick OK to continue or Cancel to remain on this page.")) {
    unlock_teetime(club_id);
    return true;    
  } else {
    return false;
  }
}
function unlock_teetime(club_id) {
  new Ajax.Request('/teetimes/cancellock?rnd='+ Math.random(),
  {
    method: 'post',
    asynchronous: false,
    parameters: 'club_id=' + club_id + "&authenticity_token=" + global_token
  });
}

function makedate(){
  $("date").value = $("isgYear").value + "-" + $("isgMonth").value + "-" + $("isgDay").value;
  return checksearchform();
}

function checksearchform() {
  errors = new Array();
  // this nasty hacky shit is due to the use of old jQuery on the search page.
  // waiting to refactor
  if (jQuery(jQuery('#course').children()[0]).attr("selected") == true && jQuery(jQuery('#region').children()[0]).attr("selected") == true) {
    errors.push("* Please choose a course or region");
  }
  if (jQuery(jQuery('#players').children()[0]).attr("selected") == true) {
    errors.push("* Please choose number of players");
  }
  if (jQuery(jQuery('#cart').children()[0]).attr("selected") == true) {
    errors.push("* Please choose a cart option");
  }
  // Now we've got new js version, trying new validation method (keep old for compat.)
  var selected_course = jQuery('#course option:selected');
  var selected_region = jQuery('#region option:selected');
  if (($(selected_course).length <= 0 || $(selected_course).attr("value") === "") && ($(selected_region).length <= 0 || $(selected_region).attr("value") === "")){
    errors.push("* Please choose a course or region");
  }
  var selected_date = jQuery('#date');
  if ($(selected_date).length <= 0 || $(selected_date).attr("value") === ""){
  	errors.push("* Please choose a date");
  }
//  var selected_players = jQuery('#players option:selected');
//  if ($(selected_players).length <= 0 || $(selected_players).attr("value") === ""){
//  	errors.push("* Please choose a number of players");
//  }
  if (errors.length == 0) {
    return true;
  } else {
    alert("Some errors have occured:\n\n" + errors.join("\n"));
    return false;
  }
}

var browser=new Object(); browser.isFirefox=true; browser.isGeckoBased=true; 
var serverDate=new Date();

function get_next_section(){
  if (data_loading == true) {
    // nothing
  } else if (my_glider.current) {
    id_bits = my_glider.current.id.split("_");
    if (last_time == "") {
      get_data("forward");    
    }
    if (my_glider.current == my_glider.sections[my_glider.sections.length - 1] && last_time != "") {
      if (my_glider.current.down(".lasttime")) {
        l = my_glider.current.down(".lasttime");
      } else {
        // if there is only one result there will be only a first time
        l = my_glider.current.down(".firsttime");
      }
      lt = l.innerHTML.replace(/(<([^>]+)>)/ig,"");
      alert("No more teetimes available after " + lt);
    } else {
      my_glider.next();
      set_current_times();
    }
  }
}

function get_previous_section(){
  if (data_loading == true) {
    // nothing
  } else if (my_glider.current) {
    id_bits = my_glider.current.id.split("_");
    if (first_time == "") {
      get_data("backward");    
    }
    if (my_glider.current == my_glider.sections[0] && first_time != "") {
      ft = my_glider.current.down(".firsttime").innerHTML.replace(/(<([^>]+)>)/ig,""); ;
      alert("No more teetimes available before " + ft);
    } else {
      my_glider.previous();
      set_current_times();
    }
  }
}

function get_current_times() {
  return get_times(my_glider.current._index);
}

function get_previous_times() {
  prev = my_glider.current._index - 1;
  if (prev >= 0) {
    return get_times(prev);
  } else {
    return false;
  }
}

function get_next_times() {
  next = my_glider.current._index + 1;
  if (next  <= my_glider.sections.length) {
    return get_times(next);
  } else {
    return false;
  }
}


function get_times(index) {
  if (my_glider.sections[index]) {
    start_time = my_glider.sections[index].down(".firsttime").innerHTML;
    if (my_glider.sections[index].down(".lasttime")) {
      end_time = my_glider.sections[index].down(".lasttime").innerHTML;
    } else {
      end_time = start_time;
    }
    if ((start_time.match(/PM/) && end_time.match(/PM/)) || (start_time.match(/AM/) && end_time.match(/AM/))) {
      // both the same
      start_time = start_time.replace(" AM","");
      start_time = start_time.replace(" PM","");
    }
    return new Array(start_time.stripTags(),end_time.stripTags());
  } else {
    return new Array();
  }
}
  
function set_current_times(){
  times = get_current_times();
  $("current_times").innerHTML = times[0] + " - " + times[1] + " ";  
  if (!data_loading){
    set_time_arrows();
  }
}

function set_time_arrows(){
  times = get_current_times();
  prev_times = get_previous_times();
  next_times = get_next_times();
  // backwards
  stimes = times[0].match(/[0-9]{2}/g);
  if (times[0].match("PM")) {
    stime = (12 + parseInt(stimes[0], 10)) + ":" + stimes[1];
  } else {
    stime = stimes[0] + ":" + stimes[1];
  }  
  // forwards
  etimes = times[1].match(/[0-9]{2}/g);
  if (times[1].match("PM")) {
    etime = (12 + parseInt(etimes[0], 10)) + ":" + etimes[1];
  } else {
    etime = etimes[0] + ":" + etimes[1];
  }

  if (stime == earliest || prev_times == false || prev_times.length == 0) {
    if (etime == latest || next_times == false || next_times.length == 0) {
      $('times_ul').innerHTML = "<li>NO MORE RESULTS TODAY</li><li class='nodata'>&nbsp;</li>";
    } else {
      $('times_ul').innerHTML = '<li><a href="javascript:void(0);" onclick="get_next_section(); return false;">' + next_times[0] + ' - ' + next_times[1] + '</a></li><li class="nodata">&nbsp;</li>';
    }
  } else {
    if (etime == latest || next_times == false || next_times.length == 0) {
      $('times_ul').innerHTML = '<li><a href="javascript:void(0);" onclick="get_previous_section(); return false;">' + prev_times[0] + ' - ' + prev_times[1] + '</a></li><li class="nodata">&nbsp;</li>';
    } else {
      $('times_ul').innerHTML = '<li><a href="javascript:void(0);" onclick="get_previous_section(); return false;">' + prev_times[0] + ' - ' + prev_times[1] + '</a></li><li><a href="javascript:void(0);" onclick="get_next_section(); return false;">' + next_times[0] + ' - ' + next_times[1] + '</a></li>';
    }
  }
}

function get_data(direction) {
  if (getting[direction] === true) {
    return false;
  }
  getting[direction] = true;
  var currpage = ttpage[direction];
  var mypage = ttpage[direction] + 1;
  ttpage[direction] = mypage;
  new Ajax.Request('/teetimes/paging?rnd=' + Math.random(),
  {
    method: 'post',
    parameters: 'direction=' + direction +'&time=' + time + "&page=" + mypage +"&clubids=" + clubids + "&date=" + date + "&players=" + players + "&holes=" + holes + "&cart=" + cart + "&courseid=" + courseid + "&secret_key=" + secret_key + "&authenticity_token=" + global_token,
    onComplete: function(response) {
      eval(response.responseText);
      add_section(mypage,data,direction);
    }
  });      
}

function create_sections() {
  get_data('forward');
}

function show_teetimes_notice (content, callback) {
  table = document.createElement('table');
  tbody = document.createElement('tbody');
  tr = document.createElement('tr');
  table.className ="teetimes no-stripe";
  table.cellspacing = "0";
  table.cellpadding = "0";
  td = document.createElement('td');
  td.innerHTML = content;
  tr.appendChild(td);
  tbody.appendChild(tr);    
  table.appendChild(tbody);
  $("spinnersection").innerHTML = '';
  $("spinnersection").appendChild(table);
  if (callback !== undefined) {
    try {
      callback();
    } catch (e) {}
  }
}

function add_section(mypage,data,direction){
  getting[direction] = false;
  if (data == "error") {
    alerted = true;
    alert('There is an error communicating with the course. iseekgolf.com has been notified');
  } else if (data != null) {
    // show the buy not box
    // put the first and last id's in an array
    data_found = true;
    // mark the first time as the earliest if going backwards
    if (direction == "backward") {
      earliest = data.teetimes[0].time;
      if (latest == "") latest = data.teetimes[(data.teetimes.length-1)].time;
    } else {
      if (earliest == "") earliest = data.teetimes[0].time;
      latest = data.teetimes[(data.teetimes.length-1)].time;
    }
    var div = document.createElement('div');
    div.className = "section";
    div.id = "section_" + mypage + "_" + direction;
    div.appendChild(add_table(data));
    if ($('spinnersection')) {
      $('glidersections').removeChild($('spinnersection'));        
    }
    if (direction == "forward") {
      $("glidersections").appendChild(div);
    } else {
      var current = my_glider.current;
      var clone = document.createElement('div');
      $(clone).addClassName('section');
      clone.innerHTML = current.innerHTML;
      clone.id = div.id;
      var backup;
      var shouldUpdateSibling = false;
      if (current != $('glidersections').down('div')) {
        backup = current.previousSibling.innerHTML;
        shouldUpdateSibling = true;
        current.previousSibling.innerHTML = current.innerHTML;
      }
      $('glidersections').insertBefore(clone, $('glidersections').down('div'));
      my_glider.isgSetup();
      my_glider.moveTo(current, my_glider.scroller, { duration: 0 });
      if (shouldUpdateSibling) { 
        setTimeout(function() { current.previousSibling.innerHTML = backup; }, 800);
      }
      setTimeout(function() { clone.innerHTML = div.innerHTML; }, 800);
    }      
    if (my_glider.current == undefined) {
      my_glider.isgSetup();
      my_glider.current = my_glider.sections[0];
      set_current_times();
    } else {
      my_glider.initialize('my-glider', {duration:0.5, initialSection: my_glider.current});        
      set_current_times();
    }
    if (backwards < 1 && forwards == 1) {
      backwards = backwards + 1;
      get_data("backward");
    }
    if (direction == "forward" && forwards < 1) {
      forwards = forwards + 1;
      get_data("forward");
    }
  } else {
    if (forwards == 0 && data_found == false) {
      // show the no result div
      txt = "<p>No results found for " + date_in_words + "</p>";
      if (cart == "true" && $("cart").options.length == 3) {
        txt = txt + "<p><a href='javascript:void(0)' onClick='$(\"cart\").selectedIndex = 2;jQuery(\"#teetimesform\").submit();return false;'>Try without a cart?</a></p>";
      }
      txt = txt + "<span id='find_more_times'><img src='/v5/images/spinner.gif'/> Finding closest times ...</span>";
      show_teetimes_notice(txt, function() {
        $('times_ul').innerHTML = "<li>NO MORE RESULTS TODAY</li><li class='nodata'>&nbsp;</li>";
      });
      last_time = "none";
      first_time = "none";
      // ajax the others
      new Ajax.Request('/teetimes/closestbookings?rnd=' + Math.random(),
      {
        asynchronous: true, 
        evalScripts: true,
        parameters: 'time=' + time + "&page=" + mypage +"&clubids=" + clubids + "&date=" + date + "&players=" + players + "&holes=" + holes + "&cart=" + cart + "&courseid=" + courseid + "&secret_key=" + secret_key + "&authenticity_token=" + global_token,
             method: 'post',
             onComplete: function(response) {
              eval(response.responseText);
              if (data == "error") {
                alerted = true;
                alert('There is an error communicating with the course. iseekgolf.com has been notified');
              } else if (data != null) {
                txt = "";
                fat = null;
                fbt = null;
                pat = null;
                pbt = null;
                for(x=0;x < data.teetimes.length ; x++) {
                  switch (data.teetimes[x].search_mode) {
                    case 'FutureAfterTime': 
                      fat = data.teetimes[x];
                      break;
                    case 'FutureBeforeTime': 
                      fbt = data.teetimes[x];
                      break;
                    case 'PastBeforeTime': 
                      pbt = data.teetimes[x];
                      break;
                    case 'PastAfterTime': 
                      pat = data.teetimes[x];
                      break;
                  }
                }
                if (fat != null || pat != null) {
                  txt += "<p>The closest available teetimes after " + human_time + ":</p>";
                  if (pat != null) {
                    txt += search_link(pat);
                  }
                  if (fat != null) {
                    txt += search_link(fat);                                  
                  }
                }
                if (fbt != null || pbt != null) {
                  txt += "<p>The closest available teetimes before " + human_time + ":</p>";
                  if (pbt != null) {
                    txt += search_link(pbt);                                  
                  }
                  if (fbt != null) {
                    txt += search_link(fbt);                                  
                  }
                }
                $('find_more_times').innerHTML = txt;
              } else {
                $('find_more_times').innerHTML = "No more times found.";
                // no times found
              }
             }
           });     
      } else {
        if (backwards < 1 && forwards == 1) {
          backwards = backwards + 1;
          get_data("backward");
        } else {
          if (direction == "forward") {
            last_time = time;
            set_current_times();
          } else {
            first_time = time;
            set_current_times();
          }          
        }
      }
    }
  }
  
function search_link(data) {
  return "<p><a href='javascript:void(0)' onClick='setdate(\"" + data.js_month + "\",\"" + data.js_day + "\",\"" + data.js_time + "\");return false;'>" + data.time + " " + data.date + "</a></p>";
}

function add_table(data) {
  table = document.createElement('table');
  tbody = document.createElement('tbody');
  tr = add_top_tr();
  table.className ="teetimes no-stripe";
  table.cellspacing = "0";
  table.cellpadding = "0";
  tbody.appendChild(tr);    
  table.appendChild(tbody);
  for(x=0;x < 10 ; x++) {
    if (data.teetimes[x]) {
      tr = add_data_tr(data.teetimes[x],(x == 0),(x == (data.teetimes.length-1) && x > 0),x);
    } else {
     tr = document.createElement('tr');
     if (x % 2 == 0) {
       tr.className = "tint";      
     }
     for(y=0; y < 8 ; y++) {
       td = document.createElement('td');
       if (y ==0) td.className = "left coursename";
       td.innerHTML = "&nbsp;";
       tr.appendChild(td);
     }
    }
    tbody.appendChild(tr);
  }
  return table;
}

function add_data_tr(teetime,first,last,index){
  tr = document.createElement('tr');
  if (index % 2 == 0) {
    tr.className = "tint";      
  }
  td = document.createElement('td');

  td.className = "left coursename";
  td.innerHTML = teetime.course_name;
  tr.appendChild(td);
  tr.appendChild(time_td(teetime.time,first,last));
  tr.appendChild(add_td(teetime.holes));
  tr.appendChild(add_td(convert_slots_available(teetime.slots_available)));
  tr.appendChild(gfee_td(teetime));
  tr.appendChild(players_dd(teetime));
  if (teetime.carts_available > 0) {
    tr.appendChild(cfee_td(teetime));  
  } else if (cart == "false") {
    td = document.createElement('td');
    td.innerHTML = "<span class='cp'>N/A</span>";
    tr.appendChild(td);  
  }
  tr.appendChild(carts_dd(teetime));
  return tr;
}

function add_top_tr(){
  tr = document.createElement('tr');
  th = add_th("Course Name");
  th.className = "left";
  tr.appendChild(th);
  tr.appendChild(add_th("Time"));
  tr.appendChild(add_th("Holes"));
  tr.appendChild(add_th("Avail"));
  tr.appendChild(add_th("Green Fee"));
  tr.appendChild(add_th("Players"));
  tr.appendChild(add_th("Cart Fee"));
  tr.appendChild(add_th("Carts"));
  return tr;
}
function add_th(title){
  th = document.createElement('th');
  th.innerHTML = title;
  return th;
}
function add_td(title,obj){
  td = document.createElement('td');
  if (obj != undefined) {
    td.appendChild(obj);
  } else {
    td.innerHTML = title;
  }
  return td;
}
function convert_slots_available(count){
  //img = document.createElement("img");
  //img.border = "0";
  //img.src = "/images/yes_" + count + ".gif";
  //return img;
  return count;
}

function gfee_td(teetime) {
  hover_txt = "";
  td = document.createElement('td');
  if (parseFloat(teetime.gfee) < parseFloat(teetime.rackrate)) {
    percent = parseFloat(teetime.percent);
    td = document.createElement('td');
    if (percent >= 10) {
      td.className = "discount3";
    }
    hover_txt = "WAS: " + formatAsMoney(teetime.rackrate) + "<br/>NOW: " + formatAsMoney(teetime.gfee) + "<br/>YOU SAVE:&nbsp;" + teetime.percent + "%";
  } else {
	  hover_txt = "Full Price Green fee";
  }
  if (teetime.greenfee_note != "" || teetime.booking_note != "") {
    hover_txt = hover_txt + "<br/>";
    gf = formatAsMoney(teetime.gfee) + "*";
  } else {
    gf = formatAsMoney(teetime.gfee);    
  }
  if (teetime.booking_note != "") {
    hover_txt += "<br/>" + URLDecode(teetime.booking_note);
	}
  if (teetime.greenfee_note != "") {
	  hover_txt += "<br/>" + URLDecode(teetime.greenfee_note);
	}
	hover_txt = hover_txt.replace(/'/g,'"').replace(/"/g,'\\\'');
  td.innerHTML = "<a href='#teetimes' onmouseover=\"Tip('" + hover_txt + "')\" onmouseout=\"UnTip()\" style='color: #000;'>" + gf + "</a>";
  return td;
}

function URLDecode(txt)
{
   // Replace + with ' '
   // Replace %xx with equivalent character
   // Put [ERROR] in output if %xx is invalid.
   var HEXCHARS = "0123456789ABCDEFabcdef"; 
   var encoded = txt;
   var plaintext = "";
   var i = 0;
   while (i < encoded.length) {
       var ch = encoded.charAt(i);
	   if (ch == "+") {
	       plaintext += " ";
		   i++;
	   } else if (ch == "%") {
			if (i < (encoded.length-2) 
					&& HEXCHARS.indexOf(encoded.charAt(i+1)) != -1 
					&& HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {
				plaintext += unescape( encoded.substr(i,3) );
				i += 3;
			} else {
				alert( 'Bad escape combination near ...' + encoded.substr(i) );
				plaintext += "%[ERROR]";
				i++;
			}
		} else {
		   plaintext += ch;
		   i++;
		}
	} // while
   return plaintext;
};


function cfee_td(teetime) {
  td = document.createElement('td');
  if (teetime.cfee_type == 0) {
   inner = formatAsMoney(teetime.cfee) + '<span class="cp">PC</span>';
  } else {
    inner = formatAsMoney(teetime.cfee) + '<span class="cp">PP</span>';
  }
  if (cart == "false") inner = '<span class="cp">' + inner + '</span>';
  td.innerHTML = inner;
 return td;
}

function time_td(time,first,last) {
  time_bits = time.split(":");
  if (time_bits[0] >= 12)  {
    if (time_bits[0] == 12) {
      td =  add_td(time + '<span class="cp">PM</span>');      
    } else {
      td =  add_td("0" + (time_bits[0] - 12) + ":" + time_bits[1] + '<span class="cp">PM</span>');        
    }      
  } else {
    td =  add_td(time + '<span class="cp">AM</span>');
  }
  if (first) {
    td.className = "firsttime";
  }
  if (last) {
    td.className = "lasttime";      
  }
  return td;
}

function players_dd(teetime) {
  select_string = "<select ";
  //select = document.createElement('select');
  id = "players_" + teetime.teetimeid;
  select_string += "id='" + id + "' class='playerdropdown' onChange='calc_carts(\"" + id.gsub("players_","") + "\"); calc_total();'>";
  max = teetime.slots_available;
  for (xx=0;xx <= max; xx++) {
    select_string += "<option value='" + xx + "'>" + xx + "</option>";
  }
  select_string += "</select>";
  td = document.createElement('td');
  td.innerHTML = select_string;
  // add in gfee prices
  var input = document.createElement('input');
  input.type = "hidden";
  input.name = "gfee_" + teetime.teetimeid;
  input.id = "gfee_" + teetime.teetimeid;
  input.value = teetime.gfee;
  $("hidden_inputs").appendChild(input);
  return td;
}

function carts_dd(teetime) {
  //select = document.createElement('select');
  id = "carts_" + teetime.teetimeid;
  max = teetime.carts_available;
  td = document.createElement('td');
  if (max > 0 ){
    select_string = "<select ";
    select_string += "id='" + id + "' class='cartdropdown' onChange='calc_total();'";
    select_string += " disabled='disabled' ";
    select_string += ">";
    select_string += "<option value='0'>0</option>";
    select_string += "</select>";
    td.innerHTML = select_string;
    // add in cart prices
    var input = document.createElement('input');
    input.type = "hidden";
    input.name = "cfee_" + teetime.teetimeid;
    input.id = "cfee_" + teetime.teetimeid;
    input.value = teetime.cfee;
    $("hidden_inputs").appendChild(input);
    var input = document.createElement('input');
    input.type = "hidden";
    input.name = "carts_available_" + teetime.teetimeid;
    input.id = "carts_available_" + teetime.teetimeid;
    input.value = teetime.carts_available;
    $("hidden_inputs").appendChild(input);
    var input = document.createElement('input');
    input.type = "hidden";
    input.name = "cartid_" + teetime.teetimeid;
    input.id = "cartid_" + teetime.teetimeid;
    input.value = teetime.cartid;
    $("hidden_inputs").appendChild(input);
    var input = document.createElement('input');
    input.type = "hidden";
    input.name = "cart_hire_type_" + teetime.teetimeid;
    input.id = "cart_hire_type_" + teetime.teetimeid;
    input.value = teetime.cfee_type;
    $("hidden_inputs").appendChild(input);
    var input = document.createElement('input');
    input.type = "hidden";
    input.name = "cart_max_users_" + teetime.teetimeid;
    input.id = "cart_max_users_" + teetime.teetimeid;
    input.value = teetime.cart_max_users;
    $("hidden_inputs").appendChild(input);
  } else if(max == -1) {
    // it's included
    td.setAttribute("colSpan",2);
    td.innerHTML = "<span class='cp'>INCLUDED IN GREEN FEE</span>";
    var input = document.createElement('input');
    input.type = "hidden";
    input.name = "cart_included_" + teetime.teetimeid;
    input.id = "cart_included_" + teetime.teetimeid;
    input.value = "true";
    $("hidden_inputs").appendChild(input);
  } else {
    if (cart == "false") {
      select_string = "<select disabled='disabled' >";
      select_string += "<option value='0'>0</option>";
      select_string += "</select>";
      td.innerHTML = select_string;
    } else {
      td.setAttribute("colSpan",2);
      td.innerHTML = "<span class='cp'>SOLD OUT</span>";
    }
  }
  return td;
}

function calc_total() {
  selects = $$(".playerdropdown");
  lock_string = "";
  total = 0;
  teetime_found = false;
  teetime_ok = true;
  for(var x=0; x<selects.length; x++){
    if(selects[x].selectedIndex > 0) {
      teetimeid = parse_teetime(selects[x].id);
      clubid = teetimeid[1].split("-")[0] + "_" + teetimeid[1].split("-")[2];
      if (chosen_club == "") {
        chosen_club = clubid;
      }
      if (chosen_club == clubid) {
        players = selects[x][selects[x].selectedIndex].value;
        gfee = $F("gfee_" + teetimeid[1]);
        total = total + (players * gfee);          
        teetime_found = true;
      } else {
        selects[x].selectedIndex = 0;
        calc_carts(teetimeid[1]);
        teetime_ok = false;
        alert("Sorry, you can only book teetimes for one course at a time.");
      }
    }
  }
  if (teetime_found == false) {
    chosen_club = "";
  }
  if (teetime_ok == true) {
    selects = $$(".cartdropdown");
    for(var x=0; x<selects.length; x++){
      if(selects[x].selectedIndex > 0) {
        teetimeid = parse_teetime(selects[x].id);
        players = $F("players_" + teetimeid[1]);
        carts = $F("carts_" + teetimeid[1]); //selects[x][selects[x].selectedIndex].value;
        cfee = $F("cfee_" + teetimeid[1]);
        cfee_cart_hire_type = $F("cart_hire_type_" + teetimeid[1]);
        cart_max_users = $F("cart_max_users_" + teetimeid[1]);
        if (cfee_cart_hire_type == "1") {
          multiply = (cart_max_users * carts) > players  ? players : (cart_max_users * carts);
          total = total + (multiply * cfee);
        } else {
          total = total + (carts * cfee);
        }
      }
    }      
  }
  $("tt_total").innerHTML = formatAsMoney(total);
}

function calc_carts(id) {
  if (!$("carts_" + id)) {
    return true;
  }
  current_carts = $F("carts_" + id);
  cart_select = $("carts_" + id);
  players_chosen = $F("players_" + id);
  carts_available = $F("carts_available_" + id);
  max_carts = parseInt(carts_available, 10) < Math.ceil(players_chosen / 2) ? carts_available : Math.ceil(players_chosen / 2);
  cart_select.options.length = 0;
  if (max_carts && players_chosen > 0 && cart == "true") {
    $("carts_" + id).disabled = false;
  } else {
    $("carts_" + id).disabled = true;
  }
  for(x = 0; x <= max_carts; x++) {
    o = document.createElement("option");
    o.innerHTML = x;
    o.value = x;
    if (x == current_carts) {
      o.selected = true;
    }
    cart_select.appendChild(o);
  }
}

function parse_teetime(teetimeid){
  t = new Array();
  t = teetimeid.split('_');
  return t;
}
  
function formatAsMoney(mnt) {
    mnt -= 0;
    mnt = (Math.round(mnt*100))/100;
    return "$" + ((mnt == Math.floor(mnt)) ? mnt + '.00' 
              : ( (mnt*10 == Math.floor(mnt*10)) ? 
                       mnt + '0' : mnt));
}


function lock_teetimes() {
  $('lockform_dynamic').innerHTML = '';
  selects = $$(".playerdropdown");
  lock_string = "";
  players_found = false;
  first_players = true;
  for(var x=0; x<selects.length; x++){
    if (selects[x].selectedIndex > 0) {
      id_data = selects[x].id.split("_");
      tt_data = id_data[1].split("-");
      players = $F(selects[x]);
          gfee = $F("gfee_" + teetimeid[1]);
      if (first_players == true) {
        $("lock_club_id").value = tt_data[0];
        $("lock_course_id").value = tt_data[2];
        $("lock_holes").value = holes;
        $("lock_cart").value = cart;
        if ($("cart_included_" + teetimeid[1]) || ($("carts_" + id_data[1]) && $F("carts_" + id_data[1]) > 0)) {
          $("lock_cart_included").value = "true";
        } else {
          $("lock_cart_included").value = "false";
        }
      
      }
      first_players = false; 
      players_found = true;
      hidden = document.createElement("input");
      hidden.type = "hidden";
      hidden.name = "teetimes[]";
      hidden.className = "hidden_teetimes";
      hidden.value = tt_data[1] + "=" + players;
      $("lockform_dynamic").appendChild(hidden);
      hidden = document.createElement("input");
      hidden.type = "hidden";
      hidden.name = "greenfees[]";
      hidden.value = tt_data[1] + "=" + gfee;
      $("lockform_dynamic").appendChild(hidden);
      if ($("carts_" + id_data[1])){
        carts = $F("carts_" + id_data[1]);
        if (carts > 0) {
          cart_id = $F("cartid_"  + id_data[1]);
          hidden = document.createElement("input");
          hidden.type = "hidden";
          hidden.name = "hireitems[]";
          hidden.value =  tt_data[1] + "=" + cart_id + "*" + carts;
          $("lockform_dynamic").appendChild(hidden);
        }          
      }
    }
  }
  if (players_found) {
    window.scrollTo(0,0);
    if (document.getElementById('TB_ajaxContent')) {
      document.getElementById('TB_ajaxContent').innerHTML = "";
    }
    tb_show("","#TB_inline?inlineId=locking_teetimes&modal=true",false);
    $('TB_ajaxContent').innerHTML = "<img src='/v5/images/iseekgolf_loading_big.gif' width='570' height='380' />";
    try
    {
      params = Form.serialize($("lockform"));
    } catch(err){
      params = "";
    }
    if (params == "" || params == undefined) {
      msg = "<p>Sorry, there seems to be a problem with your booking.</p>";
      msg = msg + "<p>If you continue to experience problems please <a href=\"/contactus\">email us</a> or call us on 1300 663 813 (Mon-Fri 9am - 5pm EST)</p>";
      msg = msg + "<p><input type='button' onClick=\"tb_remove();\" value='Ok'/></p>";
      $('TB_ajaxContent').innerHTML = msg;
    } else {
      new Ajax.Request('/teetimes/lockteetimes_now?rnd=' + Math.random(),
      {
      asynchronous: true, 
      evalScripts: true,
      parameters:params,
          method: 'post',
          onComplete: function(response) {
            eval(response.responseText);
            if (teetimes_locked) {
              submit_lock_form();
            } else {
              msg = "<p>Sorry, there seems to be a problem with your booking.</p>";
              msg = msg + "<p>" + error_message + "</p>";
              msg = msg + "<p>If you continue to experience problems please <a href=\"/contactus\">email us</a> or call us on 1300 663 813 (Mon-Fri 9am - 5pm EST)</p>";
              msg = msg + "<p><input type='button' onClick=\"tb_remove();\" value='Ok'/></p>";
              $('TB_ajaxContent').innerHTML = msg;
            }
          }
      }); 
    }
    return false;
  } else {
    alert("Please choose a teetime before pressing the Buy Now button.");
  }
}
  
/*   CAPTURE MOUSE POSITION   */
if (document.layers) { // Netscape
    document.captureEvents(Event.MOUSEMOVE);
}

var toolTipOldOnMouseMove = document.onmousemove;
document.onmousemove = function(e) {
    //if (toolTipOldOnMouseMove) { toolTipOldOnMouseMove(e); }
    captureMousePosition(e);
};

// Global variables
xMousePos = 0; // Horizontal position of the mouse on the screen
yMousePos = 0; // Vertical position of the mouse on the screen
xMousePosMax = 0; // Width of the page
yMousePosMax = 0; // Height of the page
function captureMousePosition(e) {
    if (document.layers) { // Netscape
        xMousePos = e.pageX;
        yMousePos = e.pageY;
        xMousePosMax = window.innerWidth+window.pageXOffset;
        yMousePosMax = window.innerHeight+window.pageYOffset;
    } else if (document.all) { // Internet Explorer
        var scrollLeft , scrollTop ;

        var iebody=(document.compatMode && document.compatMode != "BackCompat")? document.documentElement : document.body;

        scrollLeft=iebody.scrollLeft;
        scrollTop=iebody.scrollTop;
    if (document.documentElement && document.documentElement.clientHeight)
        // Explorer 6 Strict Mode
    {
        xMousePosMax = document.documentElement.clientWidth + scrollLeft;
        yMousePosMax = document.documentElement.clientHeight + scrollTop;
    }
    else // other Explorers
    {
        xMousePosMax = document.body.clientWidth + scrollLeft;
        yMousePosMax = document.body.clientHeight + scrollTop;
    }
        xMousePos = window.event.x + scrollLeft;
        yMousePos = window.event.y + scrollTop;

    } else if (document.getElementById) { // Netscape 6
        xMousePos = e.pageX;
        yMousePos = e.pageY;
        xMousePosMax = window.innerWidth+window.pageXOffset;
        yMousePosMax = window.innerHeight+window.pageYOffset;
    }
}

  
  
/*   TOOLTIPS   */
function showTooltip(contentToShow) {
    if (contentToShow == "") {
        return false;
    }

    var tooltip = document.getElementById('tooltip');
    if (!tooltip)
    {
        return false;
    }

    var tooltipWidth = 200; // defined in global.css (div.tooltip)
    var padding = 15;
    var leftPosition = xMousePos;
    if (leftPosition + tooltipWidth > xMousePosMax) {
        leftPosition = xMousePosMax - tooltipWidth - (padding*2);
    }
    tooltip.innerHTML = contentToShow;
    tooltip.style.top = yMousePos + padding + 'px';
    tooltip.style.left = leftPosition + 'px';
    tooltip.style.display = 'block';
    return true;
}

function hideTooltip() {
    var tooltip = document.getElementById('tooltip');
    if (!tooltip)
    {
        return false;
    }

    tooltip.style.display = 'none';
    return true;
}

function set_arrows(grey) {
  if (grey) {
    if (!$('times_ul').innerHTML.match(/RESULTS/)) {
      $('times_ul').innerHTML = "<li>LOADING MORE TIMES ...</li><li class='nodata'></li>";
    }
  } else {
    set_time_arrows();
  }
}

function firstDay(days) {
  d = new Date();
  today = new Date();
  today.setHours("23");
  today.setMinutes("59");
  today.setSeconds("59");
  d.setDate($('Day').value);
  d.setMonth($('Month').value - 1);
  d.setFullYear($('Year').value);
  yesterday = addDaysToDate(d,days);
  if (yesterday < today) {
    return true;
  } else {
    return false;
  }
}

function checkdate(days) {
  // make a date from the current thingo
  firstDay(days);
  $('date').value = yesterday.getFullYear() + "-" + (yesterday.getMonth() + 1) + "-" + yesterday.getDate();
  $('Day').value = yesterday.getDate();
  $('Month').value = yesterday.getMonth() + 1;
  $('Year').value = yesterday.getFullYear();
  jQuery('#teetimesform').submit();
}

function isg_update_month(myArray,value) {
  for (var index = 0, len = myArray.length; index < len; ++index) {
    var item = myArray[index];
    if (item.value == value) {
      $('isgMonthYear').selectedIndex = index;
    }
    ttCalendar.updateMonthYear($('isgMonthYear').options[$('isgMonthYear').selectedIndex].value); 
  }  
}
function isg_update_day(myArray,value) {
  myArray.each(function(item) {
    if (item.value == value ) {
      $('isgDay').selectedIndex = $A($('isgDay').options).indexOf(item);
    }
  });
}
function isg_update_time(myArray,value) {
  myArray.each(function(item) {
    if (item.value == value ) {
      $('isgtime').selectedIndex = $A($('isgtime').options).indexOf(item);
    }
  });
}

function setdate(month,day,time) {
  isg_update_month($A($('isgMonthYear').options),month);
  isg_update_day($A($('isgDay').options),day);
  isg_update_time($A($('isgtime').options),time);
  jQuery('#teetimesform').submit();
}

function isg_change_day(monthyear,day){
  time = $F('isgtime');
  ttCalendar.updateMonthYear(monthyear);
  isg_update_day($A($('isgDay').options,day),day);
  jQuery('#isgtime').selectOptions(time, true);
  jQuery('#teetimesform').submit();  
  return false;
}



function next_day() {
  checkdate(1);
}

function previous_day() {
  checkdate(-1);
}

function addDaysToDate(myDate,days) {
    return new Date(myDate.getTime() + days*24*60*60*1000);
}

Array.prototype.in_array = function(p_val) {
  for(var i = 0, l = this.length; i < l; i++) {
    if(this[i] == p_val) {
      return true;
    }
  }
  return false;
};

function reset_carts_holes(val) {
    jQuery("#cart").removeOption(/.*/);
    jQuery("#cart").addOption({"" : "Choose"}, false);
  	if (val != "") {
  	    if (search_data["region"]["cart"][val].in_array("compulsory") || search_data["region"]["cart"][val].in_array("optional")) {
  	      jQuery("#cart").addOption({"true" : "Yes"}, false);
  	    }
  	    if(search_data["region"]["cart"][val].in_array("notused") || search_data["region"]["cart"][val].in_array("optional")) {
  	      jQuery("#cart").addOption({"false" : "No"}, false);
  	    }
  	} else {
  		jQuery("#cart").addOption({"true" : "Yes"}, false);
  		jQuery("#cart").addOption({"false" : "No"}, false);
  	}
    $("cart").selectedIndex = 1;
    jQuery("#holes").removeOption(/.*/);
    jQuery("#holes").addOption({"" : "Choose"}, false);
  	if (val != "") {
  	    if (search_data["region"]["holes"][val].in_array("18") || search_data["region"]["holes"][val].in_array("both")) {
  	      jQuery("#holes").addOption({"18" : "18"}, false);
  	    }
  	    if(search_data["region"]["holes"][val].in_array("9") || search_data["region"]["holes"][val].in_array("both")) {
  	      jQuery("#holes").addOption({"9" : "9"}, false);
  	    }		
  	} else {
        jQuery("#holes").addOption({"18" : "18"}, false);
        jQuery("#holes").addOption({"9" : "9"}, false);			
  	}
    $("holes").selectedIndex = 1;

}

function picked(what) {
  if (what == "course") {
    jQuery("#region").selectOptions("", true);
  } else {
    jQuery("#course").selectOptions("", true);
  }
  things = new Array(jQuery("#cart"),jQuery("#holes"));
  jQuery.each(things,function() {
    name = this.attr("name");
    whatvalue = jQuery('#' + what).val();
    if(name == "holes") {
        if(search_data[what][name][whatvalue] == "18") {
            myOptions = {
              "" : "Choose",
              "18" : "18"
            };
            current = "18";
        } else if (search_data[what][name][whatvalue] == "9") {
            myOptions = {
              "" : "Choose",
              "9" : "9"
            };
            current = "9";
        } else {
            myOptions = {
              "" : "Choose",
              "18" : "18",
              "9" : "9"
            };
            current = "18";
        }
      } else if (name == "cart") {
        if (search_data[what][name][whatvalue] == "notused") {
            myOptions = {
              "" : "Choose",
              "false" : "No"
            };
            current = "false";
        } else if (search_data[what][name][whatvalue] == "compulsory") {
            myOptions = {
              "" : "Choose",
              "true" : "Yes"
            };
            current = "true";
        } else {
          myOptions = {
            "" : "Choose",
            "true" : "Yes",
            "false" : "No"
          };
          current = "true";
        }
    }
    this.removeOption(/.*/);
    this.addOption(myOptions, false);
    this.selectOptions(current, true);
  });
}

