var cur_pickup_loc = 0;
var cur_return_loc = 0;
var loc_info = [];
/**
*    Set events
**/

$(document).ready(function()
{
	 // Hide div by default.
    $('#van_info').css('display', 'none');
    
    // Prepare Pickup and Return options for first display    
    //hideOphalen(true);
    //hideInleveren(true);
    
    $('a#sel_return_loc_ec').hide();
    $('a#sel_return_loc_bl').hide();
    
    // Disable pickup time for first display
    $("#pickup_time0").attr("disabled", "disabled");

    //-------------------- Car Type Selections -----------------
    
    // Car type selected
    $("#veh_cat").change(handleCarTypeSelected);
    
    
    //-------------------- Pickup Selections -------------------
    
    // Pickup date changed
    $("#pickup_date0").change(handlePickupDateSelected);
    
    // Pickup time changed
    $("#pickup_time0").change(handlePickupTimeSelected);
    
    // One of ophalen options selected
    $("input[@name='chk_ophalen']").click(function(){              
        if ($("input[@name='chk_ophalen']:checked").val()=="0") {
        	
            $("#box_ophalen_rd1").hide();
            $("#box_ophalen_rd0").show();
            
            if($("input[@name='chk_inleveren']:checked").val()!="0") {
                $("input[@name='chk_inleveren']:nth(0)").attr("checked","checked");
                $("input[@name='chk_inleveren']").triggerHandler("click");
            }
            
            // Re-enable boels or europcar link when pickup service is disabled
            $('a#sel_return_loc_bl').fadeIn();
            
            // 
        	UpdateLocationInfo();
        } else {
            $("#box_ophalen_rd0").hide();
            $("#box_ophalen_rd1").show();
            $("#box_discount").fadeIn();
            $("#box_submit").fadeIn();
            
            // No Boels selection possible when pickup service is enabled.
            $('a#sel_return_loc_ec').fadeOut();
            $('a#sel_return_loc_bl').fadeOut();            
        	$('select#return_loc_ec').show();
        	$('select#return_loc_bl').hide();

        	UpdateLocationInfo();
        }
    })
    
    // Link location from Boels clicked
    $('a#sel_pickup_loc_bl').click(function(){
        $('select#return_loc_ec').get(0).selectedIndex = 0;
        $('select#return_loc_bl').get(0).selectedIndex = 0;
        ShowAlternateLocations('pickup_loc_bl', 'pickup_loc_ec', true);
        ShowAlternateLocations('return_loc_bl', 'return_loc_ec', true); 
        $('a#sel_return_loc_ec').show();
        $('a#sel_return_loc_bl').hide();
        
        // Select 'no discount' 
        $('#disc_none').get(0).checked = true;
        
        // Hide submit button
        $('#box_submit').hide();
        
        return false;
    })
    
    // Link location from Europcar clicked
    $('a#sel_pickup_loc_ec').click(function(){
        $('select#return_loc_ec').get(0).selectedIndex = 0;
        $('select#return_loc_bl').get(0).selectedIndex = 0;
        ShowAlternateLocations('pickup_loc_ec', 'pickup_loc_bl', true);
        ShowAlternateLocations('return_loc_ec', 'return_loc_bl', true);
        $('a#sel_return_loc_ec').hide();
        $('a#sel_return_loc_bl').hide();
        // Hide submit button
        $('#box_submit').hide();

        return false;
    })
    
    // Add event handler on location selects
    $('.loc_select').change(HandleLocationSelect);
    
    // Add event handlers on 'Check if delivery possible or not' links
    $('#btn_control_zip_code').click(function()
    {
    	var tmpZipCode = $$('pickup_zip_text').value;
    	tmpZipCode = tmpZipCode.toUpperCase();    	
    	$$('pickup_zip_text').value = tmpZipCode;

        var fullZipCode = $$('pickup_zip_text').value;
        var zip = $$('pickup_zip_text').value;
        
    	if(zip.length != 6) {
            $("#error_zip").addClass('error3');
            $("#error_zip_text").html('Helaas is de postcode onjuist ingevuld (bijv. 9999AA). </ br>');
            
            $("#succesful_zip").hide();
            $("#pickup_zip_possibility").val(-1);
            
            return false;
        }

        var level = /^[1-9][0-9]{3}[A-Z]{2}$/i;
        if (!level.test(zip))
        {
            $("#error_zip").addClass('error3');
            $("#error_zip_text").html('Helaas is de postcode onjuist ingevuld (bijv. 9999AA). </ br>');

            $("#succesful_zip").hide();
            $("#pickup_zip_possibility").val(-1);

            return false;        
        }   

        if(zip) getPickupInfo(zip, fullZipCode, "OPH");
    })
    
    if ($("input[@name='chk_ophalen']:checked").val() == 1) {
    	$('#btn_control_zip_code').click();
    }
    
    $("#pickup_zip_text").change(function(){
		$("#pickup_zip_possibility").val(-1);
    	$("#succesful_zip").fadeOut();
    });
    
    //-------------------- Return Selections ------------------- 
    
        // Return date changed
    $("#return_date0").change(handleReturnDateSelected);
    
    // Return time changed
    $("#return_time0").change(handleReturnTimeSelected);
    
    // One of inleveren options selected
    $("input[@name='chk_inleveren']").click(function(){              
        if ($("input[@name='chk_inleveren']:checked").val()=="0") {
        	$("#infobox_return").show();
        	
            $("#box_inleveren_rd1").hide();
            $("#box_inleveren_rd0").show();

            UpdateLocationInfo();
        } else {
            $("#box_inleveren_rd0").hide();
            $("#box_inleveren_rd1").show();

            UpdateLocationInfo();
        }
    })
    
    // Add event handlers on 'select alternate return location' links
    $('#sel_return_loc_bl').click(function()
    {
        ShowAlternateLocations('return_loc_bl', 'return_loc_ec', true);
        return false;
    })
    $('#sel_return_loc_ec').click(function()
    {
        ShowAlternateLocations('return_loc_ec', 'return_loc_bl', true);
        return false;
    })

    $('#btn_control_zip_code_inleveren').click(function()
    {
    	var tmpZipCode = $$('return_zip_text').value;
    	tmpZipCode = tmpZipCode.toUpperCase();    	
    	$$('return_zip_text').value = tmpZipCode;
    	
        var fullZipCode = $$('return_zip_text').value;
        var zip = $$('return_zip_text').value;        
        
        if(zip.length != 6)
        {
            $("#error_zip_inleveren").addClass('error3');
            $("#error_zip_text_inleveren").html('Helaas is de postcode onjuist ingevuld (bijv. 9999AA). </ br>');

            $("#succesful_zip_inleveren").hide();
            $("#return_zip_possibility").val(-1);

            return false;
        }
        
        var level = /^[1-9][0-9]{3}[A-Z]{2}$/i;
        if (!level.test(zip))
        {   
            $("#error_zip_inleveren").addClass('error3');
            $("#error_zip_text_inleveren").html('Helaas is de postcode onjuist ingevuld (bijv. 9999AA). </ br>');

            $("#succesful_zip_inleveren").hide();
            $("#return_zip_possibility").val(-1);

            return false;        
        }   
        if(zip)        
            getReturnInfo(zip, fullZipCode, "AFL");                            
        return false;                
    })
    
    if ($("input[@name='chk_inleveren']:checked").val() == 1) {
    	$('#btn_control_zip_code_inleveren').click();
    }
    
    $("#return_zip_text").change(function(){
    	$("#return_zip_possibility").val(-1);
    	$("#succesful_zip_inleveren").fadeOut();
    });

    
    //----------------------------------- Calendars ----------------------------
    
    // Add event handler to links to show calendars
    $('a.pickup_cal0').click(function()
    {
       	if ($('#pickup_calendar0').is(':hidden') == false) {
    		$('#pickup_calendar0').fadeOut();
    	} else {
    		// Remove calender if button/calendarimage is clicked.
    		createCalendar('pickup_calendar0', 'pickup_date0');
    	}
    	
    	// Hide the other calendar to prevent from overlapping.
        $('#return_calendar0').fadeOut();
        
        // Hide selects in pickup box in IE6, if box is visible
        if ($.browser.msie && $.browser.version == '6.0')
        {
            $('#box_return select').hide();
        }
        
        return false;
    })
    
    $('a.return_cal0').click(function()
    {
    	if ($('#return_calendar0').is(':hidden') == false) {
    		$('#return_calendar0').fadeOut();
    	} else {
    		// Remove calender if button/calendarimage is clicked.
    		createCalendar('return_calendar0', 'return_date0');
    	}

    	// Hide the other calendar to prevent from overlapping.
        $('#pickup_calendar0').fadeOut();

        return false;
    })

    //--------------------------------- LOGIN BOX ----------------------------------------
    
    // Add event handler to 'show login form' link
    $('a#show_login_form').click(function()
    {    
        $('#login_form').show();
        $('#login_username').focus();
        return false;
    })
    
    // ------------------------------- SUBMIT --------------------------------------------

     // Add event handler on submit link-button
    $('a#btn_submit').click(function()
    {
    	// Hide old error messages after a post.
    	$('#error_submit').hide();
    	
        submitLocDateForm();
        return false;
    })
    
     ExecuteOnload();
    
    // If pickup service is selected hide boels link.
    if ($("input[@name='chk_ophalen']:checked").val() == "1") {
    	$('a#sel_return_loc_bl').hide();
    }
    
    // ------------------------------- INFO LINKS -----------------------------------
    // Add event handlers on 'show res info' links
	$('#show_res_info').click(function() 
	{
		$('#box_link_info').hide('fast', function()  
		{
			$('#box_res_info').slideDown('slow');
		});
		return false;
	});
	
	$('#hide_res_info').click(function() 
	{
		$('#box_res_info').slideUp('slow', function()
		{
			$('#box_link_info').show();
		});
		return false;
	});
	
	// Add event handlers on 'show pickup info' links
	$('#show_pickup_info').click(function() 
	{
		$('#box_link_pickup_info').hide('fast', function()  
		{
			$('#box_pickup_info').slideDown('slow');
		});
		return false;
	});
	
	$('#hide_pickup_info').click(function() 
	{
		$('#box_pickup_info').slideUp('slow', function()
		{
			$('#box_link_pickup_info').show();
		});
		return false;
	});
	
	// Add event handlers on 'show return info' links
	$('#show_return_info').click(function() 
	{
		$('#box_link_return_info').hide('fast', function()  
		{
			$('#box_return_info').slideDown('slow');
		});
		return false;
	});
	
	$('#hide_return_info').click(function() 
	{
		$('#box_return_info').slideUp('slow', function()
		{
			$('#box_link_return_info').show();
		});
		return false;
	});
	handleCarTypeSelected();
});

//---------------------------------- FUNCTIONS -------------------------------------------

//----------------------------------- Display --------------------------------------------

function resetOphalen() {

//    $('#pickup_date0').val('0');
//    $('#pickup_time0').val('0');
//    $("select#pickup_loc_ec").removeOption(/./);
    
    // Hide 'select ec' link and boels offices
    $('a#sel_pickup_loc_ec').hide();
    $('select#pickup_loc_bl').hide();

    $('a#sel_return_loc_ec').hide();
    $('select#return_loc_bl').hide();
}

// Show Pickup options
function showOphalen(reset) {

    // Reset options if necessary
    if(reset) {
       resetOphalen();
    }
    
    $("#box_ophalen").show();
}

// Hide Pickup options
function hideOphalen(reset) {
    
    // Reset options if necessary
    if(reset) {
       resetOphalen();
    }
    $("#box_ophalen").hide();
}

function resetInleveren() {
    
    $('#return_date0').val('0');
    $('#return_time0').val('0');
    $("select#pickup_loc_ec").removeOption(/./);
}

// Display Return options
function showInleveren(reset){
    
    // Reset options if necessary
    if(reset) {
        resetInleveren();
    }
     
    $("#box_inleveren").show();
    
}

// Hide Return options
function hideInleveren(reset){
    
    // Reset options if necessary
    if(reset) {
        resetInleveren();
    }

    $("#box_inleveren").hide();

}


//-------------------------- Car Type --------------------------------

// Handler for car type selected
function handleCarTypeSelected(){
		DisableFuelAndTransmisson();
		DisableTime();
		showOphalen(true);
        
        
       
		if ($('#return_loc_ec').val() > 0 && $$('veh_cat').options[$$('veh_cat').selectedIndex].value == 'D') {
			SetClosingHourForVan($('#return_loc_ec').val());
		}
}

    // -----------------------------------------------------------------------

    /**
    *    OnChange event handler for the vehicle type.
    *    If the vehicle type is 'van', the fuel select is set to 'diesel'
    *    and the transmission select is set to '-- choose --' and both
    *    are disabled. If the vehicle type is anything else, it enables
    *    them again.
    *
    **/
    
function DisableFuelAndTransmisson() 
{
    // Check for van vehicle type
    if ( $$('veh_cat').options[$$('veh_cat').selectedIndex].value == 'D' ) 
    {
        
        // Find index value of 'Diesel'
        for (var i = 0; i < $$('fuel_type').options.length; i++ ) {
            if ( $$('fuel_type').options[i].value == 'D' ) {
                var index = i;
                break;
            }
        }
        
        // Set fuel type to 'diesel' 
        $$('fuel_type').selectedIndex = index;
        $("select#fuel_type").attr("disabled","disabled");

        // Find index value of 'manual'
        for (var i = 0; i < $$('trans_type').options.length; i++ ) {
            if ( $$('trans_type').options[i].value == 'A' ) {
                var index = i;
                break;
            }
        }
        
        // Set fuel type to 'diesel' and disable        
        $$('trans_type').selectedIndex = index;
        $("select#trans_type").attr("disabled","disabled");
        
        // Display div
        $('#van_info').css('display', '');
    } 
    else 
    {
        // Set fuel type to 'choose'
        //$$('fuel_type').selectedIndex = 0;
    
        // Set transmission to 'choose'
        //$$('trans_type').selectedIndex = 0;
        
        $("select#fuel_type").attr("disabled","");
        $("select#trans_type").attr("disabled","");

        // Hide div
        $('#van_info').css('display', 'none');
    }
}


//-----------------------------------------------------------------------

/**
*    OnChange event handler for the vehicle type.
*    If the vehicle type is 'van', the time select is hidden.
*    If the vehicle type is anything else, it enables
*    them again.
*
*	 Update 1: customer may not choose the pickup & return time.
*	 Update 2: customer may choose the pickup time but not return time.
*	 Update 3: customer may choose return time too.	
**/
function DisableTime() 
{
	// Check for van vehicle type
	if ( $$('veh_cat').options[$$('veh_cat').selectedIndex].value == 'D' )
	{
//		$("#return_time0").attr("disabled", "disabled");
	} 
	else 
	{
//		$("#return_time0").attr("disabled", "");
	}
}


//-----------------------------  Pickup -----------------------------------------------------

// Handler for pickup date selected ('pickup_date0')
function handlePickupDateSelected(){

    var pickup_date = $("#pickup_date0").val();
    var pickup_time = $("#pickup_time0").val();
    
    if(pickup_date != "0") {
        $("select#pickup_date0").removeOption("0");
    }
    
    // Get available pickup locations depends on pickup date and time 
    getAvailablePickupLocationsByDateTime(pickup_date, pickup_time);
    
    // Fill return locations based on pickup date and time
    getAvailableReturnLocationsByDateTime(pickup_date, pickup_time);
    
    // Check if pickup service is available for selected date and time. If availeble, show pickup service
    // if($("#pickup_time0").val() != "0") {
    if(!$("#pickup_time0").attr("disabled")) {
    	controlPickupService();
	}
	else {
        $("#pickup_time0").attr("disabled", "");
        handlePickupTimeSelected();
	}
    
    var return_date = makeDateObject(pickup_date);
    
    if ( $$('veh_cat').options[$$('veh_cat').selectedIndex].value == 'D' ) {
        return_date.setDate(return_date.getDate());
    } else {
    	return_date.setDate(return_date.getDate() + 1);
    }
        
        return_date = makeIsoDate(return_date);
        
        $('#return_date0').val(return_date);
        
     // Check if return service is available for selected date and time. If availeble, show return service
    if($("#return_date0").val() != "0" && $("#return_time0").val() != "0") {
        controlReturnService();
    }
    
    // If a van is selected then there is no need for time selection.
    // So run this method right now.
    if ( $$('veh_cat').options[$$('veh_cat').selectedIndex].value == 'D' ) {
    	
    	// Set default time if it isn't selected.
    	if ($("#pickup_time0").val() < 1) {
    		
    		// Set up default pickup time
    		var tmp_date_array = $("#pickup_date0").val().split("-");
    		var tmp_date = new Date(tmp_date_array[0], tmp_date_array[1], tmp_date_array[2]);
    		/*
    		tmp_date.setMonth(tmp_date.getMonth() - 1);
    		var default_time = "";

    		if (tmp_date.getDay() == 0) {
    			default_time = D_sunday[1];
    		} else if (tmp_date.getDay() == 6) {
    			default_time = D_saturday[1];
    		} else {
    			default_time = D_weekday[1];
    		}
    		
    		var tmp_default_time = default_time;
    		default_time = (parseInt(tmp_default_time / 100) < 10 ? "0" : "") + parseInt(tmp_default_time / 100) + ":";
    		default_time += ((tmp_default_time % 100) < 10 ? "0" : "") + tmp_default_time % 100;
    		$("#pickup_time0").val(default_time);
    		 */
    		// Update: pickup time is always: 07:00
    		$("#pickup_time0").val("07:00");
    		
    		// Set up default return time
    		if (tmp_date.getDay() == 0) {
    			default_time = D_sunday[2];
    		} else if (tmp_date.getDay() == 6) {
    			default_time = D_saturday[2];
    		} else {
    			default_time = D_weekday[2];
    		}
    		
    		var tmp_default_time = default_time;
    		default_time = (parseInt(tmp_default_time / 100) < 10 ? "0" : "") + parseInt(tmp_default_time / 100) + ":";
    		default_time += ((tmp_default_time % 100) < 10 ? "0" : "") + tmp_default_time % 100;
    		$("#return_time0").val(default_time);

    		//
    		$("#check_boxes_ophalen").show();
    		showInleveren(false);

    		controlPickupService();
    	}
    	
//    	handlePickupTimeSelected();
    }
    
    UpdateLocationInfo();
    
    $('#pickup_calendar0').fadeOut();
}
 
// Handler for pickup time selected
function handlePickupTimeSelected(){

    var pickup_date = $("#pickup_date0").val();
    var pickup_time = $("#pickup_time0").val();
    
    // Get available pickup locations depends on pickup date and time 
    getAvailablePickupLocationsByDateTime(pickup_date, pickup_time);
    
    // Check if pickup service is available for selected date and time. If availeble, show pickup service
    controlPickupService();

    // Show ophalen options
    $("#check_boxes_ophalen").show();
    
    var return_time = pickup_time;
       
       $('#return_time0').val(return_time);
       $('#return_time1').val(return_time);
    
    if(pickup_date != "0") {
        $("select#pickup_time0").removeOption("0");
        controlReturnService();
        showInleveren(false);
    }
    
    UpdateLocationInfo();
}

// -----------------------------------------------------------------------

/**
*    Event handler for selecting locations
*
**/
function HandleLocationSelect() 
{
    // Selected value
    var sel_value = $(this).val();

    // Hide login box
    $('#login_box').hide();

    // Show return box if location was selected
    if (this.id.contains('pickup'))
    {
        if (this.selectedIndex != 0)
        {
            PrepareReturnLocation();
        }
        else
        {
            $('#box_discount').fadeOut('slow');
        }
    }

    SetClosingHourForVan(0);
    
	UpdateLocationInfo();
//    handlePickupTimeSelected();
	
}

// -----------------------------------------------------------------------

/**
*    Set return location to same as pickup location
*
**/
function PrepareReturnLocation() 
{
    // Figure out which and which type of pickup location has been selected
    var type;
    var sel_loc;
    if ($('#pickup_loc_ec').val() > 0)
    {
        type = 'ec';
        sel_loc = $('#pickup_loc_ec').val();
    }
    if ($('#pickup_loc_bl').val() > 0)
    {
        type = 'bl';
        sel_loc = $('#pickup_loc_bl').val();
    }

    // Jump out if nothing was selected - shouldn't happen
    if (!type || !sel_loc)
    {
        return;
    }

    // If EC, remove 'Return at Boels' link
    if (type == 'ec')
    {
        // Reset return loc if it was Boels
        if ($('#return_loc_bl').val() > 0)
        {
            ShowAlternateLocations('return_loc_ec', 'return_loc_bl', true);
        }
    
        $('a#sel_return_loc_bl').hide();
        
        // Select same location
        $('select#return_loc_ec').val(sel_loc);
        
        // Show discount and submit box
        $('#box_discount, #box_submit').show();
    }
    
    // If BL, show Boels offices and 'return at EC' link
    if (type == 'bl')
    {
        ShowAlternateLocations('return_loc_bl', 'return_loc_ec', true);

        // Select same location
        $('select#return_loc_bl').val(sel_loc);

        // Show submit box
        $('#box_submit').show();
    }
}
    
function reset_error_zip() {
    $("#error_zip_text").html(''); 
    $("#error_zip").removeClass('error3');
    $("#error_zip").show();
//    $("#pickup_zip_text").val(''); 
}

function reset_succesful_zip() {
    $("#succesful_zip_text").html('');
    $("#succesful_zip").hide();                        
}
// -----------------------------------------------------------------------

/**
*    Shows pickup zip service available status using Ajax request or cache
*
*    - zip: 'bring' or 'take'
**/
function getPickupInfo(zip, fullZipCode, bringOrReturnCode) 
{
    $("#pickup_zip_possibility").val("-1");
    var opt = new Object();    
    opt.type = 'GET';
	opt.dataType = 'json';
    opt.url = 'ajax.php?method=getBringTakeInfo&zip=' + zip + '&bringOrReturnCode=' + bringOrReturnCode;// + '&veh_cat='+ veh_cat;
    opt.success = function(msg)
    {
        if(msg.location_id < 1)
            //showError("Deliver in specified postcode area not possible", $('pickup_zip_text'), 'error_locdate');        
        {
                $("#error_zip").addClass('error3');
                
                $("#succesful_zip").hide();
                $("#pickup_zip_possibility").val(-1);

                $("#error_zip_text").html('In dit postcodegebied is onze ophaalservice helaas niet beschikbaar<BR>');
        }
        else
        {     
            if(isDateTimeCanBringTakeService('pickup_date0','pickup_time0'))
            {
                var zip = $('#pickup_zip_text').val();
                reset_error_zip();

                $("#succesful_zip_text").html('Wij kunnen u afhalen in het postcodegebied ' + zip + ' de extra kosten zijn &euro; ' + msg.html_price + '.<br />Het exacte adres kunt u later opgeven');
//                $("#error_zip").hide();
                
                $("#succesful_zip").fadeIn();
                $("#pickup_zip_possibility").val(zip);
            }
            else
            {
                $("#error_zip").addClass('error3');
                $("#error_zip_text").html('Op gekozen datum en/of tijdstip is de ophaalservice helaas niet beschikbaar!<br />'); 
            }
        }

    };
    opt.error = function() 
    {
        alert('Bring service zip code checking operation has some errors!');
    }
    $.ajax(opt);            
}

function sortoptions(sort)
{
    var $this = $(this);
    // sort
    $this.sortOptions(sort.dir == "asc" ? true : false);
}

// Get available pickup locations depends on pickup date and time
function getAvailablePickupLocationsByDateTime(pickup_date, pickup_time){

	var selected_ec = $("#pickup_loc_ec").val();
	
	$("select#pickup_loc_ec").removeOption(/./);
    $("select#pickup_loc_bl").removeOption(/./);

    $("select#pickup_loc_ec").addOption("0","-- Kies locatie --", true);
    $("select#pickup_loc_bl").addOption("0","-- Kies locatie --", true);

    $("select#pickup_loc_ec").ajaxAddOption("ajax.php?method=getAvailableLocationsByDate&pickup_date=" + pickup_date + "&pickup_time=" + pickup_time + "&location_type=ECV", {}, false, sortoptions, [{"dir":"asc"}]);
    $("select#pickup_loc_bl").ajaxAddOption("ajax.php?method=getAvailableLocationsByDate&pickup_date=" + pickup_date + "&pickup_time=" + pickup_time + "&location_type=BL", {}, false, sortoptions, [{"dir":"asc"}]);
    
    setTimeout('select_location("' + selected_ec + '"); UpdateLocationInfo();', 2000);
}

//-------------------------- Return ------------------------------------

// Handler for pickup time selected
function  handleReturnDateSelected() {

	var returnLocationId = $('#return_loc_ec').val();
		
    var return_date = $("#return_date0").val();
    var return_time = $("#return_time0").val();
    
    // Get available return locations depends on return date and time 
    getAvailableReturnLocationsByDateTime(return_date, return_time);
    
    controlReturnService();    
    
    SetClosingHourForVan(returnLocationId);
    
    $('#return_calendar0').fadeOut();
};
    
// Handler for return time selected
function handleReturnTimeSelected() {

    var return_date = $("#return_date0").val();
    var return_time = $("#return_time0").val();
    
    // Get available return locations depends on return date and time 
    getAvailableReturnLocationsByDateTime(return_date, return_time);
    
    controlReturnService();

}

function reset_error_zip_inleveren()
{
      $("#error_zip_text_inleveren").html(''); 
      $("#error_zip_inleveren").removeClass('error3');
      $("#error_zip_inleveren").show();
//      $("#return_zip_text").val(''); 
}

function reset_succesful_zip_inleveren()
{
        $("#succesful_zip_text_inleveren").html('');
        $("#succesful_zip_inleveren").hide();                        
}

// Get available return locations depends on return date and time
function getAvailableReturnLocationsByDateTime(return_date, return_time){

	var selected_ec = $("#return_loc_ec").val();
	
    $("select#return_loc_ec").removeOption(/./);
    $("select#return_loc_bl").removeOption(/./);

    $("select#return_loc_ec").ajaxAddOption("ajax.php?method=getAvailableLocationsByDate&pickup_date=" + return_date + "&pickup_time=" + return_time + "&location_type=ECV", {}, false, sortoptions, [{"dir":"asc"}]);
    $("select#return_loc_bl").ajaxAddOption("ajax.php?method=getAvailableLocationsByDate&pickup_date=" + return_date + "&pickup_time=" + return_time + "&location_type=BL", {}, false, sortoptions, [{"dir":"asc"}]);

    $("select#return_loc_ec").addOption("0","-- Kies locatie --", true);
    $("select#return_loc_bl").addOption("0","-- Kies locatie --", true);
    
    setTimeout('return_location("' + selected_ec + '"); UpdateLocationInfo();', 2000);
}


// -----------------------------------------------------------------------

/**
*    Shows pickup zip service available status using Ajax request or cache
*
*    - zip: 'bring' or 'take'
**/

function getReturnInfo(zip, fullZipCode, bringOrReturnCode) 
{    
    $("#return_zip_possibility").val("-1");
    var opt = new Object();    
    opt.type = 'GET';
    opt.dataType = 'json';
    opt.url = 'ajax.php?method=getBringTakeInfo&zip=' + zip + '&bringOrReturnCode=' + bringOrReturnCode;// + '&veh_cat='+ veh_cat;
    opt.success = function(msg)
    {                        
        if(msg.location_id < 1)
            //showError("Deliver in specified postcode area not possible", $('pickup_zip_text'), 'error_locdate');        
        {
                $("#error_zip_inleveren").addClass('error3');
                $("#error_zip_text_inleveren").html('In dit postcodegebied is onze terugbrengservice helaas niet beschikbaar<BR>');
        }
        else
        {
            if(isDateTimeCanBringTakeService('return_date0','return_time0'))
            { 
                var zip = $('#return_zip_text').val();
                 reset_error_zip_inleveren();
                
                $("#succesful_zip_text_inleveren").html('Wij kunnen u wegbrengen in het postcodegebied ' + zip + ' de extra kosten zijn &euro; ' + msg.html_price + '.<br />Het exacte adres kunt u later opgeven');
//                $("#error_zip_inleveren").hide();            
                $("#succesful_zip_inleveren").fadeIn();
                $("#return_zip_possibility").val(zip);                           
            }
            else
            {
                $("#error_zip_inleveren").addClass('error3');
                $("#error_zip_text_inleveren").html('Op gekozen datum en/of tijdstip is de wegbrengservice niet beschikbaar!<br />'); 
            }
        }

    };
    opt.error = function() 
    {
        alert('Onafgevangen fout! Probeer het opnieuw.<br />');
    }
    $.ajax(opt);            
}


// -----------------------------------------------------------------------

/**
*    Set openning hour for pickup_time and return_time on location date form, according to selected location.
*    
*    if type is 'pickup' set  both pickup_time and return_time
*    else set only return time
**/

function SetOpeningHour(type, loc_id){
    // Get open hours of the specified location to set pickup time 
	
		var chosenDate = "";
		if(type == 'pickup') {
			chosenDate = $("#pickup_date0").val();
		} else {
			chosenDate = $("#return_date0").val();
		}
			
		
        var opt = new Object();
        opt.type = 'GET';
        opt.url = 'ajax.php?method=GetOpeningHour&loc_id=' + loc_id + '&type=' + type + '&date=' + chosenDate;  
        opt.success = function(result){
            
            hours = result.split(",");
		pickupValue = $("#pickup_time0").val();
		returnValue = $("#return_time0").val();
            
          if(type == 'pickup') {
			var alreadySet = false;
			for(i=0;i<hours.length;i=i+2) {
				if((pickupValue < hours[i])||(pickupValue > hours[i+1])) {
					if(pickupValue < hours[i]) {
						if (!alreadySet) {
							$("#pickup_time0").selectOptions(hours[i], true);
							alreadySet = true;
						}
					} else {
						$("#pickup_time0").selectOptions(hours[i+1], true);
					}
				} else {
					$("#pickup_time0").selectOptions(pickupValue, true);
					break; //correct time found
				}
			}
        	} else {
			//return always possible, script will not get here.
			var alreadySet = false;
			for(i=0;i<hours.length;i=i+2) {
				if((returnValue < hours[i])||(returnValue > hours[i+1])) {
					if(returnValue < hours[i]) {
						if (!alreadySet) {
							$("#return_time0").selectOptions(hours[i], true);
							alreadySet = true;
						}
					} else {
						//$("#return_time0").selectOptions(hours[i+1], true);
            }
          } else {
					$("#return_time0").selectOptions(returnValue, true);
					break; //correct time found
            }
            }
          }
        };
        $.ajax(opt);  
}

//-----------------------------------------------------------------------

/**
*    This is a fix for setting the time to closing hours for van vehicle. 
**/
function SetClosingHourForVan(locationId){

	if (locationId < 1) {
		locationId = $('#return_loc_ec').val()
	}
	
	// Van type vehicle can be returned till closing time. So set it to closing time.
	// Get open hours of the specified location to set pickup time
	if ($$('veh_cat').options[$$('veh_cat').selectedIndex].value == 'D') {
	    var opt = new Object();
	    opt.type = 'GET';
	    opt.url = 'ajax.php?method=GetOpeningHour&loc_id=' + locationId + '&type=return&date=' + $("#return_date0").val();

	    opt.success = function(result){
	
	        hours = result.split(",");
	
	        openFrom = hours[0];
	        openUntil = hours[1];
	
	        $("#return_time0").selectOptions(openUntil, true);
	    };
	    $.ajax(opt);  
	}          
    //
}

// Check if Pickup Service is available
function controlPickupService(){
  
  var pickup_date = $("#pickup_date0").val();
  var pickup_time = $("#pickup_time0").val();
  
  if(isDateTimeCanBringTakeService('pickup_date0', 'pickup_time0')){
	  $("#pickup_date0").val(pickup_date);
      
      $('#chk_ophalen_pickup_return').show();
      $('#lbl_chk_ophalen1').show();
      
//      $("input[@name='chk_ophalen']:nth(0)").attr("checked","");
//      $("#box_ophalen_rd0").hide();
  } else {
     $('#chk_ophalen_pickup_return').hide();
     $('#lbl_chk_ophalen1').hide();
     
     $("input[@name='chk_ophalen']:nth(0)").attr("checked","checked");
     $("input[@name='chk_ophalen']").triggerHandler("click");
  }
};

// Check if Return Service is available
function controlReturnService(){
    
  var return_time = $("#return_time0").val();
  $("#return_time1").val(return_time);

  if(isDateTimeCanBringTakeService('return_date0', 'return_time0')){
      $('#chk_inleveren_pickup_return').show();
      $('#lbl_chk_inleveren1').show();
      
//      $("input[@name='chk_inleveren']:nth(0)").attr("checked","");
//      $("#box_inleveren_rd0").hide();
  }
  else {
     $('#chk_inleveren_pickup_return').hide();
     $('#lbl_chk_inleveren1').hide();
     
     $("input[@name='chk_inleveren']:nth(0)").attr("checked","checked");
     $("input[@name='chk_inleveren']").triggerHandler("click");
  }
};

 // -----------------------------------------------------------------------

// Returns the type of the return location select
function GetReturnLocType() 
{
    var return_type = 'ec';
    if ($('select#return_loc_bl').is(':visible'))
    {
        return_type = 'bl';
    }
    return return_type;
}

// -----------------------------------------------------------------------

// Returns the selected pickup location
function GetPickupLoc() 
{
    // Find out what's visible
    var type = 'ec';
    if ($('select#pickup_loc_bl').is(':visible'))
    {
        type = 'bl';
    }
    
    // Get selected value
    return $('select#pickup_loc_' + type).val();
}

// -----------------------------------------------------------------------

/**
*    Event handler for 'select alternate locations' links/selects
*
*    - show_sel: Select to show
*    - hide_sel: Select to hide
**/
function ShowAlternateLocations(show_sel, hide_sel, trigger_change) 
{
    // Erase selection
    if (trigger_change)
    {
        $('select#' + hide_sel).get(0).selectedIndex = 0;
        $('select#' + show_sel).get(0).selectedIndex = 0;
    }
    
    // Hide location select for IE6 - workaround for very strange bug
    if ($.browser.msie && $.browser.version == '6.0' && hide_sel == 'return_loc_bl')
    {
        $('select#' + hide_sel).hide();
        //alert('U heeft gekozen om in te leveren bij een Europcar vestiging.');
        $('select#' + show_sel).show();
    }
    else
    {
        $('select#' + hide_sel).hide();
        $('select#' + show_sel).show();
    }
    
    // For return select: set to same location as pickup select, if set
    if (show_sel.contains('return_loc'))
    {
        // Get selected pickup location
        var pickup_loc_id = GetPickupLoc();
        var return_type = GetReturnLocType();

        if (pickup_loc_id > 0)
        {
            $('select#return_loc_' + return_type).val(pickup_loc_id);
        }
    }
    
    // Show location select 
    UpdateLocationInfo();

    // Trigger change event
    if (trigger_change)
    {
        $('select#' + show_sel).change();
    }

    // Swap links
    $('a#sel_' + show_sel).hide();
    $('a#sel_' + hide_sel).show();
}

// -----------------------------------------------------------------------
/**
*    Shows location details using Ajax request or cache
*
*    - type: 'pickup' or 'return'
*    - loc_id: Location ID
**/
function ShowLocationInfo(type, loc_id) 
{
    //log('show loc info, type: ' + type + ', loc_id: ' + loc_id);
    
    // Use cache if available
	// Update: do not use cache because you get double "pickup" & "return" address headers.
/*
	if (loc_info[loc_id])
    {
        //log('using cache');
        $('#infobox_' + type).html(loc_info[loc_id]).show();
        
        // Set openning hour for pickup_time and return_time on location date form
        SetOpeningHour(type, loc_id);
    }
    else
    {
*/
        //log('loading from server');
         // Get location details as HTML from server
        var opt = new Object();
        opt.type = 'GET';
        opt.url = 'ajax.php?method=GetLocationInfo&loc_id=' + loc_id + '&type=' + type;
        opt.success = function(msg)
        {
            // Show info box                      
            $('#infobox_' + type).html(msg).show()
            // Cache info
            loc_info[loc_id] = msg;
            // Set openning hour for pickup_time and return_time on location date form
            // Update opening hours for return if no time is selected.
            if (type != "return" && $("#return_time0").val() != "0") {
            	SetOpeningHour(type, loc_id);
            }
        };
        opt.error = function() 
        {
            alert('Er is een fout opgetreden bij het ophalen van de locatie informatie.');
        }
        $.ajax(opt);
/*
	}
*/
}

// -----------------------------------------------------------------------

/**
*    Updates the content and visibility of the location info boxes, 
*    depending on the value of the pickup/return selects.
*
**/
function UpdateLocationInfo() 
{
	cur_pickup_loc = 0;
	cur_return_loc = 0;
	
    // Get current pickup location
    if ($('#pickup_loc_ec').val() > 0 && $("select#pickup_loc_ec").is(":hidden") == false)
    {
        cur_pickup_loc = $('#pickup_loc_ec').val();
    }
    else if ($('#pickup_loc_bl').val() > 0 && $("select#pickup_loc_bl").is(":hidden") == false)
    {
        cur_pickup_loc = $('#pickup_loc_bl').val();
    }
    // Get current return location
    if ($('#return_loc_ec').val() > 0 && $("select#return_loc_ec").is(":hidden") == false)
    {
        cur_return_loc = $('#return_loc_ec').val();
    }
    else if ($('#return_loc_bl').val() > 0 && $("select#return_loc_bl").is(":hidden") == false)
    {
        cur_return_loc = $('#return_loc_bl').val();
    }

    // Show pickup location info
    if (cur_pickup_loc > 0 && $("input[@name='chk_ophalen']:checked").val() == "0")
    {
        ShowLocationInfo('pickup', cur_pickup_loc);
    }
    else
    {
        $('#infobox_pickup').hide().empty();
    }

    // Show return location info, if not same as pickup location
//    if (cur_return_loc > 0 && cur_pickup_loc != cur_return_loc)
    if (cur_return_loc > 0 && $("input[@name='chk_inleveren']:checked").val() == "0")
    {
        ShowLocationInfo('return', cur_return_loc);
    }
    else
    {
        $('#infobox_return').hide().empty();
    }
}

// ----------------------------- Submit ------------------------------------------

/**
*    Checks the location/date form on submit
*
**/
function storeDateAndTimeInfos()
{
    $("input[@name='pickup_date']").val($("#pickup_date0").val());
    $("input[@name='pickup_time']").val($("#pickup_time0").val());

    $("input[@name='return_date']").val($("#return_date0").val());
    $("input[@name='return_time']").val($("#return_time0").children("[@selected]").text());
}

// -----------------------------------------------------------------------

/**
*    Checks the location/date form on submit
*
**/
// Checks that the first option of a select is not selected

function checkLocDateForm() 
{
	var error_code = 0;
    var error = false;
    var err_str = "";
    var input = "";

    // Check vehicle type
/* not necessary anymore as cat is selected by default, and is not allowed to be empty
    if (!error && !checkSelectNotFirst("veh_cat")) 
    {
        error = true;
        err_str = "Kies het soort auto dat u wilt huren.";
        input = "veh_cat";
    }   */

    // Check pickup location
    if (!error && $("input[@name='chk_ophalen']:checked").val()=="0" && !checkSelectNotZero("pickup_loc_ec") && !checkSelectNotZero("pickup_loc_bl")) {
        error = true;
        err_str = "U bent vergeten de ophaallocatie in te vullen.";
        if ($('#pickup_loc_ec').val() > 0)
        {
            input = "pickup_loc_ec";
        }
        else
        {
            input = "pickup_loc_bl";
        }
    }    
    // Check return location
    if (!error &&  $("input[@name='chk_inleveren']:checked").val()=="0" && !checkSelectNotZero("return_loc_ec") && !checkSelectNotZero("return_loc_bl")) {        
    	error = true;
        err_str = "U bent vergeten de inleverlocatie in te vullen.";
        if ($('#return_loc_ec').val() > 0)
        {
            input = "return_loc_ec";
        }
        else
        {
            input = "return_loc_bl";
        }
    }

    if (!error && $("input[@name='chk_ophalen']:checked").val()=="1" && !isDateTimeCanBringTakeService('pickup_date0','pickup_time0'))
    {
        error = true;
        err_str = "Op gekozen datum en tijdstip is de afleverservice niet beschikbaar.";
        input = "pickup_date0";
    }

    if (!error && $("input[@name='chk_ophalen']:checked").val()=="1" && $("#pickup_zip_possibility").val() == -1)
    {
        error = true;
        err_str = "U heeft de postcode voor de ophaalservice nog niet gecontroleerd.";
        input = "pickup_date0";
    }

    if (!error && $("input[@name='chk_inleveren']:checked").val()=="1" && !isDateTimeCanBringTakeService('return_date0','return_time0'))
    {
        error = true;
        err_str = "Op gekozen datum en/of tijdstip is de ophaalservice niet beschikbaar!";
        input = "return_date0";
    }

    if (!error && $("input[@name='chk_inleveren']:checked").val()=="1" && $("#return_zip_possibility").val() == -1)
    {
        error = true;
        err_str = "U heeft de postcode voor de brengservice nog niet gecontroleerd.";
        input = "pickup_date0";
    }

    if(!error && ($("input[@name='chk_inleveren']:checked").val()==undefined || $("input[@name='chk_ophalen']:checked").val()==undefined))
    {
        error = true;
        err_str = "U heeft geen inlever gegevens ingevuld!";
        input = "return_date";
    }
    
    if(!error && $('#pickup_time0').val() == 0) {
    	error = true;
        err_str = "U heeft geen ophaaltijd ingevuld!";
        input = "pickup_time0";
    }
    
    // Check pickup date vs. return date: return date should be after pickup date
    if (!error && !checkDateTimeSequence("pickup_date0", "pickup_time0", "return_date0", "return_time0")) {
        error = true;
        err_str = "Het tijdstip van inleveren ligt v&oacute;&oacute;r of is gelijk aan het tijdstip van ophalen. Pas de data of tijden aan.";
        input = "pickup_date";
    }
    
    
    // Check funway id, if not blank
    try {
	    if (!error && checkChecked("chk_funway") && !checkNumber("funway_id") ) {
	        error = true;
	        err_str = "Geef een geldig Funway kaartnummer op. Ondervindt u na meerdere keren nog steeds problemen, neem dan contact op met ons Call Center 0900-0540 (€ 0,10 p.m.) zodat zij u verder kunnen helpen.";
	        input = "funway_id";
	    }
	    // Check promotion code, if not blank
	    if (!error && checkChecked("chk_promo_code") && !checkNotEmpty("promo_code") ) {
	        error = true;
	        err_str = "Geef een geldige promotiecode op. Ondervindt u na meerdere keren nog steeds problemen, neem dan contact op met ons Call Center 0900-0540 (€ 0,10 p.m.) zodat zij u verder kunnen helpen.";
	        input = "promo_code";
	    }
    } catch (err) {
    }
    
    // Show error or approve submit
    /*
    if (error) 
    {
        showError(err_str, input, 'error_locdate');
        return false;
    } 
    else 
    {      
        // Take pickup loc. id from select
        if ($('select#pickup_loc_ec').val() > 0)
        {
            $('#inp_pickup_loc').val($('select#pickup_loc_ec').val());
            $('#pickup_loc_type').val('ec');
        }
        if ($('select#pickup_loc_bl').val() > 0)
        {
            $('#inp_pickup_loc').val($('select#pickup_loc_bl').val());
            $('#pickup_loc_type').val('bl');
        }

        // Take return loc. id from select
        if ($('select#return_loc_ec').val() > 0)
        {
            $('#inp_return_loc').val($('select#return_loc_ec').val());
            $('#return_loc_type').val('ec');
        }
        if ($('select#return_loc_bl').val() > 0)
        {
            $('#inp_return_loc').val($('select#return_loc_bl').val());
            $('#return_loc_type').val('bl');
        }
        storeDateAndTimeInfos();         
        return true;
    }
    */
    
    // Let this function submit the form.
    // It's not a nice workaround because of Ajax;
    if (error) 
    {
    	// scroll to top to see the error message.
    	scroll(0, 0);
        showError(err_str, input, 'error_locdate');
        return false;
    } 
    else 
    {
    	isReservationPossible();
    }
}


function isReservationPossible() {
	
	carType = $$('veh_cat').options[$$('veh_cat').selectedIndex].value;		
	fuelType = $$('fuel_type').options[$$('fuel_type').selectedIndex].value;
	transType = $$('trans_type').options[$$('trans_type').selectedIndex].value;
	pickupLocation = $('#pickup_loc_ec').val() > 0 ? $('#pickup_loc_ec').val() : $('#pickup_loc_bl').val();
	
	if ($("input[@name='chk_ophalen']:checked").val() == 1) {
		$("#pickup_zip_possibility").val($("#pickup_zip_text").val());
		zipcode = "&zipcode=" + $("#pickup_zip_possibility").val();
	} else {
		zipcode = "";
	}

	if ($("input[@name='chk_inleveren']:checked").val() == 1) {
		$("#return_zip_possibility").val($("#return_zip_text").val());
	}

    var opt = new Object();
    opt.type = 'GET';
    opt.url = 'ajax.php?method=IsReservationPossible&veh_type=' + carType + '&fuel_type=' + fuelType + '&trans_type=' + transType + '&pickup_date=' + $('#pickup_date0').val() + '&pickup_time=' + $('#pickup_time0').val() + '&pickup_loc_id=' + pickupLocation + zipcode;
	opt.success = function(result){

        response = result.split(",");
        isPossible = response[0];
        message = response[1];
        if (isPossible == "y") {
        	
        	// Take pickup loc. id from select
            if ($('select#pickup_loc_ec').val() > 0)
            {
                $('#inp_pickup_loc').val($('select#pickup_loc_ec').val());
                $('#pickup_loc_type').val('ec');
            }
            if ($('select#pickup_loc_bl').val() > 0)
            {
                $('#inp_pickup_loc').val($('select#pickup_loc_bl').val());
                $('#pickup_loc_type').val('bl');
            }

            // Take return loc. id from select
            if ($('select#return_loc_ec').val() > 0)
            {
                $('#inp_return_loc').val($('select#return_loc_ec').val());
                $('#return_loc_type').val('ec');
            }
            if ($('select#return_loc_bl').val() > 0)
            {
                $('#inp_return_loc').val($('select#return_loc_bl').val());
                $('#return_loc_type').val('bl');
            }
            storeDateAndTimeInfos();
            
            document.forms.form_loc_date.submit();
            
        } else {
        	// scroll to top to see the error message.
        	scroll(0, 0);
        	showError(message, 'asd', 'error_locdate');
        } 
    };

    $.ajax(opt);
}



/**
*    Submits the Location & Date form, with validation
*    This function is used to compensate for the onSubmit event not firing
*    when a form is submitted with submit();
*
**/
function submitLocDateForm() {

	// Workaround: because of Ajax call let the statement inside checkLocDateForm() submit the form on success.
//    if (checkLocDateForm()) {
//        document.forms.form_loc_date.submit();
//    }
    

    checkLocDateForm();
}

    
function select_location(loc_id) { 
    $("#pickup_loc_ec").val(loc_id);
    UpdateLocationInfo();
}

function return_location(loc_id) { 
    $("#return_loc_ec").val(loc_id);
}

//-----------------------------------------------------------------------

/**
*	Checks the normal login form on submit
**/
function CheckLoginForm() {

	var error = false;
	var err_str = "";
	var input = "";

	// Check username
	if (!error && !checkNotEmpty("login_username")) {
		error = true;
		err_str = "Vul uw gebruikersnaam in. Ondervindt u na meerdere keren nog steeds problemen, neem dan contact op met ons Call Center 0900-0540 (€ 0,10 p.m.) zodat zij u verder kunnen helpen.";
		input = "username";
	}

	// Check password
	if (!error && !checkNotEmpty("plain_pwd")) {
		error = true;
		err_str = "Vul uw wachtwoord in.";
		input = "plain_pwd";
	}

	// Show error or approve submit
	if (error) {
		showError(err_str, input, 'error_login');
		return false;
	} else {
		HashPassword('plain_pwd', 'password');
		return true;
	}

}

// -----------------------------------------------------------------------

// Hash password & remove password field
function HashPassword(plain_input, hash_input) {
	$$(hash_input).value = hex_md5($$(plain_input).value);
	$$(plain_input).value = "";
}
