function findAddress2(e, which) {
    if (e.keyCode == 13) {
        if ($("#" + which + "key")[0].value != "") {
            findAddress(which);
        }
        return false;
    }    
    return true;
}
function findAddress(which) {
  var fakey = encodeURIComponent($("#"+which+"key")[0].value);
  $.get("ajax/getAddressFromKey.asp", "key=" + fakey,
    function(data) {
      if (data.indexOf(':|') > -1) {
        tmp = data.split(':|');
        $("#"+which+"ctt")[0].value = tmp[0];
        $("#"+which+"ph" )[0].value = tmp[1];
        $("#"+which+"com")[0].value = tmp[2];
        $("#"+which+"ad1")[0].value = tmp[3];
        $("#"+which+"ad2")[0].value = tmp[4];
        $("#"+which+"sub")[0].value = tmp[5];
        //$("#"+which+"key")[0].value = "";
        clearServices();
      }
      else if (data == "multiple") {
        document.booking.fakey.value = fakey;
        getaddress(which=="p"?"P":"D"); // on any error, redirect to full lookup page
      }
      else if (data == "") {
        alert("No address found");
      }
      else {
        alert(data);
      }
    });
}
function getCustomerUsers(cust) {
    $.get("ajax/customerUsers.asp", "cust=" + cust,
        function(data) {
            data = "" + data;
            if (data.length > 0) {
                var tmp = data.split("\n");
                var selectHtml = "";
                for (i = 1; i < tmp.length; i++) {
                    var idAndName = tmp[i].split("#");
                    var selTxt = "";
                    if (idAndName[0] == tmp[0])
                        selTxt = "selected='selected'"
                    selectHtml += "<option " + selTxt + " value=\"" + idAndName[0] + "\" >" + idAndName[1] + "</option>";
                }
                $("#bookedby").html(selectHtml);
            }
        });
}
function getCostCentres(cust) {
  $.get("ajax/costCentres.asp", "cust=" + cust,
    function(data) {
      data = "" + data;
      if ((data.length>0) && (data.substr(0,1) == "|")) {
        tmp = data.substring(1, data.length).split("\n");
        hasList = tmp.length > 1;
        validated = tmp[0] == "Y";
        storedCC = document.booking.ccref.value;
        selectHtml = "<select name=\"ccrefl\" id=\"ccref1\" onchange=\"changeCC();\">";
        selectHtml += "<option>&nbsp;</option>";
        if (validated || hasList) {
          for (i=1;i<tmp.length;i++) {
//            selectHtml += "<option value=\""+tmp[i]+"\" " + (storedCC==tmp[i]?"selected='selected'":"") + ">" + tmp[i] + "</option>";
            selectHtml += "<option value=\""+tmp[i]+"\" >" + tmp[i] + "</option>";
          }
        }
        selectHtml += "</select>";
        $("#ccrefltd").next().remove();
        $("#ref1list").append("<td>"+selectHtml+"</td>");
        if (validated || hasList) {
          //innerHTML = selectHtml;
//          $("#ref1list")[0].style.visibility = "visible";
//          $("#ref1list")[0].style.display = "table-row";
//          $("#ref1list").css({display:"table-row"});
        } else {
//          $("#ref1list")[0].style.visibility = "hidden";
//          $("#ref1list")[0].style.display = "none";
//          $("#ref1list").css({display:"none"});
        }
        if (validated) {
//          $("#ref1free")[0].style.visibility = "hidden";
//          $("#ref1free")[0].style.display = "none";
//          $("#ref1free").css({display:"none"});
        } else {
//          $("#ref1free")[0].style.visibility = "visible";
//          $("#ref1free")[0].style.display = "table-row";
//          $("#ref1free").css({display:"table-row"});
        }
        //$("#ccref")[0].autocompleter.resetData(eval(data));
        document.booking.ccref.value = storedCC;
      }
      else
        alert('Failed to get ref 1 list: ' + data);
    });
}
function saveaddress(src) {
  $.get("ajax/SaveAddress.asp", "src=" + src + "&"+ $("#booking").serialize(),
  function(data) { 
     if ($.trim(data) != "") {
       alert('Failed to save address: ' + data);
     } else {
       alert('Address Saved');     
     }
      });
return false;
//  if (src == 'P') {
//    alert('Save the Pickup Address');
//  } else {
//    alert('Save the Delivery Address');
//  }
//  return false;
}  

function changeCC() {
  tmp = document.booking.ccref1.value;
  document.booking.ccref1.selectedIndex = -1;
  document.booking.ccref1.value = "";
  document.booking.ccref.value = tmp;
}

function calculatebooking() {
var thistable = $('#results');
  document.booking.dmID.value = 'Price';
  $.get("ajax/BookJobPrice.asp",$("#booking").serialize(),
  function(data) { 
    thistable.children('tbody').children('tr').remove();
    //alert('This job would cost: ' + data);
    data = '<tr><td>' + data + '</td></tr>';
    thistable.children('tbody').append(data); 
  });
return false;
}
function validatebooking() {
  if (!(_cansubmit)) { return; }

  _cansubmit = false;
var thistable = $('#results');
  document.booking.dmID.value = 'Booking';
  $.get("ajax/BookJobPost.asp",$("#booking").serialize(),
  function(data) { 
    thistable.children('tbody').children('tr').remove();
    if (data.indexOf(':|') > -1) {
      tmp = data.split(':|');
      price = tmp[0];
      jobid = tmp[1];
      jobno = tmp[2];
      time = tmp[3];
      delaytxt = tmp[4];
      location.href='Job_Query_view.asp?org=j&jid='+jobid+'&err='+delaytxt;
    } else {
      data = data.replace(/<tr><td>/, "<tr><td width='*'><div class='error'>").replace(/<\/td><\/tr>/, "</div></td></tr>");
      thistable.children('tbody').append(data);
      _cansubmit = true;
    }
  });
return false;
}
function SaveBooking() {
var agree;
//if (document.booking.wu_cust_seq.value =="") {
//  alert('An User ID must be entered, try again!!');
//  document.booking.wu_cust_seq.focus();
//  return false;
//}

//if (!isNumeric(document.booking.wu_cust_seq.value)) {
//  alert('The User ID must be numeric only');
//  document.booking.wu_cust_seq.focus();
//  return false;
//}

if (document.booking.wu_name.value =="") {
  alert('A User Name must be entered, try again!!');
  document.booking.wu_name.focus();
  return false;
}

var pwd = document.booking.wu_web_password.value;
if ((pwd != "") && ((pwd.length < 6) || (pwd.length > 15))) {
  alert('Web password must be 6-15 characters');
  document.booking.wu_web_password.focus();
  return false;
}

pwd = document.booking.wu_device_password.value;
if ((pwd != "") && ((pwd.length < 4) || (pwd.length > 10))) {
  alert('Device password must be 4-10 characters');
  document.booking.wu_device_password.focus();
  return false;
}

agree=confirm("Do you want to save the changes?");
if (!agree) {
	return false ;
}

document.booking.submit() ;
}

function getPart(pname) {
  return "&" + pname + "=" + encodeURIComponent($("#"+pname).val());
}

function drill1(isuser) {
    $("#f_availsvcs").hide();
    $("#showServicesSpinner").show();
    var thistable = $('#services');
    $('#advisory').remove();
    $('#advisory2').remove();
    var selectedService = $('#booking input[name="styp"]:radio:checked').val();
    $.get("ajax/getservices.asp?cust="+encodeURIComponent(document.booking.dtrcde.value)+
                           getPart("pcom")+getPart("pad1")+getPart("psub")+getPart("dcom")+
                           getPart("dad1")+getPart("dsub")+getPart("scheddate")+getPart("scht")+
                           "&stvh=" + $('#booking input[name="stvh"]:radio:checked').val() +
                           getPart("qty")+getPart("wgt")+
                           "&rj="+($("#rj").attr("checked")?"on":""), 
        function(data) { 
            thistable.children('tbody').children('tr').remove();
            thistable.children('tbody').append(data);
            afterServices(isuser, selectedService);
            $("#f_availsvcs").show();
            $("#showServicesSpinner").hide();
        });

    return false;    
}
function getaddress(src) {
//  var urlvars = 'backto=booker&key='+GenKey+'&src='+src;
  document.booking.backto.value = 'job_booking.asp';
  document.booking.goto.value = 'fa_list.asp';
  document.booking.addsrc.value = src;
  document.booking.submit() ;
 
  return false;
}

function getLabels(cust) {
    $.get("ajax/getLabels.asp?cust=" + encodeURIComponent(cust),
  function(data) {
      if (data.indexOf(':|') > -1) {
          tmp = data.split(':|');
          if (tmp[0] == "#HIDE#")
              $("#lblref1").parent().hide()
          else {
              $("#lblref1").parent().show()
              $("#lblref1").html(tmp[0] + ":");
          }
          if (tmp[1] == "#HIDE#")
              $("#lblref2").parent().hide()
          else {
              $("#lblref2").parent().show()
              $("#lblref2").html(tmp[1] + ":");
          }
          if (tmp[2] == "#HIDE#")
              $("#lblref3").parent().hide()
          else {
              $("#lblref3").parent().show()
              $("#lblref3").html(tmp[2] + ":");
          }
      } else {
          if ($.trim(data) != '') {
              alert(data);
          }
      }
  });
}
function customerchanged() {

$.get("ajax/GetDefaultAddress.asp",$("#booking").serialize(),
  function(data) { 
    if (data.indexOf(':|') > -1) {
      tmp = data.split(':|');
      document.booking.pctt.value =  tmp[0];
      document.booking.pph.value  =  tmp[1];
      document.booking.pcom.value =  tmp[2];
      document.booking.pad1.value =  tmp[3];
      document.booking.pad2.value =  tmp[4];
      document.booking.psub.value =  tmp[5];
    } else {
      if ($.trim(data) != '') {
        alert ( data );
    }}
  });  
  getCostCentres(document.booking.dtrcde.value);
  getLabels(document.booking.dtrcde.value);
  getCustomerUsers(document.booking.dtrcde.value);
  clearServices();
}

function clearaddress(which) {
  $("#"+which+"key")[0].value = "";
  $("#"+which+"ctt")[0].value = "";
  $("#"+which+"ph" )[0].value = "";
  $("#"+which+"com")[0].value = "";
  $("#"+which+"ad1")[0].value = "";
  $("#"+which+"ad2")[0].value = "";
  $("#"+which+"sub")[0].value = "";
}

function swapaddresses() {
  var pcn = document.booking.pctt.value;
  var pph = document.booking.pph.value;
  var pco = document.booking.pcom.value;
  var pa1 = document.booking.pad1.value;
  var pa2 = document.booking.pad2.value;
  var psu = document.booking.psub.value;

  document.booking.pctt.value = document.booking.dctt.value;
  document.booking.pph.value = document.booking.dph.value;
  document.booking.pcom.value = document.booking.dcom.value;
  document.booking.pad1.value = document.booking.dad1.value;
  document.booking.pad2.value = document.booking.dad2.value;
  document.booking.psub.value = document.booking.dsub.value;
  
  document.booking.dctt.value = pcn;
  document.booking.dph.value = pph;
  document.booking.dcom.value = pco;
  document.booking.dad1.value = pa1;
  document.booking.dad2.value = pa2;
  document.booking.dsub.value = psu;
  return false;
}

function bikeSelected(which) {
  if ((which == "stvh") && ($("input[name='stvh'][checked][value='1']").length > 0))
    return 2
  else
    return $("input[name='"+which+"'][checked][class*='bike']").length > 0 ? 1: 0;
}

function chooseBike(isUser, isBike) {
    // just clear services
    clearServices();

//    if (isBike == 2) {
//        $("#services input[name='styp']").removeAttr("disabled");
//    }
//    else if (isBike == 1) {
//        if (isUser && !(bikeSelected('styp'))) {
//            $("#services input[name='styp'][class*='bike']:first").attr("checked", "checked");
//        }
//        $("#services input[name='styp']:not([class*='bike'])").attr("disabled", "disabled");
//        $("#services input[name='styp'][class*='bike']").removeAttr("disabled");
//    } else {
//        if (isUser && bikeSelected('styp')) {
//            $("#services input[name='styp']:not([class*='bike']):first").attr("checked", "checked");
//        }
//        $("#services input[name='styp'][class*='bike']").attr("disabled", "disabled");
//        $("#services input[name='styp']:not([class*='bike'])").removeAttr("disabled");
//    }

}

function clearServices() {
    $('#services').children('tbody').children('tr').remove();
}
