/*
	DATE FORMAT OPTIONS:

	dd   = 1 or 2-digit Day
	DD   = 2-digit Day
	mm   = 1 or 2-digit Month
	MM   = 2-digit Month
	yy   = 2-digit Year
	YY   = 4-digit Year
	yyyy = 4-digit Year
	month   = Month name in lowercase letters
	Month   = Month name in initial caps
	MONTH   = Month name in captital letters
	mon     = 3-letter month abbreviation in lowercase letters
	Mon     = 3-letter month abbreviation in initial caps
	MON     = 3-letter month abbreviation in uppercase letters
	weekday = name of week in lowercase letters
	Weekday = name of week in initial caps
	WEEKDAY = name of week in uppercase letters
	wkdy    = 3-letter weekday abbreviation in lowercase letters
	Wkdy    = 3-letter weekday abbreviation in initial caps
	WKDY    = 3-letter weekday abbreviation in uppercase letters

	Examples:

	calDateFormat = "mm/dd/yy";
	calDateFormat = "Weekday, Month dd, yyyy";
	calDateFormat = "wkdy, mon dd, yyyy";
	calDateFormat = "DD.MM.YY";     // FORMAT UNSUPPORTED BY JAVASCRIPT -- REQUIRES CUSTOM PARSING

*/

//--- global variables
var selectedLanguage = 'nl';			//--- default english
var calDateFormat = 'mm/dd/yyyy';		//--- default month/day/year


function getdate(textboxname, lang) {
	selectedLanguage = lang;
	if(lang=='nl'){
		calDateFormat = "Weekday dd month yyyy";
	}
	buildCalParts();
	setDateField(eval(textboxname));
	top.newWin = window.open('calendar.html','_cal','WIDTH=210,HEIGHT=210')
}

function getToday(lang) {
	selectedLanguage = lang;
	if(lang=='nl'){
		calDateFormat = "Weekday dd month yyyy";
	}
    calDate = new Date();

	createWeekdayList();		//--- bouwt weekdag arrays op basis language
	getMonthSelect();			//--- bouwt o.a. maand arrays

	return getFormatDate(calDate.getDate());
}


// hoeft inweze niet iedere keer aangeroepen te worden

function buildCalParts() {
    weekdays = createWeekdayList();
    blankCell = "<TD>&nbsp;&nbsp;&nbsp;</TD>";
    calendarBegin = "<HTML><HEAD><LINK rel=\"stylesheet\" type=\"text/css\" href=\"/js-css/reservering.css\"></HEAD><BODY><CENTER>";
    calendarBegin += "<TABLE CELLPADDING=0 CELLSPACING=1 BORDER=0 ALIGN=CENTER><TR><TD>";
    calendarBegin += "<TABLE CELLPADDING=0 CELLSPACING=1 BORDER=0 ALIGN=CENTER style=\"height: 120px\">" + weekdays + "<TR>";
	calendarEnd = "</TD></TR></TABLE></TABLE></CENTER></BODY></HTML>";
}

function setDateField(dateField) {
    calDateField = dateField;
    inDate = dateField.value;
    setInitialDate();
    calDocTop    = buildTopCalFrame();
    calDocBottom = buildBottomCalFrame();
}


function setInitialDate() {
   
    calDate = new Date(inDate);
    if (isNaN(calDate)) {
		calDate = new Date();
    }
    calDay  = calDate.getDate();
    calDate.setDate(1);
}


// frame met maand en jaar

function buildTopCalFrame() {

    var calDoc = "<HTML><HEAD><LINK rel=\"stylesheet\" type=\"text/css\" href=\"/js-css/reservering.css\"></HEAD><BODY>";
	calDoc +=	"<FORM NAME='calControl' onSubmit='return false;'><CENTER><TABLE CELLPADDING=0 CELLSPACING=1 BORDER=0>";
	calDoc +=	"<TR><TH COLSPAN=7><CENTER>" + getMonthSelect() + getYearSelect() + "</CENTER></TH></TR></TABLE></CENTER></FORM></BODY></HTML>";

    return calDoc;
}

// pulldown met jaren, dit jaar + 1

function getYearSelect() {
	var sYear = calDate.getFullYear();
	var calYear = "<SELECT NAME=\"year\" onchange=\"parent.opener.setYear()\" style=\"border: 1px solid #000000\">";
    for(var x=0;x<2;x++){
		calYear += "<OPTION VALUE=\"" + (sYear + x) + "\">" + (sYear + x) + "</OPTION>";
	}
	calYear += "</SELECT>";
	return calYear;
}


// onderste frame, met de dagen

function buildBottomCalFrame() {       

    var calDoc = calendarBegin;

    month   = calDate.getMonth();
    year    = calDate.getFullYear();
    day     = calDay;

    var i   = 0;

    var days = getDaysInMonth();

	// huidige dag nooit hoger dan hoogste dag in die maand
	
    if (day > days) {
        day = days;
    }

    var firstOfMonth = new Date (year, month, 1);

    var startingPos  = firstOfMonth.getDay();
    days += startingPos;

    var columnCount = 0;

	// dagen voor startpos leeg
	
    for (i = 0; i < startingPos; i++) {
        calDoc += blankCell;
		columnCount++;
    }

    var currentDay = 0;
    var dayType    = "weekday";

	// voor alle dagenin de maand...
	
    for (i = startingPos; i < days; i++) {

		var paddingChar = "&nbsp;";

		// spaties voor padding < 10
		
        if (i-startingPos+1 < 10) {
            padding = "&nbsp;&nbsp;";
        } else {
            padding = "&nbsp;";
        }

		// huidige dag in bold
		
        currentDay = i-startingPos+1;
		
		// VANAF DINSDAG 27 MAART IS HET MOGELIJK OM TE RESERVEREN
		
        if (columnCount % 7 == 2 && month < 2) {
			 calDoc += "<TD style=\"border: 1px solid #000000\" align=center>" + padding + currentDay + paddingChar + "</TD>";
			 
		} else if (columnCount % 7 == 2 && month == 2 && currentDay < 26) {
			 calDoc += "<TD style=\"border: 1px solid #000000\" align=center>" + padding + currentDay + paddingChar + "</TD>";

		// MAANDAG GESLOTEN
		
        } else if (columnCount % 7 == 1){
		     calDoc += "<TD style=\"border: 1px solid #000000\" align=center>" + padding + currentDay + paddingChar + "</TD>";
        }
				
		// VAKANTIE? //
		
        /*
        else if (month == 6){
			calDoc += "<TD style=\"border: 1px solid #000000\" align=center>" + padding + currentDay + paddingChar + "</TD>";
        }
        
        else if (month == 7){
				calDoc += "<TD style=\"border: 1px solid #000000\" align=center>" + padding + currentDay + paddingChar + "</TD>";
        }
		*/ 
        
        else {
	        calDoc += "<TD style=\"border: 1px solid #000000\" align=center><a style=\"text-decoration: none\" href=\"#\" onclick=\"parent.opener.returnDate(" + currentDay + "); return false\">" + padding + currentDay + paddingChar +  "</b></TD>";
        }

		// niewe col als we 7 dagen hebben
			
        columnCount++;
        if (columnCount % 7 == 0) {
            calDoc += "</TR><TR>";
        }
    }

	// resterende dagen leeg maken
		
	if(columnCount %7 != 0){
		while(columnCount % 7 != 0){
			calDoc += blankCell;
			columnCount++;
		}
		calDoc += "</TR>";
	}
	
    calDoc += calendarEnd;

    return calDoc;
}

// schrijf de calender naar het onderste frame
	
function writeCalendar() {
    calDocBottom = buildBottomCalFrame();
    top.newWin.frames['bottomCalFrame'].document.open();
    top.newWin.frames['bottomCalFrame'].document.write(calDocBottom);
    top.newWin.frames['bottomCalFrame'].document.close();
}

// zet de calendar op vandaag en schrijft dat uit
	
function setToday() {

    calDate = new Date();

    var month = calDate.getMonth();
    var year  = calDate.getFullYear();

    top.newWin.frames['topCalFrame'].document.calControl.month.selectedIndex = month;
    top.newWin.frames['topCalFrame'].document.calControl.year.value = year;

    writeCalendar();
}

// zet het jaar via de pulldown

function setYear() {
    var year  = top.newWin.frames['topCalFrame'].document.calControl.year.value;
    calDate.setFullYear(year);
    writeCalendar();
}


// zet maand via de pulldown

function setCurrentMonth() {
    var month = top.newWin.frames['topCalFrame'].document.calControl.month.selectedIndex;
    calDate.setMonth(month);
    writeCalendar();
}


// het aantal dagen in de maand

function getDaysInMonth()  {

    var days;
    var month = calDate.getMonth()+1;
    var year  = calDate.getFullYear();

	// 31 dagen voor 7 maanden, 30 voor 5 andere en 29 of 28 voor februari
	
    if (month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month==12)  {
		days=31;
    } else if (month==4 || month==6 || month==9 || month==11) {
        days=30;
    } else if (month==2){
        if (isLeapYear(year)) {
            days=29;
        } else {
            days=28;
        }
    }
    return (days);
}

// check voor leapyear

function isLeapYear (Year) {
    if (((Year % 4)==0) && ((Year % 100)!=0) || ((Year % 400)==0)) {
        return (true);
    } else {
        return (false);
    }
}

// bouw de monthlists

function getMonthSelect() {

    // IF FRENCH
    if (selectedLanguage == "fr") {
		monthArray = new Array('Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Aout', 'Septembre', 'Octobre', 'Novembre', 'Décembre');
    }
    // IF GERMAN
    else if (selectedLanguage == "de") {
        monthArray = new Array('Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember');
    }
    // IF SPANISH
    else if (selectedLanguage == "es") {
        monthArray = new Array('Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre');
    }
    // IF Dutch
    else if (selectedLanguage == "nl") {
        monthArray = new Array('Januari', 'Februari', 'Maart', 'April', 'Mei', 'Juni', 'Juli', 'Augustus', 'September', 'Oktober', 'November', 'December');
    }
    // DEFAULT TO ENGLISH
    else {
        monthArray = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
    }

    // DETERMINE MONTH TO SET AS DEFAULT
    var activeMonth = calDate.getMonth();

    // START HTML SELECT LIST ELEMENT
    monthSelect = "<SELECT NAME='month' onChange='parent.opener.setCurrentMonth()' style\"border: 1px solid #000000\">";
    for (i in monthArray) {
        if (i == activeMonth) {
            monthSelect += "<OPTION SELECTED>" + monthArray[i] + "\n";
        } else {
            monthSelect += "<OPTION>" + monthArray[i] + "\n";
        }
    }
    monthSelect += "</SELECT>";

    // RETURN A STRING VALUE WHICH CONTAINS A SELECT LIST OF ALL 12 MONTHS
	return monthSelect;

}

// maakt array met weekdates

function createWeekdayList() {

    // IF FRENCH
    if (selectedLanguage == "fr") {
        weekdayList  = new Array('Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi');
        weekdayArray = new Array('Di', 'Lu', 'Ma', 'Me', 'Je', 'Ve', 'Sa');
    }
    // IF GERMAN
    else if (selectedLanguage == "de") {
        weekdayList  = new Array('Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag');
        weekdayArray = new Array('So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa');
    }
    // IF SPANISH
    else if (selectedLanguage == "es") {
        weekdayList  = new Array('Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado')
        weekdayArray = new Array('Do', 'Lu', 'Ma', 'Mi', 'Ju', 'Vi', 'Sa');
    }
    // IF Dutch
    else if (selectedLanguage == "nl") {
        weekdayList  = new Array('Zondag', 'Maandag', 'Dinsdag', 'Woensdag', 'Donderdag', 'Vrijdag', 'Zaterdag')
        weekdayArray = new Array('Zo', 'Ma', 'Di', 'Wo', 'Do', 'Vr', 'Za');
    }
    else {
        weekdayList  = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
        weekdayArray = new Array('Su','Mo','Tu','We','Th','Fr','Sa');
    }

	// html voor weekday namen in tabel
	
    var weekdays = "<TR>";
    for (i in weekdayArray) {
        weekdays += "<TH align=center style=\"width: 50px\">" + weekdayArray[i] + "</TH>";
    }
    weekdays += "</TR>";

    return weekdays;
}


function jsReplace(inString, find, replace) {
    var outString = "";

    if (!inString) {
        return "";
    }

    if (inString.indexOf(find) != -1) {
        t = inString.split(find);
        return (t.join(replace));
    } else {
        return inString;
    }
}


function doNothing() {
}


function makeTwoDigit(inValue) {
    var numVal = parseInt(inValue, 10);

    if (numVal < 10) {
        return("0" + numVal);
    } else {
        return numVal;
    }
}


function getFormatDate(inDay) {

    calDate.setDate(inDay);

    // SET THE DATE RETURNED TO THE USER
	
    var day           = calDate.getDate();
    var month         = calDate.getMonth()+1;
    var year          = calDate.getFullYear();
    var monthString   = monthArray[calDate.getMonth()];
    var monthAbbrev   = monthString.substring(0,3);
    var weekday       = weekdayList[calDate.getDay()];
    var weekdayAbbrev = weekday.substring(0,3);

    outDate = calDateFormat;

    if (calDateFormat.indexOf("DD") != -1) {
        day = makeTwoDigit(day);
        outDate = jsReplace(outDate, "DD", day);
    } else if (calDateFormat.indexOf("dd") != -1) {
        outDate = jsReplace(outDate, "dd", day);
    }

    if (calDateFormat.indexOf("MM") != -1) {
        month = makeTwoDigit(month);
        outDate = jsReplace(outDate, "MM", month);
    } else if (calDateFormat.indexOf("mm") != -1) {
        outDate = jsReplace(outDate, "mm", month);
    }

    if (calDateFormat.indexOf("yyyy") != -1) {
        outDate = jsReplace(outDate, "yyyy", year);
    } else if (calDateFormat.indexOf("yy") != -1) {
        var yearString = "" + year;
        var yearString = yearString.substring(2,4);
        outDate = jsReplace(outDate, "yy", yearString);
    } else if (calDateFormat.indexOf("YY") != -1) {
        outDate = jsReplace(outDate, "YY", year);
    }

    if (calDateFormat.indexOf("Month") != -1) {
        outDate = jsReplace(outDate, "Month", monthString);
    } else if (calDateFormat.indexOf("month") != -1) {
        outDate = jsReplace(outDate, "month", monthString.toLowerCase());
    } else if (calDateFormat.indexOf("MONTH") != -1) {
        outDate = jsReplace(outDate, "MONTH", monthString.toUpperCase());
    }

    if (calDateFormat.indexOf("Mon") != -1) {
        outDate = jsReplace(outDate, "Mon", monthAbbrev);
    } else if (calDateFormat.indexOf("mon") != -1) {
        outDate = jsReplace(outDate, "mon", monthAbbrev.toLowerCase());
    } else if (calDateFormat.indexOf("MON") != -1) {
        outDate = jsReplace(outDate, "MON", monthAbbrev.toUpperCase());
    }

    // RETURN WEEKDAY (Initial Caps)
	
    if (calDateFormat.indexOf("Weekday") != -1) {
        outDate = jsReplace(outDate, "Weekday", weekday);
    } else if (calDateFormat.indexOf("weekday") != -1) {
        outDate = jsReplace(outDate, "weekday", weekday.toLowerCase());
    } else if (calDateFormat.indexOf("WEEKDAY") != -1) {
        outDate = jsReplace(outDate, "WEEKDAY", weekday.toUpperCase());
    }

    if (calDateFormat.indexOf("Wkdy") != -1) {
        outDate = jsReplace(outDate, "Wkdy", weekdayAbbrev);
    } else if (calDateFormat.indexOf("wkdy") != -1) {
        outDate = jsReplace(outDate, "wkdy", weekdayAbbrev.toLowerCase());
    } else if (calDateFormat.indexOf("WKDY") != -1) {
        outDate = jsReplace(outDate, "WKDY", weekdayAbbrev.toUpperCase());
    }

	return outDate;
}


function returnDate(inDay) {
	var nDate = new Date();
	nDate.setHours(0);
	nDate.setMinutes(0);
	nDate.setSeconds(0);

	calDate.setDate(inDay);
	if(calDate < nDate){
		alert("u kunt geen datum in het verleden kiezen, probeer opnieuw.");
		top.newWin.focus();
		return false;
	}

	var outDate = getFormatDate(inDay);
    calDateField.value = outDate;
    calDateField.focus();
    top.newWin.close()
}
