/********************************************************************
This work is licensed under the Creative Commons NonCommercial-
ShareAlike License. To view a copy of this license, visit 
http://creativecommons.org/licenses/nc-sa/1.0 

The software is provided "as is" and "with all faults." The author makes 
no representations or warranties of any kind concerning the quality, 
accuracy or suitability of the software, either express or implied.
********************************************************************/


/*
 * Initialize the page after onLoad
 */
function init()
{
	var currentDate = new Date();
	
	document.getElementById(FLD_CAL_MONTH).selectedIndex = currentDate.getMonth();
	buildYearSelectionList();
	
	var calType = checkCalendarType();
	setCalendarType(calType);
	
	document.getElementById(FLD_CAL_CALENDAR).innerHTML = ZCalendar.buildCalendar(new Date());
	
	var cal = ZCalendar.getCalendar();
	
	document.getElementById(FLD_DATE).value = "01-01-1960";
	document.getElementById(FLD_YEAR).value = currentDate.getFullYear();
	
	buildSelectionList(document.getElementById(FLD_ROJ), getRojOptionList(cal), false);
	buildSelectionList(document.getElementById(FLD_MAH), cal.MAH, false);
	var conversionType = document.conversionForm.conversionType.value;
	setConversionType(conversionType);
	
	
}


// check url arguments or cookie for calendar type
function checkCalendarType() {
	var url = window.location.href;
	var urlArg = "calendar=";
	var calPos = url.indexOf(urlArg);
	if (calPos > -1) {
		calType = url.substring(calPos+urlArg.length);
	}
	else {
		calType = Preferences.getPreference("calendar", ZCalendar.SHENSHAI);
	}
	return calType;
}

// switch page to the given calendar type
function setCalendarType(calType) {
	ZCalendar.setCalendarType(calType);
	Preferences.setPreference('calendar', calType);

	// since this page handles shenshai, fasli, etc. calendar types, switch the
	// display text depending on the calendar type selected.  Search for
	// any span tags with class=calendarType.
	var elems = document.getElementsByTagAndClassName("span", "calendarType");
	for (var i=0; i< elems.length; i++) {
		elems[i].innerHTML = calType.capitalize();
	}
}

/*
 * Clear conversion form.
 * Set fields back to thier default state, clear result area, etc.
 */
function clear()
{
	var currentDate = new Date();
	document.getElementById(FLD_RESULT).innerHTML = "";
	clearFormErrors(FIELDS);
	document.getElementById(FLD_DATE).value = "01-01-1960";
	document.getElementById(FLD_YEAR).value = currentDate.getFullYear();
	document.getElementById("conversionForm").rojList.selectedIndex = 0;
	document.getElementById("conversionForm").mahList.selectedIndex = 0;
}

/*
 * Clear form errors.
 * Iterate through an array of fields, resetting the fields to their
 * original state.
 * param - fields: an array of field IDs to reset
 */
function clearFormErrors(fields) {
	for (i=0; i<fields.length; i++) {
		document.getElementById(fields[i]+"Ast").style.color = FLD_COLOR_NORM;
     	document.getElementById(fields[i]+"Lbl").style.color = FLD_COLOR_NORM;
     	document.getElementById(fields[i]+"Help").style.color = FLD_COLOR_NORM;
     	document.getElementById(fields[i]+"Help").innerHTML = FIELD_HELP[i];
     }
}

/*
 * Set error message for a field.
 * Displays field in red, and shows error message in field help area.
 * param - aField: field name to set error
 * param - aMsg: the error message to display
 */
function setFieldError(aField, aMsg) {
	document.getElementById(aField+"Ast").style.color = FLD_COLOR_ERR;
    document.getElementById(aField+"Lbl").style.color = FLD_COLOR_ERR;
    document.getElementById(aField+"Help").style.color = FLD_COLOR_ERR;
    document.getElementById(aField+"Help").innerHTML = aMsg;
}

/*
 * Display the calendar for selected month & year
 */
function displayCalendar() {
	var month = document.getElementById(FLD_CAL_MONTH).value;
	var year = document.getElementById(FLD_CAL_YEAR).value;
	var aDate = new Date(year, month, 1);
	var s = ZCalendar.buildCalendar(aDate);
	document.getElementById(FLD_CAL_CALENDAR).innerHTML = s;
}

/*
 * Validates form fields for Date to Roj conversion
 */
function validateDateToRoj() 
{
	var checkStatus = true;
	var aField;
	
	// check that the date field has a value
	var aField = document.getElementById(FLD_DATE);
	if((aField == null) || (aField.value == ""))
     {
		setFieldError(FLD_DATE, "Please enter a date in the format 'mm-dd-yyyy'");
          checkStatus = false;
     }  
     // check that the date is a valid date format
	if (!checkDate(aField.value)) {
		setFieldError(FLD_DATE, "The date you entered was not valid.  Please enter a date in the format 'mm-dd-yyyy'");
		checkStatus = false;
	}
	
	// check that the year field has a value
	aField = document.getElementById(FLD_YEAR);
	if((aField == null) || (aField.value == "") || !isInteger(aField.value))
     {
		setFieldError(FLD_YEAR, "Please enter the year for which you want to find the roj.");
          checkStatus = false;
     }  
     
	// check the year is after the epoch year
	var calendar = ZCalendar.getCalendar();
	if (Number(aField.value) < calendar.EPOCH_YEAR)
     {
		setFieldError(FLD_YEAR, "Please enter a year after " + calendar.EPOCH_YEAR);
          checkStatus = false;
     }     
     
     return checkStatus;
}

/*
 * Validates form fields for Roj to Date conversion
 */
function validateRojToDate() {
	var checkStatus = true;
	var aField;
	
	// check if roj field has a value
	var aField = document.getElementById(FLD_ROJ);
	if((aField == null) || (aField.selectedIndex == 0))
     {
		setFieldError(FLD_ROJ, "Please select a roj.");
          checkStatus = false;
     }  
	
	// check if mah field has a value
	aField = document.getElementById(FLD_MAH);
	if((aField == null) || (aField.selectedIndex == 0))
     {
		setFieldError(FLD_MAH, "Please select a mah.");
          checkStatus = false;
     }  
     
     // check that year field has a value and is an integer
     aField = document.getElementById(FLD_YEAR);
	if((aField == null) || (aField.value == "") || !isInteger(aField.value))
     {
		setFieldError(FLD_YEAR, "Enter the year for which you would like to determine when the roj occurs (yyyy).");
          checkStatus = false;
     }  
     
     // check that year is after the epoch year
    var calendar = ZCalendar.getCalendar();
	if (Number(aField.value) < calendar.EPOCH_YEAR)
     {
		setFieldError(FLD_YEAR, "Please enter a year after " + calendar.EPOCH_YEAR);
          checkStatus = false;
     }     
     
     return checkStatus;
}

/*
 * Handles submission of the conversionForm.
 * Checks the conversion type, and based on type, delegates
 * form processing to helper methods.
 */
function conversionFormSubmit() {
	isConvertDateToRoj = document.conversionForm.conversionType.value=="DateToRoj";
	if (isConvertDateToRoj == true)	{
		dateToRojFormSubmit();
	}
	else {
		rojToDateFormSubmit();
	}
}

/*
 * Handles submission of conversionForm for Date to Roj conversions.
 */
function dateToRojFormSubmit() {
	
	var msg;
	var dmPair;
	inputVal = document.getElementById("conversionForm").fld_date.value;
	inputYear = document.getElementById("conversionForm").fld_year.value;
	
	// clear the result field
	document.getElementById(FLD_RESULT).innerHTML = "";
	// clear any existing errors
	clearFormErrors(FIELDS);
	
	// validate the form entry
	if (!validateDateToRoj()) {
		return;
	}
	var inputDate = Date.parseDate(inputVal);
	
	// calculate the roj, based on the given date and year
	var calendar = ZCalendar.getCalendar();
	
	var rojInfo = calendar.convertDateToRojInYear(inputDate, inputYear);
	
	msg = rojInfo.toFullString();
	
	// show the result
	document.getElementById(FLD_RESULT).innerHTML = msg;
}


/*
 * Handles submission of conversionForm for Roj to Date conversions.
 */
function rojToDateFormSubmit() {
	var msg;
	var conversionForm = document.getElementById("conversionForm");
	var roj = conversionForm.rojList.value;
	var mah = conversionForm.mahList.value;
	var year = conversionForm.fld_year.value;
	rojName = conversionForm.rojList[conversionForm.rojList.selectedIndex].text;
	mahName = conversionForm.mahList[conversionForm.mahList.selectedIndex].text;
	
	// GATHAS days start with an asterisk in our select list, 
	// so check for that and strip it off
	if (rojName.indexOf("*")==0) {
		rojName = rojName.substring(1, rojName.length);
		mahName = null;
	}
	
	// clear the result field
	document.getElementById(FLD_RESULT).innerHTML = "";
	// clear any existing form errors
	clearFormErrors(FIELDS);
	
	// validate form entry
	if (!validateRojToDate()) {
		return;
	}
	
	// calculate the date, given the roj index, mah index, and year
	var calendar = ZCalendar.getCalendar();
	var result = calendar.convertRojToDateInYear(rojName, mahName, year);
	
	// build the result message
	// if the roj index > 30, then it's a gatha and has no mah
	var zcalDate = "";
	if (roj >= 30) {
		zcalDate = new ZCalendar.CalendarDate(rojName, null, null, result);
	}
	else {
		zcalDate = new ZCalendar.CalendarDate(rojName, mahName, null, result);
	}
		
	// display the result
	document.getElementById(FLD_RESULT).innerHTML = zcalDate.toFullString();
}

/*
 * Builds a year selection list.
 * Selection list spans 20 years (10 before, 10 after current year).
 * Current year is selected by default.
 */
function buildYearSelectionList() {
	var YEARS_BEHIND = 100;
	var YEARS_AHEAD = 20;
	var yearList = new Array();
	aField = document.getElementById(FLD_CAL_YEAR);
	var currentDate = new Date();
	var currentYear = currentDate.getFullYear();
	var yearCounter = Math.floor(currentYear - YEARS_BEHIND);
	var yearRange = YEARS_BEHIND + YEARS_AHEAD;
	for (i = 0; i < yearRange; i++) {
		if (yearCounter == currentYear) {
			aField.options[i] = new Option(yearCounter, yearCounter, true);
			aField.options[i].selected = true; // set the current year (for IE)
		}
		else {
			aField.options[i] = new Option(yearCounter, yearCounter);
		}
		yearCounter++;
	}
}

/*
 * Build a Roj option list.
 */
function getRojOptionList(calendar) {
	var rojList = new Array();
	for (var i = 0; i < calendar.ROJ.length; i++) {
		rojList.push(calendar.ROJ[i]);
	}
	
	for (j=0; j < calendar.GATHAS.length; j++) {
		rojList.push("*" + calendar.GATHAS[j]);
	}
	return rojList;
}

/*
 * Builds a selection list for a given field using a given array
 * of values.
 * param - aField: the selection field to add options to
 * param - aList: a list of values to add as options
 */
function buildSelectionList(aField, aList) {
	aField[0] = new Option("-- Please Select --", "");
	for (i = 0; i < aList.length; i++) 
	{
		aField[i+1] = new Option(aList[i], aList[i]);
	}
}

/*
 * Sets an option with the given value as selected on a selection field
 * param - aField: the selection field
 * param - aValue: the value to set as selected
 */
function setSelectionValue(aField, aValue) {
	var selectIndex = 0;
	for (i = 0; i < aField.length; i++) {
		if (aField.options[i].value == aValue) {
			selectIndex = i;
			break;
		}
	}
	aField.selectedIndex = selectIndex;
}

function setConversionType(conversionType) {
	if (conversionType == null) conversionType = "DateToRoj"; //default value

	if (conversionType == "DateToRoj") {
		document.conversionForm.conversionType.value = conversionType;
		Element.addClassName('DateToRojTab', 'active');
		Element.removeClassName('RojToDateTab', 'active');
	} else {
		document.conversionForm.conversionType.value = conversionType;
		Element.removeClassName('DateToRojTab', 'active');
		Element.addClassName('RojToDateTab', 'active');
	}
	toggleConversionFields(conversionType);
}

/*
 * Toggles form fields in the conversion form based on conversion type
 * param - selection: the conversion type
 */
function toggleConversionFields(selection) 
{
	var hidden = 'none';
	var display = 'table-row';
	
	// a little hack for IE
	if (document.all) 
	{
		hidden = 'none';
		display = 'block';
	}
	if (selection == 'RojToDate')
	{
		document.getElementById('rojRow').style.display = display;
		document.getElementById('mahRow').style.display = display;
		document.getElementById('dateRow').style.display = hidden;
	}
	else
	{
		document.getElementById('rojRow').style.display = hidden;
		document.getElementById('mahRow').style.display = hidden;
		document.getElementById('dateRow').style.display = display;
	}
	document.getElementById(FLD_RESULT).innerHTML = "";
}
