// ----------------------------------------------------------------------
// Javascript form validation routines.
//
// Simple routines to quickly pick up obvious typos.
// All validation routines return true if executed by an older browser:
// in this case validation must be left to the server.
//
// ----------------------------------------------------------------------

// Ver  Date      Comment
// V31  03/01/07  New function hide_postcode - if select International, hide Postcode field


var nbsp = 160;                // non-breaking space char
var node_text = 3;        // DOM text node-type
var emptyString = /^\s*$/ ;
var global_valfield;        // retain valfield for timer thread
var error_string = "";


// Replace UPLOAD button with LOADING.... image
function show_pic_loading() {
  if (document.getElementById) {
    text_obj = document.getElementById('submit_pic_button');
  } else {
    text_obj = document[in_id];
  }

  text_obj.innerHTML = "<img src='./images/wait_loading_anim.gif'>";

}

function show_pic_submit() {
  if (document.getElementById) {
    text_obj = document.getElementById('submit_pic_button');
  } else {
    text_obj = document[in_id];
  }

  text_obj.innerHTML = "<input type='submit' name='submit' value='Upload Logo' />";

}


// --------------------------------------------
//                  trim
// Trim leading/trailing whitespace off string
// --------------------------------------------

function trim(str)
{
  return str.replace(/^\s+|\s+$/g, '');
}

function add_plusses() {
  var objRegExp = / /g; //search for whitespace globally
  //replace all matches with empty strings
  return strValue.replace(objRegExp,'+');
}

function removeCommas( strValue ) {
  var objRegExp = /,/g; //search for commas globally
  //replace all matches with empty strings
  return strValue.replace(objRegExp,'');
}

function removeDollars( strValue ) {
  var objRegExp = /\$/g; //search for $s globally
  //replace all matches with empty strings
  return strValue.replace(objRegExp,'');
}

function isNumeric(x) {
// I use this function like this: if (isNumeric(myVar)) { }
// regular expression that validates a value is numeric
var RegExp = /^(-)?(\d*)(\.?)(\d*)$/; // Note: this WILL allow a number that ends in a decimal: -452.
// compare the argument to the RegEx
// the 'match' function returns 0 if the value didn't match
var result = x.match(RegExp);
if (result == null) {
  return false;
} else {
  return true;
}

}


// -----------------------------------------
// Extract Left or Right Portions of Strings
// -----------------------------------------
function left(str, n){
        if (n <= 0) {
            return "";
        }
        else {
          if (n > String(str).length) {
            return str;
          }  else {
            return String(str).substring(0,n);
          }
        }
}
// --------------------------------------------
//                  setfocus
// Delayed focus setting to get around IE bug
// --------------------------------------------

function setFocusDelayed()
{
  global_valfield.focus();
}

function setfocus(valfield)
{
  // save valfield in global variable so value retained when routine exits
  if (error_string == "") {
    global_valfield = valfield;
    setTimeout( 'setFocusDelayed()', 100 );
  }
}


// --------------------------------------------
//                  msg
// Display warn/error message in HTML element.
// commonCheck routine must have previously been called
// --------------------------------------------

function msg(fld,     // id of element to display message in
             msgtype, // class to give element ("warn" or "error")
             message) // string to display
{
  // setting an empty string can give problems if later set to a
  // non-empty string, so ensure a space present. (For Mozilla and Opera one could
  // simply use a space, but IE demands something more, like a non-breaking space.)

  if (fld) {
  var dispmessage;
  var elem = document.getElementById(fld);

  if (emptyString.test(message)) {
    dispmessage = String.fromCharCode(nbsp);
    elem.innerHTML = dispmessage;
  } else {
    dispmessage = message;
    error_string = error_string + "* " + message + "<br />";
    elem.innerHTML = String.fromCharCode(nbsp) + "!";
  }

  }

  //elem.className = msgtype;   // set the CSS class to adjust appearance of message
}

// --------------------------------------------
//            commonCheck
// Common code for all validation routines to:
// (a) check for older / less-equipped browsers
// (b) check if empty fields are required
// Returns true (validation passed),
//         false (validation failed) or
//         proceed (don't know yet)
// --------------------------------------------

var proceed = 2;

function commonCheck    (valfield,   // element to be validated
                         infofield,  // id of element to receive info/error msg
                         required,
                         realname)   // true if required
{
  if (!document.getElementById) {
    return true;  // not available on this browser - leave validation to the server
  }

  if (emptyString.test(valfield.value)) {
    if (required) {
      msg (infofield, "error", realname + " - You must enter a value");
      setfocus(valfield);
      return false;
    }
    else {
      return proceed;
    }
  }
  return proceed;
}

// --------------------------------------------
//            validatePresent
// Validate if something has been entered
// Returns true if so
// --------------------------------------------

function validatePresent(valfield,   // element to be validated
                         infofield,
                         realname ) // id of element to receive info/error msg
{
  msg (infofield, "warn", "");
  var stat = commonCheck (valfield, infofield, true, realname);
  if (stat != proceed) {
    return stat;
  }

  return true;
}

// --------------------------------------------
//               validateEmail
// Validate if e-mail address
// Returns true if so (and also if could not be executed because of old browser)
// --------------------------------------------

function validateEmail  (valfield,   // element to be validated
                         infofield,  // id of element to receive info/error msg
                         required,
                         realname)   // true if required
{
  msg (infofield, "warn", "");
  var stat = commonCheck (valfield, infofield, required, realname);
  if (stat != proceed) {
   return stat;
  }

  var tfld = trim(valfield.value);  // value of field with whitespace trimmed off
  var email = /^[^@]+@[^@.]+\.[^@]*\w\w$/  ;
  if (!email.test(tfld)) {
    msg (infofield, "error", realname + " - Not valid e-mail");
    setfocus(valfield);
    return false;
  }

  var email2 = /^[A-Za-z][\w.-]+@\w[\w.-]+\.[\w.-]*[A-Za-z][A-Za-z]$/  ;
  if (!email2.test(tfld)) {
    msg (infofield, "warn", realname + " - Unusual e-mail??");
  } else {
    msg (infofield, "warn", "");
  }
  return true;
}


// --------------------------------------------
//            validatePhone
// Validate telephone number
// Returns true if so (and also if could not be executed because of old browser)
// Permits spaces, hyphens, brackets and leading +
// --------------------------------------------

function validatePhone  (valfield,   // element to be validated
                         infofield,  // id of element to receive info/error msg
                         required,
                         realname)   // true if required
{
  msg (infofield, "warn", "");
  var stat = commonCheck (valfield, infofield, required, realname);
  if (stat != proceed) {
    return stat;
  }


  var tfld = trim(valfield.value);  // value of field with whitespace trimmed off

  if (emptyString.test(tfld)) {
    // If empty then this is valid
    return true;
  }

  var telnr = /^\+?[0-9 ()-]+[0-9]$/  ;
  if (!telnr.test(tfld)) {
    msg (infofield, "error", realname + " - Not valid Phone Number");
    setfocus(valfield);
    return false;
  }

  var numdigits = 0;
  for (var j=0; j<tfld.length; j++) {
    if (tfld.charAt(j)>='0' && tfld.charAt(j)<='9') {
      numdigits++;
    }
  }

  if (numdigits < 10) {
    msg (infofield, "error", realname + " - Only " + numdigits + " digits - must include area code");
    setfocus(valfield);
    return false;
  }

  return true;
}

// --------------------------------------------
//            validatePhone
// Validate telephone number
// Returns true if so (and also if could not be executed because of old browser)
// Permits spaces, hyphens, brackets and leading +
// --------------------------------------------

function validateNumber  (valfield,   // element to be validated
                          infofield,  // id of element to receive info/error msg
                          required,
                          realname,inmin,inmax)   // true if required
{
  var stat = commonCheck (valfield, infofield, required, realname);
  if (stat != proceed) {
    return stat;
  }

  if (inmin == null){
    inmin = 0;
  }
  if (inmax == null){
    inmax = 0;
  }

  var tfld = trim(valfield.value);  // value of field with whitespace trimmed off
  tfld = removeCommas(tfld);
  tfld = removeDollars(tfld);

  if (emptyString.test(tfld)) {
    // If empty then this is a valid number - commonCheck will check if it is Mandatory/Required
    return true;
  }

  if (tfld != "POA") {

   if (!isNumeric(tfld)) {
    msg (infofield, "error", realname + " - Must be a Number");
    return false;
   }
   else {
    //Check it is within range
    if ((inmin != 0) && (inmax != 0)) {
       if ((inmin <= tfld) && (tfld <= inmax)) {
          // Within range, this is OK
          return true;
       }
       else {
          msg (infofield, "error", realname + " - Number out of Range (" + inmin + "-" + inmax + ")");
          return false;
       }
    }
   }
  }

  return true;
}

function validateLength(valfield,   // element to be validated
                        infofield,  // id of element to receive info/error msg
                        max_length, // max length for this field
                        required,
                        realname)
{
  var stat = commonCheck (valfield, infofield, required, realname);
  if (stat != proceed) {
    return stat;
  }

  var tfld = trim(valfield.value);  // value of field with whitespace trimmed off

  if (tfld.length > max_length) {
     msg (infofield,"error", realname + " - Too Long - max " + max_length + " chars");
     setfocus(valfield);
     return false;
  }
  else {
    msg(infofield,"error","");
    return true;
  }

}

// Check that they have either selected a category or suggested a new one
function validateCategory(catfield,
//                          newcatfield,
                          infofield)
{
  msg (infofield, "warn", "");

//  var newcat = trim(newcatfield.value);  // value of field with whitespace trimmed off

  // If they haven't selected a Category from the list they MUST suggest a NEW category
  if (document.forms.edit_item.item_cat.selectedIndex == 0) {
      msg (infofield, "error", "Please choose a Category from the List");
      return false;

    // Not chosen a category - is New Cat empty?
//    if (emptyString.test(newcat)) {
//      msg (infofield, "error", "Please choose a Category or Suggest New");
//      return false;
//    }
  }

  return true;

}


// Check that, if they say it is USED the Hours Used is filled-in and is a Number > 0
// If they say it is NEW, we ignore the Hours Used anyway so it can be anything
function validateHoursUsed(cfield,
                           hoursfield,
                           infofield)
{
  msg (infofield, "warn", "");
  if (document.forms.edit_item.item_condition[0].checked) {
     condition = "Used";
     var stat = commonCheck (hoursfield, infofield, true, "Hours Used");
     if (stat != proceed) {
       return stat;
     }
  }
  else {
     condition = "New";
  }

  var thehours = trim(hoursfield.value);  // value of field with whitespace trimmed off

  // If they choose USED then they must fill in hours
  if (condition == "Used") {
    // it is Used, are hours specified?
     if ( (thehours == "0") || (thehours == "") ) {
       msg(infofield,"error", "Please specify the Hours Used");
       return false;
     }
  }

  return true;

}


// They don't have to specify a Manufacture Date, but:
// If they choose a MONTH, they must specify a Year
// If they specify a year, it must be within range (i.e. > 1900, < current year + 1)

function validateManufDate(monthfield,
                           yearfield,
                           infofield)
{
  msg (infofield, "warn", "");
  var stat = commonCheck (yearfield, infofield, false, "Manuf Date");
  if (stat != proceed) {
   return stat;
  }

  var theyear = trim(yearfield.value);  // value of field with whitespace trimmed off

  // If they don't choose a Month, then the Year is optional
  var d = new Date();
  max_year = d.getFullYear() + 1;

  if (document.forms.edit_item.item_manuf_month.selectedIndex == 0) {
    if (!validateNumber(yearfield,infofield,false,"Year",1900,max_year)) {
      return false;
    }
  }
  else {
    // Year must be specified
    if (!validateNumber(yearfield,infofield,true,"Year",1900,max_year)) {
      return false;
    }
  }

  return true;

}

// If they say it is available to buy, then they must specify a Buy price
function validateBuyPrice(canbuyfield,
                          buypricefield,
                          infofield)
{
  msg (infofield, "warn", "");
  if (document.forms.edit_item.can_buy[0].checked) {
     canbuy = true;
     var stat = commonCheck (buypricefield, infofield, true, "Price to Buy");
     if (stat != proceed) {
       return stat;
     }
  }
  else {
    canbuy = false;
  }

  var theprice = trim(buypricefield.value);  // value of field with whitespace trimmed off
  theprice = removeCommas(theprice);
  theprice = removeDollars(theprice);

  // If they say it's available to BUY, they must enter a price
  if (canbuy == true) {
    if (!validateNumber(buypricefield,infofield,true,"Price to Buy",0,1000000)) {
      return false;
    }
  }

  return true;

}

// If they say it is available to buy, then they must specify one or more Hire prices
function validateHirePrice(canhirefield,
                           hirepdfield,
                           hirepmfield,
                           hirepwfield,
                          infofield)
{
  msg (infofield, "warn", "");
  if (document.forms.edit_item.can_hire[0].checked) {
     canhire = true;
  }
  else {
    canhire = false;
  }

  if (document.forms.edit_item.can_buy[0].checked) {
     canbuy = true;
  }
  else {
    canbuy = false;
  }

  if ( (canbuy == false) && (canhire == false) ) {
    msg (infofield, "error", "You Must select YES for either Buy or Hire");
    return false;
  }


  var pricepd = removeCommas(removeDollars(trim(hirepdfield.value)));  // value of field with whitespace trimmed off
  var pricepm = removeCommas(removeDollars(trim(hirepwfield.value)));  // value of field with whitespace trimmed off
  var pricepw = removeCommas(removeDollars(trim(hirepmfield.value)));  // value of field with whitespace trimmed off

  // If they say it's available to BUY, they must enter a price
  if (canhire == true) {
    if (emptyString.test(pricepd) && emptyString.test(pricepw) && emptyString.test(pricepm)) {
      msg (infofield, "error" , "Price to Hire - Must specify one or more prices");
      return false;
    } else {
      if ( ( (pricepd=="0") || (pricepd=="")) &&
           ( (pricepm=="0") || (pricepm=="")) &&
           ( (pricepw=="0") || (pricepw=="")) ) {
        msg (infofield, "error" , "Price to Hire - Must specify one or more prices");
        return false;
      }
      else {
        anyError = false;
        if (!validateNumber(hirepdfield,infofield,false,"Hire Price",0,1000000)) {
          anyError = true;
        }
        if (!validateNumber(hirepmfield,infofield,false,"Hire Price",0,1000000)) {
          anyError = true;
        }
        if (!validateNumber(hirepwfield,infofield,false,"Hire Price",0,1000000)) {
          anyError = true;
        }
        return !anyError;
      }
    }
  }

  return true;

}


// If they say it is available to buy, then they must specify one or more Hire prices
function validateTNC(itemfield,
                     tncfield,
                     infofield)
{
  msg (infofield, "warn", "");
  // Check if this is a Mod
  if (itemfield.value == "") {
    if (tncfield.checked) {
     return true;
    }
    else {
     msg (infofield, "error", "Please Tick the box to accept the Terms & Conditions");
     return false;
    }
  }
  else {
    // If item id is specified, it's a MOD so don't need to tick box
    return true;
  }

}


// Validate Edit Item form - used for Adding and Modifying Ads
function check_item_form() {
    var elem;
    var errs=0;
    // execute all element validations in reverse order, so focus gets
    // set to the first one in error.

    error_string = "";

//    alert("1");
    if (!validateCategory (document.forms.edit_item.item_cat,"item_cat_error")) {errs += 1;}
//    alert("2-errs = " + errs + ".");
    if (!validatePresent (document.forms.edit_item.item_name,"item_name_error","Item name"))  {errs += 1;}
//    alert("3");
    if (!validatePresent (document.forms.edit_item.item_brand,"item_brand_error","Brand"))  {errs += 1;}
//    alert("4");
    if (!validateHoursUsed  (document.forms.edit_item.item_condition_used, document.forms.edit_item.item_hours_used,"item_hours_used_error")) {errs +=1;}
//    alert("5");
    if (!validateManufDate (document.forms.edit_item.item_manuf_month, document.forms.edit_item.item_manuf_year,"item_manuf_year_error")) {errs +=1;}
//    alert("6");
    if (!validateBuyPrice (document.forms.edit_item.can_buy,document.forms.edit_item.buy_price, "buy_price_error")) {errs += 1;}
//    alert("7");
    if (!validateHirePrice (document.forms.edit_item.can_hire,document.forms.edit_item.hire_price_pd, document.forms.edit_item.hire_price_pw, document.forms.edit_item.hire_price_pm, "hire_price_pd_error")) {errs += 1;}
//    alert("8");
    if (trim(document.forms.edit_item.item_id.value) == "") {
      if (!validateTNC (document.forms.edit_item.item_id, document.forms.edit_item.accept_tnc, "accept_tnc_error")) {errs += 1;}
    }
//    alert("9");


//    if (errs>1)  {alert('Some fields failed validation - Form cannot be Submitted until these are fixed');}
//   if (errs==1) {alert('One field failed validation - Form cannot be Submitted until it is fixed');}

    if (errs > 0) {
      display_error_list();
      scroll_top();
    }
    else {
      hide_errors();
    }

    return (errs==0);
}


function hide_errors() {
      if (document.getElementById) {
        box_obj = document.getElementById("top_error_box");
      } else {
        box_obj = document["top_error_box"];
      }

      box_obj.style.display="none";
      //box_obj.style.className = "pd_error_box_hidden";
}


function display_error_list() {
      if (document.getElementById) {
        box_obj = document.getElementById("top_error_box");
        list_obj = document.getElementById("error_list");
      } else {
        box_obj = document["top_error_box"];
        list_obj = document["error_list"];
      }
      //box_obj.style.className = "pd_error_box_shown";
      box_obj.style.display="";
      list_obj.innerHTML = error_string;
}

function show_errors() {
      if (document.getElementById) {
        box_obj = document.getElementById("top_error_box");
        list_obj = document.getElementById("error_list");
      } else {
        box_obj = document["top_error_box"];
        list_obj = document["error_list"];
      }
      box_obj.style.display="";
      //box_obj.style.className = "pd_error_box_shown";
}

function scroll_top() {
  window.scroll(0,0);
}


// Validate Edit Item form - used for Adding and Modifying Ads
function check_picture_form() {
    var filename = trim(document.forms.picture_form.FILE1.value);

    if (emptyString.test(filename)) {
      show_pic_submit();
      alert("Please click the BROWSE button and select a File on your PC to be uploaded");
      return false;
    }
    else {
      return true;
    }
}



// Loop for each ITEM on the form, to make sure AT LEAST ONE ITEM HAS BEEN TICKED
function check_item_action_form () {
  var tick_count = 0;
  var theform = document.forms.item_action_form;

  // Loop for each tick_? item on the form
  // Check if they are Ticked or not

  var num_elems = theform.elements.length;

  for (i=0; i < num_elems; i++)
  {
    if (left(theform.elements[i].name,4) == "tick") {
       if (theform.elements[i].checked) {
          tick_count = tick_count + 1;
          break;
       }
    }
  }

  if (tick_count == 0) {
    alert("Please Tick at least ONE item");
    return false;
  }
  else {
    return true;
  }

}


// Loop for each ITEM on the form, to make sure all comments have been filled-in
function check_item_action_comments_form () {
  var any_empty = false;
  var theform = document.forms.item_action_comments_form;

  // Loop for each tick_? item on the form
  // Check if the comments are filled-in

  var num_elems = theform.elements.length;

  for (i=0; i < num_elems; i++)
  {
    if (left(theform.elements[i].name,8) == "comments") {
      comments_value = trim(theform.elements[i].value);
      if (emptyString.test(comments_value)) {
          any_empty = true;
          msg("error_" + theform.elements[i].name, "error", "Please enter a Reason/Comment");
      }
    }
  }

  if (any_empty) {
    alert("Please enter a reason/comment for ALL items");
    return false;
  }
  else {
    return true;
  }

}

// Tick all Tick Boxes on the List Items form
function tick_all_item_action_form() {
  var theform = document.forms.item_action_form;

  // Loop for each tick_? item on the form
  // Check if they are Ticked or not

  var num_elems = theform.elements.length;

  var new_value = "";
  if (theform.all.checked) {
    new_value = "checked";
  }

  for (i=0; i < num_elems; i++)
  {
    if (left(theform.elements[i].name,4) == "tick") {
      theform.elements[i].checked = new_value;
    }
  }

  return true;

}

/*
function check_home_search() {

  var theform = document.forms.home_search_form;

  // Check they have specified either a search term or a category

  if ( (trim(theform.searchfor.value) == "") &&
       (theform.category.selectedIndex == 0) ) {
    alert ("Please enter some words to Search For \n\n Or select a Category to Browse");
    return false;
  }
  return true;

  // Check they have selected at least one of buy new, Buy Used, Hire
    if ( (theform.buynew.value <> "on") &&
         (theform.buyused.value <> "on") &&
         (theform.hire.value <> "on") ) {
     return false;
    }
  }

}
*/

function check_left_search() {
  var theform = document.forms.search_left_form;

  if (!validateNumber(theform.pricefrom,"",false,"",0,1000000)) {
    alert("Please enter a valid price in the 'Price From' field");
    return false;
  }

  if (!validateNumber(theform.priceto,"",false,"",0,1000000)) {
    alert("Please enter a valid price in the 'Price To' field");
    return false;
  }

  return true;

}


function submitenter(myfield,e)
{
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
else return true;

if (keycode == 13)
{
   if (myfield.form.name=="search_left_form") {
     submit_left_search();
     return false;
   } else {
     myfield.form.submit();
     return false;
   }
}
else
   return true;
}


function submit_home_search() {
//  if (check_home_search() ) {
    document.forms.home_search_form.submit();
//  }
}


function submit_left_search() {
  if (check_left_search()) {
    document.forms.search_left_form.submit();
  }
}


function copy_contact_details() {

  var theform = document.forms.edit_seller_form;

  theform.contacta_firstname.value = theform.contactb_firstname.value;
  theform.contacta_surname.value = theform.contactb_surname.value;
  theform.contacta_phone1.value = theform.contactb_phone1.value;
  theform.contacta_phone2.value = theform.contactb_phone2.value;
  theform.contacta_fax.value = theform.contactb_fax.value;
  theform.contacta_email.value = theform.contactb_email.value;

}

function check_seller_form () {
   return true;
}


function check_contact_seller_form () {

  var theform = document.forms.contact_seller_form;

  var errs=0;

  error_string = "";

    if (!validatePresent (theform.your_name,"your_name_error")) {errs += 1; setfocus(theform.your_name);}
    if (!validatePhone (theform.your_phone,"your_phone_error",true,"Phone Number")) {errs += 1;setfocus(theform.your_phone);}
    if (!validateEmail (theform.your_email,"your_email_error",true,"Email")) {errs += 1;setfocus(theform.your_email);}

    if (errs > 0) {
      alert ("Please fill in all the mandatory fields.\n\n");
    }
    else {
      alert ("Your enquiry has been sent.\nThank You\n");
    }

    return (errs==0);
}


function check_contactus_form () {

  var theform = document.forms.contactus_form;

  var errs=0;

  error_string = "";

    if (!validatePresent (theform.your_name,"your_name_error")) {errs += 1; setfocus(theform.your_name);}
    if (!validatePhone (theform.your_phone,"your_phone_error",true,"Phone Number")) {errs += 1;setfocus(theform.your_phone);}
    if (!validateEmail (theform.your_email,"your_email_error",true,"Email")) {errs += 1;setfocus(theform.your_email);}

    return (errs==0);
}

// On register form, if select International, hide postcode field
function hide_postcode() {
  var theform = document.forms.edit_seller_form;

  if (theform.bus_state.selectedIndex == 8) {  	hide_obj('bus_postcode');
  	hide_obj('bus_postcode_field');
  }
  else {
  	show_obj('bus_postcode');
  	show_obj('bus_postcode_field');
  }


}