// LyDateScript.js
// Copyright (c) 2000-2009, Lyria-W4.
// All rights reserved.
// @version	$Id: LyDateScript.js,v 1.4.4.2 2009/12/03 14:12:45 nha Exp $

var dateForm;
var field;
var dateField;
var timeField;
var initialDay;
var initialMonth;
var initialYear;
var currentDate;
var yearLeftImage;
var monthLeftImage;
var monthRightImage;
var yearRightImage;
var dateLang;
var dateType;
var previousValues;
var calendarFrameId;
var dateSelectorEvent = false;

var yearTmp;

// This function displays the date selector
// @param form the form containing the date field
// @param field the date/time hidden field name
// @param fieldDate the date field name
// @param fieldTime the time field name
// @param form the language
// @param form the image path for year decrement
// @param form the image path for month decrement
// @param form the image path for month increment
// @param form the image path for year increment
// @param type the type of the date field : it's an integer and must be the same
// as constants defined in LyDate.java.
function ShowDateSelector(frameId, scriptPath, form, fieldName, fieldDateName,
	fieldTimeName, lang, yearLeft, monthLeft, monthRight, yearRight, type)
{
	if (typeof form == "undefined")
		form = this.document.forms[0];

	// Initialize values
	yearLeftImage = yearLeft;
	monthLeftImage = monthLeft;
	monthRightImage = monthRight;
	yearRightImage = yearRight;
	dateLang = lang;
	dateForm = form;
	field = fieldName;
	dateField = fieldDateName;
	timeField = fieldTimeName;
	dateType = type;
	yearTmp = null;
	calendarFrameId = frameId;

	var value = form.elements[dateField].value;

	// If not english, swap day and month
	if (dateLang != "en_US" && dateLang != "en_EN")
		value = DateLangSwapDayMonth(value);

	if (value.length <= 0)
		currentDate = new Date();
	else
	{
		currentDate = new Date(value);

		if (isNaN(currentDate))
			currentDate = new Date();
	}

	initialDay = currentDate.getDate();
	initialMonth = currentDate.getMonth();
	initialYear = currentDate.getFullYear();

	SetFrameSrc(frameId, scriptPath + '/LyDateSelector.html');
	CloseLastDivShown();
	SwitchDivVisibility(frameId);
	SetDivSize(frameId, 155, 155);
}

// This function hides the date selector immediatly
function HideDateSelector()
{
	CloseLastDivShown();
	SetDivVisibility(calendarFrameId, false);
	calendarFrameId = null;
}

// This function updates the date field.
function DateSelectorEvent()
{
	dateSelectorEvent = true;

	UpdateDate(dateForm, field, dateField, timeField, dateType, dateLang, 'false',
		'true', 10);
	HideDateSelector();

	dateSelectorEvent= false;
}

// This function swap the day and the month of the given value.
function DateLangSwapDayMonth(value)
{
	if (value.length <= 5)
		return value;

	var n1 = value.indexOf('/', 0);
	var n2 = value.indexOf('/', n1 + 1);

	if (n1>0 && n2 > n1+1)
	{
		var newDate = value.substring(n1 + 1, n2 + 1) + value.substring(0, n1) +
			value.substring(n2);

		value = newDate;
	}

	return value;
}

// This function add a 0 before the number if single-figure number.
function GetTwoFiguresNumber(number)
{
	if (number.length >= 2)
		return number;

	return (number < 10) ? '0' + number : number;
}

// This function converts a year for being Y2K compliant.
function ConvertY2K(number)
{
 	if (number < 20)
		number += 2000;
 	if (number < 100)
		number += 1900;

	return number;
}

function TransformCurrentDate(dateField, optional)
{

	var str = '';

	if (currentDate == null)
		currentDate = new Date();

	str = GetTwoFiguresNumber(currentDate.getDate());

	if ((str+"").length > 0)
		str = str + '/';

	str = str + GetTwoFiguresNumber(currentDate.getMonth() + 1);

	if ((str+"").length > 0)
		str = str + '/';

	if (dateSelectorEvent)
	{
		var s = "" + yearTmp;

		while (s.length < 4)
			s = "0" + s;

		str = str + s;

		yearTmp = null;
	}
	else
	{
		str = str + ConvertY2K(currentDate.getYear());
	}

	if (dateLang == "en_US" || dateLang == "en_EN")
		str = DateLangSwapDayMonth(str);

	if (dateField != null)
	{
		if ((dateField.value != "") ||
		    ((optional != "true") && (dateField.value == "")))
		{
			dateField.value = str;
		}
	}
}

// This function resets the internal date. Mandatory when this date was created
// by the popup date selector to "close" the links to the popup window.
function ResetDate()
{
	currentDate = new Date(currentDate.getYear(),
		currentDate.getMonth(), currentDate.getDate());

	if (currentDate == null
		|| isNaN(currentDate))
			currentDate = new Date();
}

function UpdateDateOnBlur(form, fieldName, dateFieldName, timeFieldName, type,
	lang, optional, format, error)
{
	if (typeof form == "undefined")
		form = this.document.forms[0];

	var dateField = form.elements[dateFieldName];
	var timeField = form.elements[timeFieldName];

	var length = dateField.value.length;
	var check = CheckFormatField(form, dateFieldName, format, error, 'true');

	if (check == "false")
	{
		// update the date field with the previous value
		var previousValue = GetPreviousValue(dateFieldName);

		if (previousValue != "")
		{
			dateField.value = previousValue;
			UpdateDate(form, fieldName, dateFieldName, timeFieldName, type, lang, optional, "false");
		}
		else if (optional == "true")
		{
			dateField.value = "";
			UpdateDate(form, fieldName, dateFieldName, timeFieldName, type, lang, optional, "false");
		}
		else 	// update the date with transformation of the current date
			UpdateDate(form, fieldName, dateFieldName, timeFieldName, type, lang, "false", "true");
	}
	else
	{
		var transform = "false";

		// if the new value is null and the field not optional : revert to previous value
		//var dateField = form.elements[dateFieldName];
		if ((optional != "true") && (dateField.value == ""))
			dateField.value = GetPreviousValue(dateFieldName);
		else
			StorePreviousValue(dateField); // update the previous value

		// if is optional and the date is null, set time field to null

		if ((optional == "true") && (timeField != null))
		{
			if (dateField.value == "")
				timeField.value = "";
			else if (timeField.value == "")
				timeField.value = GetDefaultTime(type);
		}
		else if ((optional != "true") && (timeField != null))
		{
		 	if ( (timeField.value == "") && (dateField.value != "") )
		 	{
				timeField.value = GetDefaultTime(type);
			}
		}

		// update the date
		UpdateDate(form, fieldName, dateFieldName, timeFieldName, type, lang, optional, transform, length);
	}
}

function UpdateTimeOnBlur(form, fieldName, dateFieldName, timeFieldName, type,
	lang, optional, format, error)
{
	var timeField = form.elements[timeFieldName];
	var dateField = form.elements[dateFieldName];
	if (CheckFormatField(form, timeFieldName, format, error, 'true') == "false")
	{
		// update the date field with the previous value
		var previousValue = GetPreviousValue(timeFieldName);

		var transform = "false";

		if (previousValue != "")
		{
			timeField.value = previousValue;
		}
		else if (optional == "true")
		{
			timeField.value = "";
		}
		else 	// update the date with transformation of the current date
		{
//			timeField.value = GetCurrentTime(type);
			transform = "true";
		}

		UpdateDate(form, fieldName, dateFieldName, timeFieldName, type, lang, optional, transform);
	}
	else
	{
		var transform = "false";
		if ((optional != "true") && (timeField.value == ""))
			timeField.value = GetPreviousValue(timeFieldName);
		else
			StorePreviousValue(timeField); // update the previous value


		// if the field is optional if the time value is empty : empty the date.
		if ( (optional == "true") && (dateField != null) )
		{

			if (timeField.value == "")
			{
				dateField.value = "";
			}
			else
			{
				if ((dateField != null) && (dateField.value == ""))
				{
					optional = "false";
					transform = "true";
				}
			}
		}
		else if (timeField.value != null)
		{
			// Obligatory: if the timeField is not null, the date field should not be null!
		 	if ( (dateField != null) && (dateField.value == "") && (timeField.value.length != 0))
		 		transform = "true";
		}
		UpdateDate(form, fieldName, dateFieldName, timeFieldName, type, lang, optional, transform);
	}
}

// This function updates a field with a date field and a time field.
function UpdateDate(form, fieldName, dateFieldName, timeFieldName, type, lang, optional, transform, length)
{
	var field = form.elements[fieldName];
	var dateField = form.elements[dateFieldName];
	var timeField = form.elements[timeFieldName];
	var value = "";

	if (currentDate == null)
		currentDate = new Date();
	dateLang = lang;

	if (transform != "false")
		TransformCurrentDate(dateField, optional);

	// check if the value of the date is Y2K compliant
	// and modify it if needed.
	if (dateField != null)
	{
		var dateValue = dateField.value;
		if (dateValue != null)
		{
			var yearStr = dateValue.substring(dateValue.lastIndexOf("/") + 1);
			var d = new Date("01/01/" + yearStr);

			yearStr = removeLeadingZeros(yearStr);
			var year = parseInt(yearStr);

			if ((year < 1000) && (length < 10)) // case of a date lower than 1000
			{
				// If lower than 20 consider it is 20xx
				if (year < 10)
					year = "200" + year;
				if (year < 20)
					year = "20" + year;
				// If lower than 100 but greater than 10 it is 19xx
				else if (year < 100)
					year = "19" + year;
				// If lower than 1000 it is 0xxx
				else if (year < 1000)
					year = "0" + year;

				// create the new value for the field
				var str = dateValue.substring(0,dateValue.lastIndexOf("/"));
				str = str+"/"+year;
				dateField.value = str;
				StorePreviousValue(dateField);
			}
		}
	}

	// FFT00099 : if date is optional do not fill the time fields
	if ((transform == "true"))
	{
		if ((timeField != null) && (timeField.value == ""))
			timeField.value = GetDefaultTime(type);
	}


	if (field != null)
	{
		if (dateField != null)
			value = dateField.value;

		if (timeField != null)
		{
			// If date and time are not null, add a space between the values
			if ((value.length != 0) && (timeField.value.length != 0))
				value += " ";

			value += timeField.value;
		}
	}

	// Notify new value only if it has changed
	var notify = false;

	if (field.value != value)
		notify = true;

	field.value = value;

	var checkDateField = form.elements['_checkDate' + fieldName];

	if (notify && (checkDateField != null))
	{
		var checkDateValue = checkDateField.value;

		FieldChange(form, field, checkDateValue);
	}
}

// This function returns the current time
function GetCurrentTime(type)
{
	var date = new Date();
	var hours;
	var minutes;
	var seconds;
	var result;

	hours = date.getHours();
	minutes = date.getMinutes();
	seconds = date.getSeconds();

	if (hours < 10)
		hours = '0' + hours;
	if (minutes < 10)
		minutes = '0' + minutes;
	if (seconds < 10)
		seconds = '0' + seconds;

	if ((type == "DATE_TIME") || (type == "TIME"))
		// DATE_TIME or TIME
		result = hours + ":" + minutes + ":" + seconds;
	else if ((type == "DATE_HOUR_MIN") || (type == "HOUR_MIN"))
		// DATE_HOUR_MIN or HOUR_MIN
		result = hours + ":" + minutes;
	else
		// HOUR
		result = hours;

	return result;
}

// This function returns the current time
function GetDefaultTime(type)
{
	var date = new Date();
	var hours;
	var minutes;
	var seconds;
	var result;

	hours = date.getHours();
	minutes = date.getMinutes();
	seconds = date.getSeconds();

	if (hours < 10)
		hours = "0" + hours;

	if (minutes < 10)
		minutes = "0" + minutes;

	if (seconds < 10)
		seconds = "0" + seconds;

	if ((type == "DATE_TIME") || (type == "TIME"))
		// DATE_TIME or TIME
		result = hours + ":" + minutes + ":" + seconds;
	else if ((type == "DATE_HOUR_MIN") || (type == "HOUR_MIN"))
		// DATE_HOUR_MIN or HOUR_MIN
		result = hours + ":" + minutes;
	else
		// HOUR
		result = hours;

	return result;
}

// This function stores the previous value of a date input
function StorePreviousValue(dateInput)
{
	if (typeof previousValues == "undefined")
		previousValues = new Array();
	previousValues[dateInput.name] = dateInput.value;
}

// retrieves the previous value for a given date field
function GetPreviousValue(dateInputName)
{
	return previousValues[dateInputName];
}
