// Define global hrData scope function
jQuery.hrData = function(){};

// Query for data function.
// Sends inquery to the hrData service to return data of free rooms.
jQuery.hrData.queryForData = function(guests, rooms, from, to, hotelId) {
    	jQuery.ajax({
    		url: "/hrparser/",
    		dataType: 'xml',
    		data: 
    			'guests='+guests
    			+'&rooms='+rooms
    			+'&from='+from
    			+'&to='+to
    			+'&hotel_id='+hotelId
    		,
    		success: function(xml){
    			var markup = '';
    			function processXml() {
    				var data = jQuery(this);
    				markup += '<tr>';
    				markup += '<td class="alt">EUR '+data.find('price').text()+'</td>';
    				markup += '<td>'+from+'</td>';
    				markup += '<td>'+to+'</td>';
    				markup += '<td><a href="' + data.find('aff_link').text() + '" rel="nofollow">'+ data.find('domain').text() +'</a></td>';
    				markup += '</tr>';
    			}

    			jQuery(xml).find('entry').each(processXml);
    			jQuery("#hrTableBody").html(markup);
    			jQuery("#hrExecuteSearch").val("Find prices");
    			jQuery("#hrExecuteSearch").removeAttr('disabled');
          	}
    	});
};

jQuery(document).ready(function($) {

	// Add check function for toDate/fromDate to check value
	function customRange() {
		if (this.id == "hrFromDate") {
			var dateMin = jQuery("#hrFromDate").datepicker("getDate");
	        var minDate = (dateMin.getFullYear() + '-' + (dateMin.getMonth()+1)  + '-' + (dateMin.getDate() + 1));
	        jQuery("#hrToDate").val(minDate);
	        return true;
		} else { 
	        var dateMin = jQuery("#hrFromDate").datepicker("getDate");
	        var minDate = new Date(dateMin.getFullYear(), dateMin.getMonth(),dateMin.getDate() + 1);
	        return {
	        	'minDate': minDate
	        };
		}
	};

	// Setup datepicker
	jQuery("#hrFromDate").datepicker({
		changeMonth: true,
		changeYear: true,
		onClose: customRange,
		dateFormat: 'yy-mm-dd',
		showWeek: true,
		firstDay: 1,
		showAnim: 'slideDown',
		minDate: 1

	});

	// Setup datepicker
	jQuery("#hrToDate").datepicker({
		changeMonth: true,
		changeYear: true,
		dateFormat: 'yy-mm-dd',
		beforeShow: customRange,
		showWeek: true,
		firstDay: 1,
		showAnim: 'slideDown',
		minDate: 2
	});

	// Define onclick for "submit" button
	$("#hrExecuteSearch").click(function(){
		// Get values
		var guests = $("#hrNumberOfGuests").val();
		var rooms = $("#hrNumberOfRooms").val();
		var from = $("#hrFromDate").val();
		var to = $("#hrToDate").val();
		var hotelId = $("#hotelId").val();

		this.value = "Checking...";
		this.disabled = true;

		// Get data from service
		var data = $.hrData.queryForData(guests, rooms, from, to, hotelId);
		
	});
});

