$(document).ready(function() {
$(serverVars.FormControlArrivalID).datepick({
        alignment: 'bottomRight',
        showOn: 'both',
        buttonImageOnly: true,
        buttonImage: '/imagescss/enquirydirect/calendar.jpg',
        buttonText: 'Calendar',
        duration: 0, //'fast',
        numberOfMonths: 1,
        stepMonths: 1,
        //        showCurrentAtPos: 1,
        minDate: +1,
        closeAtTop: false,
        changeMonth: false,
        changeYear: false,
        //        showStatus: true,
        dateFormat: serverVars.JQCalendardateFormat,
        dateStatus: serverVars.JQCalendardateFormat,
        defaultDate: +7,
        firstDay: 1,
        mandatory: true,
        //        navigationAsDateFormat: true,
        hideIfNoPrevNext: true,
        //        prevText: '< MM',
        //        currentText: 'MM y',
        //        nextText: 'MM >',
        //yearRange: '+0:+2',
        maxDate: serverVars.JQCalendardateMaxDateArrival,
        //gotoCurrent: true, // currentText: 'Current', 
        //showBigPrevNext: true, 
        //showOtherMonths: true,
        //selectOtherMonths: true,
        onSelect: function(value, date) { arrivalSelect(value, date); }
    });
    $(serverVars.FormControlDepartureID).datepick({
        alignment: 'bottomRight',
        showOn: 'both',
        buttonImageOnly: true,
        buttonImage: '/imagescss/enquirydirect/calendar.jpg',
        buttonText: 'Calendar',
        duration: 0, //'fast',
        numberOfMonths: 1,
        stepMonths: 1,
        //        showCurrentAtPos: 1,
        minDate: +2,
        closeAtTop: false,
        changeMonth: false,
        changeYear: false,
        //        showStatus: true,
        dateFormat: serverVars.JQCalendardateFormat,
        dateStatus: serverVars.JQCalendardateFormat,
        defaultDate: +14,
        firstDay: 1,
        mandatory: true,
        //        navigationAsDateFormat: true,
        hideIfNoPrevNext: true,
        //        prevText: '< MM',
        //        currentText: 'MM y',
        //        nextText: 'MM >',
        maxDate: serverVars.JQCalendardateMaxDateDeparture,
        onSelect: function(value, date) { departureSelect(value, date); }
    });
    $(serverVars.FormControlNightsID).keyup(function(event) { nightsKeyup(event); });

    $(serverVars.FormControlArrivalID).datepick('setDate', serverVars.valueArrival, serverVars.valueArrival);
    $(serverVars.FormControlDepartureID).datepick('setDate', serverVars.valueDeparture, serverVars.valueDeparture);
    $(serverVars.FormControlNightsID).val(serverVars.valueNights);
    //Calendar Theme Switcher
//    $('#styleSelect').change(function() {
//        var themes = $(this).val().split(',');
//        $.datepick.setDefaults({ useThemeRoller: !!themes[1] });
//        if (themes[1] && !$.browser.msie) {
//            $('#themeui').attr('href',
//            '/js/datepicker/' + themes[1] + '/ui.all.css');
//        }
//        $('#theme').attr('href', '/js/datepicker/' + themes[0]);
//        // Allow time to load styles, then redraw inline datepickers 
//        setTimeout(function() {
//            $('input.hasDatepick').each(function() {
//                var settings = $.data(this, 'datepick').settings;
//                $(this).datepick('destroy').datepick(
//                    $.extend(settings, { useThemeRoller: !!themes[1] }));
//            });
//        }, 500);
//    });
//    $("textarea").expandable({ within: 0, by: 1 });
});

//EVENT FUNCTIONS
function arrivalSelect(dateString, date) {
    //bevor serverVars.valueArrival geändert wird auf LessNightsThanDatespan testen
    var isLessNightsThanDatespan = TestLessNightsThanDatespan();
    //set internal Variable to new date from Datepicker
    serverVars.valueArrival = date;
    //check if new arrival is later/equal than old departure
	if (serverVars.valueDeparture <= serverVars.valueArrival) {
	    var newdeparture = new Date(GetDateWithoutTime(serverVars.valueArrival) + OneDayInMs);
		$(serverVars.FormControlDepartureID).datepick('setDate', newdeparture, newdeparture)
		serverVars.valueDeparture = newdeparture
		FlashDeparture();
	}
    //update Nights
	var nightsNewDatespan = CalcNights(serverVars.valueArrival, serverVars.valueDeparture);
	UpdateNightsField(nightsNewDatespan, isLessNightsThanDatespan);
	//set mindate departure
	$(serverVars.FormControlDepartureID).datepick('option', 'minDate', new Date(GetDateWithoutTime(serverVars.valueArrival) + OneDayInMs));
}

function departureSelect(dateString, date) {
    //bevor serverVars.valueArrival geändert wird auf LessNightsThanDatespan testen
    var isLessNightsThanDatespan = TestLessNightsThanDatespan();
    //set internal Variable to new date from Datepicker
    serverVars.valueDeparture = date;
    //check if new departure is earlier/equal than old arrival
	if (serverVars.valueDeparture <= serverVars.valueArrival) {
	    var newarrival = new Date(GetDateWithoutTime(serverVars.valueDeparture) - OneDayInMs);
	    $(serverVars.FormControlArrivalID).datepick('setDate', newarrival, newarrival)
	    serverVars.valueArrival = newarrival
	    FlashArrival();
	}
	//update Nights
	var nightsNewDatespan = CalcNights(serverVars.valueArrival, serverVars.valueDeparture);
	UpdateNightsField(nightsNewDatespan, isLessNightsThanDatespan);
	//set mindate departure
	$(serverVars.FormControlDepartureID).datepick('option', 'minDate', new Date(GetDateWithoutTime(serverVars.valueArrival) + OneDayInMs));
}

function nightsKeyup(event) {
    //                window.nightschanged = true;
    //                $('#chkforcenights').attr('checked', true);
    var nightsInField = parseInt($(serverVars.FormControlNightsID).val());
    //if user entered non-number stop 
    if (isNaN(nightsInField))
        return;
    //ensure user cannot enter less than 1 night
    if (nightsInField < 1) {
        $(serverVars.FormControlNightsID).val(1);
        nightsInField = 1;
    }
    //ensure user cannot enter more than 365 night
    var maxNightsRemaining=CalcNightsByNights(serverVars.valueArrival,nightsInField);
    if (nightsInField >maxNightsRemaining) {
        $(serverVars.FormControlNightsID).val(maxNightsRemaining);
        nightsInField = maxNightsRemaining;
    }
    //if user entered more nights than in span, post-pone departure
    var nightsSpanCurrent=CalcNights(serverVars.valueArrival, serverVars.valueDeparture);
    if (nightsInField > nightsSpanCurrent) {
        var newDeparture = CalcDepartureFromArrivalPlusNights(serverVars.valueArrival, nightsInField);
        serverVars.valueDeparture = newDeparture;
        $(serverVars.FormControlDepartureID).datepick('setDate', newDeparture, newDeparture);
        FlashDeparture();         
        UpdateNightsText(false, nightsSpanCurrent);
    } else if (nightsInField == nightsSpanCurrent) {
        UpdateNightsText(false, nightsSpanCurrent);
    } else {
        UpdateNightsText(true, nightsSpanCurrent);
    }
}
//HELPERS
var OneDayInMs = 1000 * 60 * 60 * 24;
function CalcNights(arrival, departure) {
    var nights = (new Date(Date.UTC(departure.getFullYear(), departure.getMonth(), departure.getDate())).getTime() -
                  new Date(Date.UTC(arrival.getFullYear(), arrival.getMonth(), arrival.getDate())).getTime()) / OneDayInMs;
    return nights;
}
function CalcNightsByNights(arrival, nights) {
    var maxNightsRemaining=CalcNights(serverVars.valueArrival,serverVars.JQCalendardateMaxDateDeparture);
    var departure=new Date(Date.UTC(arrival.getFullYear(), arrival.getMonth(), arrival.getDate()));
    if(nights>maxNightsRemaining)
        return maxNightsRemaining;
    return nights;
}

function CalcDepartureFromArrivalPlusNights(arrival, nights) {
    var departureTime = new Date(Date.UTC(arrival.getFullYear(), arrival.getMonth(), arrival.getDate())).getTime() + OneDayInMs * nights;
    var departure = new Date(departureTime);
    return departure;
}

function GetDateWithoutTime(value) {
    //return date.getTime();
    var temp = new Date(Date.UTC(value.getFullYear(), value.getMonth(), value.getDate()));
    return temp.getTime();
}

function TestLessNightsThanDatespan() {
    var isLessNightsThanDatespan = false;
    var nightsOldDatespan = CalcNights(serverVars.valueArrival, serverVars.valueDeparture);
    var nightsFromField = parseInt($(serverVars.FormControlNightsID).val());
    //prüfen ob nächte-in-zeitraum kleiner als zeitraum
    if (nightsOldDatespan != nightsFromField) {
        //user setted less nights in bigger Datespan before
        isLessNightsThanDatespan = true;
    }
    return isLessNightsThanDatespan;
}

function UpdateNightsField(nightsSpan, keepSmallerNightsFieldValue) {
    var nightsField = $(serverVars.FormControlNightsID).val();
    if (nightsField == "" || nightsField == undefined || nightsField == NaN) {
        $(serverVars.FormControlNightsID).val(nightsSpan);
//        console.log('UpdateNightsField.1');
        FlashNights();
        //TODO validator auslösen für nights
        $(serverVars.FormControlNightsID).keyup();
        UpdateNightsText(false, null);
    } else if (keepSmallerNightsFieldValue && nightsField < nightsSpan) {
        //keep smaller range
        UpdateNightsText(true,nightsSpan);
    } else {
        $(serverVars.FormControlNightsID).val(nightsSpan);
//        console.log('UpdateNightsField.2');
        FlashNights();
        UpdateNightsText(false, null);
    }
}

function UpdateNightsText(show, nightsSpan) {
    if (show) {
        //keep smaller range
        $('label' + serverVars.FormControlNightsRangeTextID).html(serverVars.NightsRangeText.replace('{0}', nightsSpan));
        //console.log('UpdateNightsText.1');
        //FlashNights();
    } else {
        //set new range
        if ($('label' + serverVars.FormControlNightsRangeTextID).html() != '') {
            $('label' + serverVars.FormControlNightsRangeTextID).html('')
            //console.log('UpdateNightsText.2');
            //FlashNights();
        }
    }
}

function FlashNights() {
    $(serverVars.FormControlNightsID).stop();
    $(serverVars.FormControlNightsID).css({ 'background-color': '#ff0' });
    $(serverVars.FormControlNightsID).animate({ backgroundColor: "#fff" }, 2000, function() {
        $(serverVars.FormControlNightsID).css({ 'background-color': '' });
    });
}
function FlashArrival() {
    $(serverVars.FormControlArrivalID).stop();
    $(serverVars.FormControlArrivalID).css({ 'background-color': '#ff0' });
    $(serverVars.FormControlArrivalIDl).animate({ backgroundColor: "#fff" }, 2000, function() {
        $(serverVars.FormControlArrivalID).css({ 'background-color': '' });
    });
}
function FlashDeparture() {
    $(serverVars.FormControlDepartureID).stop();
    $(serverVars.FormControlDepartureID).css({ 'background-color': '#ff0' });
    $(serverVars.FormControlDepartureID).animate({ backgroundColor: "#fff" }, 2000, function() {
        $(serverVars.FormControlDepartureID).css({ 'background-color': '' });
    });
}
function ShowAGB(obj) {
    if (confirm(serverVars.AGB)) {
        $(serverVars.FormControlAgbID).attr('checked', true);
    } else {
        $(serverVars.FormControlAgbID).attr('checked', false);
    };
}

////http://www.nabble.com/Validate-plugin-with-radio-button-in-IE-6---7-td22459108s27240.html
//jQuery.validator.addMethod("defaultvalue", function(value, element) {
//    //defaultValueJQ    wurde in jquery.defaultvalue-1.0.js mittels mxg hack gesetzt
//    return this.optional(element) || $(element).attr('defaultValueJQ') != value || $(element).attr('defaultValueStripOnSubmit') == value;
//}, " ");

