/**
 * This calendar code is a modification of
 * Dave's Quick Search Deskbar
 * http://sourceforge.net/projects/dqsd/ 
 * Version 3.1.8.0
 * Copyright (c) 2002 David Bau
 * Distributed under the terms of the
 * GNU Public License, Version 2 (http://www.gnu.org/copyleft/gpl.txt)
 *
 * It was modified for use on this website
 * Most of the modifications involve turning off features that are not needed
 * Also the user cannot go beyond the "today" date
 * or prior to the "not before" date.
 * Lastly many of the files were merged to reduce the total number of files required by the site.
 * Their original sources are noted wherever possible.
*/
/**
 * script to display a popup calendar
 * added by Sidney Chong (sidney@gamebox.net) 12/12/2001
 * modified by Sidney Chong (sidney@gamebox.net) 15/01/2002
 *  - added display of events (eg holidays) specified
 *    in a file referenced by the var 'eventsfileurl'
 * modified by Sidney Chong (sidney@gamebox.net) 16/01/2002
 *  - changed event month to run from 1-12 instead of 0-11
 *  - assume event date to be recurring if month or year attribute
 *    is not specified.
 * modified by Monty Scroggins  31/03/2002
 *  - added support for a local events file with referenced by
 *    a the var 'localeventsfileurl'
 * modified by Neel Doshi 31/03/2002
 *  - configured the calendar to use the stylesheet
 *  - fixed the bug where "today" was not being highlighted if today is Sunday
 * modified by Harry-Anton Talvik 03/11/2002
 *  - configured the calender to use week start day
 * modified by Will Dean 2003-1-9
 *  - Speed improvements to very large strcat operation in build
 *  - Caching of inlinestyle conversion
 *
 * TODO:
 *  - add ability to distingush b/w different kind of events
 *  - add ability to input events directly from search box
 */


// from preferences.js
			calwidth=179;
			calheight=156;
			calStart=0;
			weekStartDay = 1;
			defaultcal="localpage";
			eventsfileurl="holidays.us.xml";

var ents = null;
var lents = null;

//vars used by the calendar script
var DAYS_OF_WEEK = 7;    // "constant" for number of days in a week
var DAYS_OF_MONTH = 31;    // "constant" for number of days in a month
var CAL_DAY_START = 1;    // "constant" to indicate which date starts a month (usually people like it to be 1. day of the month)
var WEEK_START_DAY = weekStartDay;    // "constant" to indicate a day which starts a week -- 1=Sun, 2=Mon, .. ; weekStartDay is declared in preferences.js

// moving to html page
// var Calendar = new Date(); //stores the date the user is looking at
// var Today = new Date(2004, 02, 02); // stores the date marked as today

var popcal = null;
var bNeverBuilt = true;
var formFieldObj = null;

function showcal(fieldObj, buttonObj)
{
	formFieldObj = fieldObj;
	setCalendarDate() // new function to set the calendar date to the value in the text field
  if (!dopopup) // calendar only works in IE 5.5+
    return true;
  if (popcal == null)
  {
    popcal = window.createPopup();
    popcal.document.body.innerHTML = buildcal();
    popcal.document.body.className="cal";
  }
  else if (Today.getDate() != (new Date()).getDate())
  {
    popcal.document.body.innerHTML = buildcal();
  }
  popcal.show(0, 0, calwidth, calheight, buttonObj);
  return false;
}
calupdatetimer = null;

function movecal(nMths) // function to change months or years
{
  Calendar.setMonth(Calendar.getMonth()+nMths);
  popcal.document.all["calhead"].innerHTML = buildcalheader();
  if (calupdatetimer == null)
    calupdatetimer = setTimeout("updatecal()", 0);
}

function updatecal()
{
  calupdatetimer = null;
  popcal.document.body.innerHTML = buildcal();
  
  var gCompleteTime = new Date();
}

function opencal(d) // function called when a date is clicked
{
// this function was quite a bit more extensive previously
// allowing the user to have a date selection have a wide variety of effects
// but was greatly simplifed here to just put the date back into the field
// in the correct format
  if (popcal)
    popcal.hide();
  var dobj = new Date(d);
  var yy = dobj.getYear();
  if (yy < 100) yy += 1900;
	var MM = dobj.getMonth()+1
	if (MM < 10) MM = "0" + MM;
	var dd = dobj.getDate()
	if (dd < 10) dd = "0" + dd;
	if(dateMask == "MM/dd/yyyy"){
		returnDate = MM + "/" + dd + "/" + yy
	}else{
		returnDate = dd + "/" + MM + "/" + yy
	}
	formFieldObj.value = returnDate

}

function buildcalhtmlhead()
{
  if(bNeverBuilt)
  {
  	// the styles original came from an external css file
    inlineStyles =
    	  "body{margin: 0px; border: 0; padding: 0; background-color:#D5D5D9;}"
    	+ "td, th{font-family: verdana; font-size:11px;}"
    	+ ".cal{border:2px; border-style:outset;}"
			+ ".calnavmonth, .calnavmonthhigh, .calnavyear, .calnavyearhigh{font-weight:bold; border-width:0; border-style:solid; border-color:none; color:990000;}"
			+ ".calnavyear, .calnavyearhigh{color:990000; font-weight:bold;}"
			+ ".calmonth, .calmonthhigh{font-weight:bold;}"
			+ ".caleventday, .caleventdayhigh{color:990000;}"
			+ ".caltodayevent, .caltodayeventhigh{color:990000; background-color:window; font-weight:bold; border-width:1; border-style:solid; border-color:none;}"
			+ ".caltoday, .caltodayhigh{background-color:window; font-weight:bold; border-width:1; border-style:solid; border-color:990000;}"
			+ ".calgray, .calgrayhigh{color:908F8F;}"
			+ ".calgraystrike{color:908F8F; text-decoration: line-through; text-align:center;}"
			+ ".caldow{text-align:center; font-weight:bold;}"
			+ ".calmonth, .calnavmonth, .calnavyear, .calday, .caleventday, .caltodayevent, .caltoday, .calgray{text-align:center; cursor:hand;}"
			+ ".calmonthhigh, .calnavmonthhigh, .calnavyearhigh, .caldayhigh, .caleventdayhigh, .caltodayeventhigh, .caltodayhigh, .calgrayhigh{cursor:hand; background-color:990000; color:highlighttext; text-align:center;}"
			+ ".calmonth{cursor:default;}"
    bNeverBuilt = false;
  } 
  return '<table class=cal width=100% height=100% cellpadding=0 cellspacing=0 border=0><tr><td><style>' + inlineStyles + '</style>';
}

function buildcalheader()
{
  return getMonthName(Calendar.getMonth()+1)  + ' ' + Calendar.getFullYear();
}

function buildcal()
{
  var year = Calendar.getFullYear();  // Returns year in 4 digits
  var month = Calendar.getMonth();    // Returns month (0-11)

  //Today = new Date();
  // this was overwriting the value that I'm setting on the page...
  var weekday = -1;  // Just init weekday

  if (Today.getMonth() == Calendar.getMonth() && Today.getYear() == Calendar.getYear())
    weekday = Today.getDay();
  
  var pastday = -1 // init pastday
  if(Calendar.getMonth() == notBefore.getMonth() && Calendar.getYear() == notBefore.getYear()){
  	pastday = notBefore.getDay();
  }
  
  var futureMayShow = false // By default, we can't see the future
  var nextMonth = new Date(Calendar.getFullYear(), Calendar.getMonth(), 1);
  	if(Calendar.getMonth() == 11){
  		nextMonth.setMonth(0)
  		nextMonth.setYear(Calendar.getYear() + 1)
  	}else{
  		nextMonth.setMonth(nextMonth.getMonth() + 1)
  	}
  if (Today.getMonth() == nextMonth.getMonth() && Today.getYear() == nextMonth.getYear())
  	futureMayShow = true;

  var aYearAhead = true // By default, we can look a year ahead
  var nextYear = new Date(Calendar.getFullYear(), Calendar.getMonth(), 1);
  		nextYear.setYear(nextYear.getFullYear() + 1)
  var todayMonth = new Date(Today.getFullYear(), Today.getMonth(), 1);
  if (todayMonth < nextYear)
  	aYearAhead = false;

	var aYearBehind = true // By default, we can look a year back
  var lastYear = new Date(Calendar.getFullYear(), Calendar.getMonth(), 1);
  		lastYear.setYear(lastYear.getFullYear() - 1)
  var notBeforeMonth = new Date(notBefore.getFullYear(), notBefore.getMonth(), 1);
  		
  if (lastYear < notBeforeMonth)
  	aYearBehind = false;

  var cal;    // Used for printing
  Calendar.setDate(CAL_DAY_START);    // Start the calendar day at '1', '2', ..
  var TR_start = '<tr>';
  var TR_end = '</tr>';
  var day_start = '<td width=14.2857% class=caldow>';
  var day_end = '</td>';
//try to remove
//  function eventday_start(d, ttl)
//  {
//    return '<td class=caleventday' +
//      (defaultcal ? ' onmouseover=this.className="caleventdayhigh" onmouseout=this.className="caleventday" onmouseup=this.className="caleventday";parent.opencal(' + d + ');' : ' ') +
//      ' title="' + ttl + '">';
//  }
//  var eventday_end   = '</td>';

//  function todayevent_start(d, ttl)
//  {
//    return '<td class=caltodayevent' +
//      (defaultcal ? ' onmouseover=this.className="caltodayeventhigh" onmouseout=this.className="caltodayevent" onmouseup=this.className="caltodayevent";parent.opencal(' + d + ');' : ' ') +
//      ' title="' + ttl + '"' + '>';
//  }
//  var todayevent_end   = '</td>';

  function today_start(d)
  {
    return '<td class=caltoday' +
        (defaultcal ? ' onmouseover=this.className="caltodayhigh" onmouseout=this.className="caltoday" onmouseup=this.className="caltoday";parent.opencal(' + d + ');' : ' ') + '>';
  }
  var today_end   = '</td>';

  function gray_start(d)
  {
  	if(futurelight || pastlight){
  		// change this for future dates in the previous or next month
  		return '<td class=calgraystrike>'
  	}else{
  		// standard cell for dates in the previous or next month
  		return '<td class=calgray' +
         (defaultcal ? ' onmouseover=this.className="calgrayhigh" onmouseout=this.className="calgray" onmouseup=this.className="calgray";parent.opencal(' + d + ');' : ' ') + '>';
  	}     
  }
  var gray_end   = '</td>';

  function TD_start(d)
  {
  	if(futurelight || pastlight){
  		// change this for future dates in the current month
  		return '<td class=calgraystrike>'
  	}else{
  		// standard for the current month
    	return '<td class=calday' +
        (defaultcal ? ' onmouseover=this.className="caldayhigh" onmouseout=this.className="calday" onmouseup=this.className="calday";parent.opencal(' + d + ');' : ' ') + '>';
  	}
  }
  var TD_end = '</td>';

  var cal = buildcalhtmlhead();

  var tableStart = '<table width=100% height=100% border=0 cellspacing=0 cellpadding=0><tr>';
  tableStart += '<td colspan=7><table width=100% height=100% border=0 cellspacing=0 cellpadding=0><tr>';
  tableStart += '<td><table align=left height=100% border=0 cellspacing=0 cellpadding=0><tr>';
  if(aYearBehind){ // new code to prevent the user from going back past the not before date
  	tableStart += '<td class=calnavyear width=0 title="' + local(PREV_YEAR) + '" ' +
	         ' onmouseup="parent.movecal(-12);return false;" ' +
	         ' onmouseover=this.className="calnavyearhigh" ' +
	         ' onmouseout=this.className="calnavyear" >&nbsp;&laquo;&nbsp;</td>';
	}else{
		tableStart += '<td class=calnavyear width=0 style=\"cursor: default;\">&nbsp;&nbsp;&nbsp;</td>';
	}
  if(pastday < 0){ // new code to prevent the user from going back past the not before date
	  tableStart += '<td class=calnavmonth width=0 title="' + local(PREV_MONTH) + '" ' +
	         ' onmouseup="parent.movecal(-1);return false;" ' +
	         ' onmouseover=this.className="calnavmonthhigh" ' +
	         ' onmouseout=this.className="calnavmonth" >&nbsp;&lsaquo;&nbsp;</td></tr></table></td>';
	}else{
		tableStart += '<td class=calnavmonth width=0 style=\"cursor: default;\">&nbsp;&nbsp;&nbsp;</td></tr></table></td>';
	}
  if (weekday < 0)
  {
    tableStart += '<td id=calhead class=calmonth title="' + local(GO_TO_TODAY) + '" ' +
      ' onmouseup="parent.Calendar=new Date();parent.movecal(0);" ' +
      ' onmouseover=this.className="calmonthhigh" ' +
      ' onmouseout=this.className="calmonth" >';
  }
  else
  {
    tableStart += '<td id=calhead class=calmonth colspan=' + (DAYS_OF_WEEK - 2) + '>';
  }

  tableStart += buildcalheader();

  tableStart += '</td>';
  tableStart += '<td><table align=RIGHT height=100% border=0 cellspacing=0 cellpadding=0><tr>';
  if (weekday < 0){ // new code to prevent the user from going forward past today
	  tableStart += '<td class=calnavmonth width=0 title="' + local(NEXT_MONTH) + '" ' +
	         ' onmouseup="parent.movecal(+1);return false;" ' +
	         ' onmouseover=this.className="calnavmonthhigh" ' +
	         ' onmouseout=this.className="calnavmonth" >&nbsp;&rsaquo;&nbsp;</td>';
	}else{
		tableStart += '<td class=calnavmonth width=0 style=\"cursor: default;\">&nbsp;&nbsp;&nbsp;</td>';
	}
	if(aYearAhead){ // new code to prevent the user from going forward past today
	  tableStart += '<td class=calnavyear width=0 title="' + local(NEXT_YEAR) + '" ' +
	         ' onmouseup="parent.movecal(+12);return false;" ' +
	         ' onmouseover=this.className="calnavyearhigh" ' +
	         ' onmouseout=this.className="calnavyear" >&nbsp;&raquo;&nbsp;</td></tr></table></td>';
	}else{
		tableStart += '<td class=calnavyear width=0 style=\"cursor: default;\">&nbsp;&nbsp;&nbsp;</td></tr></table></td>';
	}
  tableStart += '</td></tr></table>';
  tableStart += TR_end + TR_start;

  cal += tableStart;

  //printing day labels
  var tempString = new String();
  for(index=0; index < DAYS_OF_WEEK; index++)
  {
    tempString += day_start;
    tempString += getDayName(DAYS_OF_WEEK + ((index + WEEK_START_DAY - 1) % DAYS_OF_WEEK) + 1);
    tempString += day_end;
  }
  tempString += TD_end;
  
  cal += tempString;

  //fill spaces until first day in the month
  var whichmonth = -1;
  var filldays = Calendar.getDay() - (WEEK_START_DAY - 1);
  if (filldays < 0) filldays += DAYS_OF_WEEK;

  Calendar.setDate(Calendar.getDate() - filldays);
  var tableString = new String();

  //draw six weeks loop for each day in the month
  for (index=0; index < DAYS_OF_WEEK * 6; index++)
  {
    var month_day = Calendar.getDate();
    if (month_day == CAL_DAY_START) whichmonth += 1;
    var dayString = new String();
    var nowTime = Calendar.getTime();

    week_day = Calendar.getDay();

    // start new row if we hit a new week
    if (week_day == WEEK_START_DAY - 1) dayString += TR_end + TR_start;

// shouldn't need this, unless we decide to do events for some reason
// but I'm not sure how to get rid of it...
    var ent = null;
    var lent = null;

    querystr = 'event[date[(number(@year)="'+year+'" || not(@year)) && (number(@month)="'+(month+1)+'" || not(@month)) && number(@day)="'+month_day+'"]]';
    if (ents)
      ent = ents.selectSingleNode(querystr);
    if (lents)
      lent = lents.selectSingleNode(querystr);
//alert("weekday: " + weekday + "\nwhichmonth: " + whichmonth + "\nmonth_day: " + month_day)
// is it the current day? if it is the cell is highlighted
    var highlight = false;
    if( weekday>=0 && Today.getDate()==month_day)
      highlight = true;

// added by JHC
// if it's a date in the future people can't select it, so we're going to use
// another kind of highlight... the futurelight!
    var futurelight = false;
    if( weekday>=0 && ((whichmonth == 0 && Today.getDate() < month_day) || (whichmonth == 1)))
      futurelight = true;
    if (futureMayShow && whichmonth == 1 && Today.getDate() < month_day)
    	futurelight = true;
// if it's a date before which people can't see we use yet
// another kind of highlight... the pastlight!
    var pastlight = false;
    if( pastday >=0 && (whichmonth == 0 && notBefore.getDate() > month_day))
      pastlight = true;
    if( pastday >=0 && whichmonth == -1)
      pastlight = true;
    // highlight appropriately
    if (whichmonth != 0)
      dayString += gray_start(nowTime) + month_day + gray_end;
    else
    {
      if (highlight && ent)
        dayString += todayevent_start(nowTime, ent.getAttribute("name"));
      else
        if (highlight)
          dayString += today_start(nowTime);
        else
          if (ent)
            dayString += eventday_start(nowTime, ent.getAttribute("name"));
          else
            if (lent)
              dayString += eventday_start(nowTime, lent.getAttribute("name"));
            else
              dayString += TD_start(nowTime);

      dayString += month_day;

      if (highlight && ent)
        dayString += todayevent_end;
      else
        if (highlight)
          dayString += today_end;
        else
          if (ent)
            dayString += eventday_end;
          else
            dayString += TD_end;
            
    }

    //advance the date for next iteration
    Calendar.setDate(Calendar.getDate()+1);

    tableString += dayString;

  }// end for loop

  cal += tableString + TR_end + '</table></td></tr></table>'
  
  //reset back the calendar's month
  Calendar.setMonth(Calendar.getMonth()-1);
  
//  var endTime = new Date();
//  var timeDiff = endTime - startTime;
//  alert(timeDiff);

  //return the html string
  return cal;
}


// added by JHC
// for use on bglobal
function setCalendarDate(){
	var calString = formFieldObj.value // update this to reflect what's used on the page
	var dateArray = calString.split("/");
	if(dateMask == "MM/dd/yyyy"){
		Calendar = new Date(dateArray[2], dateArray[0]-1, dateArray[1]);
	}else{
		Calendar = new Date(dateArray[2], dateArray[1]-1, dateArray[0]);
	}
  if(isNaN(Calendar)) Calendar = new Date(Today.getYear(), Today.getMonth(), Today.getDay());
	if(Calendar < notBefore) Calendar = new Date(notBefore.getYear(), notBefore.getMonth(), notBefore.getDay());
	if(Calendar > Today) Calendar = new Date(Today.getYear(), Today.getMonth(), Today.getDay());
}

// from tools.js
var uaMatch = navigator.userAgent.toLowerCase().match("msie\\s+(\\d+\\.\\d*)");
var ie_version = (uaMatch ? parseFloat(uaMatch[1]) : 0.0);
dopopup = (ie_version >= 5.5);

function getDefaultLanguage()
{
  if (typeof language == "undefined" || language == "")
  {
    language = navigator.userLanguage.substr(0,2);
  }
}
if (is_ie5_5up){
	getDefaultLanguage();
}


