///////////////////////////////////////
//  $RCSfile: date_functions.js,v $
// $Revision: 1.10 $
// Copyright: UNiREZ, Inc. 2003
///////////////////////////////////////

// For use with the date_select and start_end_select subroutines from
// wrsobj.pm.

// my $date = $w->date_select(-name => 'MY_DATE');
// or for a combo date_select:
// my $combo = $w->date_select(-name => 'COMBO', -combo => 1);
// or for a start and end date:
// my ($start_date, $end_date) = $w->start_end_select(-name => 'DATE');
// or for a combo start and end date:
// my ($in, $out) = $w->start_end_select(-name => 'DATE', -combo => 1);

function validDate (yr, mon, day) {
// If the year, month and day passed in
// make a valid date, then return true
// otherwise return false.
  mon--; // month is zero based
  var test = new Date (yr, mon, day);
  return (yr  == test.getFullYear() &&
          mon == test.getMonth() &&
          day   == test.getDate()
         ) ? true : false;
}

function date2Array (date) {
// Takes a date object and turns it into an array.
  var yr = date.getFullYear();
  var mon = date.getMonth();
  var day = date.getDate();
  var datea = new Array(yr, mon, day);
  return datea;
}

function vDate (yr, mon, day) {
// Returns a date object if the year,
// month and day passed represents a valid date.
  if (!validDate(yr, mon, day)) {
    alert("Invalid date " + yr + "-" + mon + "-" + day + " passed.");
    return;
  }
  return new Date(yr, mon - 1, day);
}

function getDate (f, id, combo) {
// Gets the date from the form.
  var yr, mon;
  var day = f.elements[id + 'DD'].value;
  if (combo) {
    var temp = f.elements[id + 'YM'].value.split(":");
    yr = temp[0];
    mon = temp[1];
  } else {
    yr = f.elements[id + 'YY'].value;
    mon = f.elements[id + 'MM'].value;
  }
  var date = vDate(yr, mon, day);
  return date;
}

function setDate (f, id, datea, combo) {
// Sets the date in the form.
// datea is an array created by date2Array
// the month should be in the range 0..11
  var yr = datea[0];
  var mon = datea[1] + 1;
  if (mon < 10) {
    mon = '0' + mon;
  }
  var day = datea[2];
  if (day < 10) {
    day = '0' + day;
  }
  f.elements[id + 'DD'].value = day;
  if (combo) {
    datea = Array(yr, mon);
    f.elements[id + 'YM'].value = datea.join(":");
  } else {
    f.elements[id + 'MM'].value = mon;
    f.elements[id + 'YY'].value = yr;
  }
}

function returnOneDayAfterStart (start, end) {
// If the start date is greater than or equal to the end date,
// return a date that is one day after the start date.
  var enda = false;
  if (start >= end) {
    end.setTime(start.getTime() + 86400000);
    enda = date2Array(end);
  }
  return enda;
}

function returnOneDayBeforeEnd (start, end) {
// If the start date is greater than or equal to the end date,
// return a date that is one day before the end date.
  var starta = false;
  if (start >= end) {
    start.setTime(end.getTime() - 86400000);
    starta = date2Array(start);
  }
  return starta;
}

function adjustStartEnd (f, id, startx, endx, sid, eid, start, end, combo) {
// Checks the start and end date and adjusts as needed.
  var eym,ey,em,sym,sy,sm;
  var ed = f.elements[eid+'DD'];
  var sd = f.elements[sid+'DD'];
  if (combo) {
    eym = f.elements[eid+'YM'];
    sym = f.elements[sid+'YM'];
  } else {
    ey = f.elements[eid+'YY'];
    em = f.elements[eid+'MM'];
    sy = f.elements[sid+'YY'];
    sm = f.elements[sid+'MM'];
  }
  if (startx.test(id)) {
    var enda = returnOneDayAfterStart(start, end);
    if (combo) {
      if (sym.selectedIndex == (sym.length - 1) &&
          sd.selectedIndex == (sd.length - 1)) {
        eym.selectedIndex = eym.length - 1;
        ed.selectedIndex = ed.length - 1;
        sd.selectedIndex = sd.length - 2;
        return;
      }
    } else {
      if (sy.selectedIndex == (sy.length - 1) &&
          sm.selectedIndex == (sm.length - 1) &&
          sd.selectedIndex == (sd.length - 1)) {
        ey.selectedIndex = ey.length - 1;
        em.selectedIndex = em.length - 1;
        ed.selectedIndex = ed.length - 1;
        sd.selectedIndex = sd.length - 2;
        return;
      }
    }
    if (enda) {
      setDate(f, eid, enda, combo);
    }
  } else if (endx.test(id)) {
    var starta = returnOneDayBeforeEnd(start, end);
    if (combo) {
      if (eym.selectedIndex == 0 &&
          ed.selectedIndex == 0) {
        sym.selectedIndex = 0;
        sd.selectedIndex = 0;
        ed.selectedIndex = 1;
        return;
      }
    } else {
      if (ey.selectedIndex == 0 &&
          em.selectedIndex == 0 &&
          ed.selectedIndex == 0) {
        sy.selectedIndex = 0;
        sm.selectedIndex = 0;
        sd.selectedIndex = 0;
        ed.selectedIndex = 1;
        return;
      }
    }
    if (starta) {
      setDate(f, sid, starta, combo);
    }
  }
}

function checkStartEnd (f, id, combo) {
// Checks the start or end date and corrects
// the other as needed given:
  var sid, eid, start, end, startx, endx;
  if (combo) {
    startx = /^IN/;
    endx = /^OUT/;
    if (startx.test(id)) {
      sid = id;
      eid = 'OUT' + id.substr(2);
    } else if (endx.test(id)) {
      sid = 'IN' + id.substr(3);
      eid = id;
    } else {
      alert("Unknown id: " + id);
      return;
    }
  } else {
    startx = /^START/;
    endx = /^END/;
    if (startx.test(id)) {
      sid = id;
      eid = 'END' + id.substr(5);
    } else if (endx.test(id)) {
      sid = 'START' + id.substr(3);
      eid = id;
    } else {
      alert("Unknown id: " + id);
      return;
    }
  }
  start = getDate(f, sid, combo);
  end = getDate(f, eid, combo);

  adjustStartEnd (f, id, startx, endx, sid, eid, start, end, combo);
}

function swapStartEnd (f, id, combo) {
// Checks the start and end date and swaps them
// if the start date is later than the end date.
  var startx = /^START/;
  var endx = /^END/;
  var sid, eid, start, end;
  if (combo) {
    startx = /^IN/;
    endx = /^OUT/;
    if (startx.test(id)) {
      sid = id;
      eid = 'OUT' + id.substr(2);
    } else if (endx.test(id)) {
      sid = 'IN' + id.substr(3);
      eid = id;
    } else {
      alert("Unknown id: " + id);
      return;
    }
  } else {
    if (startx.test(id)) {
      sid = id;
      eid = 'END' + id.substr(5);
    } else if (endx.test(id)) {
      sid = 'START' + id.substr(3);
      eid = id;
    } else {
      alert("Unknown id: " + id);
      return;
    }
  }
  var start, end;
  start = getDate(f, sid, combo);
  end = getDate(f, eid, combo);
  if (start > end) {
    var temp = start;
    start = end;
    end = temp;
    var starta = date2array(start);
    var enda = date2array(end);
    setDate(f, sid, starta, combo);
    setDate(f, eid, enda, combo);
  } else if (start == end) {
    adjustStartEnd (f, id, startx, endx, sid, eid, start, end, combo);
  }
}

function fixDate (f, id, combo) {
// Fixes invalid dates like 31 Apr 2003 or 29 Feb 2003.
  if (combo) {
    // grabs the form values and sets the form elements later
    var day = f.elements[id + 'DD'].value;
    var temp = f.elements[id + 'YM'].value.split(":");
    var yr = temp[0];
    var mon = temp[1];
	while (!validDate(yr, mon, day)) {  // valid date yet?
      day--;  // no?  move back one day
    }
    if (day.length < 2 && day < 10) {
      day = '0' . day;
    }
    temp = Array(yr, mon);
    f.elements[id + 'DD'].value = day;
    f.elements[id + 'YM'].value = temp.join(":");
  } else {
    // works directly on the form elements
    var day = f.elements[id + 'DD'];
    var mon = f.elements[id + 'MM'];
    var yr = f.elements[id + 'YY'];
    while (!validDate(yr.value, mon.value, day.value)) {  // valid date yet?
      day.value--;  // no?  move back one day
    }
  }
}

function checkDates (e, pair, swap) {
// This is the basic function to call when you want to check the dates.
// If you have two date selections (ie a start and end date), you need
// to pass in a true value for pair. (This is done automatically by
//start_end_select.)
// If you want to swap the dates instead of correcting by 1, pass a true
// value in for swap.  (Only valid with pair).
  var f = e.form; // which form?
  var n = e.name; // name of this element?
  var id = n.substr(0, n.length - 2);
  
  var combo = 0;
  var inout = new RegExp("^IN|^OUT");
  if (inout.test(id)) {
    combo = 1;
  }
  fixDate(f, id, combo);
  if (pair) {
    if (swap) {
      swapStartEnd(f, id, combo);
    } else {
      checkStartEnd(f, id, combo);
    }
  }
}

	// check if arrival date is valid, if so, forward arrival date to departure date + 2
	function changeEndDate() {
	theForm = document.forms['FORM1'];
	arrDate = new Date(theForm.IN_DATE_YY.value,theForm.IN_DATE_MM.value-1,theForm.IN_DATE_DD.value);
	if (!isDate(theForm.IN_DATE_DD.value,theForm.IN_DATE_MM.value,theForm.IN_DATE_YY.value))
	alert('The selected Arrival Date is not a valid date.');
	else	
	depDate = addDays(arrDate,2);
	theForm.OUT_DATE_YY.value = padout(depDate.getYear());
	theForm.OUT_DATE_MM.value = padout(depDate.getMonth()+1);
	theForm.OUT_DATE_DD.value = padout(depDate.getDate());
	}
	
	// check if end date is a valid date
	function checkEndDate() {
	theForm = document.forms['FORM1'];
	if (!isDate(theForm.OUT_DATE_DD.value,theForm.OUT_DATE_MM.value,theForm.OUT_DATE_YY.value))
	alert('The selected Departure Date is not a valid date.');
	return (false);
	}
	// attempt to convert a 2 digit year into a 4 digit year
	function y2k(number) { return (number < 1000) ? number + 1900 : number; }

	// checks a give date for validity	
	function isDate (day,month,year) {
		var today = new Date();
		year = ((!year) ? y2k(today.getYear()):year);
		month = ((!month) ? today.getMonth():month-1);
		if (!day) return false
		var test = new Date(year,month,day);
		if ( (y2k(test.getYear()) == year) &&
			 (month == test.getMonth()) &&
			 (day == test.getDate()) )
			return true;
		else
			return false
	}
	
	// adds a given number of days to a give date object
	function addDays(myDate,days) {
    return new Date(myDate.getTime() + days*24*60*60*1000);
	}
	
// if the number is less than ten put a 0 in front of it...
function padout(number) { return (number < 10) ? '0' + number : number; }

// calculates the time difference between 2 supplied date objects
function timeDifference(laterdate,earlierdate) {
var difference = laterdate.getTime() - earlierdate.getTime();
return difference;
}

// Unirez form validation routine
function fnSubmit() {
// set variables
	var oForm = document.forms['FORM1'];
	var vCount = 0;
	var foo = new Array();
	var timeStamp = new Date();
	var todaysDate = new Date(timeStamp.getYear() , timeStamp.getMonth() , timeStamp.getDate());
	var arriveDate = new Date(oForm.elements['IN_DATE_YY'].value,oForm.elements['IN_DATE_MM'].value-1,oForm.elements['IN_DATE_DD'].value);
	var departDate = new Date(oForm.elements['OUT_DATE_YY'].value,oForm.elements['OUT_DATE_MM'].value-1,oForm.elements['OUT_DATE_DD'].value);

// check if arrival date is prior to today	   
	if (timeDifference(arriveDate,todaysDate) < 0) {
		alert('Arrival Date cannot be prior to today');
		return (false);
	}
	
// check if dparture date is prior to arrival date	   
	if (timeDifference(departDate,arriveDate) <= 0) {
		alert('Departure Date must be later than Arrival Date');
		return (false);
	}
// checks to make sure there is a value for the property
   if (oForm.p.selectedIndex <= 0) {
	alert("Please select a property before continuing.");
	oForm.p.focus();
	return (false);
	}

// checks if the arrival date is a valid date 
	if (!isDate(oForm.elements['IN_DATE_DD'].value,oForm.elements['IN_DATE_MM'].value,oForm.elements['IN_DATE_YY'].value)) {
	  alert('The selected Arrival Date is not a valid date.');
	  return (false);
	}	   

// checks if the departure date is a valid date 
	if (!isDate(oForm.elements['OUT_DATE_DD'].value,oForm.elements['OUT_DATE_MM'].value,oForm.elements['OUT_DATE_YY'].value)) {
	  alert('The selected Departure Date is not a valid date.');
	  return (false);
	}
	
// checks that a user only entered a group id or a corp id, not both
   if (oForm.elements['GROUP_ID']) {
	   if (oForm.elements['GROUP_ID'].value != '') {
		  vCount += 1;
	   }
	   if (oForm.elements['CORP_ID'].value != '') {
		  vCount += 1;
	   }
	   if (vCount > 1) {
		  alert("You may only search using one special access code at a time.  Enter a Group / Event Id or a Corporate Code, not both.");
	   	  oForm.CORP_ID.select();
		  return(false);
	   }
	   else {
		  oForm.submit();
	   }
	   
	} else {
	  oForm.submit();
	}
}
