function days_between(date1, date2) {
    var DSTAdjust = 0;
    // constants used for our calculations below
    oneMinute = 1000 * 60;
    var oneDay = oneMinute * 60 * 24;
    // equalize times in case date objects have them
    date1.setHours(0);
    date1.setMinutes(0);
    date1.setSeconds(0);
    date2.setHours(0);
    date2.setMinutes(0);
    date2.setSeconds(0);
    // take care of spans across Daylight Saving Time changes
    if (date2 > date1) {
        DSTAdjust = 
            (date2.getTimezoneOffset() - date1.getTimezoneOffset()) * oneMinute;
    } else {
        DSTAdjust = 
            (date1.getTimezoneOffset() - date2.getTimezoneOffset()) * oneMinute;    
    }
    var diff = Math.abs(date2.getTime() - date1.getTime()) - DSTAdjust;
    Mydifference= Math.ceil(diff/oneDay)-1;
	return Mydifference;
}



function number_format(a, b, c, d) {
 a = Math.round(a * Math.pow(10, b)) / Math.pow(10, b);
 e = a + '';
 f = e.split('.');
 if (!f[0]) {
  f[0] = '0';
 }
 if (!f[1]) {
  f[1] = '';
 }
 if (f[1].length < b) {
  g = f[1];
  for (i=f[1].length + 1; i <= b; i++) {
   g += '0';
  }
  f[1] = g;
 }
 if(d != '' && f[0].length > 3) {
  h = f[0];
  f[0] = '';
  for(j = 3; j < h.length; j+=3) {
   i = h.slice(h.length - j, h.length - j + 3);
   f[0] = d + i +  f[0] + '';
  }
  j = h.substr(0, (h.length % 3 == 0) ? 3 : (h.length % 3));
  f[0] = j + f[0];
 }
 c = (b <= 0) ? '' : c;
 return f[0] + c + f[1];
}

$(document).ready(function()
{
	$('a[rel="external"]').click( function() {
        window.open( $(this).attr('href') );
        return false;
    });
	
	
	$('.faq_question').hover(function(){},function(){})
	$('.faq_question').click(function()
	{
		$('.faq_question').css('color','#ffffff');
		$(this).css('color','#a4a4a4');
		$('.faq_answer').hide();
		$(this).parent('div').find('.faq_answer').show('');	
	});
	
	$('.kadertje').click(function()
	{
		window.location= $(this).parent('.car_list_item').find('a').attr('href');
	});
	
	$('#barTitle a').lightBox(); // opens a lightbox on gallery image click

	// Additional info box reservation form
	$('.addi_info').hover(function(){
		var id = $(this).attr('id');
		$('#info_'+id).show();
	},function(){
		var id = $(this).attr('id');
		$('#info_'+id).hide();
	});

	// Shows opening hours locations
	$("#pu_location").change(function() {
        var info = $('#pu_location option:selected').attr('rel');
		if(typeof(info)!="undefined"){
			$("#pu_info").html('<small>'+info+'</small>');
		}else{
			$("#pu_info").html('<small><span style="color:red">Please select a location.</span></small>');
		}
    });

	// Shows opening hours locations
	$("#do_location").change(function() {
        var info = $('#do_location option:selected').attr('rel');
		if(typeof(info)!="undefined"){
			$("#do_info").html('<small>'+info+'</small>');
		}else{
			$("#do_info").html('');
		}
    });

	// Check form 1
	$("#form_step_1").submit(function(){
		var error = false;
		if ($("#do_location option:selected").val() == "Select location"){
			$("#do_info").html('<small style="color:red">Please select a location.</small>');
			error = true;
		}
		if ($("#pu_location option:selected").val() == "Select location"){
			$("#pu_info").html('<small style="color:red">Please select a location.</small>');
			error = true;
		}
		//check if starting date is less than 3 days in the future
		current_date=new Date();
		selected_date = $('#f-calendar-field-1').val();
		dp=selected_date.split('-');
		current_date=new Date(current_date.getYear(),current_date.getMonth(),current_date.getDate());
		//alert(current_date);
		d=new Date();
		d.setFullYear(parseInt(dp[2]));
		d.setMonth((parseInt(dp[1])-1));
		d.setDate(parseInt(dp[0]));
		if(days_between(current_date,d)<3)
		{			
			$("#date_error").html("Bookings must be made at least 3 days in advance");
			error = true;
		}
		else
		{
			$("#date_error").html("");		
		}
		
		//alert(selected_date_part)
		//alert(days_between(selected_date_part,current_date));
		
		
		if(error){		
			return false;
		}
		return true;
	});

	// Check form 3
	$("#form_step_3").submit(function(){
		$("#ccnum_error").html('');
		$("#email_error").html('');
		$("#fn_error").html('');
		$("#ln_error").html('');
		$("#exp_error").html('');
		var error = false;
		if(!creditCardTypeFromNumber($("#ccnum").val())){
			$("#ccnum_error").html('This creditcardnumber is not valid. Please try again.');
			$("#ccnum_error_tr").show();
			error = true;
		}
		if($("#email").val() == ''){
			$("#email_error").html('The e-mail adress you filled in is incorrect. Please try again.');
			$("#email_error_tr").show();
			error = true;
		}
		if($("#firstname").val() == ''){
			$("#fn_error").html('Please fill in your firstname.');
			$("#fn_error_tr").show();
			error = true;
		}
		if($("#lastname").val() == ''){
			$("#ln_error").html('Please fill in your lastname.');
			$("#ln_error_tr").show();
			error = true;
		}
		if($("#expiration").val() == ''){
			$("#exp_error").html('Please fill in the expiration date of your creditcard.');
			$("#exp_error_tr").show();
			error = true;
		}
		if (!$("#cc_accept:checked").length){
			$("#accept_error").show();
			$("#accept_error2").show();
			error = true;
		}
		if(error){		
			return false;
		}
		return true;
	});

	function creditCardTypeFromNumber(num) {
       // first, sanitize the number by removing all non-digit characters.
       num = num.replace(/[^\d]/g,'');
       // now test the number against some regexes to figure out the card type.
       if (num.match(/^5[1-5]\d{14}$/)) {
         return true;
       } else if (num.match(/^4\d{15}/) || num.match(/^4\d{12}/)) {
         return true;
       } else if (num.match(/^3[47]\d{13}/)) {
         return true;
       } else if (num.match(/^6011\d{12}/)) {
         return true;
       }
       return false;
     };

	$(".print_this").click(function(){
		window.print();
		return false;
	});

	$(".live_calc").click(function() {
		var extras_price 	= 0;
		var days 			= Number($("#tot_days").val());
		var pu_perc 		= Number($("#pu_perc").html());
		var do_perc 		= Number($("#do_perc").html());
		var tax_perc 		= Number($("#tax_perc").html());
		var car_price 		= $("#car_price").html();
		var count 			= 1;
		var fields			= Number($("#nr_fields").val());
		var value, opt_price, 
		subotal, pu_price, 
		do_price, tax_price,
		total_price, subtotal = '';
		car_price = car_price.replace(' ','');
		car_price = Number(car_price);
		while(count<=fields){
			if($("#O"+count).is(":checked")) { value = $("#O"+count).val(); }
			else if($("#O"+count+" option:selected")) { value = $("#O"+count+" option:selected").val();  }
			else { value = 'off'; }
			opt_price = Number($("#O"+count).attr('rel'));
			if(value == 'on'){
				if($("#O"+count +":checked").length){
					extras_price = Number(extras_price) + opt_price;
				}
			}else if(value != undefined){
				extras_price = Number(extras_price) + (opt_price * Number(value));
			}
			count++;
		}
		extras_price = Number(extras_price * days);
		$("#extras_price").html(number_format(extras_price, 2, '.', ' '));
		subtotal = (Number(extras_price) + car_price);
		$("#subtotal_price").html(number_format(subtotal, 2, '.', ' '));
		pu_price = ((subtotal / 100) * pu_perc);
		$("#pu_price").html(number_format(pu_price, 2, '.', ' '));
		do_price = ((subtotal / 100) * do_perc);
		$("#do_price").html(number_format(do_price, 2, '.', ' '));
		subtotal2 = Number(subtotal) + Number(pu_price) + Number(do_price)
		tax_price = ((subtotal2 / 100) * tax_perc);
		$("#tax_price").html(number_format(tax_price, 2, '.', ' '));
		total_price = Number(subtotal) + Number(pu_price) + Number(do_price) + Number(tax_price);
		total_price = Number(total_price);
		$("#total_price").html(number_format(total_price, 2, '.', ' '));
	});
});
