// global vars
var need_give_focus = true;
var pagedirty = false;
var hasKeyBeenPressed = false;
var processing = false;


/** shared javascript code **/
var agt=navigator.userAgent.toLowerCase();
var is_ns6 = (document.getElementById && !document.all && document.documentElement)
? 1 : 0;
var is_iex = (document.all && window.offscreenBuffering) ? 1 : 0;
var is_ie4 = (is_iex && agt.indexOf("msie 5")==-1);
var is_ie5 = (is_iex && agt.indexOf("msie 5")!=-1);
var is_ie6 = (is_iex && agt.indexOf("msie 6")!=-1);

function fGetXY(a){
  var p=[0,0], bl, bt;
  while(a&&a.tagName.toUpperCase()!="BODY") {
	bl=parseInt(a.style.borderLeftWidth,10);
	bt=parseInt(a.style.borderTopWidth,10);
  	p[0]+=a.offsetLeft-(a.scrollLeft?a.scrollLeft:0)+(isNaN(bl)?0:bl);
  	p[1]+=a.offsetTop-(a.scrollTop?a.scrollTop:0)+(isNaN(bt)?0:bt);
  	a=a.offsetParent;
  }
  if (a) {
	p[0]+=a.offsetLeft;
	p[1]+=a.offsetTop;
  }
  return p;
}

function cancelEvent(evt) {
  evt.cancelBubble = true;
  evt.returnValue = false;
}

function click_primary_button(evt) {
  var src = (is_iex ? window.event.srcElement : evt.target);

  // ignore enter from creditCard number
  if(src.name && src.name == 'prefix_05_set-string_creditCard_number_true')
    return;

  // if page has no forms, or has its own onkeyup handler (ez-search), or a text-area, return
  if(!document.forms[0] || src.onkeyup != null || src.type == 'textarea' || src.type == 'button')
    return;

  // if source element has a primary button, click it
  if(src.form) {
    var el = src.form.elements;
    for(var j=0; j < el.length; j++) {
      if(el[j].name == "primary" && el[j].type == "button") {
        cancelEvent(evt);
        el[j].click();
        return;
      }
    }
  }

  // check for the primary button first
  for(var i=0; i < document.forms.length; i++) {
    var el = document.forms[i].elements;
    for(var j=0; j < el.length; j++) {
      if(el[j].name == "primary" && el[j].type == "button") {
        cancelEvent(evt);
        el[j].click();
        return;
      }
    }
  }

  // otherwise pick the first button in the first form
  for(var i=0; i < document.forms.length; i++) {
    var el = document.forms[i].elements;
    for(var j=0; j < el.length; j++) {
      if(el[j].type == "button" && el[j].name != "popcal") {
        cancelEvent(evt);
        el[j].click();
        return;
      }
    }
  }
}

function isProcessing() {
  if(processing)
    return true;

  processing = true;
  window.defaultStatus = "Processing... Please wait...";
  return false;
}

function notProcessing() {
  processing = false;
  window.defaultStatus = "";
}

// gives focus to first non-hidden non-disabled input field, and sets global onchange handler
window.onload = function (evt) {
  if(!need_give_focus || !document.forms[0] || hasKeyBeenPressed) return;
  var setFocus = false;

  var df = document.forms;

  for(var i=0; i < df.length; i++) {
    for(var j=0; j < df[i].elements.length; j++) {
      var elem = df[i].elements[j];
      // Would like to give focus to ezSearchForm if no other fields are found
      if(!setFocus && (elem.type!='hidden' && elem.id != 'selX' && elem.disabled==false && elem.form.name != 'ezSearchForm')) {
        elem.focus();
        setFocus = true;
      }
      if(elem.onchange == null) {
        elem.onchange = pgch;
      }
    }
  }

  // auto hide ezsearch
  var selX = document.getElementById('selX');
  if(selX) {
    selX.style.visibility = 'hidden';
  }
}

// auto hide popup calendar
document.onclick=function(e){
	var t=!e?self.event.srcElement.name:e.target.name;
	if (t!="popcal") {
	  if(typeof gfPop != "undefined") {
	    gfPop.fHideCal();
	  }
	}
}

document.onhelp = function() {
  if(event.ctrlKey)
    return false;

  cancelEvent(event);
  document.getElementById('fkey_F9').click();
}

// key events
document.onkeydown = function (evt) {
  // set key pressed flag
  hasKeyBeenPressed = true;

  if(evt == null) evt = event;
  var lnk;

  // ctrl-N executes new window
  // Capture and throw away event
  if(evt.ctrlKey && evt.keyCode == 78) {
    return false;
  }

  // CTRL-ALT-N
  else if(evt.ctrlKey && evt.altKey && evt.keyCode == 78) {
    lnk = document.getElementById('newwindow');
  }

  // if a function key is pressed, execute a link with id="fkey_Fxx"
  else if((evt.keyCode >= 112 && evt.keyCode <= 123) && evt.ctrlKey)
  {
    var fkey = evt.keyCode - 111;
    lnk = document.getElementById('fkey_F' + fkey);
  }
  else if(evt.keyCode == 13) {
    click_primary_button(evt);
    return;
  }

  if(lnk)
  {
    if(is_iex)
    {
      cancelEvent(evt);
      lnk.click();
    }
    else
    {
      window.open( lnk.href, myhmsSession);
    }
  }
}

// mark global variable that page has changed
function pgch() { pagedirty = true; }


// global functions
function sqldate_to_jsdate(str) {
  var year = str.substr(0, 4);
  var month = str.substr(5, 2);
  var day = str.substr(8, 2);

  return new Date(year, --month, day);
}

function jsdate_to_sqldate(d) {
  var str = d.getFullYear() + '-';
  str += (d.getMonth()+1 < 10 ? '0'+ (d.getMonth()+1) : (d.getMonth()+1)) + '-';
  str += (d.getDate()  < 10 ? '0'+d.getDate() : d.getDate());

  return str;
}

function add_to_sqldate(numdays, str) {
  var d = sqldate_to_jsdate(str);
  return jsdate_to_sqldate( add_to_jsdate(numdays, d) );
}

function add_to_jsdate(numdays, d) {
  d.setDate(d.getDate() + parseInt(numdays));
  return d;
}

function trim(x) {
  return x.replace(/[^0123456789\-\.]/gi,'');
}

function get_sqldate(str) {
  return str.substr(0, 10);
}

function get_jsdate(str) {
  return sqldate_to_jsdate(get_sqldate(str));
}

function get_roomtypeid(str) {
  return str.substr(11);
}

function checkAll(radio)
{
  var orig = radio.checked;
  for(var i=0; i < radio.form.elements.length; i++)
  {
    var elem = radio.form.elements[i];
    if(elem.type == 'checkbox')
    {
      elem.click();
    }
  }
}

function clickAllByName(radio, name)
{
  var orig = radio.checked;
  var list = document.getElementsByName(name);
  for(var i=0; i < list.length; i++)
  {
    list[i].click();
  }
}

function giveElementFocus(ele)
{
  if(ele.disabled || ele.type=='hidden')
    return;

  ele.focus();
  ele.value += '';
  need_give_focus = false;
}


// ******************************************************************
// Non-global functions
// ******************************************************************

// AVAILABILITY-MODULE-HTML
function myOnClick(cell, notselectedcolor)
{
  var date = get_sqldate(cell.id);
  var roomTypeId = get_roomtypeid(cell.id);

  // is firstCell set?
  if(firstCell == null) {
    // look for first cell in mystate
    for(var key in mystate) {
      if(mystate[key] != 0) {
        firstCell = document.getElementById(key + '_' + mystate[key]);

        if(firstCell == null)
          continue;

        break;
      }
    }

    // nope, use the cell pressed
    if(firstCell == null)
      firstCell = cell;
  }

  // is lastCell set?
  if(lastCell == null) {
    // look for first cell in mystate in reverse
    var arrayIndex = new Array();
    var cnt=0;
    for(key in mystate) {
      arrayIndex[cnt++] = key;
    }
    for(var i = arrayIndex.length - 1; i >= 0; i--) {
      if(mystate[arrayIndex[i]] != 0) {
        lastCell = document.getElementById(arrayIndex[i] + '_' + mystate[arrayIndex[i]]);

        if(lastCell == null)
          continue;

        break;
      }
    }

    // nope, use the cell pressed
    if(lastCell == null)
      lastCell = cell;
  }

	//Cell was selected, make un-selected
	if( mystate[date] == roomTypeId ) {
	  if(get_jsdate(cell.id) < get_jsdate(lastCell.id)) {
      var ed = get_jsdate(lastCell.id);
      var d = get_jsdate(cell.id);
      while( (d = add_to_jsdate(1, d)) <= ed) {
        var oldCell = document.getElementById( jsdate_to_sqldate(d) + '_' + mystate[jsdate_to_sqldate(d)]);
        oldCell.className = mycolors[jsdate_to_sqldate(d)];
        mystate[jsdate_to_sqldate(d)] = 0;
        document.availabilityForm['selection(' + jsdate_to_sqldate(d) + ')'].value = 0;
      }

      lastCell = cell;
	  }
	  else if(firstCell == lastCell) {
	    firstCell = null;
	    lastCell = null;
	    mystate[ date ] = 0;
		  cell.className = notselectedcolor;
		}
	}

	else if(mystate[date] != 0) {
    var oldCell = document.getElementById( date + '_' + mystate[date]);

    if (oldCell != null) {
    	oldCell.className = mycolors[date];
    }

    mycolors[date] = cell.className;
    mystate[date] = roomTypeId;
    cell.className = 'selected';

    if(date == get_sqldate(lastCell.id))
      lastCell = cell;
    if(date == get_sqldate(firstCell.id))
      firstCell = cell;
	}

	//Cell was non-selected, AND no other cell was selected, make selected
	else if( mystate[ date ] == 0 ) {
	  //before firstdate
	  if(get_jsdate(cell.id) < get_jsdate(firstCell.id) ) {
	    if(roomTypeId == get_roomtypeid(firstCell.id)) {
        var ed = get_jsdate(firstCell.id);
        var d = get_jsdate(cell.id);
        while( (d = add_to_jsdate(1, d)) < ed) {
          var newCell = document.getElementById( jsdate_to_sqldate(d) + '_' + roomTypeId);
          mycolors[jsdate_to_sqldate(d)] = newCell.className;
          newCell.className = 'selected';
          mystate[jsdate_to_sqldate(d)] = roomTypeId;
          document.availabilityForm['selection(' + jsdate_to_sqldate(d) + ')'].value = roomTypeId;
        }

        firstCell = cell;
	    }
	    else { //different roomtype
	      if(date != add_to_sqldate(-1, lastCell.id))
	        return;

	      firstCell = cell;
	    }
	  }

	  //after enddate
	  else if(get_jsdate(cell.id) > get_jsdate(lastCell.id)) {
	    if(roomTypeId == get_roomtypeid(lastCell.id)) {
        var ed = get_jsdate(cell.id);
        var d = get_jsdate(lastCell.id);
        while( (d = add_to_jsdate(1, d)) < ed) {
          var newCell = document.getElementById( jsdate_to_sqldate(d) + '_' + roomTypeId);
          mycolors[jsdate_to_sqldate(d)] = newCell.className;
          newCell.className = 'selected';
          mystate[jsdate_to_sqldate(d)] = roomTypeId;
          document.availabilityForm['selection(' + jsdate_to_sqldate(d) + ')'].value = roomTypeId;
        }

        lastCell = cell;
	    }
	    else { //different roomtype
	      if(date != add_to_sqldate(1, lastCell.id))
	        return;

	      lastCell = cell;
	    }
	  }

	  mystate[ date ] = roomTypeId;
	  mycolors[date] = cell.className;
		cell.className = 'selected';
  }

	//Change HTML hidden input form values.
	//This is the mechanism that which HTML selected cells are communicated back
	//to the server.
	document.availabilityForm['selection(' + date + ')'].value = mystate[date];
}

function procFieldChange(inp)
{
  var fieldName = inp.name;
  var field = fieldName.substr(0, fieldName.indexOf('('));
  var flag = document.getElementById('copy_'+field);
  var val = inp.value;
  if(flag.checked)
  {
    var a = document.getElementsByTagName("input");
    for(var i=0; i < a.length; i++)
    {
      if(a[i].name.indexOf(field)==0)
      {
        a[i].value = val;
      }
    }
  }
}

function updateRates(inp)
{
  var a = inp.form.getElementsByTagName("input");
  var adjust = parseFloat(inp.value);
  var posnegSel = inp.form['posneg'];
  var modeSel = inp.form['mode'];

  var positive = posnegSel.selectedIndex==0;
  var flat = modeSel.selectedIndex==0;

  for(var i=0; i < a.length; i++)
  {
    // Only process rates
    if(a[i].type!='text' || a[i].name.indexOf('onePerson') < 0)
      continue;

    var val = parseFloat(a[i].value);

    if( isNaN(val) )
      continue;

    if(flat)
    {
      val += parseFloat(positive?adjust:-adjust);
    }
    else
    {
      val *= parseFloat(positive?1+(adjust/100):1-(adjust/100));
    }

    if( val < 0 )
      val = 0;

    a[i].value=To_Currency(val);
  }
}

function To_Currency( num )
{
   var str = Math.round( num * 100 ).toString();

   return str.substring( 0, str.length - 2 )
      + "."
      + str.substring( str.length - 2, str.length );
}

function Convert(x)
{
   return To_Currency( paseFloat(x) );
}

// New 3/9/2004: add a random number to the reports' request path
// (i.e. "/reports/20065/arrivals.html"). This is in order to fool
// Excel into thinking this is a different file. Otherwise, if a
// user has tries to load an Excel version of a report with that
// report already open in a window, Excel won't actually submit
// the second request.
function randomizeURL(_form) {
	_form.action = _form.action.replace(/[0-9]+/, Math.floor(1+(Math.random()*100000)));
}

function reportToExcel(_form) {
	randomizeURL(_form);
	_form.action = _form.action.replace(/\.html/, '.xls');
}

function reportToHTML(_form) {
	randomizeURL(_form);
  _form.action = _form.action.replace(/\.xls/, '.html');
}

/*
This function is used to simulate the availability
interface to create a reservation in the tape chart.
This was modified from the myOnClick() function above.
This code could probably be simplified because the tapechart
will only allow (at the moment) for a single room to be chosen.
*/
function tapeChartClick(cell, notselectedcolor)
{
  var date = get_sqldate(cell.id);
  // This gets the part after the 'date_', which
  // in this case is the roomId
  var roomId = get_roomtypeid(cell.id);

  // is firstCell set?
  if(firstCell == null) {
      firstCell = cell;
  }

  // is lastCell set?
  if(lastCell == null) {
      lastCell = cell;
  }

	//Cell was selected, make un-selected
	if( mystate[date] == roomId ) {
	  if(get_jsdate(cell.id) < get_jsdate(lastCell.id)) {
      var ed = get_jsdate(lastCell.id);
      var d = get_jsdate(cell.id);
      while( (d = add_to_jsdate(1, d)) <= ed) {
        var oldCell = document.getElementById( jsdate_to_sqldate(d) + '_' + mystate[jsdate_to_sqldate(d)]);
        oldCell.className = mycolors[jsdate_to_sqldate(d)];
        mystate[jsdate_to_sqldate(d)] = 0;
      }

      lastCell = cell;
	  }
	  else if(firstCell == lastCell) {
	    firstCell = null;
	    lastCell = null;
	    mystate[ date ] = 0;
		  cell.className = notselectedcolor;
		}
	}

	// If different room, ignore
  else if(mystate[date] != 0) {
    return;
  }

	//Cell was non-selected, AND no other cell was selected, make selected
	else if( mystate[ date ] == 0 && get_roomtypeid(firstCell.id) == roomId) {
	  //before firstdate
	  if(get_jsdate(cell.id) < get_jsdate(firstCell.id) ) {
	    if(roomId == get_roomtypeid(firstCell.id)) {
        var ed = get_jsdate(firstCell.id);
        var d = get_jsdate(cell.id);
        while( (d = add_to_jsdate(1, d)) < ed) {
          var newCell = document.getElementById( jsdate_to_sqldate(d) + '_' + roomId);
          mycolors[jsdate_to_sqldate(d)] = newCell.className;
          newCell.className = 'selected';
          mystate[jsdate_to_sqldate(d)] = roomId;
        }

        firstCell = cell;
	    }
	    else { //different roomtype
	      if(date != add_to_sqldate(-1, lastCell.id))
	        return;

	      firstCell = cell;
	    }
	  }

	  //after enddate
	  else if(get_jsdate(cell.id) > get_jsdate(lastCell.id) && get_roomtypeid(firstCell.id) == roomId) {
	    if(roomId == get_roomtypeid(lastCell.id)) {
        var ed = get_jsdate(cell.id);
        var d = get_jsdate(lastCell.id);
        while( (d = add_to_jsdate(1, d)) < ed) {
          var newCell = document.getElementById( jsdate_to_sqldate(d) + '_' + roomId);
          mycolors[jsdate_to_sqldate(d)] = newCell.className;
          newCell.className = 'selected';
          mystate[jsdate_to_sqldate(d)] = roomId;
        }

        lastCell = cell;
	    }
	    else { //different roomtype
	      if(date != add_to_sqldate(1, lastCell.id))
	        return;

	      lastCell = cell;
	    }
	  }
	}

	// DIFFERENT ROOM IS SELECTED, IGNORE
  else {
    return;
  }

  arrivalDate = get_sqldate(firstCell.id);
  departureDate = get_sqldate(lastCell.id);

  mystate[ date ] = roomId;
  mycolors[date] = cell.className;
	cell.className = 'selected';
}

// ROOM-ASSIGNMENT-MODULE-HTML
function rmAssign( cell, currentReservation, date, roomId) {
	if( myroom[date] == roomId ) {
		// Cell was selected, make un-selected
		myroom[ date ] = 0;
		cell.className = 'ragreen';
	}

	else if( myroom[ date ] == 0 ) {
		// Cell was non-selected, AND no other cell was selected, make selected -->
		myroom[ date ] = roomId;
		cell.className = 'raselected';
	}


	// Change HTML hidden input form values.
	// This is the mechanism that which HTML selected cells are communicated back
	// to the server.

	if(!currentReservation) {
	  document.roomAssignmentForm['room('+date+')'].value = myroom[date];
	}
	else
	{
	  cell.className = 'raselected';
	  document.roomAssignmentForm['room('+date+')'].value = 'roomId';
	}
}

function addHidden(frm, param, value)
{
  var input = document.createElement('INPUT');
  input.type = 'HIDDEN';
  input.name = param;
  input.value = value;
  frm.appendChild(input);
}

// Next two functions are used on AR Uninvoiced and Invoice pages
// NOTE: This may be being called by "AR Invoices" page, in which
// case the arFolioId is REALLY the arInvoiceId
function ar_checkOnClick(ele, arFolioId, amount)
{
  var amountField = ele.form['amount('+arFolioId+')'];
  var updateAmount = parseFloat(amountField.value);

  if(amountField.value != '')
  {
    amountField.value = '';
  }
  else
  {
    updateAmount = -parseFloat(amount);
    amountField.value = To_Currency(parseFloat(amount));
  }

  // JJM TODO: This may end up being called twice depending on
  // how browser handled changing the value of an input field by js
  // (i.e. does it call onchange)
  ar_updateAmounts(ele.form);
}


function ar_updateAmounts(frm)
{
  var checkAmountEle = frm['checkAmount'];
  var remainingAmountEle = frm['remainingAmount'];
  var paymentAmountEle = frm['paymentAmount'];

  var checkAmount = parseFloat(checkAmountEle.value);

  var bCheckAmountEntered = !isNaN(checkAmount);
  var balance = checkAmount;
  var total = 0;

  for(var i=0; i < frm.elements.length; i++)
  {
    var ele = frm.elements[i];
    if(ele.name.indexOf('amount') >= 0)
    {
      var eleVal = parseFloat(ele.value);
      if(!isNaN(eleVal))
      {
        total += eleVal;
        balance += -eleVal;
      }
    }
  }

  // If valid check amount, update remaining amount
  if(bCheckAmountEntered)
    remainingAmountEle.value = To_Currency(balance);
  // Otherwise blank out remaining amount
  else
    remainingAmountEle.value = '';

  paymentAmountEle.value = To_Currency(total);
}

// Shift a row up or down in a form in side a table.
function shiftRow(objForm, objTable, bUp)
{
    for( var j = 0; j < objForm.elements.length; j++ )
    {
        i = objForm.elements[j];
        if( i.type == "radio" && i.checked && i.name.indexOf("Id") > -1 )
        {
            oRow = objTable.rows["row" + i.value];
            if( bUp )
            {
                if( oRow.rowIndex > 1 )
                {
                    oRow.swapNode(oRow.previousSibling);
                    i.checked = true;
                }
            }
            else
            {
                if( oRow.rowIndex < objTable.rows.length - 1 )
                {
                    oRow.swapNode(oRow.nextSibling);
                    i.checked = true;
                }
            }
            break;
        }
    }
}

// Make sure search criteria is entered
function csSearch(frm, errorMsg) {
  var eles = frm.elements;
  for(var i=0; i < eles.length; i++) {
    var e = eles[i];
    if(e.type=='text' && e.value!='')
      return true;
    // value==0 for null, except status where null is ''
    else if(e.type=='select-one' && (e.value!='0' && e.value!=''))
      return true;
  }

  alert(errorMsg);
  return false;
}

function arrivalChanged(gdCtrl)
{
  var arrEle = gdCtrl.form['arrival'];
  var depEle = gdCtrl.form['departure'];
  var nnEle = gdCtrl.form['numNights'];

  var dArr = gfPop.fParseDate(gdCtrl.value);
  var y = dArr[0];
  var m = dArr[1];
  var d = dArr[2];

  var numNights = nnEle.value;
  var d = new Date(y, m-1, d+parseInt(numNights));
  depEle.value = gfPop.fFormatDate(d.getFullYear(), d.getMonth()+1, d.getDate());
}

function departureChanged(gdCtrl)
{
  var arrEle = gdCtrl.form['arrival'];
  var depEle = gdCtrl.form['departure'];
  var nnEle = gdCtrl.form['numNights'];

  var dArr = gfPop.fParseDate(gdCtrl.value);
  var y = dArr[0];
  var m = dArr[1];
  var d = dArr[2];

  var aArr = gfPop.fParseDate(arrEle.value);
  var arrival = new Date(aArr[0], aArr[1]-1, aArr[2]);
  var departure = new Date(y,m-1,d);
  var dd = dateDiff(arrival, departure);

  if(dd > 30)
  {
    return false;
  }
  else
  {
    nnEle.options[dd-1].selected = true;
  }

  return false;
}

function dateDiff(d1, d2)
{
  return Math.ceil((d2.getTime()-d1.getTime())/(60*60*1000*24));
}

function numNightsChanged(gdCtrl)
{
  arrivalChanged(gdCtrl.form['arrival']);
}

// the following two functions are designed to avoid changes lost
// and limited user to change values on a form at a time... amao
function disableOtherForms(frm)
{
  for(i = 0; i < document.forms.length; i++ )
  {
    var f = document.forms[i];
    if( f != frm && f.name != "activeSearchForm")
      f.disabled = true;
  }
}

function enableOtherForms()
{
  for(i = 0; i < document.forms.length; i++ )
  {
    var f = document.forms[i];
    f.disabled = false;
  }
}

function ccGoSubmit(frm) {
  var btn = document.getElementById('goButton');
  if(btn != null) {
    btn.click();
  }
}
