var MONTH_IN_MILLIS = 2592000000;

//-------------------------------------------------------------
//This class is used to maintain correct monthnames and number of days
//in the drop down selects in the form. 
function DateHandler(currentDate, months){
	
	//attributes
	//The current date in the format: 20050404
	this.currentDate = stringToDate(currentDate);
	//An array of localized month names. months[0]= "January", months[1] = "February", etc...
	this.months = months;

	//An array for keeping track of the number of days in each months
	this.monthDay = new Array(12);
	this.monthDay['01'] = '31'; //January
	this.monthDay['02'] = '28'; //February
	//Handles leap years
	if (this.currentDate.getFullYear() % 400 == 0 || (this.currentDate.getFullYear() % 4  ==  0 && this.currentDate.getFullYear() % 100 != 0) ) {
		this.monthDay['02'] = '29';
	}
	this.monthDay['03'] = '31';
	this.monthDay['04'] = '30';
	this.monthDay['05'] = '31';
	this.monthDay['06'] = '30';
	this.monthDay['07'] = '31';
	this.monthDay['08'] = '31';
	this.monthDay['09'] = '30';
	this.monthDay['10'] = '31';
	this.monthDay['11'] = '30';
  this.monthDay['12'] = '31';

	//methods
	this.getMonthOptions = dh_getMonthOptions;
	this.getDayOptions = dh_getDayOptions;
	this.updateDaysInDropDown = dh_updateDaysInDropDown;
	this.updateDestLeave = dh_updateDestLeave;


}


//This function disbles the select controls for the destination in the form if isReturn is
//set to false
function dh_updateDestLeave(isReturnSelect, destLeaveDaySelect, destLeaveMonthYearSelect){
	if(isReturnSelect){
        var isReturn = isReturnSelect.value;

        if(isReturn == "false"){ // oneway
            destLeaveDaySelect.disabled = true;
            destLeaveMonthYearSelect.disabled = true;
        }else{
            destLeaveDaySelect.disabled = false;
            destLeaveMonthYearSelect.disabled = false;
        }
    }
}

//This function builds a string of HTML-options of the format: April 2005, etc 	
//The parameters will decide which month and year will be selected
function dh_getMonthOptions(selectedYear, selectedMonth, size) {
		if (size == 0) {
			// 100 is big enough to hold any date in any language :)
			size = 100;			
		}
		
		selectedMonth = doubleZero(selectedMonth);
		
		var selectedYearMonth = selectedYear + selectedMonth;
		var months;
		if(this.months != null){
			months = this.months;
			
		}
		else{
			months = new Array('January','February','March','April','May','June','July','August','September','October','November','December');
		}
		
		var dtNow;
		if(this.currentDate != null){
			dtNow = new Date(this.currentDate);
		}
		else{
			dtnow = new Date();
		}
		
		var str = ''
		dtNow.setDate(1);
		var dtEnd = new Date(dtNow.getFullYear(), dtNow.getMonth(), dtNow.getDate());
		//Done this way for safari compatibility
		dtEnd = new Date().setTime(dtEnd.getTime() + (13 * MONTH_IN_MILLIS));
		var iMonth
		do {
			iMonth = dtNow.getMonth() + 1;
			var yearMonth = dtNow.getFullYear() + doubleZero(iMonth);
			str += '<option value="' + yearMonth + '" ';
			if(yearMonth == selectedYearMonth){
				str += ' selected';
			}
			str	+= '>' + months[dtNow.getMonth()].substring(0,size) + ' ' + dtNow.getFullYear() + '</option>';
			dtNow.setMonth(dtNow.getMonth() + 1);
		} while (dtNow < dtEnd);
	
		return str
}


//This function fill the day selects with the correct number of days for the selected month
function dh_getDayOptions(daySelect, selectedDay, selectedMonth){
	selectedDay = removeFirstZero(selectedDay);
	selectedMonth = doubleZero(selectedMonth);
	var numberOfDaysInMonth = parseInt(this.monthDay[selectedMonth]);
	
	var str = '';
	for(i = 1; i <= numberOfDaysInMonth; i++){
		
		str += '<option value="' + doubleZero(i) + '" ';
		
		if(i == selectedDay){
			str+= ' selected'; 
		}
		
		str+= '>' + doubleZero(i)+ '</option>';
	}
	
	return str;
	
}
	

//This function will update the number of days in the daySelect dropdown 
//To reflect the selected month
 function dh_updateDaysInDropDown(yearMonth, daySelect) {
 //yearMonth should have the following format: 200502

  var month = yearMonth.value.substring(4,6);
  var activeDay = daySelect.value;
  daySelect.options.length = 0;
  var numberOfDaysInMonth = parseInt(this.monthDay[month]);
  for (i = 1; i <= numberOfDaysInMonth; i++){
  	daySelect.options[i-1] = new Option(doubleZero(i), doubleZero(i));
    if(i == activeDay) {
    	daySelect.options[i-1].selected = 'selected';
    }
  } 
  var myDate=new Date()
  myDate.setFullYear(yearMonth.value.substring(0,4), yearMonth.value.substring(4,6)-1, activeDay-1);
  calcNumDays(getHomeLeaveDate(), myDate);
  calcNumDays(getHomeLeaveDate(), myDate, true);

      
}



//This function takes a date and returns an earlier one with the specified number of days
function getEarlierDate(originalDate, numDays){
	var newDate = new Date(originalDate.getFullYear(), originalDate.getMonth(), originalDate.getDate());
	newDate.setDate(newDate.getDate() - numDays);
	return newDate;
	
}
//This function takes a date and returns a later one with the specified number of days
function getLaterDate(originalDate, numDays){
	var newDate = new Date(originalDate.getFullYear(), originalDate.getMonth(), originalDate.getDate());
	newDate.setDate(newDate.getDate() + numDays);
	return newDate;
}

//Used to fix default home- and dest dates to avoid that they are in different months
function fixHomeDate(homeLeave, destLeave, duration) {
	if (destLeave.getMonth() != homeLeave.getMonth()) {
		var firstDateInMonth = new Date(destLeave.getFullYear(), destLeave.getMonth(), 1);
		
		destDiff = destLeave.getTime() - firstDateInMonth.getTime();
		homeDiff = firstDateInMonth.getTime() - homeLeave.getTime();
		
		if (homeDiff > destDiff) {
			//The diff between homeLeave and the month break is greatest. 
			//Home and DestLeave shall be in the end of the first month.
			homeLeave = new Date(firstDateInMonth.getTime() - (duration + 1) * 24 * 60 * 60 * 1000);
		}
		else {
			//The diff between destLeave and the month break is greatest. 
			//Home and DestLeave shall be in the start of the second month.
			homeLeave = new Date(destLeave.getFullYear(), destLeave.getMonth(), 1);
		}
	}
	return homeLeave;
}

//Used to fix default home- and dest dates to avoid that they are in different months
function fixDestDate(homeLeave, destLeave, duration) {
	//DestLeave is [duration] days after homeLeave. Add an extra hour to make sure
	//we dont end up exactly at midnight.
	destLeave = new Date(homeLeave.getTime() + duration * 25 * 60 * 60 * 1000);
	return destLeave;
}

/*
	Generates a date object for a dateString of the format yyyyMMdd.
*/
function stringToDate(dateString){
  dateString = new String(dateString);
	var year = dateString.substring(0,4);
	var month = dateString.substring(4,6);
	var day = dateString.substring(6,8);
	
	month = removeFirstZero(month);
	day = removeFirstZero(day);
	month = month -1; 
	
	var myDate = new Date(year, month, day);
	return myDate;
}

//This function takes a data and returns a string representation of the form: "20050623"
function dateToString(date){
	var myDate = date;
	var year = myDate.getFullYear();
	var month = myDate.getMonth();
	var day = myDate.getDate();
	
	month = month +1;
	month = doubleZero(month);
	day = doubleZero(day);

	
	var dateString = year + month + day;
	return dateString;
	
	
}

//this function adds a zero in front of a numberif it is below 10. 9 becomes 09 etc..
function doubleZero(piNumber) {
	if (piNumber < 10) {
	    return '0' + piNumber;
	}
	else
	{
		return '' + piNumber
	}
}

//This functions removes the first zero from a string if it has one
function removeFirstZero(inString){
	inString = new String(inString);

	if(inString.charAt(0) == "0"){
			inString = inString.substring(1, inString.length);
	}
	return inString;

}

//This function takes a date and returns a later one with the specified number of days
function getLaterDate(originalDate, numDays){
	var newDate = new Date(originalDate.getFullYear(), originalDate.getMonth(), originalDate.getDate());
	newDate.setDate(newDate.getDate() + numDays);
	return newDate;
}

//checks if it is a leap year and then sets it
function checkLeapYear(dateHandler, tempDate) {
	tempDate = tempDate.substring(0,4);
	if (tempDate % 400 == 0 || (tempDate % 4  ==  0 && tempDate % 100 != 0) ) {
		dateHandler.monthDay['02'] = '29';
	} else {
		dateHandler.monthDay['02'] = '28';
	}
}