var win = null;
function mail(mypage,myname,w,h){
	LeftPosition = (screen.width) ? (screen.width-w)/2 : 0;
	TopPosition = (screen.height) ? (screen.height-h)/2 : 0;
	settings =
	'height='+h+',width='+w+',top='+TopPosition+',left='+LeftPosition+',scrollbars=yes,resizable=yes'
	win = window.open(mypage,myname,settings);
}

$(document).ready(function(){
    $("#arrival").datepicker({minDate:0,dateFormat:"dd/mm/yy"});
    
    function launchBookingButton(property, date, nights, adults, children, dateParts) {           
    	var endDate = new Date();
    	var startDate = new Date();
    	startDate.setDate(dateParts[0]);
    	startDate.setMonth(dateParts[1]-1);
    	
    	endDate.setDate(dateParts[0]);
    	endDate.setMonth(dateParts[1]-1);
    	endDate.setDate(endDate.getDate() + new Number(nights));
    
    	var baseURL = "https://www.thebookingbutton.co.uk/properties/"+property;
    	  var inDay = new String(startDate.getUTCDate());
    	  if(inDay.length < 2) inDay = "0"+inDay;
    	  var inMonth = new String((startDate.getUTCMonth()+1));
    	  if(inMonth.length < 2) inMonth = "0"+inMonth;
    	  //console.log(inDay);
    	  //console.log(inMonth);
    	  
    	  var outDay = new String(endDate.getUTCDate());
    	  if(outDay.length < 2) outDay = "0"+outDay;
    	  var outMonth = new String((endDate.getUTCMonth()+1));
    	  if(outMonth.length < 2) outMonth = "0"+outMonth;
    
    	var bookingURL = baseURL+"?check_in_date="+startDate.getUTCFullYear()+"-"+inMonth+"-"+inDay+
    					"&check_out_date="+endDate.getUTCFullYear()+"-"+outMonth+"-"+outDay+
    					"&number_adults="+adults+
    					"&number_children="+children;
    	//alert(bookingURL);
    	mail(bookingURL, 'bookingbutton', 1020, 750, 'yes');
    }
    
    $('#book-submit').click(function() {
    	var day = '';
    	day = $('#arrival').val();
    				
    	var dateParts = day.split("/");
    	var date =  new Date();
    	date.setUTCFullYear(dateParts[2], dateParts[1] - 1, dateParts[0]);            
    	if(dateParts[2] != date.getUTCFullYear() 
    	|| dateParts[1] != (date.getUTCMonth()+1)
    	|| dateParts[0] != date.getUTCDate()) {
    		 console.warn("Please enter arrival date: dd/mm/yyyy");
    	}
    			  
    	nights = $('#nights').val();
    	adults = $('#adults').val();
    	children = $('#children').val();
    	//console.log(adults);			
    	launchBookingButton('TREASUREBEACHDIRECT',day,nights,adults,children,dateParts);            
    	
    });
});
