/* nonights */
function calc_checkoutdate() {

  var value = $('nonights-inp').getValue().toInt();
  var values = $('checkin-inp').getValue().split('/');
  var d = values[0];
  var m = values[1];
  var y = values[2]; 

  var date = new Date(y,m-1,d);
  var checkout = 'dd/mm/yyyy';

  if (!isNaN(date) && !isNaN(value)) {
	var ms = date.getTime() + value * 24 * 60 * 60 * 1000;
	date.setTime(ms);
	checkout = date.getDate() + '/' + (date.getMonth() + 1) + '/' + date.getFullYear();
  }

  $('checkout-inp').value = checkout;

}

function calc_nonights() {

  var values1 = $('checkin-inp').getValue().split('/');
  var values2 = $('checkout-inp').getValue().split('/');
  var checkin = new Date(values1[2],values1[1]-1,values1[0]).getTime();
  var checkout = new Date(values2[2],values2[1]-1,values2[0]).getTime();

  var nonights = '';

  if (!isNaN(checkin) && !isNaN(checkout) && checkout >= checkin) {
	var ms = checkout - checkin;
	nonights = Math.round(ms / (24*60*60*1000));
  }  
  else {
	nonights = 0;
	$('checkout-inp').value = $('checkin-inp').getValue();
  }

  $('nonights-inp').value = nonights;

}

function calc_checkin() {

  var values1 = $('checkin-inp').getValue().split('/');
  var values2 = $('checkout-inp').getValue().split('/');
  var checkin = new Date(values1[2],values1[1]-1,values1[0]).getTime();
  var checkout = new Date(values2[2],values2[1]-1,values2[0]).getTime();

  var nonights = 0;

  if (checkin > checkout) {
	$('checkin-inp').value = $('checkout-inp').getValue();
  }
  else {
	if (!isNaN(checkin) && !isNaN(checkout) && checkout >= checkin) {
		var ms = checkout - checkin;
		nonights = Math.round(ms / (24*60*60*1000));
	}
  }  

  $('nonights-inp').value = nonights;

}

$('checkin-inp').addEvent('keyup', function() {

  if ($('checkout-inp').getValue() == 'dd/mm/yyyy') {
	calc_checkoutdate();
  } else {
	calc_nonights();
  }

});

$('checkin-inp').addEvent('change', function() {

  if ($('checkout-inp').getValue() == 'dd/mm/yyyy') {
	calc_checkoutdate();
  } else {
	calc_nonights();
  }

});

$('checkout-inp').addEvent('change', function() {
	calc_checkin();
});

$('checkout-inp').addEvent('keyup', function() {
	calc_checkin();
});

$('checkout-inp').addEvent('mousedown', function() {
	calc_checkin();
});

$('nonights-inp').addEvent('keyup', function(e) {
  calc_checkoutdate();
});

