//
//
//
// Init page specific static data
//
//
//

MW.i18n = {
    /*ERR_MSG_NO_COUNTRY        : "Please select your pick up country.",
    ERR_MSG_NO_CITY           : "Please select a pick up city.",
    ERR_MSG_NO_LOCATION       : "Please select a pick up location.",
    */
    ERR_MSG_NO_COUNTRY        : "Bitte w"+String.fromCharCode(228)+"hlen Sie ein Anmietland.",
    ERR_MSG_NO_CITY           : "Bitte w"+String.fromCharCode(228)+"hlen Sie einen Anmietort.",
    ERR_MSG_NO_LOCATION       : "Bitte w"+String.fromCharCode(228)+"hlen Sie eine Anmietstation.",
    ERR_MSG_WRONG_DATEFORMAT  : "Bitte geben Sie das Datum im folgenden Format ein: TT.MM.JJJJ",
    ERR_MSG_NO_DATES_IN_PAST  : "Bitte geben Sie ein Datum ein, das in der Zukunft liegt.",
    ERR_MSG_TO_EARLIER_FROM   : "Das Anmietdatum muss vor dem R"+String.fromCharCode(252)+"ckgabedatum liegen.",
    ERR_MSG_BOOKTIME_TOO_LONG : "Die maximale Anmietdauer wurde "+String.fromCharCode(252)+"berschritten.",
    ERR_MSG_INCORRECT_TIME    : "Die Mindestanmietdauer betr"+String.fromCharCode(228)+"gt 1 Stunde.",
    ERR_MSG_NO_PICKUPSTATION  : "Bitte w"+String.fromCharCode(228)+"hlen Sie eine Anmietstation",
    ERR_MSG_NO_DRIVER_AGE     : "Bitte geben Sie ein g"+String.fromCharCode(252)+"ltiges Fahreralter an.",
    ERR_MSG_NO_DROPOFFSTATION : "Bitte w"+String.fromCharCode(228)+"hlen Sie eine R"+String.fromCharCode(252)+"ckgabestation"
};

MW.settings = {
    ////  "fromDate" offset from the current date, in days.
    //
    fromdate_offset : 14,

    ////  "toDate" offset from the current date, in days.
    //
    todate_offset   : 21,

    //// Maximum interval between "fromDate" and "toDate, a.k.a "maxRentalTime".
    //   If exceeded, the ERR_MSG_BOOKTIME_TOO_LONG error message will be shown.
    //   Expressed in days
    //
    max_rental_time : 30,

    //// Minimal interval between "fromDate" and "toDate, a.k.a "minRentalTime"
    //   If less, the ERR_MSG_INCORRECT_TIME error message will be shown.
    //   Expressed in days. 1/24 of a day is one hour.
    //
    min_rental_time : 1/24,

    date_format : '%d.%m.%Y'    
}


//
//
//
//
// Classes
//
//
//
//
MW.classes.tabs = Class.create({
    initialize: function(options){
        this.options = Object.extend({
            tabs_selector        : '#tab-links li a:nth-child(1)',
            active_tab_classname : 'active',
            hidden_classname     : 'hidden',
            fade_time            : 0.2,
            play_timeout         : 1,
            resume_playback_after: 5,
            effect               : false
        }, options || {});

        this.tabs               = $$(this.options.tabs_selector);
		this.tabs_detected      = !!this.tabs.length;

		if(this.tabs_detected)
		{
	        this.current_active_tab = this.tabs[0];
	        this.autoplay_timeout   = false;
	        this._effect_active     = false;
	
	        // Bind internal callbacks to this instance
	        this.tab_click_callback = this._tab_click_callback.bind(this);
	        this.play_iteration     = this._play_iteration.bind(this);
	
	        // Register tab click event observers
	        this.tabs.invoke('observe', 'click', this.tab_click_callback);
	
	        // Mark the first tab active
	        this.tabs.invoke('removeClassName', this.options.active_tab_classname);
	        this.tabs[0].addClassName(this.options.active_tab_classname);
	
	        // Hide all tabs but the first one
	        this.tabs.each(function(elm, pos){
	            this.tab_content_ref(elm).addClassName(pos?this.options.hidden_classname: '');
	        }.bind(this));
		}
    },

    //
    //
    //
    //
    //
    //

    //
    //
    tab_content_ref: function(elm){
        return $(elm.href.substr(elm.href.lastIndexOf('#')+1));
    },
    next_tab: function(){
        var result = this.current_active_tab;
        for(var i=0, cnt=this.tabs.length; i<cnt; i++)
            if(this.tabs[i] == this.current_active_tab)
                result = (i+1 == cnt) ? this.tabs[0]: this.tabs[i+1];

        return result;
    },

    switch_tabs: function(prev, next){
        var prev_content = this.tab_content_ref(prev);
        var next_content = this.tab_content_ref(next);

        this._effect_active = true;
        switch(this.options.effect)
        {
            ////
            //
            default:
                //
                ////
                prev_content.addClassName(this.options.hidden_classname);
                next_content.removeClassName(this.options.hidden_classname);
                break;

            ////
            //
            case 'fade':
                //
                ////
                prev_content.fade({
                    duration: this.options.fade_time,
                    afterFinish: function(next){
                        next_content.removeClassName(this.options.hidden_classname).setStyle({
                            'display': 'none'
                        }).appear({
                            duration: this.options.fade_time
                            });
                    }.bind(this, next_content)
                    });
                break;
        }
        this._effect_active = false;

        // Mark the tab active
        this.tabs.invoke('removeClassName', this.options.active_tab_classname);
        next.addClassName(this.options.active_tab_classname);

        this.current_active_tab = next;
    },
    switch_to_tab: function(next){
        this.switch_tabs(this.current_active_tab, next);
    },
    switch_to_next_tab: function(){
        this.switch_tabs(this.current_active_tab, this.next_tab());
    },


    //
    //
    //
    //
    //

    //
    //
    _tab_click_callback: function(evt){
        evt.stop();
        var elm = evt.element();

        // Don't do anything if we clicked the already active tab
        if(this.current_active_tab == elm)
            return;

        // Reset the autoplay timeout
        clearTimeout(this.autoplay_timeout);
        this.autoplay_timeout = setTimeout(this.play_iteration, this.options.resume_playback_after*1000);

        if(this._effect_active)
            this.switch_to_tab.delay(this.options.fade_time*2, elm);
        else
            this.switch_to_tab(elm);
    },


    //
    //
    _play_iteration: function(delay){
        if(!delay)
            this.switch_to_next_tab();
        this.autoplay_timeout = setTimeout(this.play_iteration, this.options.play_timeout*1000);
    },

    //
    //
    play: function(delay){
		if(this.tabs_detected)
	        this.play_iteration(delay);
    },

    //
    //
    stop: function(){
        clearTimeout(this.autoplay_timeout);
    }
});




//
//
//
// Functions
//
//
//

MW.functions.load_countries = function(country_id){
    out.info('load_countries('+country_id+')');
    // 'loading' image
    $('carCountry_loading').setStyle({visibility: 'visible'});
    // Disable and clear the dropdown, show loader over it
    out.log('Disabling dropdown, clearing previos entries and showing loader...');
    MW.ref.country.disable().truncate();

    // Do AJAX
    MW.ajax.request({
    	host: 'www.m-broker.de',
    	uri: '/ajax.php',
    	module: 77,
        action: 'get_country_list'
    }, function(country_id, reply, request) {
        // 'loading' image
        $('carCountry_loading').setStyle({visibility: 'hidden'});
        // Cache returned results
        out.log('Storing the result in cache');
        MW.ajax.data.countries = reply.countries;
        MW.ajax.data.areas     = reply.areas;

        // Build dropdown
        out.log('Building dropdown, hiding loader and enabling the dropdown...');
        MW.ref.country.build(reply.countries, reply.areas);


        // Hide the 'hidden' countries and if they have areas, remove their margin
        for(var i=0, cnt=reply.countries.length; i<cnt; i++)
        {
            if(reply.countries[i].hidden != 0)
            {
                // Hide this country in the dropdown
                var option = $(MW.ref.country.find(reply.countries[i].value));
                option.parentNode.removeChild(option);

                // Remove the marging from the areas
                var areas = $H(reply.areas).get(reply.countries[i].value);
                if(areas)
                    for(var j=0, cnt2=areas.length; j<cnt2; j++)
                        $(MW.ref.country.find(areas[j].value)).addClassName('no-margin');
            }
        }

        MW.ref.country.choose(country_id);
		MW.functions.add_top_countries();

        // Enable the dropdown once we're done
        MW.ref.country.enable();
    }.bind(this, country_id)
        );
};

//
//
//

MW.functions.add_top_countries = function(){
	if(MW.page.topCountries && MW.page.topCountries.length)
	{
	    var select = MW.ref.country;
	    var clones = [];
	    var tmp;

	    for(var i=0, cnt=MW.page.topCountries.length; i<cnt; i++)
	    {
	        tmp = select.find(MW.page.topCountries[i]);
	        tmp && clones.push(tmp.cloneNode(true));
	    }
	
	    if(clones.length)
	    {
	        var blank = (new Element('option', {value:'0'})).update('&mdash;'.times(15));
	        select.down().insert({after: blank.cloneNode(true)});
	
	        for(var i=clones.length-1; i>=0; i--)
	            select.down().insert({after: clones[i]});
	
	        select.down().insert({after: blank.cloneNode(true)});
	    }
	}
};

MW.functions.validate_form_data = function(){
    var error = false;

    //  Check if the country was selected
    //
    if($F(MW.ref.country) == 0)
        error = MW.i18n.ERR_MSG_NO_COUNTRY;


    ////  Check that the city has been selected
    //
    if(!error && $F(MW.ref.city) == 0)
        error = MW.i18n.ERR_MSG_NO_CITY;

    ////  Check that the city has been selected
    //
    if(!error && $F(MW.ref.location) == 0)
        error = MW.i18n.ERR_MSG_NO_LOCATION;


    var currentDate = new Date();
    var suppliedFromDate = MW.functions.date_get_from_value($F('carFromDate'), $F('carFromHour'), $F('carFromMinute'));
    var suppliedToDate   = MW.functions.date_get_from_value($F('carToDate')  , $F('carToHour')  , $F('carToMinute')  );


    ////  Make sure both dates are properly formatted
    //
    if(!error && !(suppliedFromDate || suppliedToDate))
        error = MW.i18n.ERR_MSG_WRONG_DATEFORMAT;

    ////  Make sure we are not trying to use dates in the past
    //
    if(!error && (suppliedFromDate < currentDate.getTime() || suppliedToDate < currentDate.getTime()))
        error = MW.i18n.ERR_MSG_NO_DATES_IN_PAST;

    ////  Make sure the "from" date is actually earlier then the "end" date
    //
    if(!error && (suppliedFromDate >= suppliedToDate))
        error = MW.i18n.ERR_MSG_TO_EARLIER_FROM;

    ////  Make sure the user doesn't book a car for less then MIN_RENTAL_TIME period
    //
    if(!error && ((suppliedToDate - suppliedFromDate) < MW.settings.min_rental_time*60*60*24*1000))
        error = MW.i18n.ERR_MSG_INCORRECT_TIME;

    ////  Make sure the user doesn't book a car over the MAX_RENTAL_TIME period
    //
    if(!error && ((suppliedToDate - suppliedFromDate) > MW.settings.max_rental_time*60*60*24*1000))
        error = MW.i18n.ERR_MSG_BOOKTIME_TOO_LONG;


    ////  Make sure we are not trying to book from a date that is more then a year in the future
    //
    var todayDate = new Date();
    var tmpMaxDate = todayDate.getTime() + Date.DAY*365*2;

    if(!error && (suppliedFromDate > tmpMaxDate || suppliedToDate > tmpMaxDate))
        error = MW.i18n.ERR_MSG_BOOKTIME_TOO_LONG;
    
    ////  Check that the driver age has been selected
    //
    if(!error && $F(MW.ref.driver_age) == 0)
    	error = MW.i18n.ERR_MSG_NO_DRIVER_AGE;

    return error;
}



//
//
//
//
MW.functions.init_form = function(){
    // Initially disable all the selects in the form
    //
    MW.ref.country.disable();
    MW.ref.city.disable();
    MW.ref.location.disable();

    // Determine the form initial data
    //
    var use_country  = MW.input&&MW.input.page1&&MW.input.page1.country   ? MW.input.page1.country   : MW.page.url.country   ? MW.page.url.country   : MW.page.form.country;
    var use_city     = MW.input&&MW.input.page1&&MW.input.page1.city      ? MW.input.page1.city      : MW.page.url.city      ? MW.page.url.city      : MW.page.form.city;
    var use_location = MW.input&&MW.input.page1&&MW.input.page1.location  ? MW.input.page1.location  : MW.page.url.location  ? MW.page.url.location  : MW.page.form.location;
    var use_fromdate = MW.input&&MW.input.page1&&MW.input.page1.from_date ? MW.input.page1.from_date : MW.page.url.from_date ? MW.page.url.from_date : MW.page.form.from_date;
    if(!use_fromdate)
    {
        var tmpDate = new Date();

        tmpDate.setTime(tmpDate.getTime() + MW.settings.fromdate_offset*60*60*24*1000);
        use_fromdate = tmpDate.print(MW.settings.date_format);
    }

    var use_from_hour   = MW.input&&MW.input.page1&&MW.input.page1.from_hour   ? MW.input.page1.from_hour   : MW.page.url.from_hour   ? MW.page.url.from_hour   : MW.page.form.from_hour;
    var use_from_minute = MW.input&&MW.input.page1&&MW.input.page1.from_minute ? MW.input.page1.from_minute : MW.page.url.from_minute ? MW.page.url.from_minute : MW.page.form.from_minute;

    var use_todate = MW.input&&MW.input.page1&&MW.input.page1.to_date ? MW.input.page1.to_date : MW.page.url.to_date ? MW.page.url.to_date : MW.page.form.to_date;
    if(!use_todate)
    {
        var tmpDate = new Date();

        tmpDate.setTime(tmpDate.getTime() + MW.settings.todate_offset*60*60*24*1000);
        use_todate = tmpDate.print(MW.settings.date_format);
    }

    var use_to_hour   = MW.input&&MW.input.page1&&MW.input.page1.to_hour ? MW.input.page1.to_hour : MW.page.url.to_hour ? MW.page.url.to_hour : MW.page.form.to_hour;
    var use_to_minute = MW.input&&MW.input.page1&&MW.input.page1.to_minute ? MW.input.page1.to_minute : MW.page.url.to_minute ? MW.page.url.to_minute : MW.page.form.to_minute;


    out.log('Determining the form initial data...');
    out.log('use_country    : %s', use_country);
    out.log('use_city       : %s', use_city);
    out.log('use_location   : %s', use_location);
    out.log('use_fromdate   : %s', use_fromdate);
    out.log('use_from_hour  : %s', use_from_hour);
    out.log('use_from_minute: %s', use_from_minute);
    out.log('use_todate     : %s', use_todate);
    out.log('use_to_hour    : %s', use_to_hour);
    out.log('use_to_minute  : %s', use_to_minute);

    //
    // Action
    //

    MW.functions.load_countries(use_country);

    if(use_country)
    {
        // Disable the interface controls
        //
        MW.ref.city.disable().truncate();
        MW.ref.location.disable();

        // Do AJAX
        MW.ajax.request({
        	host: 'www.m-broker.de',
        	uri: '/ajax.php',
        	module: 77,
            action: 'get_city_list',
            country_id: use_country
        }, function(city_id, reply, request) {
            // Cache returned results
            out.log('Storing the result in cache');
            MW.ajax.data.cities = reply;

            // Build dropdown, hide loader and enable dropdown
            out.log('Building dropdown, %d items', reply.length);
            out.log('Hiding loader and enabling dropdown...');
            MW.ref.city.build(reply).choose(use_city).enable();
        }.bind(this, use_city)
            );


        //
        //
        //
        if(use_city)
        {
            MW.ref.location.disable();
            while(MW.ref.location.options.length > 2)
                MW.ref.location.options[2] = null;

            MW.ref.location.disable();

            MW.ajax.request({
            	host: 'www.m-broker.de',
            	uri: '/ajax.php',
            	module: 77,
                action: 'get_location_list',

                country_id: use_country,
                city_id   : use_city
            }, function(location_id, reply, request){
                // Cache returned results
                MW.ajax.data.locations = reply;

                MW.ref.location.build(reply).choose(location_id).enable();
            }.bind(this, use_location)
                );
        }
    }

    MW.ref.from_date.value = use_fromdate;
    MW.ref.to_date.value   = use_todate;

    MW.ref.from_hour.choose(use_from_hour);
    MW.ref.from_minute.choose(use_from_minute);
    MW.ref.to_hour.choose(use_to_hour);
    MW.ref.to_minute.choose(use_to_minute);
};


//
//
//
//
MW.functions.init_calendars = function(){
    //
    // Calendar
    //

    ////  Make sure we have only the current and the next years enabled in the calendar.
    //    yearRange is an array of 2 elements, [startYear, endYear]
    //
    var yearRange;
    var tmpDate     = new Date();
    var currentYear = tmpDate.getFullYear();
    yearsRange      = [currentYear, currentYear+1];

    ////  Calendar setup constructs
    //
    Calendar.setup({
        inputField     : MW.ref.from_date.id,
        //button         : 'carFromDate_calendar',
        button         : 'fromdate-calendar-trigger',
        ifFormat       : MW.settings.date_format,
        singleClick    : true,
        firstDay       : 1,
        //align          : "Br",
        range          : yearsRange,
        weekNumbers    : false,
        disableFunc    : MW.callbacks.fromdate_disableDate_callback,
        onUpdate       : MW.callbacks.fromdate_onUpdate_callback,
        showsTime      : false,
        timeFormat     : "24",
        step           : 1,
        position       : null
    });

    Calendar.setup({
        inputField     : MW.ref.to_date.id,
        //button         : 'carToDate_calendar',
        button         : 'todate-calendar-trigger',
        ifFormat       : MW.settings.date_format,
        singleClick    : true,
        firstDay       : 1,
        //align          : "Br",
        range          : yearsRange,
        weekNumbers    : false,
        disableFunc    : MW.callbacks.todate_disableDate_callback,
        onUpdate       : MW.callbacks.todate_onUpdate_callback,
        showsTime      : false,
        timeFormat     : "24",
        step           : 1,
        position       : null
    });
};


//
//
//
//
//
MW.functions.init_tabs = function(){
    MW.ref.tabs = new MW.classes.tabs({
        tabs_selector        : '#offers ul.tab-nav li a:nth-child(1)',
        active_tab_classname : 'active',
        hidden_classname     : 'hidden',
        fade_time            : 1,
        play_timeout         : 10,
        resume_playback_after: 20,
        effect               : 'fade'
    });
    MW.ref.tabs.play(1);
};


//
//
//
//
MW.functions.init_top_offers = function(){
    $$('#top-offers li a').invoke('observe', 'click', function(evt){
        var elm = evt.element();

        $$('#top-offers li a').invoke('removeClassName', 'active');
        elm.addClassName('active');

        var country = /country=(\d+)/.exec(elm.href);
        var city    = /city=(\d+)/.exec(elm.href);

        country && (country = country[1]);
        city    && (city = city[1]);

        if(country && city)
        {
            evt.stop();

            MW.ref.country.disable();

            // Check to see if we need to load a new city list
            if(country != parseInt($F(MW.ref.country), 10))
            {
                // Need to load a new city list
                MW.ref.city.disable().truncate();
                MW.ajax.request({
                	host: 'www.m-broker.de',
                	uri: '/ajax.php',
                	module: 77,
                    action: 'get_city_list',
                    country_id: country
                }, function(city, reply, request) {
                    // Cache returned results
                    out.log('Storing the result in cache');
                    MW.ajax.data.cities = reply;

                    // Build dropdown, hide loader and enable dropdown
                    out.log('Building dropdown, %d items', reply.length);
                    out.log('Hiding loader and enabling dropdown...');
                    MW.ref.city.build(reply).choose(city).enable();
                }.bind(this, city)
                    );

                // Load locations
                while(MW.ref.location.options.length > 1)
                    MW.ref.location.options[1] = null;
                MW.ref.location.disable();

                MW.ajax.request({
                	host: 'www.m-broker.de',
                	uri: '/ajax.php',
                	module: 77,
                    action: 'get_location_list',

                    country_id: country,
                    city_id   : city
                }, function(reply, request){
                    // Cache returned results
                    MW.ajax.data.locations = reply;

                    MW.ref.location.build(reply).options[0].selected = true;
                    MW.ref.location.enable();
                }.bind(this)
                    );
            }
            // Select the active country
            MW.ref.country.choose(country);
            MW.ref.country.enable();
        }
    });
};



//
//
//
//
//
// Callbacks
//
//
//
//
//
MW.callbacks.load_cities = function(evt){
    var country_id = $F(evt.element());

    out.info('load_cities(%d)', country_id);

    MW.ref.location.disable();

    if(parseInt(country_id, 10) <= 0)
    {
        // Default country selected.
        out.log('Default country selected, nothing to load...');
        MW.ref.city.truncate();
        MW.ref.city.disable();

        return false;
    }

    // Disable the interface controls
    //
    MW.ref.city.disable().truncate();

    out.log('Non-zero country or area selected. Loading cities....');

    // Disable and clear the dropdown, show loader over it
    out.log('Disabling dropdown, clearing previos entries and showing loader...');
    // Do AJAX
    // 'loading' image
    $('carCity_loading').setStyle({visibility: 'visible'});
    MW.ajax.request({
    	host: 'www.m-broker.de',
    	uri: '/ajax.php',
    	module: 77,
        action: 'get_city_list',
        country_id: country_id
    }, function(reply, request) {
    	// 'loading' image
        $('carCity_loading').setStyle({visibility: 'hidden'});
        // Cache returned results
        out.log('Storing the result in cache');
        MW.ajax.data.cities = reply;

        // Build dropdown, hide loader and enable dropdown
        out.log('Building dropdown, %d items', reply.length);
        out.log('Hiding loader and enabling dropdown...');
        MW.ref.city.build(reply).enable();
    }
    );
};


//
//
//
//
//
MW.callbacks.load_locations = function(evt){
    var country_id = parseInt($F(MW.ref.country), 10);
    var city_id    = parseInt($F(evt.element()), 10);

    out.info('load_locations(%d, %d)', country_id, city_id);

    MW.ref.location.disable();
    while(MW.ref.location.options.length > 1)
        MW.ref.location.options[1] = null;

    if(city_id == 0)
    {
        // Default city selected, nothing to load
        out.log('Default city selected, nothing to load...');
    }
    else
    {
        out.log('Non-zero city selected. Loading locations....');

        MW.ref.location.disable();
        // 'loading' image
        $('carStations_loading').setStyle({visibility: 'visible'});
        MW.ajax.request({
        	host: 'www.m-broker.de',
        	uri: '/ajax.php',
        	module: 77,
            action: 'get_location_list',

            country_id: country_id,
            city_id   : city_id
        }, function(reply, request){
            // 'loading' image
            $('carStations_loading').setStyle({visibility: 'hidden'});
            // Cache returned results
            MW.ajax.data.locations = reply;

            out.log(MW.ajax.data.locations.length);
            out.log(MW.ajax.data.locations[0].name );
            if(MW.ajax.data.locations.length == 1 && MW.ajax.data.locations[0].name == 'Stadtstation'){
                MW.ref.location.build(reply).options[1].selected = true;
            }else{
                MW.ref.location.build(reply).options[0].selected = true;
            }
            MW.ref.location.enable();
        }.bind(this)
            );
    }
};



MW.callbacks.proceed = function(evt){
    evt.stop();

    var err_msg = MW.functions.validate_form_data();

    if(err_msg)
        alert(err_msg);
    else
    {
        MW.input.page1 = $('booking-form').to_json(['button-submit']);
		MW.input.page1 = Object.extend(MW.input.page1, {'partner_no': MW_PAGE.url.partner_no});

		// 200 000 is base parter_no for ferienauto.de
		MW.input.page1.partner_no = MW.input.page1.partner_no == '0' ?  200000 : MW.input.page1.partner_no;


        var input = Object.flatten_json(MW.input, 'input');
        var data  = Object.flatten_json(MW.data , 'data');

        var form = MW.functions.create_hidden_form('/auswahl/')
        form.extend_from_json(input).extend_from_json(data).submit();
    }
}



//
//
//
// Calendar
//
//
//

// Is called for every day of the month when calendar is displayed onscreen.
// Receives the Javascript Date object of the date the check is supposed to be made on.
// If returns "true", the date is rendered as 'disabled'
MW.callbacks.fromdate_disableDate_callback = function(givenDate){
    givenDate.setHours(0);
    givenDate.setMinutes(0);
    givenDate.setSeconds(0);

    var todayDate = new Date();
    var dateDisabled;

    ////  disable all dates selection prior the current day
    //
    if(givenDate.getTime()+Date.DAY > todayDate.getTime())
        dateDisabled = false;
    else
        dateDisabled = true;

    return dateDisabled;
};


// Calendar functions are called whenever the date in the 'fromdate' calendar is changed.
// Receives a instance of the calendar object
MW.callbacks.fromdate_onUpdate_callback = function(cal){
    var cal_fromday = Math.round(cal.date.getTime()/Date.DAY);
    var tempdate    = new Date();
    var now_day     = Math.round(tempdate.getTime()/Date.DAY);

    if(cal_fromday < now_day)
    {
        MW.ref.from_date.value = tempdate.print(cal.params.ifFormat);
        cal.date.setTime(tempdate.getTime());
        cal.refresh();
    }

    ////  update the "toDate" field according to the "fromDate" field date value
    //
    var tempdate = new Date();
    tempdate.setTime(cal.date.getTime()+(MW.settings.todate_offset - MW.settings.fromdate_offset)*60*60*24*1000);

    MW.ref.to_date.value = tempdate.print(cal.params.ifFormat);
};



// Is called whenever the date in the 'fromdate' calendar is changed.
// Receives a instance of the calendar object
MW.callbacks.todate_onUpdate_callback = function(cal){
    return true;
};


// Is called for every day of the month when calendar is displayed onscreen.
// Receives the Javascript Date object of the date the check is supposed to be made on.
// If returns "true", the date is rendered as 'disabled'
MW.callbacks.todate_disableDate_callback = function(date){
    date.setHours(0);
    date.setMinutes(0);
    date.setSeconds(0);

    var cal_date          = date.getTime();
    var current_from_date = MW.functions.date_get_from_value($F('carFromDate'), '00', '00')
    var max_time          = current_from_date + MW.settings.max_rental_time*60*60*24*1000;


    if(cal_date <= max_time && cal_date+Date.DAY > current_from_date)
        return false;
    else
        return true;
};










//
//
//
// DOM:LOADED event
//
//
//

document.observe('dom:loaded', function(){
    // Initialize internal data storage
    //
    MW.input = (typeof(MW_INPUT) == 'undefined') ? {} : MW_INPUT;
    MW.data  = (typeof(MW_DATA)  == 'undefined') ? {} : MW_DATA;
    MW.page  = (typeof(MW_PAGE)  == 'undefined') ? {} : MW_PAGE;
    //
    // Init references
    //
    MW.ref.country  = $('carCountry');
    MW.ref.city     = $('carCity');
    MW.ref.location = $('carStations');

    MW.ref.from_date   = $('carFromDate');
    MW.ref.from_hour   = $('carFromHour');
    MW.ref.from_minute = $('carFromMinute');

    MW.ref.to_date   = $('carToDate');
    MW.ref.to_hour   = $('carToHour');
    MW.ref.to_minute = $('carToMinute');

    MW.ref.fromdate_calendar = $('carFromDate_calendar');
    MW.ref.todate_calendar   = $('carToDate_calendar');

    MW.ref.driver_age   = $('driverAge');

    MW.ref.proceed = $('button-submit');


    //
    // Register event observers
    //
    MW.ref.country.observe('change', MW.callbacks.load_cities);
    MW.ref.city.observe('change', MW.callbacks.load_locations);
    $('button-submit').observe('click', MW.callbacks.proceed);


    //
    // Init
    //
    MW.functions.init_form();
    MW.functions.init_calendars();
    MW.functions.init_top_offers();
    MW.functions.init_tabs();


    // positioned calendars
    $("fromdate-calendar-trigger").observe("click",function(){
        var targetLocation = $("carFromHour");
        var targetOffset = targetLocation.cumulativeOffset();
        calendar.showAt(targetOffset[0],targetOffset[1]);
    });
    $("todate-calendar-trigger").observe("click",function(){
        var targetLocation = $("carFromHour");
        var targetOffset = targetLocation.cumulativeOffset();
        calendar.showAt(targetOffset[0],targetOffset[1]);
    });
    // driver age validation
    $('driverAge').observe('keydown', function(evt){
		var key = evt.keyCode;
		if(((key >= 48 && key <= 57) || (key >= 96 && key <= 105) 
				|| (key == 35) || (key == 36) || (key == 37) 
				|| (key == 39) || (key == 46)|| (key == 8)) == false ) {
			evt.stop();
		}
	})
	// submit by ENTER key
	$$('input, select').each(function(elt){
	    elt.observe('keydown', function(evt){
            var elm = evt.element().tagName.toLowerCase();
	    	if(evt.keyCode == 13 && (elm == 'input' || elm == 'select'))
			{
                evt.stop();
                setTimeout(function(){MW.callbacks.proceed()}, 20);
	    	}
	    })
	});

});

