// If enter is pressed, submit the form with given name.
function handleKeyPress(formName, e) {
    var enter = (document.all || document.layers || document.getElementById) ? IsEnter(e) : IsEnter(window.event);
	if (enter) {
		submitFormAndAction(formName, '');
		return true;
	}
	return false;
}
// If enter is pressed, set the action and submit the form with given name.
function handleKeyPressAndAction(formName, action, e) {
    var enter = (document.all || document.layers || document.getElementById) ? IsEnter(e) : IsEnter(window.event);
	if (enter) {
		submitFormAndAction(formName, action);
		return true;
	}
	return false;
}
// Return true if the enter key was pressed, false otherwise.
function IsEnter(e) {
	var Character = (navigator.appName =="Netscape") ? e.which : e.keyCode
	if (Character==13) return true
	return false
}


/***************************** TextTag, TextAreaTag */

// Check if an input field has a value and display an image if not
// Used by the InputTextFieldTag
function checkRequired(field, property, asteriks, no_asteriks, required) {
	if (required) {
	    if (field.value=="") {
            	document.images[property].src=asteriks;
            } else {
		 document.images[property].src=no_asteriks;
	    }
    }
}

/****************************** SelectTag */

function checkRequiredOnValue(field, property, asteriks, no_asteriks, required,value) {
	if (required) {
	    if (field.value==value) {
            	document.images[property].src=asteriks;
            } else {
		 document.images[property].src=no_asteriks;
	    }
    }
}

/***************************** TextAreaTag */

function checkMaxLength(textarea, maxLength, message) {
    var msg = textarea.value;
    var msgLength= msg.length;
    //maximum length
    if (msgLength > maxLength){
        textarea.value=msg.substring(0,maxLength);
        if (message != null && ''!=message) {
           alert(message);
        }
    }
}

function checkMaxLengthOnKeyPress(textarea, maxLength) {
    var msg = textarea.value;
    var msgLength= msg.length;
    //maximum length
    if (msgLength >= maxLength){
        return window.event.returnValue=false;
    }
}


/***************************** NumberTag */

function signed_decimal_keypress() {
    if ((window.event.keyCode != 45) &&
        (window.event.keyCode != 43) &&
        (window.event.keyCode != 46) &&
        (window.event.keyCode != 44) &&
        ((window.event.keyCode < 48) || (window.event.keyCode > 57))
        ){
        window.event.returnValue=false
    }
}

// Disables non-numeric input
// Used by the InputNumberFieldTag when the mode is decimal
function decimal_keypress() {
	if ((window.event.keyCode != 46) && (window.event.keyCode != 44) && ((window.event.keyCode < 48) || (window.event.keyCode > 57))) {
		window.event.returnValue=false
	}
}

function signed_integer_keypress() {
    if ((window.event.keyCode != 45) &&
        (window.event.keyCode != 43) &&
        ((window.event.keyCode < 48) || (window.event.keyCode > 57))
        ) {
        window.event.returnValue=false
    }
}

// Disables non-numeric input
// Used by the InputNumberFieldTag when the mode is integer
function integer_keypress() {
	if ((window.event.keyCode < 48) || (window.event.keyCode > 57)) {
		window.event.returnValue=false
	}
}


/***************************** DateTag */

// Title: Tigra Calendar
// Description: See the demo at url
// URL: http://www.softcomplex.com/products/tigra_calendar/
// Version: 3.1 (European date format)
// Date: 08-08-2002 (mm-dd-yyyy)
// Feedback: feedback@softcomplex.com (specify product title in the subject)
// Note: Permission given to use this script in ANY kind of applications if
//    header lines are left unchanged.
// Note: Script consists of two files: calendar?.js and calendar.jsp
// if two digit year input dates after this year considered 20 century.
function dummy() {}

function popupDatePicker(host,path,format,styleClass, mode, e) {
    //IMPORTANT : works with calendar1.js!!!!!!!!!AND ConvertDate.js!!!!!!!!!
    //host = field that is used as container for the date, format is desired format
    //      create calendar object(s) just after form tag closed
    //      specify form element as the only parameter (document.forms['formname'].elements['inputname']);
    //      note: you can have as many calendar objects as you need for your application
    if (!host) return;
    var cal1 = new calendar(host,path,mode);
    cal1.popup(host.value,format,styleClass, e);
}

var NUM_CENTYEAR = 30;
// is time input control required by default
var BUL_TIMECOMPONENT = false;
// are year scrolling buttons required by default
var BUL_YEARSCROLL = true;

var calendars = [];
var RE_NUM = /^\-?\d+$/;

var date_window;


function calendar(obj_target, path, calendarmode) {
    this.Path = path;

	// assing methods
	this.gen_date = cal_gen_date1;
	this.gen_time = cal_gen_time1;
	this.gen_tsmp = cal_gen_tsmp1;
	this.prs_date = cal_prs_date1;
	this.prs_time = cal_prs_time1;
	this.prs_tsmp = cal_prs_tsmp1;
	this.popup    = cal_popup1;
	this.error_timestamp = 'invalid time format';
	this.error_date = 'invalid date format';

	// validate input parameters
	if (!obj_target)
		return cal_error("Error calling the calendar: no target control specified");
	if (obj_target.value == null)
		return cal_error("Error calling the calendar: parameter specified is not valid tardet control");
	this.target = obj_target;
	this.mode = calendarmode;
	if (calendarmode == 'datetime' || calendarmode =='timestamp') {
	    this.time_comp = true;
	} else {
	    this.time_comp = false;
    }
	this.year_scroll = BUL_YEARSCROLL;
	if (date_window) date_window.close()

    date_window = 'no_window';

	// register in global collections
	this.id = calendars.length;
	calendars[this.id] = this;
}

function cal_popup1 (str_datetime, format, styleClass, e, anchor) {
	this.dt_current = this.prs_tsmp(str_datetime, format);
	if (!this.dt_current) return;
	if (str_datetime.length == 0) {
		var today = new Date();
		this.dt_current = today;
	}
	var location = this.Path + 'datepicker.jsp?'+
                    'dateFormat='+format+
                    '&styleClass='+styleClass+
                    '&datetime=' + this.dt_current.valueOf()+
                    '&id=' + this.id;
	if (date_window!='no_window') {
	    date_window.location.href = location;

    } else {
        var winwidth = 200;
        var winheight = (this.time_comp ? 205 : 175);
        var winLeft = 0; // center the window right to left
        var winTop = 0; // center the window top to bottom
        var margin = 60;
        if (e != '' & e != 'no_event') {
            if (navigator.userAgent.indexOf('Opera') > -1) {
                 winLeft = 20;
                 winTop = 20;
            } else {
                winLeft = e.screenX;
                winTop = e.screenY;
            }
            if (winLeft > (screen.width - winwidth)) {
                winLeft = (screen.width - winwidth) - 10;
            }
            if (winTop > (screen.height - winheight - margin)) {
                winTop = (screen.height - winheight) - margin
            }
        }
        date_window = window.open(
            location,
            'Calendar', 'width='+winwidth+',height='+winheight+
            ',status=no,resizable=yes,top='+winTop+',left='+winLeft+',dependent=yes,alwaysRaised=yes'
        );
    }
	date_window.opener = window;
	date_window.focus();

}

// timestamp generating function
function cal_gen_tsmp1 (dt_datetime) {
	return(this.gen_date(dt_datetime) + ' ' + this.gen_time(dt_datetime));
}

// date generating function
function cal_gen_date1 (dt_datetime) {
	return (
		(dt_datetime.getDate() < 10 ? '0' : '') + dt_datetime.getDate() + "-"
		+ (dt_datetime.getMonth() < 9 ? '0' : '') + (dt_datetime.getMonth() + 1) + "-"
		+ dt_datetime.getFullYear()
	);
}
// time generating function
function cal_gen_time1 (dt_datetime) {
	return (
		(dt_datetime.getHours() < 10 ? '0' : '') + dt_datetime.getHours() + ":"
		+ (dt_datetime.getMinutes() < 10 ? '0' : '') + (dt_datetime.getMinutes()) + ":"
		+ (dt_datetime.getSeconds() < 10 ? '0' : '') + (dt_datetime.getSeconds())
	);
}

// timestamp parsing function
function cal_prs_tsmp1 (str_datetime, format) {
	// if no parameter specified return current timestamp
	if (!str_datetime)
		return (new Date());

	// if positive integer treat as milliseconds from epoch
	if (RE_NUM.exec(str_datetime))
		return new Date(str_datetime);

	// else treat as date in string format
	var arr_datetime = str_datetime.split(' ');
	return this.prs_time(arr_datetime[1], this.prs_date(arr_datetime[0], format));
}

// date parsing function
function cal_prs_date1 (str_date, format) {

	//date always to parse in format 'dd-MM-yyyy' so that the dateppicker can handle
	//and put picker on correct initial date

    var convertedDate = "";
    var strDateFinal = "";

    if (format)
    {
        convertedDate = convertDate(str_date, format, 'dd-MM-yyyy');
        strDateFinal = convertedDate;
    }
    else
    {
        strDateFinal = str_date;
    }

	//return new Date();			//voorlopig op datum van vandaag

	//var arr_date = str_date.split('-');
    var arr_date = strDateFinal.split('-');

	if (arr_date.length != 3) return cal_error (this.error_date);
	if (!arr_date[0]) return cal_error (this.error_date);
	if (!RE_NUM.exec(arr_date[0])) return cal_error (this.error_date);
	if (!arr_date[1]) return cal_error (this.error_date);
	if (!RE_NUM.exec(arr_date[1])) return cal_error (this.error_date);
	if (!arr_date[2]) return cal_error (this.error_date);
	if (!RE_NUM.exec(arr_date[2])) return cal_error (this.error_date);

	var dt_date = new Date();
	dt_date.setDate(1);

	if (arr_date[1] < 1 || arr_date[1] > 12) return cal_error (this.error_date);
	dt_date.setMonth(arr_date[1]-1);

	if (arr_date[2] < 100) arr_date[2] = Number(arr_date[2]) + (arr_date[2] < NUM_CENTYEAR ? 2000 : 1900);
	dt_date.setFullYear(arr_date[2]);

	var dt_numdays = new Date(arr_date[2], arr_date[1], 0);
	dt_date.setDate(arr_date[0]);
	if (dt_date.getMonth() != (arr_date[1]-1)) return cal_error (this.error_date);

	return (dt_date)
}

// time parsing function
function cal_prs_time1 (str_time, dt_date) {
	if (!dt_date) return null;
	var arr_time = String(str_time ? str_time : '').split(':');
	if (!arr_time[0]) dt_date.setHours(0);
	else if (RE_NUM.exec(arr_time[0]))
		if (arr_time[0] < 24) dt_date.setHours(arr_time[0]);
		else {
		    return cal_time_error(dt_date, this.error_timestamp);
		}
	else {
	    return cal_time_error(dt_date, this.error_timestamp);
    }
	if (!arr_time[1]) dt_date.setMinutes(0);
	else if (RE_NUM.exec(arr_time[1]))
		if (arr_time[1] < 60) dt_date.setMinutes(arr_time[1]);
		else {
		    return cal_time_error(dt_date, this.error_timestamp);
		}
	else {
	    return cal_time_error(dt_date, this.error_timestamp);
	}
	if (!arr_time[2]) dt_date.setSeconds(0);
	else if (RE_NUM.exec(arr_time[2]))
		if (arr_time[2] < 60) dt_date.setSeconds(arr_time[2]);
		else {
		    return cal_time_error(dt_date, this.error_timestamp);
		}
	else {
	    return cal_time_error(dt_date, this.error_timestamp);
	}
	dt_date.setMilliseconds(0);
	return dt_date;
}


function cal_time_error(dt_date, message) {
    alert(message);
	dt_date.setHours(0);
	dt_date.setMinutes(0);
	dt_date.setSeconds(0);
	dt_date.setMilliseconds(0);
	return dt_date;
}

function cal_error (str_message) {
	alert(str_message);
}

// ------------------------------------------------------------------
//  CONVERT FUNCTIONS
//  convert date to any valid format (d, M, y)
//  ex: x = convertDate('02-10-2002', 'dd-MM-yyyy', 'dd/MM/yyyy')
//      returns 02/10/2002
// ------------------------------------------------------------------


var MONTH_NAMES=new Array('January','February','March','April','May','June','July','August','September','October','November','December');
var SHORTMONTH_NAMES=new Array('JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC');
function LZ(x) {return(x<0||x>9?"":"0")+x}


// ------------------------------------------------------------------
// returns a date in correct format
// odate = date to convert as string
// oformat is the format of odate
// newformat is the format tobe
// ------------------------------------------------------------------
function convertDate(odate, oformat, newformat) {
    var dateToFormat = getDateFromFormat(odate, oformat)
	return formatDate( new Date(dateToFormat), newformat );
}
// ------------------------------------------------------------------
// isDate ( date_string, format_string )
// Returns true if date string matches format of format string and
// is a valid date. Else returns false.
// It is recommended that you trim whitespace around the value before
// passing it to this function, as whitespace is NOT ignored!
// ------------------------------------------------------------------
function isDate(val,format) {
	var date=getDateFromFormat(val,format);
	if (date==0) { return false; }
	return true;
}
// ------------------------------------------------------------------
// formatDate (date_object, format)
// Returns a date in the output format specified.
// The format string uses the same abbreviations as in getDateFromFormat()
// ------------------------------------------------------------------
function formatDate(date,format) {
	format=format+"";
	var result="";
	var i_format=0;
	var c="";
	var token="";
	var y=date.getYear()+"";
	var M=date.getMonth()+1;
	var d=date.getDate();
	var H=date.getHours();
	var m=date.getMinutes();
	var s=date.getSeconds();
	var yyyy,yy,MMM,MM,dd,hh,h,mm,ss,ampm,HH,H,KK,K,kk,k;
	// Convert real date parts into formatted versions
	var value=new Object();
	if (y.length < 4) {y=""+(y-0+1900);}
	value["y"]=""+y;
	value["yyyy"]=y;
	value["yy"]=y.substring(2,4);
	value["M"]=M;
	value["MM"]=LZ(M);
	value["MMM"]=SHORTMONTH_NAMES[M-1];
	value["d"]=d;
	value["dd"]=LZ(d);
	value["H"]=H;
	value["HH"]=LZ(H);
	if (H==0){value["h"]=12;}
	else if (H>12){value["h"]=H-12;}
	else {value["h"]=H;}
	value["hh"]=LZ(value["h"]);
	if (H>11){value["K"]=H-12;} else {value["K"]=H;}
	value["k"]=H+1;
	value["KK"]=LZ(value["K"]);
	value["kk"]=LZ(value["k"]);
	if (H > 11) { value["a"]="PM"; }
	else { value["a"]="AM"; }
	value["m"]=m;
	value["mm"]=LZ(m);
	value["s"]=s;
	value["ss"]=LZ(s);
	while (i_format < format.length) {
		c=format.charAt(i_format);
		token="";
		while ((format.charAt(i_format)==c) && (i_format < format.length)) {
			token += format.charAt(i_format++);
			}
		if (value[token] != null) { result=result + value[token]; }
		else { result=result + token; }
		}
	return result;
}

// ------------------------------------------------------------------
// Utility functions for parsing in getDateFromFormat()
// ------------------------------------------------------------------
function _isInteger(val) {
	var digits="1234567890";
	for (var i=0; i < val.length; i++) {
		if (digits.indexOf(val.charAt(i))==-1) { return false; }
		}
	return true;
}
function _getInt(str,i,minlength,maxlength) {
	for (var x=maxlength; x>=minlength; x--) {
		var token=str.substring(i,i+x);
		if (token.length < minlength) { return null; }
		if (_isInteger(token)) { return token; }
		}
	return null;
}

// ------------------------------------------------------------------
// getDateFromFormat( date_string , format_string )
//
// This function takes a date string and a format string. It matches
// If the date string matches the format string, it returns the
// getTime() of the date. If it does not match, it returns 0.
// ------------------------------------------------------------------
function getDateFromFormat(val,format) {
	val=val+"";
	format=format+"";
	var i_val=0;
	var i_format=0;
	var c="";
	var token="";
	var token2="";
	var x,y;
	var now=new Date();
	var year=now.getYear();
	var month=now.getMonth()+1;
	var date=now.getDate();
	var hh=now.getHours();
	var mm=now.getMinutes();
	var ss=now.getSeconds();
	var ampm="";

	while (i_format < format.length) {
		// Get next token from format string
		c=format.charAt(i_format);
		token="";
		while ((format.charAt(i_format)==c) && (i_format < format.length)) {
			token += format.charAt(i_format++);
			}
		// Extract contents of value based on format token
		if (token=="yyyy" || token=="yy" || token=="y") {
			if (token=="yyyy") { x=4;y=4; }
			if (token=="yy")   { x=2;y=2; }
			if (token=="y")    { x=2;y=4; }
			year=_getInt(val,i_val,x,y);
			if (year==null) { return 0; }
			i_val += year.length;
			if (year.length==2) {
				if (year > 70) { year=1900+(year-0); }
				else { year=2000+(year-0); }
				}
			}
		else if (token=="MMM"){
			month=0;
			for (var i=0; i<SHORTMONTH_NAMES.length; i++) {
				var month_name=SHORTMONTH_NAMES[i];
				if (val.substring(i_val,i_val+month_name.length).toLowerCase()==month_name.toLowerCase()) {
					month=i+1;
					if (month>12) { month -= 12; }
					i_val += month_name.length;
					break;
					}
				}
			if ((month < 1)||(month>12)){return 0;}
			}
		else if (token=="MM"||token=="M") {
			month=_getInt(val,i_val,token.length,2);
			if(month==null||(month<1)||(month>12)){return 0;}
			i_val+=month.length;}
		else if (token=="dd"||token=="d") {
			date=_getInt(val,i_val,token.length,2);
			if(date==null||(date<1)||(date>31)){return 0;}
			i_val+=date.length;}
		else if (token=="hh"||token=="h") {
			hh=_getInt(val,i_val,token.length,2);
			if(hh==null||(hh<1)||(hh>12)){return 0;}
			i_val+=hh.length;}
		else if (token=="HH"||token=="H") {
			hh=_getInt(val,i_val,token.length,2);
			if(hh==null||(hh<0)||(hh>23)){return 0;}
			i_val+=hh.length;}
		else if (token=="KK"||token=="K") {
			hh=_getInt(val,i_val,token.length,2);
			if(hh==null||(hh<0)||(hh>11)){return 0;}
			i_val+=hh.length;}
		else if (token=="kk"||token=="k") {
			hh=_getInt(val,i_val,token.length,2);
			if(hh==null||(hh<1)||(hh>24)){return 0;}
			i_val+=hh.length;hh--;}
		else if (token=="mm"||token=="m") {
			mm=_getInt(val,i_val,token.length,2);
			if(mm==null||(mm<0)||(mm>59)){return 0;}
			i_val+=mm.length;}
		else if (token=="ss"||token=="s") {
			ss=_getInt(val,i_val,token.length,2);
			if(ss==null||(ss<0)||(ss>59)){return 0;}
			i_val+=ss.length;}
		else if (token=="a") {
			if (val.substring(i_val,i_val+2).toLowerCase()=="am") {ampm="AM";}
			else if (val.substring(i_val,i_val+2).toLowerCase()=="pm") {ampm="PM";}
			else {return 0;}
			i_val+=2;}
		else {
			if (val.substring(i_val,i_val+token.length)!=token) {return 0;}
			else {i_val+=token.length;}
			}
		}
	// If there are any trailing characters left in the value, it doesn't match
	if (i_val != val.length) { return 0; }
	// Is date valid for month?
	if (month==2) {
		// Check for leap year
		if ( ( (year%4==0)&&(year%100 != 0) ) || (year%400==0) ) { // leap year
			if (date > 29){ return false; }
			}
		else { if (date > 28) { return false; } }
		}
	if ((month==4)||(month==6)||(month==9)||(month==11)) {
		if (date > 30) { return false; }
		}
	// Correct hours value
	if (hh<12 && ampm=="PM") { hh=hh-0+12; }
	else if (hh>11 && ampm=="AM") { hh-=12; }
	var newdate=new Date(year,month-1,date,hh,mm,ss);
	return newdate.getTime();
}
