//var q = Math.floor(Math.random()*4+1);

$(function(){
	
	do_filter();
	
	//$('#home_banner').html('<img src="/img/banner_' + q + '.jpg" id="banner_img" />');
	//setTimeout('loadBanner()',5000);
	
	$('.datepicker').datepicker({ altField: 'input.datepicker', altFormat: 'dd-mm-yy' });
	
	$.datepicker.regional['nl'] = {
		closeText: 'Sluiten',
		currentText: 'Vandaag',
		monthNames: ['januari', 'februari', 'maart', 'april', 'mei', 'juni',
		'juli', 'augustus', 'september', 'oktober', 'november', 'december'],
		monthNamesShort: ['jan', 'feb', 'maa', 'apr', 'mei', 'jun',
		'jul', 'aug', 'sep', 'okt', 'nov', 'dec'],
		dayNames: ['zondag', 'maandag', 'dinsdag', 'woensdag', 'donderdag', 'vrijdag', 'zaterdag'],
		dayNamesShort: ['zon', 'maa', 'din', 'woe', 'don', 'vri', 'zat'],
		dayNamesMin: ['zo', 'ma', 'di', 'wo', 'do', 'vr', 'za'],
		weekHeader: 'Wk',
		dateFormat: 'dd-mm-yy',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['nl']);


	$('#sidebar_filters input[type=checkbox]').change(function(){
		
		do_filter();

	});
	
	$("#villa_thumbs").thumbnailScroller({ 
		scrollerType:"hoverPrecise", 
		scrollerOrientation:"horizontal", 
		scrollSpeed:2, 
		scrollEasing:"easeOutCirc", 
		scrollEasingAmount:600, 
		acceleration:4, 
		scrollSpeed:800, 
		noScrollCenterSpace:10, 
		autoScrolling:0, 
		autoScrollingSpeed:2000, 
		autoScrollingEasing:"easeInOutQuad", 
		autoScrollingDelay:500 
	});
	
	$('#villa_thumbs a').click(function(){
		var newimage = $('#villa_photo_img').clone();
		$(newimage).css('position','absolute');
		$(newimage).css('top','183px');
		//$(newimage).css('marginLeft','-780px');
		//$(newimage).css('maxHeight','391px');
		newimage.insertAfter("#villa_photo_img");
	
		$('#villa_photo_img').attr('src',$(this).find('img').attr('src'));
	
		$(newimage).fadeOut(1200, function(){
			$(newimage).remove();
		});
	});
	
	$('.add_to_my_list').livequery('click',function(){
		var cookie = $.cookie('phu_vil');
		items = cookie ? cookie.split(/,/) : new Array();
		
		items.push('i=' + $('#villa_id').val() + 'd=' + $('#villa_name').text());
		
		$.cookie('phu_vil', items.join(','), { expires: 100, path: '/' });
		
		location.reload(true);

	});
	
	$('.villa_delete').click(function(){
		var cookie = $.cookie('phu_vil');
		items = cookie ? cookie.split(/,/) : new Array();
		
		for(var i=0; i<items.length; i++) {
			if(items[i] == $(this).attr('id')){
				items.splice(i,1);
			}
		}
		
		$.cookie('phu_vil', null);
		$.cookie('phu_vil', items.join(','), { expires: 100, path: '/' });
		
		$("#my_list").load(location.href + " .villa_list");
	});
	
	$('#select_valuta').livequery('change',function(){

		if($(this).val() != 'USD'){
			$.post('/ajax.php', {'action':'convert_currency','to':$(this).val()}, function(data){
				
				$('.price_number').each(function(index){
					$(this).text(Math.ceil(parseInt($(this).text())*parseFloat(data)));
				});
				
			});
		}else{
			$('body').load(location.href + ' #container');
		}
		
		$('.currency_symbol').text($(this).val());
		
	});
	
	$('.show_more').click(function(){
		$(this).parent().find('span.full').show();
		$(this).hide();
		$(this).next('.show_less').show();
	});
	
	$('.show_less').click(function(){
		$(this).parent().find('span.full').hide();
		$(this).hide();
		$(this).prev('.show_more').show();
	});
	
	$('.remove_filter').livequery('click',function(){
		$('#' + $(this).parent().attr('id').substr(11)).attr('checked',false)
		
		$(this).parent().fadeOut(200);
		
		do_filter();
	});
	
	$('#island_map a').mouseenter(function(){
		$('.island_map_details').hide();
		$('#details_' + $(this).attr('id')).fadeIn();
	});
	
	$('#share_my_list_dialog').dialog({autoOpen:false, width:450, height:300, modal:true, resizable:false});
	
	$('.share_my_list').click(function(){
		$('#share_my_list_dialog').dialog('open');
	});
	
	$('#share_my_list_dialog_close').click(function(){
		$('#share_my_list_dialog').dialog('close');
	});

});

function set_checkin_date(){
	if($('select[name=checkin_Day]').val() != '' && $('select[name=checkin_Month]').val() != '' && $('select[name=checkin_Year]').val() != ''){
		$('#checkin_date').text($('select[name=checkin_Day]').val() + ' ' + $('select[name=checkin_Month] option[value=' + $('select[name=checkin_Month]').val() + ']').text() + ' ' + $('select[name=checkin_Year]').val());
	}
	
	set_summary();
}

function set_checkout_date(){
	if($('select[name=checkout_Day]').val() != '' && $('select[name=checkout_Month]').val() != '' && $('select[name=checkout_Year]').val() != ''){
		$('#checkout_date').text($('select[name=checkout_Day]').val() + ' ' + $('select[name=checkout_Month] option[value=' + $('select[name=checkout_Month]').val() + ']').text() + ' ' + $('select[name=checkout_Year]').val());
	}
	
	set_summary();
}

function set_summary(){
	checkin_date = new Date($('select[name=checkin_Year]').val(), $('select[name=checkin_Month]').val(), $('select[name=checkin_Day]').val(), 0, 0, 0, 0);
	checkout_date = new Date($('select[name=checkout_Year]').val(), $('select[name=checkout_Month]').val(), $('select[name=checkout_Day]').val(), 0, 0, 0, 0);

	days = days_between(checkin_date,checkout_date);
	nights = days+1;
	
	$('.days_data').text(days);
	$('.nights_data').text(nights);
}

function loadBanner(){
	if(q < 4){
		q++;
	}else{
		q = 1;
	}
	
	var clone = $('#banner_img').clone();
	$(clone).css('position','absolute');
	$(clone).css('marginLeft','-782px');
	clone.insertAfter("#banner_img");

	$('#banner_img').attr('src','/img/banner_' + q + '.jpg');

	$(clone).fadeOut(5000, function(){
		$(clone).remove();
	});
	
	setTimeout('loadBanner()',12000);

}

function do_filter(){

	$.post('/ajax.php', {'action': 'set_checked', 'checked': $('#sidebar_filters input[type=checkbox]:checked').serializeArray()}, function(data){
			
	});
	
	var checked_daily_budget = [];
	$('#sidebar_filters #filters_daily_budget input[type=checkbox]:checked').each(function () {
		checked_daily_budget.push($(this).val());
	});
	
	var checked_activity = [];
	$('#sidebar_filters #filters_activity input[type=checkbox]:checked').each(function () {
		checked_activity.push($(this).val());
	});
	
	var checked_facility = [];
	$('#sidebar_filters #filters_facility input[type=checkbox]:checked').each(function () {
		checked_facility.push($(this).val());
	});
	
	var checked_location = [];
	$('#sidebar_filters #filters_location input[type=checkbox]:checked').each(function () {
		checked_location.push($(this).val());
	});
	
	var checked_capacity = [];
	$('#sidebar_filters #filters_capacity input[type=checkbox]:checked').each(function () {
		checked_capacity.push($(this).val());
	});
	
	$.post('/ajax.php', {'action': 'find_villas', 'checked_daily_budget': checked_daily_budget, 'checked_activity': checked_activity, 'checked_facility': checked_facility, 'checked_location': checked_location, 'checked_capacity': checked_capacity }, function(data){
		
		if(data != null){
		
			villas = [];
			
			$.each(data, function(key, val) {
				villas.push(val.id);
			});
			
			$('ul#villa_results > li').each(function(index) {

				if($.inArray($(this).attr('id').substr(6), villas) == -1){
					$(this).fadeOut();
				}else{
					$(this).fadeIn();
				}

			});
		
		}else{
			$('ul#villa_results > li').fadeOut();	
		}
		
		$("#filter_details").load(location.href + " #filter_matches");	
		
	},'json');

}

function sendContactForm(){

	var name = $("input#name").val(); 
	var tel = $("input#tel").val(); 
	var email = $("input#email").val(); 
	var message = $("textarea#message").val(); 
	
	var dataString = 'name='+ name + '&tel='+ tel + '&email='+ email + '&message='+ message;
	
	if(name == '' || email == '' || message == ''){
		if(name == ''){
			$("input#name").css('border','1px solid red');
		}
		
		if(email == ''){
			$("input#email").css('border','1px solid red');
		}
		
		if(message == ''){
			$("textarea#message").css('border','1px solid red');
		}
	}else{
		$.ajax({  
			type: "POST",  
			url: "/processContact.php",  
			data: dataString,  
			success: function() { 
				$("input#name").val('');
				$("input#tel").val('');
				$("input#email").val('');
				$("textarea#message").val('');
				
				setTimeout("location.href = '/' + lang + '/contactform-sent'",700);
			}  
		});
	}
}

function sendBookingForm(){

	var checkin = $("select[name=checkin_Day]").val()+'-'+$("select[name=checkin_Month]").val()+'-'+$("select[name=checkin_Year]").val();
	var checkout = $("select[name=checkout_Day]").val()+'-'+$("select[name=checkout_Month]").val()+'-'+$("select[name=checkout_Year]").val();
	var gender = $("input#gender").val();
	var firstname = $("input#firstname").val();
	var surname = $("input#surname").val();
	var date_of_birth = $("select[name=date_of_birth_Day]").val()+'-'+$("select[name=date_of_birth_Month]").val()+'-'+$("select[name=date_of_birth_Year]").val();
	var address = $("input#address").val();
	var zipcode = $("input#zipcode").val();
	var city = $("input#city").val();
	var country = $("input#country").val();
	var email = $("input#email").val();
	var secondemail = $("input#secondemail").val();
	var tel = $("input#tel").val();
	
	var dataString = 'checkin='+ checkin + '&checkout='+ checkout + '&gender='+ gender + '&firstname='+ firstname + '&surname='+ surname + '&date_of_birth='+ date_of_birth + '&address='+ address + '&zipcode='+ zipcode + '&city='+ city + '&country='+ country + '&email='+ email + '&secondemail='+ secondemail + '&tel='+ tel;
	
	if(firstname == '' || surname == '' || email == '' || secondemail == ''){
		if(firstname == ''){
			$("input#firstname").css('border','1px solid red');
		}
		
		if(surname == ''){
			$("input#surname").css('border','1px solid red');
		}
		
		if(email == ''){
			$("input#email").css('border','1px solid red');
		}
		
		if(secondemail == ''){
			$("input#secondemail").css('border','1px solid red');
		}
	}else{
		$.ajax({  
			type: "POST",  
			url: "/processBooking.php",  
			data: dataString,  
			success: function() { 
				$("input#firstname").val('');
				$("input#tel").val('');
				$("input#email").val('');
				$("textarea#message").val('');
				
				setTimeout("location.href = '/' + lang + '/bookingform-sent'",700);
			}  
		});  
		 
	}
}

function sendShareList(){
	
	var your_email = $('input#share_email').val();
	var friends_email = $('input#friends_email').val();
	
	var dataString = 'your_email='+ your_email + '&friends_email='+ friends_email;
	
	if(your_email == '' || friends_email == ''){
		
		if(your_email == ''){
			$("input#your_email").css('border','1px solid red');
		}
		
		if(friends_email == ''){
			$("input#friends_email").css('border','1px solid red');
		}
		
	}else{
		$.ajax({  
			type: "POST",  
			url: "/processShareList.php",  
			data: dataString,  
			success: function() { 
				$("input#share_email").val('');
				$("input#friends_email").val('');
				
				$('#share_sent').show();
				
				setTimeout("$('#share_my_list_dialog').dialog('close')",1500);
			}  
		});
	}
	
}

function days_between(date1, date2) {

    // The number of milliseconds in one day
    var ONE_DAY = 1000 * 60 * 60 * 24

    // Convert both dates to milliseconds
    var date1_ms = date1.getTime()
    var date2_ms = date2.getTime()

    // Calculate the difference in milliseconds
    var difference_ms = Math.abs(date1_ms - date2_ms)
    
    // Convert back to days and return
    return Math.round(difference_ms/ONE_DAY)

}

