$(document).ready(function() { 
	
	$( '#AanbodLink' ).bind('mouseenter', function() { 
		$( '#AanbodImage' ).hide();
		$( '#AanbodImageHover' ).show();
	}).bind('mouseleave', function() {
		$( '#AanbodImage' ).show(); 
		$( '#AanbodImageHover' ).hide();
	}); 
	
	$( 'div.Select select, div.Select input' ).bind('change', function () {
		var ItemID = $(this).attr('id');
		var NewValue = $( '#' + ItemID + ' option:selected' ).html();	
		var VisibleID = ItemID.substr(6); // remove prefix Select
		VisibleID = 'Value' + VisibleID;
		$( '#' + VisibleID ).html( NewValue );
		if( VisibleID == 'ValueSearchLeaveDate' ) {
			hideBookingMessage();
			updatePriceTable();				
		}
	});

	$( '.MapActivator' ).bind('click', function( element ) {
		if( $( '#MapHolder' ).hasClass( 'Active' ) ) {
			$( '#MapHolder' ).hide();
			$( '#MapHolder' ).addClass( 'Inactive' );
			$( '#MapHolder' ).removeClass( 'Active' );
		} else if( $( '#MapHolder' ).hasClass( 'Inactive' ) ) {
			$( '#MapHolder' ).show();
			$( '#MapHolder' ).addClass( 'Active' );
			$( '#MapHolder' ).removeClass( 'Inactive' );
		} else {
			$( '#MapHolder' ).show();
			InitMap();
			DisplayMap();
			InitActions();	
			$( '#MapHolder' ).addClass( 'Active' );
		}
	});		
	
	$( '.MapClose' ).bind('click', function( element ) {
		if( $( '#MapHolder' ).hasClass( 'Active' ) ) {
			$( '#MapHolder' ).hide();
			$( '#MapHolder' ).addClass( 'Inactive' );
			$( '#MapHolder' ).removeClass( 'Active' );
		} 
	});
	
	$.datepicker.setDefaults($.datepicker.regional['nl']);
	$('#SearchLeaveDate').datepicker({
		dateFormat : 'dd-mm-yy',
		minDate : new Date (),
		changeYear : true,
		showWeek : true,
		maxDate: '31-12-13'
	});
	/*$('#PriceTableLeaveDate').datepicker({
		dateFormat : 'MM yy',
		minDate : new Date (),
		changeYear : true,
		showWeek : false,
		maxDate: 'december 2013'
	});*/
	
	$('#SearchKwaliteitDiv').slider({
		range: true,
		min: 0,
		max: 5,
		values: [ 1, 5 ],
		slidechange: function( event, ui ) {
			$( "#SearchKwaliteit" ).val( "" + ui.values[ 0 ] + "-" + ui.values[ 1 ] );
		},
		slide: function( event, ui) {
		}
	});
	
	$('#AanbodLink').bind('click', function() {
		$(this).closest('form').submit();
	});
	
	$( 'span.Increase' ).bind('click', function( element ) {
		var ElemID = $(this).attr('id').substr(8); // remove prefix Increase		
		var CurrentValue = $( '#Amount' + ElemID ).val(); 
		CurrentValue = parseInt( CurrentValue );
		var NewValue = CurrentValue + 1;
		
		if( $('#MaxAmount'+ElemID) ) {
			var MaxAmount = parseInt($('#MaxAmount'+ElemID).text());
			if ( NewValue > MaxAmount ) {
				NewValue = MaxAmount;
			}
		}
		$( '#Amount' + ElemID ).attr('value', NewValue ).change();
		
	});	
	$( 'span.Decrease' ).bind('click', function( element ) {
		var ElemID = $(this).attr('id').substr(8); // remove prefix Decrease
		var CurrentValue = $( '#Amount' + ElemID ).val();
		var NewValue = parseInt( CurrentValue ) - 1; 
		if( NewValue >= 0 ) {
			$( '#Amount' + ElemID ).attr('value', NewValue ).change();
		}		
	});	
	
	$( 'input.Amount' ).bind('change', function( element ) {
		var ElemID = $(this).attr('id').substr(6); // remove prefix Amount		
		var CurrentValue = $(this).val(); 
		CurrentValue = parseInt( CurrentValue );
		var NewValue = CurrentValue;
		
		if( isNaN( NewValue ) ) {
			NewValue = 0;
		}
		if( $('#MaxAmount'+ElemID) ) {
			var MaxAmount = parseInt($('#MaxAmount'+ElemID).text());
			if ( NewValue > MaxAmount ) {
				NewValue = MaxAmount;
			}
		}
		$( '#Amount' + ElemID ).attr('value', NewValue );		
	});	
	
	$( 'span.Checkbox' ).bind('click', function( element ) {
		var ElemID = $(this).attr('id').substr(8); // remove prefix Checkbox
		if( $(this).hasClass('On') ) {
			$(this).removeClass('On');
			$( '#CheckboxValue' + ElemID ).val( 0 ).change();
		} else {
			$(this).addClass('On');
			$( '#CheckboxValue' + ElemID ).val( 1 ).change();
		}				
	});	
	
	$( 'span.QualitySelect' ).bind('click', function( element ) {
		var ElemValue = $(this).attr('id').substr(13); // remove prefix QualitySelect
		ElemValue = parseInt( ElemValue );
		if( ElemValue == 1 && $(this).hasClass('Active') ) {
			ElemValue = 0;
		}
		$( '#SearchQuality' ).val( ElemValue );
		$('span.QualitySelect').each(function() {
			var StarValue = $(this).attr('id').substr(13); // remove prefix QualitySelect
			StarValue = parseInt( StarValue );	
			if( ElemValue >= StarValue ) {
				$(this).addClass('Active');
			} else {
				$(this).removeClass('Active');
			}	
		});
	});	
	
	$('img.EditGuestAmount, img.EditRoompotCost').bind('click', function() {
		$(this).closest('form').submit();
	});
	
	$('#optionalcosts input').bind('change', function() {
		$(this).closest('form').submit();
	});
	
	// make sure that all form elements with the same name have the same value
	$("#optionalcosts input[type=text]").bind('keyup', function() {
		$(this).closest('form').find("input[name='"+$(this).attr('name')+"']").attr('value', $(this).attr('value'));
	});
	
	$('#goto_order_overview').bind('click', function(e) {
		e.preventDefault();
		$(this).closest('form').submit();
		return false;
	});
	
	$('.jQueryDatePicker').datepicker({
		dateFormat : 'dd-mm-yy',
		showWeek : true
	});
	
	makePriceTable();
	
	$('.ImageScroller').each(function() {
		$(this).attr('scrollTop', 0);
		var scrollHeight = $(this).prop('scrollHeight');
		doScrolling($(this), scrollHeight);
	});
	
	// automatisch herladen van prijstabel bij wijzigingen aan settings
	$('#SearchLeaveDate, #SelectDuration').bind('change', function() {
		if( !$(this).hasClass( 'NonUpdate' ) ) {
			hideBookingMessage();
			updatePriceTable();			
		}
		//makePriceTable();
	});
	$('#IncreaseAdultCount, #DecreaseAdultCount').bind('click', function() {
		if( !$(this).hasClass( 'NonUpdate' ) ) {
			hideBookingMessage();
			updatePriceTable();			
		}
	});
	$('#IncreaseAdultCount').bind('click', function() {
		$('span.Amount').each(function() {
			$(this).removeClass('Error');
		});	
	});
	
	$('input.Date').bind('click', function() {
		if( $(this).val() == 'dd-mm-yyyy'
			|| $(this).val() == 'dd-mm-jjjj' ) {
			$(this).val('');
		}	
	});	
	
	$('div.AccommodationClick').bind('click', function() {
		var url = $(this).find('a.Accommodation').attr( 'href' );
		window.location = url;
	});	
	
	$('div.AvailabilityClick').bind('click', function() {
		var url = $(this).find('a.AvailabilityClick').attr( 'href' );
		window.location = url;
	});
});

function makePriceTable() {
	// prijstabel
	$('table.PriceTable.ClickableItems td.Clickable').each(function() {
		//var bookNow = $(this).parent('div.PriceTable').find('input.DoBooking');
		$(this).children('a').each(function() {
			var txt = $(this).text();
			var url = $(this).attr('href');
			$(this).parent().append(txt).data('url', url);
			$(this).remove();
		});
		
		$(this).bind('click', function(ev) {
			hideBookingMessage();
			deselectAll();
			ev.preventDefault();
			if ( $(this).hasClass('Clickable') ) {
				$(this).parent('table.PriceTable td').removeClass('selected');
				$(this).addClass('selected', true);
			}
			return false;
		});
	});
}

function updatePriceTable() {
	var persons = $('#AmountAdultCount').attr('value');
	//var duration = $('#SelectDuration').attr('value');
	var from = $('#SelectSearchLeaveDate').attr('value');
	var accoID = $('#accommodationID').attr('value');

	if( $('#priceTable').hasClass( 'Large' ) ) {
		var tableType = 'getPriceTableLarge';
	} else {
		var tableType = 'getPriceTable';
	}
	//console.log(persons);
	//console.log(duration);
	//console.log(from);
	//console.log(accoID);
	$.ajax({
		url : AbsPath + 'api/ajax.php',
		data : { method : tableType, persons : persons, from : from, accommodation : accoID },
		dataType : 'html',
		async : true,
		success : function(data) {
			$('#priceTable').html(data);
			makePriceTable(); // added
		}
	});
}

function deselectAll() {
	$('table.PriceTable.ClickableItems td.selected').each(function() {
		$(this).removeClass('selected');
	});
}

function doScrolling(element, scrollHeight) {
	//console.log(scrollHeight);
	$(element).animate({
		scrollTop: scrollHeight
	}, 6000, function() {
		if ( scrollHeight == 0 ) {
			scrollHeight = $(this).prop('scrollHeight') - $(this).height(); 
		} else {
			scrollHeight = 0;
		}
			window.setTimeout(function() {
				doScrolling(element, scrollHeight);
			}, 3000);
	});
}

/**
 * 
 * @param ptIdentifier price table identifier
 * @return
 */
function doBooking(ptIdentifier) {
	var adultCount = $('#AmountAdultCount').val();
	if( adultCount > 0 ) {
		var selected = $('.PriceTable.ClickableItems').find('td.selected');
		if (selected.size() > 0 ) {
			var first = $(selected[0]);
			//alert( first.data('url') );
			window.location.href = first.data('url');
		} else {
			displayBookingMessage( 'Selecteer eerst een vertrekdatum en verblijfsperiode' );
		}		
	} else {
		$('span.Amount').each(function() {
			$(this).addClass('Error');
		});		
		displayBookingMessage( 'Het aantal personen moet minimaal 1 persoon zijn' );
	}
}

function displayBookingMessage( msg ) {
	$('#BookingMessage').html( msg );
	$('#BookingMessage').show();
}

function hideBookingMessage() {
	$('#BookingMessage').hide();
}

function getRegions() {
	var countryId = $('#SelectCountry').val();
	$('#ValueRegion').html('');
	$.ajax({
		url : AbsPath + 'includes/Components/Search/Regions.php',
		data : { country : countryId },
		dataType : 'json',
		async : true,
		contentType: "application/x-www-form-urlencoded; charset=UTF-8",
		success : function(data) {
			if( data.length > 0 ) {
				//$('#regions').show();
				var regions = eval( data );
				$('#SelectRegion option').remove();
				var option = document.createElement('option');
				option.text = 'alle regio\'s';
				option.value = 'null';
				document.SearchDestination.Area.options.add(option);
					$.each(regions, function(i,v) {
						var option = document.createElement('option');
						option.text = v.Name;
						option.value = v.ID;
						document.SearchDestination.Area.options.add(option);
					});
			} else {
				$('span#ValueRegion').html('');
				$('#SelectRegion option').remove();
			}
		}
	});
	
}
