var autosendform = false;

jq(function() {
	initCars();		
	if (autosendform == true)
		OnSubmitForm();
});

var focused = null;
var hidden = true;
var autocomp = null

var DESTINATIONINFO = "Stad, luchthaven, streek of land.";

function initCars() {
	initLayout();
	//initAutocomplete();
};

function initLayout(){
	// Datepicker
    var sbDates = jq('#pickupdate, #returndate').datepicker({
        numberOfMonths: 2,
        /*showButtonPanel: true,*/
        buttonImage: globalVars.calendar_image_new /*"images/calendar.gif"*/,
        buttonImageOnly: true,
        showOn: 'both',
        dateFormat: 'dd/mm/yy',
        constrainInput: true,
        stepMonths: 2,
        changeMonth: true,
        minDate: "+3D",
        maxDate: "+1Y",
        defaultDate: "+2D",
        onSelect: function (selectedDate)
        {
			if (this.id == "pickupdate")
			{
				var retourDatePicker = jq('#returndate');
				var dateRetour = retourDatePicker.datepicker("getDate");
				var instance = jq(this).data("datepicker");
				var dateSel = jq.datepicker.parseDate(
						instance.settings.dateFormat ||
						jq.datepicker._defaults.dateFormat,
						selectedDate, instance.settings);

				if (dateRetour && dateSel > dateRetour)
				{
					retourDatePicker.datepicker("setDate", dateSel);
				}
			}
			
            if (this.id == "pickupdate")
            {
                window.setTimeout(function ()
                {
                    jq("#returndate").datepicker('show');
                }, 300);
            }
        }
    });
	
	jq("#pickuplocation_ac").autocomplete({
        source: function (request, response)
        {
            jq.ajax({
                url: "http://www.cheaptickets.nl/autocomplete.cfm",
                dataType: "jsonp",
                jsonp: "jsonCallback",
                data: {
					p_lang: globalVars.lang,
                    product: "cars",
                    value: request.term
                },
                success: function (data)
                {
                    response(jq.map(data.auto, function (item)
                    {
						if (item.c == "")
						{
							return {
								isHtml: true,
								noSelect: true,
								label: item.l,
								value: item.c       // l = full name, c = airport code
							}
						}
						else
						{
							return {
								label: item.l,
								value: item.c       // l = full name, c = airport code
							}
						}
                    }));
                }
            });
        },
        minLength: 3,
        select: function (event, ui)
        {
            // manually copy the value to the fields, since we'll cancel the event
            var field = jq('#' + this.id);
			if (ui.item.noSelect)
			{
				return false;
			}
            field.val(ui.item.label)

            // scroll to the start of the text
            field.setCursorPosition(0);

            // update the related airport code hidden field
            var prefix = this.id.split('_')[0];
            jq('#' + prefix + '_apcode').val(ui.item.value);
			jq('#pickuplocationid').val(ui.item.value);
			jq('#pickuplocation').val(ui.item.label);

            // cancel the event
            return false;
        }
        /*open: function ()
        {
        },
        close: function ()
        {
        }*/
    });
};

function ControleStap1(f) {
	var datum1  = back_date(f.SPickupdate.value);
	var datum2  = back_date(f.SDropdate.value);
	var vandaag = new Date();
	if(isNaN(datum1)) {
		alert("Please enter a valid pick-up date (dd-mm-yyyy).");
		f.Svertrekdate.focus();
		return false;
	}else if (isNaN(datum2) ) {
		alert("Please enter a valid drop-off date (dd-mm-yyyy).");
		f.Sretourdate.focus();
		return false;
	}else{
		if(datum1 <= vandaag) {
			alert('Your pick-up date has passed !');
			f.SPickupdate.focus();
			return false;
		}else if (datum2 <= vandaag) {
			alert('Your drop-off date has passed !');
			f.SDropdate.focus();
			return false;
		}else if (datum2 < datum1) {
			alert('Your drop-off date is before your pick-up date !');
			f.SPickupdate.focus();
			return false;
		}else{				  
			if (f.SDestinationValue.value == '') {
				alert('Please select a destination.');
				f.SDestinationValue.focus();
				return false;
			}else{
				if(document.getElementById('WaitPage')) document.getElementById('WaitPage').style.visibility='visible';
				return true;
			}
		}
	}
}

function OnSubmitForm()
{		
	// destination have to be filled
	var destinationValue = document.getElementById("pickuplocation_ac").value;
	if ((destinationValue == "") || (destinationValue == DESTINATIONINFO))
	{
		alert("U dient eerst een bestemming te selecteren.");
		return false;
	}

	// date
	var pickupdateformat = document.getElementById("pickupdate").value;
	var returndateformat = document.getElementById("returndate").value;
	
	// time
	var pickuptimeformat = document.getElementById("pickuptime").value;
	var dropofftimeformat = document.getElementById("dropofftime").value;
	
	var datum1  = new Date(pickupdateformat.substring(6), pickupdateformat.substring(3,5)-1, pickupdateformat.substring(0,2), pickuptimeformat.substring(0,2), pickuptimeformat.substring(3,5), 0, 0);
	var datum2  = new Date(returndateformat.substring(6), returndateformat.substring(3,5)-1, returndateformat.substring(0,2), dropofftimeformat.substring(0,2), dropofftimeformat.substring(3,5), 0, 0);


	// pickupdate can not be within 2 days of today
	/* This had been disabled for conversion reasons */
	/*
	var currentTime = new Date();
	var oneDay = 1000*60*60*24;
	var difference = Math.ceil( (datum1.getTime()-currentTime.getTime())/(oneDay));

	// end date need to greater than start date (considering date+time)
	if (difference < 2){
		alert("Het is helaas niet mogelijk om deze auto binnen twee dagen voor vertrek online te reserveren. Wij reserveren deze auto graag telefonisch voor u.  Neemt u hiervoor contact op met een van onze medewerkers via 0900-8150 (Ma - Za 9u - 24u. \u20AC 0,30 per min. tot max \u20AC 15).");
		return false;
	}
	*/

	// end date need to greater than start date (considering date+time)
	if (datum1 >= datum2)
	{
		alert("Uw inleverdatum is vroeger dan uw ophaaldatum!");
		return false;
	}

	// parse date format: "dd-mm-yyyy" -> "yyyy/mm/dd"
	document.getElementById("pickupdate").value = pickupdateformat.substring(6) + "/" + pickupdateformat.substring(3,5) + "/" + pickupdateformat.substring(0,2);
	document.getElementById("returndate").value = returndateformat.substring(6) + "/" + returndateformat.substring(3,5) + "/" + returndateformat.substring(0,2);
	
	// remove unnecessary items
	try {
		var pickuplocation = document.getElementById("pickuplocation");
		var pickuplocation_ac = document.getElementById("pickuplocation_ac");
		
		pickuplocation.parentNode.removeChild(pickuplocation);
//		pickuplocation_ac.parentNode.removeChild(pickuplocation_ac);
	}
	catch(exception) {}
		
	// send form
	document.searchForm.action = "http://autohuur.cheaptickets.nl/select_car.aspx";
	if (autosendform == true)
		document.searchForm.submit();
}

function ClearDestinationInfo(ctrl) 
{
	if (ctrl.value == DESTINATIONINFO) 
	{
		ctrl.style.color = "#000";
		ctrl.style.fontStyle = "normal";
		ctrl.value = "";
	}
}

function FillDestinationInfo(ctrl) 
{
	if (ctrl.value == "") 
	{
		ctrl.style.color = "#555";
		ctrl.style.fontStyle = "italic";
		ctrl.value = DESTINATIONINFO;
 	}
} 
