/**
 * DateSelector for date selecting in advanced searches
 *
 * The methods are in alphabetical order
 *
 * @version $Id: DateSelector.js 16704 2009-11-25 16:37:50Z sucec $
 * requires common.js
 *
 */
function DateSelector() {
	this.checkDate = checkDate;
	this.getDateString = getDateString;
	this.updateDate = updateDate;
	this.setAlertMsg = setAlertMsg;
	this.setFormName = setFormName;
	this.setDateValuesFrom = setDateValuesFrom;
	this.setDateValuesTo = setDateValuesTo;
	var alertMsg = "DATE_ERROR";
	var FIRST_YEAR = 2000;
	var FIRST_MONTH = 0;
	var LAST_MONTH = 12;
	var FIRST_DAY = 1;
	var LAST_DAY = 31;
	var QueryString = null;
	var formname = "searchform";
	var monthnames = new Array();
	
	initMonthArray();

	function checkDate() {
		// Get from date
		fromyear = document.forms[formname].startdate_yearfrom.value;
		frommonth = document.forms[formname].startdate_monthfrom.value;
		fromday = document.forms[formname].startdate_dayfrom.value;
		toyear = document.forms[formname].startdate_yearto.value;
		tomonth = document.forms[formname].startdate_monthto.value;
		today = document.forms[formname].startdate_dayto.value;
		
		// Check date
		var fDate = null, tDate = null;
		if( fromyear != '' && frommonth != '' && fromday != '') {
			fDate = new Date();
			fDate.setTime(Date.parse(fromyear+'/'+frommonth+'/'+fromday));
		}
		if( toyear != '' && tomonth != '' && today != '') {
			tDate = new Date();
			tDate.setTime(Date.parse(toyear+'/'+tomonth+'/'+today));
		}
		if( fDate != null && tDate != null ) {
			if( tDate < fDate ) { alert(alertMsg); }
		}
		
		var isFromYearFilled = (fromyear != null  && fromyear != '' && fromyear != '-');
		var isToYearFilled = (toyear != null && toyear != '' && toyear != '-');
		var isYearsEqual = (isFromYearFilled && isToYearFilled && fromyear*1 == toyear*1 );
		
		// Filtering 'to' values after checking 'from' - YEAR
		if( isFromYearFilled )
		{
			// Year update
			var d = new Date();
			var yearlm = getElements('to')['yearlm'];
			var selected = null;
			if ( isToYearFilled )
			{
				selected = toyear;
			}
			createYear(fromyear,d.getFullYear(),yearlm, selected);
		}
		
		// Filtering 'from' values after checking 'to' - YEAR
		if( isToYearFilled )
		{
			// Year update
			var d = new Date();
			var yearlm = getElements('from')['yearlm'];
			var selected = null;
			if ( isFromYearFilled && toyear*1 < fromyear*1 )
			{
				setSelectedItem(getElements('to')['yearlm'],fromyear);
			}
		}
		
		// If the years are filled and equal
		if ( isYearsEqual )
		{
			var isFromMonthFilled = ( frommonth != null && frommonth != '' && frommonth != '-' );
			var isToMonthFilled = ( tomonth != null && tomonth != '' && tomonth != '-' );
			var isMonthsEqual = ( isFromMonthFilled && isToMonthFilled && frommonth*1 == tomonth*1 );
			
			if ( isFromMonthFilled )
			{
				var monthlm = getElements('to')['monthlm'];
				var selected = null;
				if ( isToMonthFilled )
				{
					selected = tomonth;
				}
				createMonth(frommonth,LAST_MONTH,monthlm, selected);
			}
			
			if ( isToMonthFilled )
			{
				var monthlm = getElements('from')['monthlm'];
				var selected = null;
				if ( isFromMonthFilled && tomonth*1 < frommonth*1 )
				{
					setSelectedItem(getElements('to')['monthlm'],frommonth);
				}
			}
			
			// If the years and months are filled and equal
			if ( isMonthsEqual )
			{
				var selectedMonthId = monthlm.options[monthlm.selectedIndex].value;
				var daycount = getDayCountOfMonth(selectedMonthId, yearlm.options[yearlm.selectedIndex].text);
				var isFromDayFilled = ( fromday != null && fromday != '' && fromday != '-' );
				var isToDayFilled = ( today != null && today != '' && today != '-' );
				
				if ( isFromDayFilled )
				{
					var daylm = getElements('to')['daylm'];
					var selected = null;
					if ( isToDayFilled )
					{
						selected = today;
					}
					createDay(fromday, daycount, daylm, selected);
				}
				
				if ( isToDayFilled )
				{
					var daylm = getElements('from')['daylm'];
					var selected = null;
					if ( isFromDayFilled && today*1 < fromday*1 )
					{
						setSelectedItem(getElements('to')['daylm'],fromday);
					}
				}
			}else
			{
				var daycount = LAST_DAY;
				if( isToYearFilled )
				{
					var fromYearLm = getElements('from')['yearlm'];
					daycount = getDayCountOfMonth(selectedMonthId, fromYearLm.options[fromYearLm.selectedIndex].text);
				}
				var toDayLm = getElements('to')['daylm'];
				createDay(FIRST_DAY, daycount, toDayLm, toDayLm.options[toDayLm.selectedIndex].value);
			}
		}else
		{
			var toMonthLm = getElements('to')['monthlm'];
			createMonth(FIRST_MONTH,LAST_MONTH,toMonthLm,toMonthLm.options[toMonthLm.selectedIndex].value);
			
			var daycount = LAST_DAY;
			if( isToYearFilled )
			{
				var fromYearLm = getElements('from')['yearlm'];
				daycount = getDayCountOfMonth(selectedMonthId, fromYearLm.options[fromYearLm.selectedIndex].text);
			}
			var toDayLm = getElements('to')['daylm'];
			createDay(FIRST_DAY, daycount, toDayLm, toDayLm.options[toDayLm.selectedIndex].value);
		}
	}//end of checkDate

	/**
	 * Létrehozza a megadott elemre az éveket, a 'from' és 'to' évszámok zárt intervallumán, 
	 * valamint beállítja az alapértelmezett értéket, ha megadtuk.
	 */
	function createYear(from, to, element, selected) {
		element.length=0;
		element.options[0] = new Option("-");
		for (var i=1,j=to; j >= from ; i++, j--)
		{
			var y= String(j);
			element.options[i] = new Option(y,y);
			if( selected == y )
			{
				element.options[i].selected = true;
			}
		}
		return element;
	}//end of createYears
	
	/**
	 * Létrehozza a megadott elemre a hónapokat, a 'from' és 'to' hónapazonosítók zárt 
	 * intervallumán, valamint beállítja az alapértelmezett értéket, ha megadtuk.
	 */
	function createMonth(from, to, element, selected) {
		element.length = 0;
		element.options[0] = new Option("-");
		for ( i=1, j = Math.max(0,from-1); j < Math.min(to+0,monthnames.length); i++, j++ )
		{
			element.options[i] = new Option(monthnames[j],j+1);
			if ( selected == j+1 )
			{
				element.options[i].selected = true;
			}
		}
	}//end of createMonth
	
	function createDay(from, to, element, selected) {
		element.length = 0;
		element.options[0] = new Option('-','');
		for ( i=from, j = 1; i <= to; i++, j++)
		{
			var x= ( i < 10 && String(i).length == 1 ) ? String('0'+i) : String(i);
			element.options[j] = new Option(x,x);
			if ( selected == i )
			{
				element.options[j].selected = true;
			}
		}
	}//end of createDay
	
	function getDateString(whichElement) {
		today = new Date();
		// Get elements of modification
		var elements = getElements(whichElement);
		if( elements == null ) { return; }
		var yearlm = elements['yearlm'];
		var monthlm = elements['monthlm'];
		var daylm = elements['daylm'];
		var y = yearlm.value;
		var m = monthlm.value;
		var d = daylm.value;
		if( y == "" || y == "-" ) { y = today.getFullYear(); }
		if( m == "" || m == "-" ) { m = today.getMonth()+1; }
		if (d == "" || d == "-" ) { d = today.getDate(); }
		return str= y+'-'+m+'-'+d;
	}//end of getDateString
	
	function getDayCountOfMonth(monthId, year) {
		monthId = monthId+0;
		var daycount = 31;
		if ( monthId == 2 )
		{
			if ( parseInt(year)%4==0 )
			{
			    daycount = 29;
			}else
			{
			    daycount=28;
			}
		}else
		if( monthId == 4 || monthId == 6 || monthId == 9 || monthId == 11 )
		{
			daycount = 30;
		}
		return daycount;
	}//end of getDayCountOfMonth
	
	/**
	 * Visszaadja a módosításhoz szükséges elemeket.
	 */
	function getElements(whichElement) {
		// Get elements of modification
		var m = {"yearlm":null,"monthlm":null,"daylm":null};
		if( whichElement == "from" ) {
			m['yearlm'] = document.forms[formname].startdate_yearfrom;
			m['monthlm'] = document.forms[formname].startdate_monthfrom;
			m['daylm'] = document.forms[formname].startdate_dayfrom;
		}else
		if( whichElement == "to" ) {
			m['yearlm'] = document.forms[formname].startdate_yearto;
			m['monthlm'] = document.forms[formname].startdate_monthto;
			m['daylm'] = document.forms[formname].startdate_dayto;
		}else
		{
			return null;
		}
		return m;
	}//end of getElements
	
	/**
	 * A HTML kódban található 'from' hónap mező alapján feltölti a saját, hónapokat
	 * tartalmazó tömbjét - így a hónapnevek mindig lokalizáltak. Az objektum 
	 * létrehozásakor meghívjuk.
	 */
	function initMonthArray() {
		var m = getElements('from');
		var monthlist = m['monthlm'].options;
		var j = 0;
		for( i = 0; i < monthlist.length; i++ ) {
			if( monthlist[i].value != '' && monthlist[i].value != '-' )
			{
				monthnames[j] = monthlist[i].text;
				j++;
			}
		}
	}//end of initMonthArray
	
	function isToday(datepart, type) {
		if( datepart == undefined || datepart == null ) { return false; }
		var today = new Date();
		var tyear = today.getFullYear();
		var tmonth = today.getMonth();
		var tday = today.getDate();
		
		if( type == 'year' && datepart == tyear ) {
			return true;
		}else
		if( type == 'month' && datepart == tmonth ) {
			return true;
		}else
		if( type == 'day' && datepart == tday ) {
			return true;
		}
		return false;
	}//end of isToday
	
	/**
	 * private String[] parseDate(Date pdate)
	 *
	 * A dátum átalakítása asszociatív szövegtömbbé, amelyben nap mélységig
	 * szerepelnek az elemek.
	 */
	function parseDate(pdate) {
		var elements = new Array();
		// Get values of date elements
		elements['year'] = pdate.getFullYear();
		elements['month'] = pdate.getMonth()+1;
		elements['day'] = pdate.getDate();
		return elements;
	}
	
	function setAlertMsg(message) {
		alertMsg = message;
	}//end of setAlertMsg
	
	function setFormName(formNameToSet) {
    formname = formNameToSet;
	}//end of setFormName
	
	/**
	 * private void setDate(String whichElement, String[] datum)
	 *
	 * Beállítja egy elem (from,to) dátumát vagy annak egy részletét.
	 * 
	 * A dátum egy asszociatív tömb, amely year, month, day elemeket tartalmaz.
	 * Ha az elemek közül valamelyik üres, abban az esetben az adott elem
	 * (természetesen) az alapértelmezett értéken marad.
	 */
	function setDate(whichElement, datum, method) {
		// Get elements of modification
		var elements = getElements(whichElement);
		if( elements == null ) { return; }
		var yearlm = elements['yearlm'];
		var monthlm = elements['monthlm'];
		var daylm = elements['daylm'];
		
		if( datum != null )
		{
			// Set selected year
			for ( i = 0; i < yearlm.options.length; i++ )
			{
				if ( datum['year'] != '' && yearlm.options[i].value == datum['year'] )
				{
					yearlm.options[i].selected = true;
				}
			}
			// Set month
			for ( i = 0; i < monthlm.options.length; i++ )
			{
				if ( datum['month'] != '' && monthlm.options[i].value == datum['month'] )
				{
					monthlm.options[i].selected = true;
				}
			}
		}
		
		if( method != null && method == 'init' )
		{
			var d = new Date();
			yearlm = createYear(FIRST_YEAR,d.getFullYear(),yearlm, null);
		}
		
		// Set day
		
		var selectedMonthId = monthlm.options[monthlm.selectedIndex].value;
		var daycount = getDayCountOfMonth(selectedMonthId, yearlm.options[yearlm.selectedIndex].text);
		
		var selectedDay = null;
		if ( datum != null && datum['day'] != '' )
		{
			selectedDay = datum['day'];
		}
		createDay(FIRST_DAY, daycount, daylm, selectedDay);
		
		// Set method dependent elements
		if ( method == 'initWithToday' )
		{
			today = new Date();
			createYears(FIRST_YEAR,today.getFullYear(),yearlm);
			setDate(whichElement, parseDate(today), null);
		}else
		if ( method == 'init' )
		{
			setPreviousValues();
		}else
		{
			checkDate();
		}
	}//end of setDate
	
	function setDateValuesFrom(year, month, day) {
		fDate = new Date();
		fDateString = year+'/'+day+'/'+month;
		fDate.setTime(Date.parse(fDateString));
		setDate('from',parseDate(fDate), null);
	}//end of setDateValuesFrom
	
	function setDateValuesTo(year, month, day) {
		tDate = new Date();
		tDateString = year+'/'+day+'/'+month;
		tDate.setTime(Date.parse(tDateString));		
		setDate('to',parseDate(tDate), null);
	}//end of setDateValuesFrom
	
	/**
	 * A datummezok frissitese
	 * Parameterkent meg kell adni hogy a from vagy a to mezoket kivanjuk
	 * frissiteni, valamint a metodust, amely lehet init, initWithToday.
	 */
	function updateDate(whichElement, method) {
		setDate(whichElement, null, method);
		// Get elements of modification
//		var elements = getElements(whichElement);
//		if( elements == null ) { return; }
//		var yearlm = elements['yearlm'];
//		var monthlm = elements['monthlm'];
//		var daylm = elements['daylm'];
		// Set up years
//		if( method == 'init' ) {
//			var d = new Date();
//			yearlm = createYear(FIRST_YEAR,d.getFullYear(),yearlm, null);
//		}
		// Set up month
		// Generation not required, because it is a language dependent array
		// Get day of month
//		var selectedMonthId = monthlm.options[monthlm.selectedIndex].value;
//		var daycount = getDayCountOfMonth(selectedMonthId, yearlm.options[yearlm.selectedIndex].text);
		// Clear days
//		daylm.length = 0;
		// Set up days
//		daylm.options[0] = new Option('-','');
//		for( i=1; i <= daycount; i++) {
//			var x= i<10?String('0'+i):String(i);
//			daylm.options[i] = new Option(x,x);
//		}
		// Set specialities
//		if( method == 'initWithToday' ) {
//			today = new Date();
//			createYears(FIRST_YEAR,today.getFullYear(),yearlm);
//			setDate(whichElement, parseDate(today), null);
//		}else
//		if( method == 'init' ) {
//			setPreviousValues();
//		}
	}//end of updateDate
	
	/**
	 * A korabbi ertekeket tartalmazo objektum inicializalasa
	 */
	function setPreviousValues() {
		// Check querystring (via JS - common.js:parseQueryString(location:search))
		if( QueryString == null ) {
			if( location.search == "" ) {
				QueryString = null; return;
			}else
			{
				QueryString = parseQueryString(location.search);
			}
		}
		if( QueryString == null ) { return;	}
		var dv = {'from':{'year':'','month':'','day':''},'to':{'year':'','month':'','day':''}};
		if( QueryString.startdate_yearfrom != undefined ) { dv['from']['year'] = QueryString.startdate_yearfrom; }
		if( QueryString.startdate_monthfrom != undefined ) { dv['from']['month'] = QueryString.startdate_monthfrom; }
		if( QueryString.startdate_dayfrom != undefined ) { dv['from']['day'] = QueryString.startdate_dayfrom; }
		if( QueryString.startdate_yearto != undefined ) { dv['to']['year'] = QueryString.startdate_yearto; }
		if( QueryString.startdate_monthto != undefined ) { dv['to']['month'] = QueryString.startdate_monthto; }
		if( QueryString.startdate_dayto != undefined ) { dv['to']['day'] = QueryString.startdate_dayto; }
		setDate('from',dv['from']);
		setDate('to',dv['to']);
	}//end of setPreviousValues
	
	/**
	 * Beallitja egy select objektum value-val jelzett objektumat
	 */
	function setSelectedItem(selectLm, value) {
		for( i = 0; i < selectLm.options.length; i++ )
		{
			if ( value != '' && selectLm.options[i].value == value )
			{
				selectLm.options[i].selected = true;
			}
		}
	}
}
