// copied from form_library_adv.js

// Adds an option to the specified select object
function addOptionToSelect(selectObj, text, value, selected)
{
  var new_Option = new Option(text, value, selected, selected);

  selectObj.options[selectObj.options.length] = new_Option;
}


// Move the selected option up one entry
function moveOptionUpInSelect(selectObj)
{
  if (!selectObj.selectedIndex) {
    // We are already at the top
    return false;
  }

  // Have to store selected index since once we move an option it gets unselected.
  var selectedIndex = selectObj.selectedIndex;
  var nextOption    = selectObj.options[selectedIndex - 1];

  selectedValue = new Number(selectObj.options[selectedIndex].value);
  nextValue     = new Number(nextOption.value);

  selectObj.options[selectedIndex - 1] = new Option(selectObj.options[selectedIndex].text, selectedValue);
  selectObj.options[selectedIndex]     = new Option(nextOption.text,nextValue);

  // Re select the option
  selectObj.selectedIndex = selectedIndex - 1;

  return true;
}


// Move the selected option down one entry
function moveOptionDownInSelect(selectObj)
{
  if (selectObj.selectedIndex == selectObj.options.length - 1) {
    // We are already at the bottom
    return false;
  }

  // Have to store selected index since once we move an option it gets unselected.
  var selectedIndex = selectObj.selectedIndex;
  var nextOption = selectObj.options[selectedIndex + 1];
  selectObj.options[selectedIndex + 1] = new Option(selectObj.options[selectedIndex].text, selectObj.options[selectedIndex].value);
  selectObj.options[selectedIndex]     = new Option(nextOption.text,nextOption.value);

  // Re select the option
  selectObj.selectedIndex = selectedIndex + 1;
  return true;
}


// Replace the selected option in a select with a new value
function replaceSelectedOptionInSelect(selectObj,text,value)
{
  if (!selectObj.selectedIndex) {
    return false;
  }

  selectObj.options[selectObj.selectedIndex] = new Option(text,value);
  return true;
}


// Remove the selected option
function removeSelectedOptionFromSelect(selectObj)
{
  if (!selectObj.selectedIndex < 0) {
    // nothing is selected so just return
    return false;
  }

  // Loop through the select
  for (count=0; count < selectObj.options.length; count++) {
    // If the value is selected, delete it
    if  (selectObj.options[count].selected) {
      selectObj.options[count] = null;
      // Since we just deleted one item from the array, we need to decrease the count
      // due to the array key shift
      count--;
    }
  }
  return true;
}


// Remove all options from the select
function removeAllOptionsFromSelect(selectObj)
{
  for (index = 0; index < selectObj.options.length; index++) {
    selectObj.options[index] = null;
    index--;
  }
  return true;
}


// Deselect all the options of the select box
function deselectAllOptions(selectObj)
{
  if (!selectObj || !selectObj.options) {
    return false;
  }

  for (count = 0; count < selectObj.options.length; count++) {
    selectObj.options[count].selected = false;
  }

  return true;
}


// Select all the options of the select box
function selectAllOptions(selectObj)
{
  if (!selectObj || !selectObj.options) {
    return false;
  }

  for (count = 0; count < selectObj.options.length; count++) {
    selectObj.options[count].selected = true;
  }

  return true;
}

// Return the texts from the select object as an array.
function getTextArrayFromSelect(selectObj)
{
  if (!selectObj || !selectObj.options) {
    return false;
  }

  result = new Array();
  for (count =0; count < selectObj.options.length; count++) {
    result[count] = selectObj.options[count].text;
  }

  return result;
}

// Return the option that is selected (only for single select) and return the object
function getSelectedOptionFromSelect(select_obj)
{
  if (!select_obj || !select_obj.options || select_obj.selectedIndex < 0) {
    return false;
  }

  return select_obj.options[select_obj.selectedIndex];
}


// Sets the selected index or the selected options (multiple) to what it was originally
function setSelectedToDefaultSelected(select_obj)
{
  if (!select_obj || !select_obj.options) {
    return false;
  }

  for (index = 0; index < select_obj.options.length; index++) {
    if (select_obj.multiple) {
      select_obj.options[index].selected = select_obj.options[index].defaultSelected;
    }
    else {
      if (select_obj.options[index].defaultSelected) {
        select_obj.selectedIndex = index;
        break;
      }
    }
  }
}

/**************************************************************************************

The below code provides the ability to turn any element on a page into a select option.
Essentially you have created a hidden form with a clean display.

Ex. You have an html table display records in the database. Each TR is a record with a
unique id. When you click on a row, the row highlighting is toggled and its id is
added/removing from a hidden select. Ctrl+click will allow the toggling and
adding/removing of multiple rows. Basically you have just turned the entire table into
a big select box.

The highlighting/unhighlighting css can be customized by overriding the class name.

Sample Script:

<link rel="stylesheet" type="text/css" href="{LINK_ROOT}/css/default.css">
<script type="text/javascript" src="{LINK_ROOT}/js/form_library_adv.js"></script>
<script type="text/javascript">
  var new_select = new customSelect();

  //override default css
  new_select.highlightClassName = 'hi';
  new_select.unhighlightClassName = 'low';
</script>

<style type="text/css">
//custom css
.hi { color : red; font-weight: bold; background-color: black;}
.low { color: black; font-weight: normal; background-color: white; }

</style>

<!-- The select object can be visible or hidden, if it is visible it should be disabled -->
<select name="ids[]" id="ids[]" multiple disabled></select>

<table width="100%">
   <tr id="1" onclick="new_select.customToggleSelect(this.id, event, 'ids[]');"><td> 1 </td></tr>
   <tr id="2" onclick="new_select.customToggleSelect(this.id, event, 'ids[]');"><td> 2 </td></tr>
   <tr id="3" onclick="new_select.customToggleSelect(this.id, event, 'ids[]');"><td> 3 </td></tr>
</table>

This insanity was created by Brandon, Sabrina and Sean with love from Alex Roger

**************************************************************************************/

//Constructor for custom select object
function customSelect()
{
  //initialize default values
  this.highlightClassName         = 'highlight';
  this.unhighlightClassName       = 'unhighight';
  this.current_id                 = '';
  this.customToggleSelect         = customToggleSelect;
  this.addOptionToSelect          = addOptionToSelect;
  this.removeAllOptionsFromSelect = removeAllOptionsFromSelect;
}

/*
 * toggle element highlighting and selection
 *
 * @param string the element id
 * @param object the captured event
 * @param string the select object name
*/
function customToggleSelect(id, e, select_name)
{
  //get the current class name for the element
  class_name = document.getElementById(id).className;
  //get the select object
  select_obj = document.getElementById(select_name);

  //capture the event based on the browser
  //Reference: http://www.thescripts.com/forum/post1883743-4.html
  e = e || window.event;

  //we are holding the ctrl key to perform multiple selections
  if (e.ctrlKey) {
    //check to see if the the element is already selected
    if (document.getElementById(id).className == this.highlightClassName) {
      //unhighlight the element
      document.getElementById(id).className = this.unhighlightClassName;

      //check to see if the select object has options
      if (select_obj.options.length) {
        //loop through the options
        for (x = 0; x < select_obj.options.length; x++) {
          //if the option is the same as the id then remove it
          if (select_obj.options[x].value == id) {
            select_obj.options[x] = null;
            return;
          }
        }
      }
      return;
    }

    //check to see if the object was not already selected
    if (document.getElementById(id).className == this.unhighlightClassName || document.getElementById(id).className == '') {
      //highlight the new selection, set it as the current id and add it to the select
      document.getElementById(id).className = this.highlightClassName;
      this.current_id = id;
      addOptionToSelect(select_obj, id, id, true);
      return;
    }
  }
  //we are performing single selects
  else {
    //check to see if we already have an current id
    if (this.current_id) {
      //check to see if we have options in our select obj
      if (select_obj.options.length) {
        //loop through the options of the select object
        for (x = 0; x < select_obj.options.length; x++) {
          if (select_obj.options[x].value != id) {
            //if the option is not the same as the new id then unhighlight it
            document.getElementById(select_obj.options[x].value).className = this.unhighlightClassName;
          }
        }
      }

      //clear the select obj
      removeAllOptionsFromSelect(select_obj);
    }

    //highlight the new selection, set it as the current id and add it to the select
    document.getElementById(id).className = this.highlightClassName;
    this.current_id = id;
    addOptionToSelect(select_obj, id, id, true);
    return;
  }

  return;
}

// end form_library_adv.js

// copied from form_check.js
/**
 * Form field checking functions
 *
 * This file contains form field checking functions
 * This file requires form_library.js to function properly
 */

function checkField(formField, errorMsg) {
  if (!checkFieldValue(formField)) {
    alert(errorMsg);
    formField.focus();
    return false;
  }
  return true;
}

function checkFieldValue(formField) {
  if (trim(formField.value) == "") {
    return false;
  }
  return true;
}

function checkSelectField(formField, errorMsg) {
  if (formField.selectedIndex == 0 || !checkSelectFieldValue(formField)) {
    alert(errorMsg);
    formField.focus();
    return false;
  }
  return true;
}

function checkSelectFieldValue(formField, errorMsg) {
  if (trim(formField.options[formField.selectedIndex].value) == "") {
    if (errorMsg) {
      alert(errorMsg);
      formField.focus();
    }
    return false;
  }
  return true;
}

function checkRadioButton(formField, errorMsg) {
  for (radioIndex=0;radioIndex<formField.length;radioIndex++) {
    if (formField[radioIndex].checked) {
      return true;
    }
  }
  alert (errorMsg);
  return false;
}

function emailCheck(formField, errorMsg) {
  var EmailOk = true
  var Temp = formField;
  var AtSym = Temp.value.indexOf('@');
  var Period = Temp.value.lastIndexOf('.');
  var Space = Temp.value.indexOf(' ');
  var Length = Temp.value.length - 1;
  if ((AtSym < 1) || (Period <= AtSym+1) || (Period == Length ) || (Space  != -1)) {
    EmailOk = false;
    alert(errorMsg);
    formField.focus();
  }
  return EmailOk;
}

function emailCheck2(email1Field, email2Field, errorMsg) {
  var EmailOk = true
  var Email1 = email1Field.value;
  var Email2 = email2Field.value;
  if (Email1 != Email2) {
    alert(errorMsg);
    email1Field.focus();
    return false;
  }
  return EmailOk
}

function echeck(str, message) {
  var at    = "@";
  var dot   = ".";
  var lat   = str.indexOf(at);
  var lstr  = str.length;
  var ldot  = str.indexOf(dot);
  if (str.indexOf(at) == -1) {
	   alert(message);
	   return false;
	}

	if (str.indexOf(at) == -1 || str.indexOf(at) == 0 || str.indexOf(at) == lstr) {
    alert(message);
    return false;
	}

	if (str.indexOf(dot) == -1 || str.indexOf(dot) == 0 || str.indexOf(dot) == lstr) {
    alert(message);
    return false;
	}

  if (str.indexOf(at,(lat+1)) != -1) {
    alert(message);
    return false;
  }

  if (str.substring(lat-1,lat) == dot || str.substring(lat+1,lat+2) == dot) {
    alert(message);
    return false;
  }

  if (str.indexOf(dot,(lat+2)) == -1) {
    alert(message);
    return false;
  }

  if (str.indexOf(" ") != -1) {
    alert(message);
    return false;
	}

		return true;
}

function validateEmail(formField, message) {
	var emailID = formField;

	if ((emailID.value == null) || (emailID.value == "")) {
		alert(message);
		emailID.focus();
		return false;
	}
	if (echeck(emailID.value, message) == false) {
		emailID.value = "";
		emailID.focus();
		return false;
	}

  return true;
}

function checkCountry(formField, errorMsg) {
  if (formField.selectedIndex == 0) {
    //alert('Select a country please!');
    alert(errorMsg);
    formField.focus();
    return false;
  }
  return true;
}

function checkCountryState(countryField, stateField, errorMsg1, errorMsg2) {
  stateUSarray = new Array ("AL","AK","AZ","AR","CA","CO","CT","DE","DC","FL","GA","HI","ID","IL","IN","IA","KS","KY","LA","ME","MD","MA","MI","MN","MS","MO","MT","NE","NV","NH","NJ","NM","NY","NC","ND","OH","OK","OR","PA","RI","SC","SD","TN","TX","UT","VT","VA","WA","WV","WI","WY");
  stateCanadaArray = new Array ("AB","BC","MB","NB","NF","NT","NS","ON","PE","QC","SK","YT");
  indexUS = 1;
  indexCanada = 2;
  countryValue = countryField.value;
  stateValue = countryField.value;
  if (countryValue == indexUS) {
    for (x=0;x<stateUSarray.length;x++) {
      if (stateValue == stateUSarray[x]) return true;
    }
    //alert('Please enter the two character state code.');
    alert(errorMsg1);
    stateField.focus();
    return false;
  } else if (countryValue == indexCanada) {
    for (x=0;x<stateCanadaArray.length;x++) {
      if (stateValue == stateCanadaArray[x]) return true;
    }
    //alert('Please enter the two character province code.');
    alert(errorMsg2);
    stateField.focus();
    return false;
  }
  return true;
}
function checkCountryStateSelect(countryField, stateField, errorMsg1, errorMsg2) {
  stateUSarray = new Array ("AL","AK","AZ","AR","CA","CO","CT","DE","DC","FL","GA","HI","ID","IL","IN","IA","KS","KY","LA","ME","MD","MA","MI","MN","MS","MO","MT","NE","NV","NH","NJ","NM","NY","NC","ND","OH","OK","OR","PA","RI","SC","SD","TN","TX","UT","VT","VA","WA","WV","WI","WY");
  stateCanadaArray = new Array ("AB","BC","MB","NB","NF","NT","NS","ON","PE","QC","SK","YT");
  countryValue = countryField.options[countryField.selectedIndex].value;
  stateValue = stateField.options[stateField.selectedIndex].value;
  if (countryValue == 'US') {
    for (x=0;x<stateUSarray.length;x++) {
      if (stateValue == stateUSarray[x]) return true;
    }
    alert(errorMsg1);
    stateField.focus();
    return false;
  } else if (countryValue == 'CA') {
    for (x=0;x<stateCanadaArray.length;x++) {
      if (stateValue == stateCanadaArray[x]) return true;
    }
    alert(errorMsg2);
    stateField.focus();
    return false;
  }
  return true;
}

function passwordCheck (pass1Field, pass2Field, errorMsg1, errorMsg2) {
  password1 = pass1Field.value;
  password2 = pass2Field.value
  if (password1.length < 4) {
    //alert ('Password must be at least 4 characters long');
    alert(errorMsg1);
    pass1Field.focus();
    return false;
  } else if (password1 != password2) {
    //alert ('Passwords must match');
    alert(errorMsg2);
    pass1Field.focus();
    return false;
  }
  return true;
}

function checkCardExpiration (cardExpMonthField, cardExpYearField, errorMsg)
{
  // perform validation
  currentDate = new Date();
  currentYear = currentDate.getYear();
  if (currentYear < 1990) currentYear+= 1900;

  if (cardExpYearField.value < 2000) {
    cardExpYearField.value='20'+cardExpYearField.value;
  }

  input_month = cardExpMonthField.value;
  input_year  = cardExpYearField.value;

  // determine exit condition
  if ((input_month < 1 || input_month > 12) ||
      (input_year < currentYear || input_year > currentYear + 10) ||
      (input_year == currentYear && input_month < currentDate.getMonth())
      )  {
    alert (errorMsg);
    cardExpMonthField.focus();
    return false;
  }

  return true;
}

function checkPhoneNumber(formField, errorMsg) {
  var allowedchars = "0123456789()-+ ";
  var i = 0;
  for (i = 0; i <= formField.value.length -1; i++) {
    if (allowedchars.indexOf(formField.value.charAt(i)) == -1) {
      alert(errorMsg);
      return false;
    } // End if statement
  } // End for loop
  return true;
}

function checkName(nameField, errorMsg) {
  if (nameField.value.search(/^[\sa-zA-Z\'\-]+$/) != -1) {
    return true;
  }
  else {
    nameField.focus();
    alert(errorMsg);

    return false;
  }
}

function checkTextBoxAgainstSelectBox(objSelectBox, objTextBox, errorMsg, objLabel) {
  var flag        = false;
  var hCode       = objTextBox.value;
  var selectValue = null;

  hCode = hCode.replace(/^\s*|\s*$/g,"");
  hCode = hCode.toUpperCase();

  if (hCode != null && hCode != '') {
    for (var i = 0; i < objSelectBox.length; i++) {
      if (objSelectBox[i].value.toUpperCase() == hCode) {
        objSelectBox[i].selected = true;
        flag = i;
        break;
      }
    }

    if (flag == false) {
      alert(hCode + ' ' + errorMsg);
      objTextBox.value = null;
      return false;
    }
    else {
      if (objLabel) {
        objLabel.innerHTML = objSelectBox.options[flag].text;
      }
    }
  }
  objTextBox.value = hCode;
}


function checkBirthdate(yearObj, monthObj, dayObj, errorMsg)
{
  today = new Date();

  year   = new Number(yearObj.options[yearObj.selectedIndex].value);
  month  = new Number(monthObj.options[monthObj.selectedIndex].value);
  day    = new Number(dayObj.options[dayObj.selectedIndex].value);

  bdate_timestamp = (fixYear(year)*10000) + (month*100) + day;
  tdate_timestamp = (fixYear(today.getYear())*10000) + ((today.getMonth() + 1)*100) + today.getDate();  // getMonth() returns 0..11

  if (bdate_timestamp > tdate_timestamp) {
    alert(errorMsg)
    return false;
  }

  return true;
}

function alertError(formObj,errorMsg)
{
  if (errorMsg && errorMsg.length) {
    alert(errorMsg);
  }

  formObj.focus();
  return false;
}

function integerCheck(inputObj, errorMsg, updateValue)
{
  num = new Number(inputObj.value);

  if (isNaN(num)) {
    return alertError(inputObj, errorMsg);
  }

  intVal = parseInt(inputObj.value);

  if (intVal.toString().length != inputObj.value.length) {
    return alertError(inputObj, errorMsg);
  }

  if (updateValue) {
    inputObj.value = intVal;
  }

  return true;
}

function floatCheck(inputObj, errorMsg, allowInt, updateValue)
{
  num = new Number(inputObj.value);

  if (isNaN(num)) {
    return alertError(inputObj, errorMsg);
  }

  if (!allowInt && inputObj.value.search(/\./) == -1) {
    // Did not find a "." so not a valid float.
    return alertError(inputObj, errorMsg);
  }

  if (updateValue) {
    inputObj.value = num;
  }

  return true;
}

function urlCheck(inputObj, errorMsg)
{
  if (inputObj.value.search(/^(ht|f)tp(s)*\:\/\/([a-z0-9]+[a-z0-9_-]*[\.]{1,1})+[a-z]{2,6}[\/]*$/) == -1 &&
      inputObj.value.search(/^([a-z0-9]+[a-z0-9_-]*[\.]{1,1})+[a-z]{2,6}$/) == -1) {
    return alertError(inputObj, errorMsg);
  }

  return true;
}

function colorCheck(inputObj, errorMsg)
{
  if (inputObj.value.toUpperCase().search(/^\#([A-H0-9]){6,6}$/) == -1) {
    return alertError(inputObj, errorMsg);
  }

  return true;
}

/**
 * Check to see if card expires before final payment due date.
 *
 * @param (Form Object) formName
 * @return bool
 */
function checkFinalDueDateWithCreditCardExpiryDate(form_object, final_payment_date)
{
  // Disregard check if no expiry year select
  if (!form_object.ccValidTilYear || form_object.ccValidTilYear.selectedIndex == 0) {
    return true;
  }

  // Disregard check if no expiry month select
  if (!form_object.ccValidTilMonth || form_object.ccValidTilMonth.selectedIndex == 0) {
    return true;
  }

  // Disregard check if no final payment date.
  if (!final_payment_date || !final_payment_date.length) {
    return true;
  }

  expiry_year  = form_object.ccValidTilYear.options[form_object.ccValidTilYear.selectedIndex].value;
  expiry_month = form_object.ccValidTilMonth.options[form_object.ccValidTilMonth.selectedIndex].value;
  expiry       = new Date(expiry_year, expiry_month - 1);

  // We expect final due date in the format 'yyyy-mm-dd hh:mm:ss' or 'yyyy-mm-dd'.
  try {
    final_payment_date = final_payment_date.split(' ');
    final_payment_date = final_payment_date[0];
    final_payment_date = final_payment_date.split('-');

    final_date = new Date(final_payment_date[0], final_payment_date[1] - 1);
  }
  catch(ex)
  {
    // There was an error with the date conversion.
    // Not the customers fault, we must have sent a bad final_payment_date to the template.
    return true;
  }

  if (final_date.getTime() > expiry.getTime()) {
    return false;
  }


  return true;
}
// end form_check.js

// copied from main cruise search

function checkCruiseForm(formObj) {
	if (checkField(formObj.DestinationID, "Please select a destination.")) {
		return true;
	}
	return false;
}
function checkCruiseLineForm(formObj) {
	if (checkField(formObj.VendorID, "Please select a cruise line.")) {
		return true;
	}
	return false;
}

function initialize_default_departure_dates()
{
  var today = new Date();
  today.setDate(today.getDate());
  document.getElementById('cruise_month').selectedIndex = today.getMonth()+1;
}

// end main cruise search

// copied from CalendarPopup.js

function updateTravelYear(monthObj,yearObj)
{
  month = monthObj.options[monthObj.selectedIndex].value;

  current_date = new Date();
  current_year = current_date.getFullYear();

  if (month > 0 ) {
    validYear = get_valid_year(month);
  }
  else {
    validYear = current_year;
  }

  for (i = 0; i < yearObj.options.length; i++) {
    if (yearObj.options[i].value == validYear) {
      yearObj.selectedIndex = i;
      break;
    }
  }
}

// end CalendarPopup.js
