//-----------------------------------------------------------------------------
//
// Global Variables
//
//-----------------------------------------------------------------------------
SENT = false; // Indicates form submition status - prevent double submit
CHECK_MANDATORY_FIELDS = false; // Indicates whether to test the form for valid values int the mandatory field
//-----------------------------------------------------------------------------
//
// Prevent user from being tricked to follow a link to a 3rd party website that
// encapsulates the MITAS web application within a frame
//
//-----------------------------------------------------------------------------
if (top != self)
{
  top.location = self.location;
}
//-----------------------------------------------------------------------------
//
// FillSelectFromArray function
//
// - fills dropdown/list box from an array and selects its default value
// - parameters: VAR_SELECT  - dropdows/list box object
//               VAR_ARRAY   - array with values to fill into dropdows/list box
//               VAR_DEFAULT - default value to be selected
//
//-----------------------------------------------------------------------------
function FillSelectFromArray(VAR_SELECT, VAR_ARRAY, VAR_DEFAULT)
{
  if (typeof VAR_SELECT == "undefined") {
    window.alert("Invalid List Box parameter passed to FillSelectFromArray()");
    return false;
  }
  if ( (typeof VAR_ARRAY == "undefined") || (VAR_ARRAY.length < 1) ) {
    window.alert("Invalid Array parameter passed to FillSelectFromArray()");
    return false;
  }

  var i = 0;
  var new_option;

  VAR_SELECT.options.length = 0;

  //if (VAR_DEFAULT == "")
  //{
  //  new_option = new Option("", "");
  //  VAR_SELECT.options[VAR_SELECT.options.length] = new_option;
  //}

  new_option = new Option("Please Select", "None");
  VAR_SELECT.options[VAR_SELECT.options.length] = new_option;
  VAR_SELECT.options[VAR_SELECT.options.length - 1].selected = true;

  for (i = 0; i < VAR_ARRAY.length; i++)
  {
    new_option = new Option(VAR_ARRAY[i][0], VAR_ARRAY[i][1]);
    VAR_SELECT.options[VAR_SELECT.options.length] = new_option;
    if (VAR_SELECT.options[VAR_SELECT.options.length - 1].value == VAR_DEFAULT )
    {
      VAR_SELECT.options[VAR_SELECT.options.length - 1].selected = true;
    }
  }

  return true;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//
// FillSelectFromArrayExt function
//
// - fills dropdown/list box from an array and selects its default value
// - parameters: VAR_SELECT  - dropdows/list box object
//               VAR_ARRAY   - array with values to fill into dropdows/list box
//               VAR_MATCH   - match value
//               VAR_DEFAULT - default value to be selected
//-----------------------------------------------------------------------------
function FillSelectFromArrayExt(VAR_SELECT, VAR_ARRAY, VAR_MATCH, VAR_DEFAULT)
{
  if (typeof VAR_SELECT == "undefined")
  {
    window.alert("Invalid List Box parameter passed to FillSelectFromArray()");
    return false;
  }
  if ( (typeof VAR_ARRAY == "undefined") || (VAR_ARRAY.length < 1) )
  {
    window.alert("Invalid Array parameter passed to FillSelectFromArray()");
    return false;
  }

  if (VAR_MATCH == "")
  {
    FillSelectFromArray(VAR_SELECT, VAR_ARRAY, VAR_DEFAULT);
    return true;
  }

  var i = 0;
  var new_option;

  VAR_SELECT.options.length = 0;

  //if (VAR_DEFAULT == "")
  //{
  //  new_option = new Option("", "");
  //  VAR_SELECT.options[VAR_SELECT.options.length] = new_option;
  //}
  new_option = new Option("Please Select", "None");
  VAR_SELECT.options[VAR_SELECT.options.length] = new_option;
  VAR_SELECT.options[VAR_SELECT.options.length - 1].selected = true;

  for (i = 0; i < VAR_ARRAY.length; i++)
  {
    if ( (VAR_ARRAY[i][2] == VAR_MATCH) || (VAR_ARRAY[i][2] == "") || (VAR_MATCH == "  "))
    {
      new_option = new Option(VAR_ARRAY[i][0], VAR_ARRAY[i][1]);
      VAR_SELECT.options[VAR_SELECT.options.length] = new_option;
      if (VAR_SELECT.options[VAR_SELECT.options.length - 1].value == VAR_DEFAULT )
      {
        VAR_SELECT.options[VAR_SELECT.options.length - 1].selected = true;
      }
    }
  }
  return true;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//
// TodaysDateStringL function
//
//-----------------------------------------------------------------------------
function TodaysDateStringL()
{
	today = new Date();

	var year = today.getFullYear();
	var monthnum = today.getMonth();
	var date = today.getDate();
	var day = today.getDay();

	var week = new Array();
	week[0] = "Sunday";
	week[1] = "Monday";
	week[2] = "Tuesday";
	week[3] = "Wednesday";
	week[4] = "Thursday";
	week[5] = "Friday";
	week[6] = "Saturday";

	var month = new Array();
	month[0] = "January";
	month[1] = "Febuary";
	month[2] = "March";
	month[3] = "April";
	month[4] = "May";
	month[5] = "June";
	month[6] = "July";
	month[7] = "August";
	month[8] = "September";
	month[9] = "October";
	month[10] = "November";
	month[11] = "December";

	document.write((week[day]) +", " + (month[monthnum]) +" "+ (date) + ", "+ (year));
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//
// GoToFirstField
//
//-----------------------------------------------------------------------------
function GoToFirstField()
{
  var firstField = document.getElementById("firstfield");
  var type = typeof firstField;
  if (type != "undefined" && firstField != null)
  {
    firstField.focus();
    firstField.select();
  }
}
//-----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
//
// ShowSubmitMessage
//
//-----------------------------------------------------------------------------
function ShowSubmitMessage()
{
  document.getElementById("mitas_screen").style.display="none";
  document.getElementById("mitas_screen").style.display="";
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//
// XRefPopup function
//
// - popup window cross referebce
// - parameters: var_form           - HTML form object
//               var_field          - HTML field receiving the selected value
//               var_data_array     - array of available values
//               var_default_value  - default value selectred in the cross reference window
//               var_popup_title    - title of the popup window
//
//-----------------------------------------------------------------------------
function XRefPopup(var_form, var_field, var_data_array, var_default_value, var_popup_title) {
	this.field = var_field;
	this.data = var_data_array;
	var index = 0;
	var selectSize = var_data_array.length > 10 ? 10 : var_data_array.length;
	var w = 450;
	var h = 240;
	var move = screen ? ',left=' + ((screen.width - w) >> 1) + ',top=' + ((screen.height - h) >> 1) : '';
	var o_popupWindow = window.open('', null, "help=no,status=no,scrollbars=no,resizable=no,dependent=yes,alwaysRaised=yes" + move + ",width=" + w + ",height=" + h + ",dependent=yes", true);

	var selectIndexString = 'window.document.forms[' + "'xreference'" + '].elements[' + "'xref0'" + '].selectedIndex';
	var selectValueString = 'window.document.getElementsByTagName(' + "'select'" + ').item(' + "'xref0'" + ').options[' + selectIndexString + '].text';

	o_popupWindow.opener = window;
	o_popupWindow.document.open('text/html', 'replace');
	o_popupWindow.document.writeln('<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">');
	o_popupWindow.document.writeln('<html>');
	o_popupWindow.document.writeln('<head>');
	o_popupWindow.document.writeln('<title>' + var_popup_title + '</title>');
	o_popupWindow.document.writeln('<meta name="AUTHOR" content="The Mitas Group, Inc.">');
	o_popupWindow.document.writeln('<meta http-equiv="Pragma" content="no-cache">');
	o_popupWindow.document.writeln('<meta http-equiv="Cache-Control" content="no-cache">');
	o_popupWindow.document.writeln('<LINK rel="stylesheet" type="text/css" href="css/mitas_styles.css" title="site">');
	o_popupWindow.document.writeln('</head>');
	o_popupWindow.document.writeln('<body>');
	o_popupWindow.document.writeln('<form name="xreference">');
	o_popupWindow.document.writeln('<table size="100%" border="0" cellpadding="0" cellspacing="0" align="left" class="mainTable">');
	o_popupWindow.document.writeln('<tr><td colspan="4" align="center" size="100%" class="contentLarge">&nbsp;</td></tr>');
	o_popupWindow.document.writeln('<tr>');
	o_popupWindow.document.writeln('<td colspan="1" align="center" size="25%" class="contentLarge">&nbsp;</td>');
	o_popupWindow.document.writeln('<td align="center" colspan="2" size="50%" class="contentLarge"><select name="xref0" size="' + selectSize + '" align="center">');
	for (index = 0; index < var_data_array.length;  index++) {
		if ( var_default_value == var_data_array[index]) {
			o_popupWindow.document.writeln('<option selected>' + var_data_array[index] + '</option>');
		}else{
			o_popupWindow.document.writeln('<option>' + var_data_array[index] + '</option>');
		}
	}
	o_popupWindow.document.writeln('</select></td>');
	o_popupWindow.document.writeln('<td colspan="1" align="center" size="25%" class="contentLarge">&nbsp;</td>');
	o_popupWindow.document.writeln('</tr>');
	o_popupWindow.document.writeln('<tr><td colspan="4" align="center" size="100%" class="contentLarge">&nbsp;</td></tr>');
	o_popupWindow.document.writeln('<tr>');
	o_popupWindow.document.writeln('<td colspan="1" align="center" size="25%" class="contentLarge">&nbsp;</td>');
	o_popupWindow.document.writeln('<td align="right" size="25%" class="contentLarge"><input type="button" value="  Ok  " size="25" onClick="javascript:if (' + selectIndexString + ' < 0) { window.alert(' + "'Please select an item from the list and then click Ok'" + '); }else{ opener.document.forms[' + "'" + var_form.name + "'" + '].elements[' + "'" + var_field.name + "'" + '].value = ' + selectValueString + '; window.close(); }"></td>');
	o_popupWindow.document.writeln('<td align="left" size="25%" class="contentLarge"><input type="button" value="Cancel" size="25" onClick="javascript:window.close();"></td>');
	o_popupWindow.document.writeln('<td colspan="1" align="center" size="25%" class="contentLarge">&nbsp;</td>');
	o_popupWindow.document.writeln('</tr>');
	o_popupWindow.document.writeln('<tr><td colspan="4" align="center" size="100%" class="contentLarge">&nbsp;</td></tr>');
	o_popupWindow.document.writeln('<table>');
	o_popupWindow.document.writeln('</form>');
	o_popupWindow.document.writeln('</body>');
	o_popupWindow.document.writeln('</html>');
	o_popupWindow.document.close();
	o_popupWindow.focus();
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//
// ForceLogoff
//
//-----------------------------------------------------------------------------
function ForceLogoff()
{
	document.tabs.target='';
	document.tabs.menu_type.value='0005';
	document.tabs.submit();
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//
// Redirection Notification
//
//-----------------------------------------------------------------------------
function RedirectWarning(VAR_REDIRECT_URL)
{
    window.alert("You are leaving the Internet Loan Reservation System in order to access\nthird party website at " + VAR_REDIRECT_URL + ".\r");
    return true;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//
// User Input Validation/Cleanup
//
//-----------------------------------------------------------------------------
function CheckInput(_form)
{
  if (document.all) {
//    window.alert("CheckInputNonDOM");
    return ValidateFieldsNonDOM(_form);
  }else{
//    window.alert("CheckInputDOM");
    return ValidateFieldsDOM(_form);
  }
}
//-----------------------------------------------------------------------------
function ValidateFieldsNonDOM(_form)
{
//  var formField;
//  var fieldType;
//  var fieldValue;
//
//  for (var e_idx = 0; e_idx < _form.elements.length; e_idx++)
//  {
//    formField = _form.elements[e_idx];
//    if ( (typeof formField) == "undefined" )
//    {
//      continue;
//    }
//    if ( (typeof formField.type) == "undefined" )
//    {
//      continue;
//    }
//    fieldType = formField.type.toUpperCase();
//    fieldValue = formField.value;
//
////    window.alert("Passing '" + formField.value + "'");
//   formField.value = RemoveBadCharacters(fieldValue);
////    window.alert("Returned '" + formField.value + "'");
//  }

  if (CHECK_MANDATORY_FIELDS == true)
  {
    return form_validate(_form);
  } else {
    _form.submit();
    return true;
  }
}
//-----------------------------------------------------------------------------
function ValidateFieldsDOM(_form)
{
//  var formField;
//  var fieldType;
//  var fieldValue;
//
//  for (var e_idx = 0; e_idx < _form.elements.length; e_idx++)
//  {
//    formField = _form.elements.item(e_idx);
//    fieldType = formField.type.toUpperCase();
//    fieldValue = formField.value;
//
////    window.alert("Passing '" + formField.value + "'");
//    formField.value = RemoveBadCharacters(fieldValue);
////    window.alert("Returned '" + formField.value + "'");
//  }

  if (CHECK_MANDATORY_FIELDS == true)
  {
    return form_validate(_form);
  } else {
    _form.submit();
    return true;
  }
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
function RemoveBadCharacters(inputString)
{
  var outputString = "";
  for (var s_idx = 0; s_idx < inputString.length; s_idx++)
  {
    switch (inputString.charAt(s_idx))
    {
      case '<':
      {
        outputString = outputString + "&lt;";
        break;
      }
      case '>':
      {
        outputString = outputString + "&gt;";
        break;
      }
      case '"':
      {
        outputString = outputString + "&quot;";
        break;
      }
      case '\'':
      {
        outputString = outputString + "&#39;";
        break;
      }
      case '&':
      {
        outputString = outputString + "&amp;";
        break;
      }
      case '%':
      {
        outputString = outputString + "&#37;";
        break;
      }
      case ';':
      {
        outputString = outputString + "&#59;";
        break;
      }
      case '(':
      {
        outputString = outputString + "&#40;";
        break;
      }
      case ')':
      {
        outputString = outputString + "&#41;";
        break;
      }
      case '+':
      {
        outputString = outputString + "&#43;";
        break;
      }
      default:
      {
        outputString = outputString + inputString.charAt(s_idx);
        break;
      }
    }
  }
  return outputString;
}
//-----------------------------------------------------------------------------
// Check if string contains only whitespace characters
//-----------------------------------------------------------------------------
function isBlankString(_string)
{
  for(var i = 0; i < _string.length; i++) {
      var c = _string.charAt(i);
      if ((c != ' ') && (c != '\n') && (c != '\t'))
      {
        return false;
      }
  }
  return true;
}
//-----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
// Check if string contains invalid value
// function isInvalidValue( _field_value, _data_type)
//-----------------------------------------------------------------------------
function isInvalidValue( field_value, data_type)
{
  switch ( data_type)
  {
    case 'number':
    {
      var tempnumber1 = parseFloat(field_value);
      if ( isNaN(tempnumber1) ) {
        return true;
      }
      break;
    }
    case 'number_nonzero':
    {
      var tempnumber2 = parseFloat(field_value);
      if (isNaN(tempnumber2) || (tempnumber2 < 1) || tempnumber2 == '') {
        return true;
      }
      break;
    }
    case 'date':
    {
      var date_whitespace = /[\W\/\-]/g;
      var tempstr1 = field_value.replace(date_whitespace, ' ');
      var result = tempstr1.split(' ');

      var bk_mo;
      var bk_da;
      var bk_yr;
      switch ( result.length )
      {
        case 3:
        {
          bk_mo = result[0];
          bk_da = result[1];
          bk_yr = result[2];
          break;
        }
        case 1:
        {
          if ( (field_value.length != 8) && (field_value.length != 10) )
          {
            return true;
          }
          if (field_value.length == 8)
          {
            bk_mo = field_value.substr(0,2);
            bk_da = field_value.substr(2,2);
            bk_yr = field_value.substr(4,4);
          }
          if (field_value.length == 10)
          {
            bk_mo = field_value.substr(0,2);
            bk_da = field_value.substr(3,2);
            bk_yr = field_value.substr(6,4);
          }
          break;
        }
        default:
        {
          return true;
          break;
        }
      }
      if ( isNaN(bk_mo) || isNaN(bk_da) || isNaN(bk_yr) )
      {
          return true;
      }
      if ( (bk_mo < 1) || (bk_mo > 12))
      {
          return true;
      }
      if ( (bk_da < 1) || (bk_da > 31) || (bk_yr < 1) )
      {
          return true;
      }
      break;
    }
    default:
    {
      if ( field_value.length == 0 ) {
        return true;
      }
      break;
    }
  }
  return false;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Validate form
//   - assumes that an array 'REQUIRED_FIELDS' exists and contains
//     names and types of fields that are required
//-----------------------------------------------------------------------------
function form_validate(_form)
{
  if ( (typeof REQUIRED_FIELDS) == "undefined" ) {
    _form.submit();
    return true;
  }
  if ( REQUIRED_FIELDS.length < 1 ) {
    _form.submit();
    return true;
  }

  if (document.all) {
    return FormValidateNonDOM(_form);
  }else{
    return FormValidateDOM(_form);
  }
}
//-----------------------------------------------------------------------------
function FormValidateNonDOM(_form)
{
  var msg = "";
  var empty_fields = "";
  var errors = "";
  var form_field;

  for (var i = 0; i < REQUIRED_FIELDS.length; i++)
  {
    form_field = _form.elements[REQUIRED_FIELDS[i][0]];
    if ( (typeof form_field) != "undefined" )
    {
      if ( (typeof form_field.type) == "undefined" )
      {
        if ( (form_field[0].type).toUpperCase() == "RADIO" )
        {
          var isChecked = false;
          for (var idx = 0; idx < form_field.length; idx ++)
          {
            if ( form_field[idx].checked )
            {
              isChecked = true;
              break;
            }
          }
          if ( !isChecked )
          {
            if (REQUIRED_FIELDS[i].length == 3)
            {
              empty_fields += "\n\t" + REQUIRED_FIELDS[i][2];
            }else{
              empty_fields += "\n\t" + form_field[0].name;
            }
          }
        }
        continue;
      }
      if ( form_field.type.toUpperCase() == "CHECKBOX" )
      {
        if ( ! form_field.checked )
        {
          empty_fields += "\n\t" + REQUIRED_FIELDS[i][2];
        }
        continue;
      }
      if ( isBlankString(form_field.value) )
      {
        if (REQUIRED_FIELDS[i].length == 3)
        {
          empty_fields += "\n\t" + REQUIRED_FIELDS[i][2];
        }else{
          empty_fields += "\n\t" + form_field.name;
        }
        continue;
      }
      if ( isInvalidValue(form_field.value, REQUIRED_FIELDS[i][1] ) )
      {
        if (REQUIRED_FIELDS[i].length == 3)
        {
          errors += "\n\t" + REQUIRED_FIELDS[i][2];
        }else{
          errors += "\n\t" + form_field.name;
        }
        continue;
      }
    }
  }

  if (empty_fields)
  {
    msg += "\nFollowing fields are required:\n" + empty_fields + "\n";
  }
  if (errors)
  {
    msg += "\n" + "Invalid values in following fields:\n" + errors;
  }
  if  (msg)
  {
    document.getElementById("mitas_screen").style.display="";
    document.getElementById("mitas_processing").style.display="none";
    window.alert( msg );
    return false;
  } else {
    _form.submit();
    return true;
  }
}
//-----------------------------------------------------------------------------
function FormValidateDOM(_form)
{
  var msg = "";
  var empty_fields = "";
  var errors = "";
  var form_field;
  var radio_buttons = new Array();
  var check_boxes;

  for (var i = 0; i < _form.elements.length; i++)
  {
    form_field = _form.elements.item(i);
    var fieldFound = "false";
    var j = 0;
    while( (j < REQUIRED_FIELDS.length) && (form_field.name != REQUIRED_FIELDS[j][0]) )
    {
      j+=1;
    }
    if (j == REQUIRED_FIELDS.length)
    {
      continue;
    }
    if ( form_field.type.toUpperCase() == "RADIO" )
    {
      var k = 0;
      while( (k < radio_buttons.length) && (form_field.name != radio_buttons[k][0]) )
      {
        k+=1;
      }
      if (k == radio_buttons.length)
      {
        var radio_buttons_item = new Array();
        radio_buttons_item.push(form_field.name);
        radio_buttons_item.push(form_field.checked);
        if (REQUIRED_FIELDS[j].length == 3)
        {
          radio_buttons_item.push(REQUIRED_FIELDS[j][2]);
        }else{
          radio_buttons_item.push(form_field.name);
        }
        radio_buttons.push(radio_buttons_item);
      }else{
        if (!radio_buttons[k][1])
        {
          radio_buttons[k][1] = form_field.checked;
        }
      }
      continue;
    }
    if ( form_field.type.toUpperCase() == "CHECKBOX" )
    {
      if (!form_field.checked)
      {
      	empty_fields += "\n\t" + REQUIRED_FIELDS[j][2];
      }
      continue;
    }
    if ( isBlankString(form_field.value) )
    {
      if (REQUIRED_FIELDS[j].length == 3)
      {
        empty_fields += "\n\t" + REQUIRED_FIELDS[j][2];
      }else{
        empty_fields += "\n\t" + form_field.name;
      }
    }

    if ( isInvalidValue(form_field.value, REQUIRED_FIELDS[j][1] ) )
    {
      if (REQUIRED_FIELDS[j].length == 3)
      {
        errors += "\n\t" + REQUIRED_FIELDS[j][2];
      }else{
        errors += "\n\t" + form_field.name;
      }
    }
  }

  if (radio_buttons.length > 0)
  {
    for(var i = 0; i < radio_buttons.length; i++)
    {
      if (!radio_buttons[i][1])
      {
        empty_fields += "\n\t" + radio_buttons[i][2];
      }
    }
  }
  if (empty_fields)
  {
    msg += "\nFollowing fields are required:\n" + empty_fields + "\n";
  }
  if (errors)
  {
    msg += "\n" + "Invalid values in following fields:\n" + errors;
  }
  if  (msg == "")
  {
    _form.submit();
    return true;
  } else {
    document.getElementById("mitas_screen").style.display="";
    document.getElementById("mitas_processing").style.display="none";
    window.alert( msg );
    return false;
  }
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Validate Upload Form - simple
//   - tests if a file was selectwed fo an upload form
//-----------------------------------------------------------------------------
function upload_form_validate(upload_form)
{
  if ( upload_form.FILE1.value.length == 0 )
  {
    window.alert('You must enter a name of file to upload!');
    return false;
  } else {
    upload_form.submit();
    return false;
  }
}
//-----------------------------------------------------------------------------

