/*

		COMMENTS 			:	Requires Get_Txt.js and '$lang'.globals.js
	
*/

// Start at 1930
var minyear = 1920;
var maxyear = new Date().getFullYear() + 30;
	
var datePickerDivID = "datepicker";
var iFrameDivID = "datepickeriframe";

var shortWeekday = new Array( Get_Txt('SHORT_WEEKDAY_1'), 
																														Get_Txt('SHORT_WEEKDAY_2'), 
																														Get_Txt('SHORT_WEEKDAY_3'), 
																														Get_Txt('SHORT_WEEKDAY_4'), 
																														Get_Txt('SHORT_WEEKDAY_5'), 
																														Get_Txt('SHORT_WEEKDAY_6'), 
																														Get_Txt('SHORT_WEEKDAY_7'));

var longMonth = new Array( Get_Txt('MONTH_01'), 
																											Get_Txt('MONTH_02'), 
																											Get_Txt('MONTH_03'), 
																											Get_Txt('MONTH_04'), 
																											Get_Txt('MONTH_05'), 
																											Get_Txt('MONTH_06'), 
																											Get_Txt('MONTH_07'), 
																											Get_Txt('MONTH_08'), 
																											Get_Txt('MONTH_09'), 
																											Get_Txt('MONTH_10'), 
																											Get_Txt('MONTH_11'), 
																											Get_Txt('MONTH_12'));
 
	
// these variables define the date formatting we're expecting and outputting.
// If you want to use a different format by default, change defaultDateFormat variables either here or on your HTML page.
var defaultDateFormat = "d/m/Y";
var dateFormat = defaultDateFormat;

function DatePicker() {
		this.dateFormat = 'Y/m/d';
		this.target_element = null;
		this.node = null;
		this.minyear = minyear;
		this.maxyear = maxyear;
		this.minmonth = null;
		this.maxmonth = null;
		this.minday = null;
		this.maxday = null;
		
		this.draw = function( x, y ) {
				var dt = getFieldDate( this.target_element.value );
				
		
				// the datepicker table will be drawn inside of a <div> with an ID defined by the
				// global datePickerDivID variable. If such a div doesn't yet exist on the HTML
				// document we're working with, add one.
				if (!document.getElementById(datePickerDivID)) {
						// don't use innerHTML to update the body, because it can cause global variables
						// that are currently pointing to objects on the page to have bad references
						//document.body.innerHTML += "<div id='" + datePickerDivID + "' class='dpDiv'></div>";
						var newNode = document.createElement("div");
						newNode.setAttribute("id", datePickerDivID);
						newNode.setAttribute("class", "dpDiv");
						newNode.setAttribute("className", "dpDiv");
						newNode.setAttribute("style", "visibility: hidden;");
						document.body.appendChild(newNode);
						this.node = newNode;
				} else {
						this.node = document.getElementById(datePickerDivID);
				}
			
				// move the datepicker div to the proper x,y coordinate and toggle the visiblity
				this.node.style.position = "absolute";
				this.node.style.left = x + "px";
				this.node.style.top = y + "px";
				this.node.style.visibility = (this.node.style.visibility == "visible" ? "hidden" : "visible");
				this.node.style.display = (this.node.style.display == "block" ? "none" : "block");
				this.node.style.zIndex = 10000;
			
				// draw the datepicker table
				this.refresh(dt.getFullYear(), dt.getMonth(), dt.getDate());
		}
		
		this.createRefreshButton = function(dateVal, adjust, label) {
			
				var newMonth = (dateVal.getMonth () + adjust) % 12;
				var newYear = dateVal.getFullYear() + parseInt((dateVal.getMonth() + adjust) / 12);
				if ((newMonth < 0)) {
						newMonth += 12;
						newYear += -1;
				}
				
				var instance = this;
				
				var button = document.createElement("button");
				button.className = "dpButton";
				button.innerHTML = label;
				
				var onclick = null;
				if ( newYear >= this.minyear && newYear <= this.maxyear && 
								( this.minmonth === null || newYear != this.minyear || newMonth >= this.minmonth ) && 
								( this.maxmonth === null || newYear != this.maxyear || newMonth >= this.maxmonth ) ) { 
						onclick = function () { 
								instance.refresh( newYear, newMonth ); 
						}; 
				} else {
					onclick = function () { return false; }; 
				}
				
				button.onclick = onclick;
			
				return button;
		}
		
		this.setDayOnclick = function ( cell, date_string ) {
				var instance = this;
				cell.onclick = function () { 
						instance.update( date_string ); 
				};
		}
		
		this.refresh = function(year, month, day) {
			
				var thisDay = new Date();
			
				if ((month >= 0) && (year > 0)) {
						thisDay = new Date(year, month, 1);
				} else {
						day = thisDay.getDate();
						thisDay.setDate(1);
				}
				
				var instance = this;
				
				var table = document.createElement("table");
				table.className = "dpTable";
				
				var yearselector = document.createElement("select");
				yearselector.className = "dpYearSelect";
				yearselector.setAttribute("id", "year");
				yearselector.onchange = function () { 
					 instance.refresh( this.value, thisDay.getMonth() ); 
		  };
				
				var year = this.minyear;
				var currentyear = new Date().getFullYear();
				// Add each year from 1930 to today+20 years to the select box
				do {
					yearselector.options[yearselector.options.length] = new Option( year, year );
					year++;
				} while ( year <= this.maxyear)
				
				yearselector.value = thisDay.getFullYear();
				
				var title_row = table.insertRow( table.rows.length );
				title_row.className = "dpTitleTR";
				
				var previous_year_td = title_row.insertCell(title_row.cells.length);
				previous_year_td.className = "dpButtonTD";
				previous_year_td.appendChild( this.createRefreshButton(thisDay, -12, "&lt;&lt;") );
				
				var previous_month_td = title_row.insertCell(title_row.cells.length);
				previous_month_td.className = "dpButtonTD";
				previous_month_td.appendChild( this.createRefreshButton(thisDay, -1, " &lt; ") );
				
				var title_td = title_row.insertCell(title_row.cells.length);
				title_td.className = "dpTitleTD";
				title_td.setAttribute("colspan", "3");
				title_td.colSpan = 3;
				
				var title_div = document.createElement("div");
				title_div.className = "dpTitleText";
				title_div.appendChild( document.createTextNode(" " + longMonth[ thisDay.getMonth()] + " ") );
				title_div.appendChild( yearselector );
				title_div.appendChild( document.createTextNode(" ") );
				title_td.appendChild( title_div );
				
				var next_month_td = title_row.insertCell(title_row.cells.length);
				next_month_td.className = "dpButtonTD";
				next_month_td.appendChild( this.createRefreshButton(thisDay, 1, " &gt; ") );
				
				var next_year_td = title_row.insertCell(title_row.cells.length);
				next_year_td.className = "dpButtonTD";
				next_year_td.appendChild( this.createRefreshButton(thisDay, 12, "&gt;&gt;") );
				
				var header_row = table.insertRow( table.rows.length );
				
				for(i = 0; i < shortWeekday.length; i++) {
						var day_td = header_row.insertCell(header_row.cells.length);
						day_td.className = "dpDayTD";
						day_td.appendChild( document.createTextNode(shortWeekday[i]) );
				}
				
				var current_row = table.insertRow( table.rows.length );
				
				for (i = 0; i < thisDay.getDay(); i++) {
						var td = current_row.insertCell(current_row.cells.length);
						td.setAttribute("class", "dpTD");
						td.className = "dpTD";
						td.appendChild( document.createTextNode(" ") );
				}
			
				// now, the days of the month
				do {
						dayNum = thisDay.getDate();
						
						var current_cell = current_row.insertCell(current_row.cells.length);
						if (dayNum == day) {
								current_cell.setAttribute("class", "dpDayHighlightTD");
								current_cell.className = "dpDayHighlightTD";
								var selected_div = document.createElement('div');
								selected_div.className = "dpDayHighlight";
								selected_div.appendChild(document.createTextNode(dayNum));
								current_cell.appendChild(selected_div);
						} else {
								current_cell.setAttribute("class", "dpTD");
								current_cell.className = "dpTD";
								current_cell.appendChild( document.createTextNode(dayNum) );
								current_cell.onmouseout = function () { this.className="dpTD"; }; 
								current_cell.onmouseover = function () { this.className="dpTDHover"; }; 
						}
						
						current_year = thisDay.getFullYear();
						current_month = thisDay.getMonth();
						current_day = thisDay.getDate();
						
						if ( current_year >= this.minyear && current_year <= this.maxyear && 
											( this.minmonth === null || current_year != this.minyear || current_month >= this.minmonth ) && 
											( this.minmonth === null || this.minday === null || current_year != this.minyear || current_month != this.minmonth || current_day >= this.minday ) && 
											( this.maxmonth === null || current_year != this.maxyear || current_month <= this.maxmonth ) && 
											( this.maxmonth === null || this.maxday === null || current_year != this.maxyear || current_month != this.maxmonth || current_day <= this.maxday ) ) {
								this.setDayOnclick( current_cell, getDateString( thisDay, instance.dateFormat ) );
						} else {
								current_cell.setAttribute("class", "dpTDdisabled");
								current_cell.className = "dpTDdisabled";
								current_cell.onmouseout = null; 
								current_cell.onmouseover = null; 
						}
						
						// if this is a Saturday, start a new row
						if ( thisDay.getDay() == 6 ) {
								current_row = table.insertRow( table.rows.length );
						}
						
						// increment the day
						thisDay.setDate(thisDay.getDate() + 1);
				} while (thisDay.getDate() > 1);
			
				// fill in any trailing blanks
				if ( thisDay.getDay() > 0 ) {
						for ( i = 6; i > thisDay.getDay(); i-- ) {
								var td = current_row.insertCell(current_row.cells.length);
								td.setAttribute("class", "dpTD");
								td.className = "dpTD";
								td.appendChild( document.createTextNode(" ") );
						}
				}
				
				var footer_row = table.insertRow( table.rows.length );
				footer_row.className = "dpTodayButtonTR";
				
				var footer_td = footer_row.insertCell(footer_row.cells.length);
				footer_td.className = "dpTodayButtonTD";
				footer_td.setAttribute("colspan", "7");
				footer_td.colSpan = 7;
				var today = new Date();
				var todayString = "Today is " + shortWeekday[today.getDay()] + ", " + longMonth[ today.getMonth()] + " " + today.getDate();
				
				var today_button = document.createElement("button");
				today_button.className = "dpTodayButton";
				today_button.innerHTML = Get_Txt('TODAY');
				today_button.onclick = function () { 
						instance.refresh(); 
				};
				footer_td.appendChild(today_button);
				
				var close_button = document.createElement("button");
				close_button.className = "dpTodayButton";
				close_button.innerHTML = Get_Txt('CLOSE');
				close_button.onclick = function () { 
						instance.update('',true); 
				};
				footer_td.appendChild(close_button);
				
				this.node.innerHTML = '';
				this.node.appendChild(table);
				
				// add an "iFrame shim" to allow the datepicker to display above selection lists
				adjustiFrame();
		}
		
		this.update = function ( dateString, bypass_onchange ) { 

				if ( dateString ) {
						this.target_element.value = dateString;
						// We have a value in the date field, so show the 'Clear' link
						if ( document.getElementById('clear_' + this.target_element.id) ) {
							document.getElementById ('clear_' + this.target_element.id).style.visibility = 'visible';
						}
				}
				
				if ( this.node ) {
					this.node.style.visibility = "hidden";
					this.node.style.display = "none";
				
		
					adjustiFrame();
				}
				if ( this.target_element ) {
						this.target_element.focus();
				}
			
				// after the datepicker has closed, optionally run a user-defined function called
				// datePickerClosed, passing the field that was just updated as a parameter
				// (note that this will only run if the user actually selected a date from the datepicker)
				if ((dateString) && (typeof(datePickerClosed) == "function"))
						datePickerClosed(this.target_element);
			
				// Call onchange on the input field in case it has an onchange event associated with it
				// The onchange event is not fired if the element doesn't have/lose focus, and in our case it doesn't,
				// so we have to call it manually
				if ( !bypass_onchange && this.target_element ){
						if ( this.target_element.onchange ){
								this.target_element.onchange();
						}
				}
		}
}

/**
This is the main function you'll call from the onClick event of a button.
Normally, you'll have something like this on your HTML page:

Start Date: <input name="StartDate">
<input type=button value="select" onclick="displayDatePicker('StartDate');">

That will cause the datepicker to be displayed beneath the StartDate field and
any date that is chosen will update the value of that field. If you'd rather have the
datepicker display beneath the button that was clicked, you can code the button
like this:

<input type=button value="select" onclick="displayDatePicker('StartDate', this);">

So, pretty much, the first argument (dateFieldName) is a string representing the
name of the field that will be modified if the user picks a date, and the second
argument (displayBelowThisObject) is optional and represents an actual node
on the HTML document that the datepicker should be displayed below.


This would display the datepicker beneath the StartDate field (because the
displayBelowThisObject parameter was false), and update the StartDate field with
the chosen value of the datepicker using a date format of dd.mm.yyyy
*/
function displayDatePicker(dateFieldId, displayBelowThisObject, dtFormat, min_year, max_year, min_month, max_month, min_day, max_day )
{

  var targetDateField = document.getElementById (dateFieldId);
 
  // if we weren't told what node to display the datepicker beneath, just display it
  // beneath the date field we're updating
  if (!displayBelowThisObject)
    displayBelowThisObject = targetDateField;
 
  // if a date format was given, update the dateFormat variable
  if (dtFormat)
    dateFormat = dtFormat;
  else
    dateFormat = defaultDateFormat;
 
  var x = displayBelowThisObject.offsetLeft;
  var y = displayBelowThisObject.offsetTop + displayBelowThisObject.offsetHeight ;
 
  // deal with elements inside tables and such
  var parent = displayBelowThisObject;
  while (parent.offsetParent) {
    parent = parent.offsetParent;
    x += parent.offsetLeft;
    y += parent.offsetTop;
  }
		
		var picker = new DatePicker();
		picker.dateFormat = dtFormat;
		picker.target_element = targetDateField;
		
		if ( typeof min_year != 'undefined' && min_year !== null ) {
				picker.minyear = min_year;
				if ( typeof min_month != 'undefined' && min_month !== null ) {
						picker.minmonth = min_month;
						if ( typeof min_day != 'undefined' && min_day !== null ) {
								picker.minday = min_day;
						}
				}
		}
		
		if ( typeof max_year != 'undefined' && max_year !== null ) {
				picker.maxyear = max_year;
				if ( typeof max_month != 'undefined' && max_month !== null ) {
						picker.maxmonth = min_month;
						if ( typeof max_day != 'undefined' && max_day !== null ) {
								picker.maxday = max_day;
						}
				}
		}
 
  picker.draw(x, y);
}

function clearDatePicker( dateFieldId ){
		var targetDateField = document.getElementById (dateFieldId);
		document.getElementById ('clear_' + targetDateField.id).style.visibility = 'hidden'; 
		targetDateField.value = ''; 
		var picker = new DatePicker();
		picker.target_element = targetDateField; 
		picker.update();
}


/**
Convert a JavaScript Date object to a string, based on the dateFormat and dateSeparator
variables at the beginning of this script library.
*/
function getDateString( dateVal, format )
{
  var dayString = "00" + dateVal.getDate();
  var monthString = "00" + (dateVal.getMonth()+1);
  dayString = dayString.substring(dayString.length - 2);
  monthString = monthString.substring(monthString.length - 2);
 
		var output_format = dateFormat;
		if ( typeof format != 'undefined' ) {
						
		}
	
  switch (output_format) {
			
    case "d/m/Y" :
      return dayString + "/" + monthString + "/" + dateVal.getFullYear();
    case "Y/m/d" :
      return dateVal.getFullYear() + "/" + monthString + "/" + dayString;
    case "m/d/Y" :
    default :
      return monthString + "/" + dayString + "/" + dateVal.getFullYear();
  }
}


/**
Convert a string to a JavaScript Date object.
*/
function getFieldDate(dateString)
{
	
  var dateVal;
  var dArray;
  var d, m, y;
 
  try {
    dArray = splitDateString(dateString);
    if (dArray) {
      switch (dateFormat) {
        case "d/m/Y" :
          d = parseInt(dArray[0], 10);
          m = parseInt(dArray[1], 10) - 1;
          y = parseInt(dArray[2], 10);
          break;
        case "Y/m/d" :
          d = parseInt(dArray[2], 10);
          m = parseInt(dArray[1], 10) - 1;
          y = parseInt(dArray[0], 10);
          break;
        case "m/d/Y" :
        default :
          d = parseInt(dArray[1], 10);
          m = parseInt(dArray[0], 10) - 1;
          y = parseInt(dArray[2], 10);
          break;
      }
						
						dateVal = new Date(y, m, d);
								
    } else if (dateString) {
      dateVal = new Date(dateString);
    } else {
      dateVal = new Date();
    }
  } catch(e) {
    dateVal = new Date();
  }
 
  return dateVal;
}


/**
Try to split a date string into an array of elements, using common date separators.
If the date is split, an array is returned; otherwise, we just return false.
*/
function splitDateString(dateString)
{
  var dArray;
  if (dateString.indexOf("/") >= 0)
    dArray = dateString.split("/");
  else if (dateString.indexOf(".") >= 0)
    dArray = dateString.split(".");
  else if (dateString.indexOf("-") >= 0)
    dArray = dateString.split("-");
  else if (dateString.indexOf("\\") >= 0)
    dArray = dateString.split("\\");
  else
    dArray = false;
 
  return dArray;
}




/**
Use an "iFrame shim" to deal with problems where the datepicker shows up behind
selection list elements, if they're below the datepicker. The problem and solution are
described at:

http://dotnetjunkies.com/WebLog/jking/archive/2003/07/21/488.aspx
http://dotnetjunkies.com/WebLog/jking/archive/2003/10/30/2975.aspx
*/
function adjustiFrame(pickerDiv, iFrameDiv)
{
  // we know that Opera doesn't like something about this, so if we
  // think we're using Opera, don't even try
  var is_opera = (navigator.userAgent.toLowerCase().indexOf("opera") != -1);
  if (is_opera)
    return;
  
  // put a try/catch block around the whole thing, just in case
  try {
    if (!document.getElementById(iFrameDivID)) {
      // don't use innerHTML to update the body, because it can cause global variables
      // that are currently pointing to objects on the page to have bad references
      //document.body.innerHTML += "<iframe id='" + iFrameDivID + "' src='javascript:false;' scrolling='no' frameborder='0'>";
      var newNode = document.createElement("iFrame");
      newNode.setAttribute("id", iFrameDivID);
      newNode.setAttribute("src", "javascript:false;");
      newNode.setAttribute("scrolling", "no");
      newNode.setAttribute ("frameborder", "0");
      document.body.appendChild(newNode);
    }
    
    if (!pickerDiv)
      pickerDiv = document.getElementById(datePickerDivID);
    if (!iFrameDiv)
      iFrameDiv = document.getElementById(iFrameDivID);
    
    try {
      iFrameDiv.style.position = "absolute";
      iFrameDiv.style.width = pickerDiv.offsetWidth;
      iFrameDiv.style.height = pickerDiv.offsetHeight ;
      iFrameDiv.style.top = pickerDiv.style.top;
      iFrameDiv.style.left = pickerDiv.style.left;
      iFrameDiv.style.zIndex = pickerDiv.style.zIndex - 1;
      iFrameDiv.style.visibility = pickerDiv.style.visibility ;
      iFrameDiv.style.display = pickerDiv.style.display;
    } catch(e) {
    }
				
  } catch (ee) {
  }
 
}

