/**
 * JavaScript file for popup calendar.
 *
 * TODO: Write this properly. Ah, the folly of youth. :(
 */

var popup_calendar, switch_calendar, return_date, popup_calendar_today;

function popup_calendar( html_root, field )
{
	field = document.getElementById( field );
	if ( field )
	{
		var date = ( field.value !== '' ? field.value : '' );
		if ( date !== '' )
		{
			date = date.split('/');
			date = date[0] + '-' + date[1] + '-' + date[2];
		}
		var popup_calendar = window.open( html_root + '/pub/popup_calendar/popup_calendar.php?field=' + field.id + '&date=' + date, 'popup_calendar', 'width=300,height=220,menubar=0,status=0,scrollbars=0,location=0,resizable=0,directories=0' );
		if ( popup_calendar )
			popup_calendar.focus( );
		else
			alert( 'Could not open window - are you blocking popups? You can enter the date manually if you wish.' );
	}
	else
		alert( 'Unknown error. Please input date manually and contact your web developer.' );
	return false;
}

function switch_calendar( year, month )
{
	var year = document.getElementById( 'year' ).value;
	var month = document.getElementById( 'month' ).value;
	var field = document.getElementById( 'field' ).value;
	document.forms.date.submit( );
	return false;
}

function return_date( day )
{
	if ( window.opener )
	{
		if ( window.opener.closed )
			alert( 'You seem to have closed the window in which you clicked the calendar!' );
		else
		{
			var year = document.getElementById( 'year' ).value;
			var month = document.getElementById( 'month' ).value;
			var field = document.getElementById( 'field' ).value;
			var date = day + '/' + month + '/' + year;
			field = window.opener.document.getElementById( field );
			if ( field ) {
				field.value = date;
                if (field.fireEvent) {
                    field.fireEvent("change");
                }
			} else {
				alert( 'Unknown error! Please input date manually and contact your web developer.' );
            }
			window.close( );
		}
	}
	else
		alert( 'You should only get to this page by clicking a calendar icon.' )
	return false;
}

popup_calendar_today = function (fieldName) {
    var date = new Date(),
        dateString = "",
        field = document.getElementById(fieldName);
    dateString = (date.getDate()) + '/' + (date.getMonth() + 1) + '/' + (date.getFullYear());
    if (field) {
        field.value = dateString;
        if (field.onchange) {
            field.onchange();
        }
    }
    return true;
}
