/*
 * Returns the default calendar width.
 */
function getDefaultCalendarWidth() {
	return 400;
}

/*
 * Returns the default calendar height.
 */
function getDefaultCalendarHeight() {
	return 200;
}

/*
 * Spawns a calendar window that interacts with a single
 * input field containing a complete date.
 * myField: The input field
 * months: Number of months to display (starting with the current month)
 * pattern: The date pattern used in the input field. See parseDate for allowed patterns.
 * width: width of the popup window (optional; defaults to 310)
 * height: height of the popup window (optional; defaults to 400)
 * validateCalendar: (optional) Indicates whether to modify an additional
 *                   date field after changes in the calendar
 * otherField: (optional) only sensible when validateCalendar is true
 */
function spawnInputFieldCalendar(myField, months, pattern, width, height, validateCalendar, otherField) {	
	originalArgs = new Array();
	for(var i=0; i<arguments.length; i++){
		originalArgs[i] = arguments[i];
	}

	var fields = new Array();
	
	if (otherField != null) {
		fields = new Array(myField.name , otherField.name);
	} else {
		fields = new Array(myField.name);
	}
	
	var ds = myField.value;
	
	var start = parseDate(pattern, myField.value);
	if(otherField){
		var end = parseDate(pattern, otherField.value);
	}else{
		var end = parseDate(pattern, myField.value);
	}
	var w = width;
	var h = height;
	var numberOfMonths = 14;
	if (months == 12){months = 14}
	if (months != null) numberOfMonths = months;
	if (isNaN(w) || w == null) w = getDefaultCalendarWidth();
	if (isNaN(h) || h == null) h = getDefaultCalendarHeight();
	
	if (validateCalendar) {
		generateCal(self, 0, myField.form.name, fields, start, start, numberOfMonths, validateCalendar, -1, pattern, false, true, end, end);
	} else {
		generateCal(self, 0, myField.form.name, fields, start, start, numberOfMonths, validateCalendar, -1, pattern, false, true, end, end);
	}
}



/*
 * Change the selected month in the calendar window.
 * See generateCal for the params.
 */
function calendarChooseMonth(window, mode, formname, formelements, originalChosenTime, chosenTime, numberOfMonths, validateCalendar, selectedArea, pattern, submit, chosenTime2, originalChosenTime2) {
	parts = formelements.split(",");
	formelements = new Array();
	for(var i=0; i<parts.length; i++){
		formelements[i] = parts[i];
	}
	
	var chosen = new Date();
	var chosen2 = new Date();
	var originalChosen = new Date();
	var originalChosen2 = new Date();
	originalChosen.setTime(originalChosenTime);
	originalChosen2.setTime(originalChosenTime2);
	chosen.setTime(chosenTime);
	chosen2.setTime(chosenTime2);		
	
	// Gradebiegen des vor dem montaswechsel ausgesuchten Tages
	if(chosen2.getMonth() == myArrivalMonth){
		// kein neuer Monat
		originalChosen2 = new Date(myArrivalYear, myArrivalMonth, myArrivalDay);	
	}
	
	if(chosen.getMonth() == myDepartureMonth){
		// kein neuer Monat
		originalChosen = new Date(myDepartureYear, myDepartureMonth, myDepartureDay);	
	}

	
	generateCal(window, mode, formname, formelements, originalChosen, chosen, numberOfMonths, validateCalendar, selectedArea, pattern, submit, false, chosen2, originalChosen2);
}

/*
 * Returns a String representing the given date using the given pattern.
 * See source for allowed patterns.
 * day: Day
 * month: Month
 * year: Year
 * pattern: The date pattern, e.g. "dd.MM.yyyy"
 */
function formatDate(day, month, year, pattern) {
	var dayString = day < 10 ? '0' + day : day;
	var monthString = (month+1) < 10 ? '0' + (month+1) : (month+1);
	
	if (pattern == 'dd.MM.yyyy') {
	    return dayString + "." + monthString + "." + year;
   	} else if (pattern == 'dd/MM/yyyy') {
    	return dayString + "/" + monthString + "/" + year;
   	} else if (pattern == 'MM/dd/yyyy') {
    	return monthString + "/" + dayString + "/" + year;
   	}
   	return "";
}

/*
 * Sets the given date into the given input field after
 * formatting it using the given pattern.
 * See formatData for allowed patterns.
 */
function setDateToFreeTextField(formname, fieldName, day, month, year, pattern) {
	if(fieldName != "undefined"){
		var field = document.forms[formname].elements[fieldName];
		
		// Safari findet das Feld nicht
		if(typeof(field) == "undefined"){
			allFields = document.forms[formname].getElementsByTagName("input");			
			for(var i=0; i<allFields.length; i++){				
				if(allFields[i].name == fieldName){
					field = allFields[i];
					break;
				}
			}
		}						
		field.value = formatDate(day, month, year, pattern);
	}
}

/*
 * Checks whether a given combobox (containing complete dates) contains the month
 * of the given date. Returns false if not, true otherwise.
 * t: a Date
 * formname: name of a form
 * comboname: name of a combobox
 * date pattern
 */
function comboboxContainsMonth(t, formname, comboname) {
	var txm = "" + (t.getMonth() + 1);
	if (txm.length < 2) txm = "0" + txm;
	var txy = "" + t.getFullYear();
	
	var combo = document.forms[formname].elements[comboname];

	for (i = 0; i < combo.options.length; i++) {
		if ((txm + "." + txy) == combo.options[i].value.substring(3)) {
			return true;
		}
	}
	return false;
};

/*
 * Parses a date string given in the parameter value
 * according to the given pattern.
 * Allowed patterns (in java.text.SimpleDateFormat syntax)
 * are "dd.MM.yyyy", "dd/MM/yyyy" and "MM/dd/yyyy".
 * The optional parameter allowPast indicates whether dates
 * in the past are allowed.
 * Returns a Date object representing the given date
 * or today if an error occured.
 * If the pattern is unrecognized, an alert-box is displayed.
 */
function parseDate(pattern, value, allowPast) {
	var d = parseDateInsecure(pattern, value, allowPast);
	if (d == null) d = new Date();
	return d;
}

/*
 * Parses a date string given in the parameter value
 * according to the given pattern.
 * Allowed patterns (in java.text.SimpleDateFormat syntax)
 * are "dd.MM.yyyy", "dd/MM/yyyy" and "MM/dd/yyyy".
 * The optional parameter allowPast indicates whether dates
 * in the past are allowed.
 * Returns a Date object representing the given date
 * or null if an error occured.
 * If the pattern is unrecognized, an alert-box is displayed.
 */
function parseDateInsecure(pattern, value, allowPast) {
	var pattern;
	var day;
	var month;
	var year;

    if (pattern=='dd.MM.yyyy') {
		pattern = /^(([1-9]|[0-2]\d|[3][0-1])\.([1-9]|[0]\d|[1][0-2])\.[2][0]\d{2})$|^(([1-9]|[0-2]\d|[3][0-1])\.([1-9]|[0]\d|[1][0-2])\.[2][0]\d{2})$/;
		if (pattern.exec(value) != null) {
			var test = value.split(".");
			year = test[2];
			month = test[1] - 1;
			day = test[0];
		} else {
			return null;
		}
	} else if (pattern=='dd/MM/yyyy') {
		pattern = /^(\d\d)\/(\d\d)\/(\d\d\d\d)$/;
		if (pattern.exec(value) != null) {
			year = RegExp.$3;
			month = RegExp.$2-1;
			day = RegExp.$1;
		} else {
			return null;
		}
	} else if (pattern=='MM/dd/yyyy') {
		pattern = /^(\d\d)\.(\d\d)\.(\d\d\d\d)$/;
		if (pattern.exec(value) != null) {
			year = RegExp.$3;
			month = RegExp.$1-1;
			day = RegExp.$2;
		} else {
			return null;
		}
	} else {
		alert("Unsupported pattern " + pattern);
		return null;
	}

    if (!allowPast) {
        var today = new Date();
		if (year < today.getFullYear()) {
			return null;
		}
        
		if (year == today.getFullYear()) {
            if (month < today.getMonth()) {
				return null;
			}
			if (month == today.getMonth()) {
                if (day < today.getDate()) {
					return null;
				}
            }
        }
    }

    if ((month >= -1)
            && (month<=11)
            && (day >= 1)
            && (day <= 31)) {
        return new Date(year, month, day);
    }

    return null;
}

/*
 * Returns a date being toIncrease days later than the given date.
 * If toIncrease is not set, 7 is used.
 */
function increaseDay(templDate, toIncrease) {
	var retVal;	
	if (toIncrease == null ) {
		//toIncrease = 1;
		toIncrease = getDefaultToIncrease();
	}
	newTimestamp = templDate.getTime() + (1000 * 60 * 60 * 24 * toIncrease);	
	retVal = new Date(newTimestamp);	
	return retVal;
}

function getDefaultToIncrease() {
    return 7;
}

/*
 * Returns the number of days that should be added to a start date in order
 * to propose a return date.
 */
function getValidateVacationDateReturnOffset() {
    return 7;
}

/*
* Validates the given arrival and departure Date by the pattern
*/
/*function validateDate(pattern, arrivalDay, arrivalMonth, arrivalYear, 
							 departureDay, departureMonth, departureYear) {
	var newDate;

	var arrMonInt = parseInt(arrivalMonth) + 1;
	var depMonInt = parseInt(departureMonth) + 1;
	var departureDate = parseDate(pattern, departureDay + "." + depMonInt + "." + departureYear);
	var arrivalDate = parseDate(pattern, arrivalDay + "." + arrMonInt + "." + arrivalYear);
	
	if (arrivalDate.getTime() < departureDate.getTime()) {
		newDate = increaseDay(departureDate, getValidateVacationDateReturnOffset());
        return newDate;
	} else { 
		return null;
	}
}*/

/*
* Sets the selDiv Element as Selected
*/
function setSelection(popup, selDiv) {
	if (selDiv.parentNode.parentNode.parentNode.getAttribute("id") == "genCalPopupCalendar") { 
		if (popup.document.getElementById("genCalPopupDayChosen") && selDiv.getAttribute("id") != "genCalPopupDayToday") {
			popup.document.getElementById("genCalPopupDayChosen").setAttribute("id", "");
			selDiv.setAttribute("id", "genCalPopupDayChosen");
		} else if (selDiv.getAttribute("id") == "genCalPopupDayToday") {
			popup.document.getElementById("genCalPopupDayChosen").setAttribute("id", "");
			selDiv.setAttribute("id", "genCalPopupDayTodayChosen");
		} else if (popup.document.getElementById("genCalPopupDayTodayChosen")) {
			popup.document.getElementById("genCalPopupDayTodayChosen").setAttribute("id", "genCalPopupDayToday");
			selDiv.setAttribute("id", "genCalPopupDayChosen");
		} else {
			selDiv.setAttribute("id", "genCalPopupDayChosen");
		}
	} else {
		if (popup.document.getElementById("genCalPopupDayChosen2") && selDiv.getAttribute("id") != "genCalPopupDayToday") {
			popup.document.getElementById("genCalPopupDayChosen2").setAttribute("id", "");
			selDiv.setAttribute("id", "genCalPopupDayChosen2");
		} else if (selDiv.getAttribute("id") == "genCalPopupDayToday") {
			popup.document.getElementById("genCalPopupDayChosen2").setAttribute("id", "");
			selDiv.setAttribute("id", "genCalPopupDayTodayChosen2");
		} else if (popup.document.getElementById("genCalPopupDayTodayChosen2")) {
			popup.document.getElementById("genCalPopupDayTodayChosen2").setAttribute("id", "genCalPopupDayToday");
			selDiv.setAttribute("id", "genCalPopupDayChosen2");
		} else {
			selDiv.setAttribute("id", "genCalPopupDayChosen2");
		}
	}
}

function setDepartureDate(departureDay, departureMonth, departureYear, selDiv) {
	myDepartureDay = departureDay; 
	myDepartureMonth = departureMonth; 
	myDepartureYear = departureYear; 

	var arrivalDate = new Date(myArrivalYear, myArrivalMonth, myArrivalDay);
	var departureDate = new Date(myDepartureYear, myDepartureMonth, myDepartureDay);
	// Anfang nach Ende = Fehler...
	if(departureDate.getTime() > arrivalDate.getTime()){		
		newArrivalDate = increaseDay(departureDate, 7);		
		myArrivalDay = newArrivalDate.getDate();
		// Monat ändert sich rechts
		if(myArrivalMonth != newArrivalDate.getMonth()){	
			a4 = (originalArgs[6] != null) ? originalArgs[0].name +',' + originalArgs[6].name : originalArgs[0].name;
			equalTimestamp = document.calForm2.monthBox2.options[document.calForm2.monthBox2.selectedIndex].value;
			equalDate = new Date(Number(equalTimestamp));
		
			if(newArrivalDate.getMonth() == equalDate.getMonth()){
				myNewMonth = document.calForm2.monthBox2.selectedIndex;
			}else{				
				for(var i=0; i<document.calForm2.monthBox2.length; i++){
					ed = new Date(Number(document.calForm2.monthBox2.options[i].value));
					if(ed.getMonth() == newArrivalDate.getMonth()){
						myNewMonth = i;
						break;
					}	
				}				
			}
			
			//myNewMonth = () ? document.calForm2.monthBox2.selectedIndex : document.calForm2.monthBox2.selectedIndex + 1;
			calendarChooseMonth(self, 0, originalArgs[0].form.name, a4 , new Date(myDepartureYear, myDepartureMonth, myDepartureDay,0,0,0,0).getTime(),document.calForm.monthBox.options[document.calForm.monthBox.selectedIndex].value, originalArgs[1], originalArgs[5], document.calForm2.areas.options[document.calForm2.areas.selectedIndex].value, originalArgs[2], false, document.calForm2.monthBox2.options[myNewMonth].value, new Date(myArrivalYear, myArrivalMonth, myArrivalDay,0,0,0,0).getTime());
		}				
		myArrivalMonth = newArrivalDate.getMonth();
		myArrivalYear = newArrivalDate.getFullYear();	
	}

	foundedDiv = findDiv('left');
	setSelection(self, foundedDiv);
		
	foundedDiv = findDiv('right');	
	setSelection(self, foundedDiv);
}

function setArrivalDate(arrivalDay, arrivalMonth, arrivalYear, selDiv) {
	myArrivalDay = arrivalDay; 
	myArrivalMonth = arrivalMonth; 
	myArrivalYear = arrivalYear; 
	/*var newArrivalDate =  validateDate('dd.MM.yyyy', myArrivalDay, myArrivalMonth, myArrivalYear, myDepartureDay, myDepartureMonth, myDepartureYear); 
	if (newArrivalDate != null) { 
		myArrivalDay = newArrivalDate.getDate(); 
		myArrivalMonth = newArrivalDate.getMonth(); 
		myArrivalYear = newArrivalDate.getFullYear();
	}*/
	setSelection(self, selDiv);	
	
	foundedDiv = findDiv('left');
	setSelection(self, foundedDiv);	
}


function findDiv(cal){
	var myGlobalDiv = "";
	if(cal == "left"){
		myGlobalDiv = document.getElementById('genCalPopupCalendar');
		equalDay = myDepartureDay;
	}else if(cal == "right"){
		myGlobalDiv = document.getElementById('genCalPopupCalendar2');
		equalDay = myArrivalDay;		
	}		
	links = myGlobalDiv.getElementsByTagName("a");
	for(var i=0; i<links.length; i++){					
		if(links[i].innerHTML.toString() == equalDay.toString()){			
			return links[i].parentNode;
		}
	}	
}

function getX(elm){
   	var x = 0;
   	if (elm && typeof elm.offsetParent != "undefined") {
     		while (elm && typeof elm.offsetLeft == "number") {
      	 	x += elm.offsetLeft;
       		elm = elm.offsetParent;
     		}
   	}
   	return x;
}

function getY(elm){
   	var y = 0;
   	if (elm && typeof elm.offsetParent != "undefined") {
     		while (elm && typeof elm.offsetTop == "number") {
       		y += elm.offsetTop;
       		elm = elm.offsetParent;
     		}
   	}
   	return y;		
}

function hideCal(){
	var div = document.getElementById("calDocDiv");	
	document.getElementsByTagName("body")[0].removeChild(div);
	if(document.getElementById("calIframe")){
		var frame = document.getElementById("calIframe");	
		document.getElementsByTagName("body")[0].removeChild(frame);
	}
}