$(document).ready(function(){
		
		$('.arriba_button').click(function () { 
		  window.scrollTo(0,0);
		  return false;
		});
		
		$('#nav li').hover(function(){
		  $(this).find('div').show();
		},function(){
		  $(this).find('div').hide();
		});
		
		if ($.browser.safari) {
    		$('textarea').css('resize', 'none');
			$('input.text').css('resize', 'none');
 		}
		
		$('#print').click(function(){
			window.print();
			return false;
		});
		
		$("#link_zoom").toggle(
		  function () {
			$('body').addClass('font_mayor');
		  },
		  function () {
			$('body').removeClass('font_mayor');
		  }
		);
		if(($("#box_title").offset().top+$("#box_title").outerHeight())< ($("#box_title .title_page").offset().top+$("#box_title .title_page").outerHeight())){
			var limit = parseInt($("#box_title").offset().top+$("#box_title").outerHeight());
			var diff =  parseInt($("#box_title .title_page").offset().top+$("#box_title .title_page").outerHeight())-limit+10;
			var paddingTop = parseInt($("#box_title .title_page").css("paddingTop"));
			$("#box_title .title_page").css("paddingTop",(paddingTop-diff)+"px");
		}
		
	});

//********************************HOUSE DETAILS***********************************************

function changeHouseImage(image,title){
	
	$(".list_paginator_photo ul li").removeClass("active");
	$(".list_paginator_photo ul li a[onclick*='"+image+"']").parent().addClass("active");
	var currentw = $(".img_detalle_box img:first").width();
	var currenth = $(".img_detalle_box img:first").height();
	addAjaxLoader("current_picture",true);
	
	var objPreload = new Image();
	objPreload.onload=function(){
		var largePreload = new Image();
		largePreload.src = image.replace('thumb_','large_');
		$("#current_picture img").replaceWith('<img style="display:none"  class="img_border float_left img_detalle"  width="'+objPreload.width+'" height="'+objPreload.height+'" src="'+image+'" title="'+title+'" onclick="$(\'#enlarge_picture\').trigger(\'click\');">');
		$("#current_picture img").fadeIn("fast",function(){
			removeAjaxLoader("current_picture");
		});	
			
	};
	objPreload.src=image;
	
}


//****************************AVAILABILITY CALENDAR***********************************************

function toogleCalendar(el){
	
	var class_name = el.attr("class").split(" ").join(".");
	if(el.css("display")=='none'){
		$("."+class_name).each(function(){
			if($(this)[0]!=el[0]){
				$(this).hide();
				$(this).parents(".calendar_content").find(".btn_gray").removeClass("active");
			}
		});
		el.slideDown("slow");
	}
	else{
		el.slideUp("slow");
	}
}

function highlightDays(el,id_apartment){

	el.find("*").removeClass("ui-corner-all").removeClass("ui-corner-left").removeClass("ui-corner-right"); 
	el.find(".ui-datepicker-calendar .ui-state-default").css("background","none");
	el.find(".ui-datepicker-calendar .ui-state-default").css("border","1px solid #D4CCB0");
	el.find(".ui-datepicker-calendar").each(function(idx){
			var start_year  = $(this).parents(".hasDatepicker").data("year");
			var start_month = $(this).parents(".hasDatepicker").data("month");
			
			var auxyear		=	start_year;
			var auxmonth	=	start_month;
			
			if(idx>0){
				if((start_month+idx) > 12){
					auxmonth = (start_month+idx) - 12;
					auxyear = start_year + 1;
				}
				else{
					auxmonth = start_month + 1;
					auxyear  = start_year;
				}
			}
			
			/*Reset day states*/ 
			$(this).find(".ui-state-default").each(function(idx){
				$(this).addClass("day_state_available");
			});
			
			var states = [1,2]; /* 1=>Booked, 2=>Reserved */
			highlightDaysStates(auxyear,auxmonth,id_apartment,$(this),states,0);
			
			
	});
	if(el.find(".ui-datepicker-prev").length ==0){
		el.find(".ui-datepicker-group-first .ui-state-default").each(function(){
			if(parseInt($(this).html()) < new Date().getDate()){
				
				$(this).removeClass("day_state_available").addClass("day_state_booked");
			}
		});
	}
	
}


function highlightDaysStates(year,month,id_apartment,calendarObj,statesArray,idx){
	var mat;
	
	var state = statesArray[idx];/* Current state*/
	$.ajax({
		   async: true,
		   type: "GET",
		   url: "_ajax.php",
		   data: "opc=getDaysByState&year="+year+"&month="+month+"&state="+state+"&id="+id_apartment,
		   success: function(data){
				mat = data!=''?data.split(","):new Array();
				calendarObj.find(".ui-state-default").each(function(){
					$(this).parents("td").attr("onclick","");
					$(this).css("cursor","default");
					$(this).attr("href","javascript:void(0);");
					if(in_array(mat,parseInt(Math.round($(this).html())))){
						if(state == 1 || state == 2){
							$(this).addClass("day_state_booked");
							$(this).removeClass("day_state_available");
						}
					}
				});
				if(idx < (statesArray.length-1)){/* Recursive call for next state*/
					highlightDaysStates(year,month,id_apartment,calendarObj,statesArray,idx+1);
				}
				else{/* En of statesArray, remove ajax loader from parent box*/
					calendarObj.parents(".hasDatepicker").removeAjaxLoader();
				}
	   	   }
	});
}
//**********************************END AVAILABILITY CALENDAR***********************************************

//**********************************RESERVATION***********************************************
function makeReservation(el,code){
	el.parents(".content_list_casas,#table_tarifas").addAjaxLoader(true);
	$.ajax({
	   async: true,
	   type: "POST",
	   url: "_ajax.php",
	   contentType: "application/x-www-form-urlencoded;charset=UTF-8",
	   data: "opc=showReservationDateSelector&code="+code,
	   success: function(data){
			MySimpleLightBox.opacity="80";
			MySimpleLightBox.loadHTML(data);
			$(".date_selector #checkin").datepicker({minDate:0,dateFormat:'dd/mm/yy'});
			$(".date_selector #checkout").datepicker({minDate:0+1,dateFormat:'dd/mm/yy'});
			$('.date_selector #checkin').datepicker('option', {dateFormat: 'dd/mm/yy',minDate: 0,hideIfNoPrevNext:true,onSelect:function(){
		   		var auxd = $('#checkin').datepicker('getDate');
					auxd.setDate(auxd.getDate()+1);
					$('.date_selector #checkout').datepicker('option',{minDate:auxd});
				} 
			});
			$('.date_selector #checkout').datepicker('option', {dateFormat: 'dd/mm/yy',minDate: 0,onSelect:function(){
				var auxd = $('.date_selector #checkout').datepicker('getDate');
				auxd.setDate(auxd.getDate()-1);
					$('.date_selector #checkin').datepicker('option',{maxDate:auxd});
				}
			});
			$(".date_selector #adults,.date_selector #under_age").bind("keypress",function(evt){
				onlyIntegerInputAllowed(evt);	
			});
			$('.date_selector .go').bind("click",function(){
				if(checkFormFields('make_reservation',1,0,"#444444","#FFFFFF")){
					$('.date_selector').addAjaxLoader(true);
					if(parseInt($("#adults").val()) < 1){
						alert(getTranslateEntry("select_one_adult_at_least"));
						$('.date_selector').removeAjaxLoader();
					}
					else{
						$(this).parents("form").trigger("submit");
					}
					
				}	
			});
			$(".ui-datepicker").css("zIndex","10003");
			el.parents(".content_list_casas,#table_tarifas").removeAjaxLoader();
			
   	   }
	});
		
}

function getHouseList(checkin,checkout,adults,under_age,code){
	checkin = checkin==undefined?'':checkin;
	checkout = checkout==undefined?'':checkout;
	adults = adults == undefined?0:adults;
	under_age = under_age == undefined?0:under_age;
	code = code == undefined?'':code;
	
	if((checkin!='' && checkout!='') || (checkin=='' && checkout=='')){
		$(".reservation_form_item_list").addAjaxLoader(true);
		$.ajax({
		   async: true,
		   type: "POST",
		   url: "_ajax.php",
		   contentType: "application/x-www-form-urlencoded;charset=UTF-8",
		   data: "opc=getHouseList&checkin="+checkin+"&checkout="+checkout+"&adults="+adults+"&under_age="+under_age+"&code="+code,
		   success: function(data){
				if(data!="0"){
					$(".reservation_form_item_list").html(data);
				}
				$(".reservation_form_item_list").removeAjaxLoader();
	   	   }
		});
	}	
}

function updateUnits(el){
	var capacity 		= parseInt(el.parents("td").find(".reservation_form_capacity").val());
	var units    		= parseInt(el.parents("td").find(".reservation_form_units option:last").val());
	var guests   		= parseInt(el.parents("td").find(".reservation_form_guests.adults").val())+parseInt(el.parents("td").find(".reservation_form_guests.under_age").val());
	var selected		= parseInt(el.val());
	var units_needed	= Math.ceil(guests/capacity);
	
	if(capacity > 0){
		if(selected < units_needed){
			el.parents("td").addClass("disable");
			el.parents("td").find("input[type='checkbox']:first").attr("disabled",true).attr("checked",false);
			
			var callback = function(el,units_needed,translation){
				el.parents("tr").find(".reservation_item_state").html("min. "+units_needed+" "+translation);
			};
			getTranslateEntry("units",true,callback,[el,units_needed]);
		}
		else{
			if(!el.parents("td").hasClass("booked")){
				el.parents("td").removeClass("disable");
				el.parents("td").find("input[type='checkbox']").attr("disabled",false);
				el.parents("tr").find(".reservation_item_state").html("");
				if(selected>guests){
					el.val(units_needed);
				}
			}
		}
	}	
}

function checkAvailableUnits(el){
	
	var capacity 		= parseInt(el.parents("td").find(".reservation_form_capacity").val());
	var units    		= parseInt(el.parents("td").find(".reservation_form_units option:last").val());
	var adults			= parseInt(el.parents("td").find(".adults").val());
	var under_age		= parseInt(el.parents("td").find(".under_age").val());
	var guests   		= adults+under_age;
	var units_needed	= Math.ceil(guests/capacity);
	var txt_units 		= getTranslateEntry("units");
	
	if(capacity > 0){
		if(units_needed > units){
			el.parents("td").addClass("disable");
			el.parents("td").find("input[type='checkbox']:first").attr("disabled",true).attr("checked",false);
			var callback = function(el,units_needed,translation){
				el.parents("tr").find(".reservation_item_state").html("min. "+units_needed+" "+translation);
			};
			getTranslateEntry("units",true,callback,[el,units_needed]);
		}
		else{
			if(!el.parents("td").hasClass("booked")){
				el.parents("td").removeClass("disable");
				el.parents("td").find("input[type='checkbox']").attr("disabled",false);
				el.parents("tr").find(".reservation_item_state").html("");
				el.parents("td").find(".reservation_form_units").val(units_needed);
			}
		}
	}
}
function toggleReservationOptions(){
	var checkin  = $("#checkin").val();
	var checkout = $("#checkout").val();

	$(".reservation_form_item_list").find("input[type='checkbox']").each(function(){
		if(!$(this).parents("td").hasClass("disable")){
			if(checkin == '' || checkout == ''){
				$(this).attr("disabled",true);
			}
			else{
				$(this).attr("disabled",false);
			}
		}
		else{
			$(this).attr("disabled",true);
		}
	});
}

function updateReservationSubtotal(){
	$("#form_reservas").addAjaxLoader(true);
	var checkin  = $("#checkin").val();
	var checkout = $("#checkout").val();
	var codes = new Array();
	var adults = new Array();
	var under_age = new Array();
	var units	= new Array();
	if(checkin!='' && checkout!=''){
		$(".reservation_form_item_list").find("input[type='checkbox'][checked=true]").each(function(idx){
			codes.push($(this).parents("td").find(".reservation_form_code").val());
			adults.push($(this).parents("td").find(".reservation_form_guests.adults").val()); 
			under_age.push($(this).parents("td").find(".reservation_form_guests.under_age").val());
			units.push($(this).parents("td").find(".reservation_form_units").val());
		});
	}
	getReservationSubtotal(checkin,checkout,units,adults,under_age,codes,0,0);
	
	
}
function getReservationSubtotal(checkin,checkout,units,adults,under_age,codes,idx,subtotal){
	if(idx < codes.length){
		$.ajax({
		   async: true,
		   type: "GET",
		   url:  "_ajax.php",
		   data:  "opc=getItemStayValue&checkin="+checkin+"&checkout="+checkout+"&code="+codes[idx]+"&adults="+adults[idx]+"&under_age="+under_age[idx]+"&units="+units[idx],
		   success: function(data){
				subtotal+=parseFloat(data);
				if(idx < (codes.length-1)){
					idx+=1;
					getReservationSubtotal(checkin,checkout,units,adults,under_age,codes,idx,subtotal);
				}
				else{
					var additionals=getAdditionalsAmount();
					$(".reservation_form_subtotal").html((subtotal+additionals));
					updateReservationDetails();
				}
		   }	
		});
	}
	else{
		if(codes.length < 1){
			$(".reservation_form_subtotal").html(getAdditionalsAmount());
			updateReservationDetails();
		}
	}
}
function getAdditionalsAmount(){
	var additionals=0;
	$(".additional_item").each(function(){
		if($(this).find("input[type='checkbox']").attr("checked")==true){
			var additional_price = parseFloat($(this).find(".additional_price").html());
			var additional_units = parseInt($(this).find(".reservation_form_units").val());
			var additional_name	 = $(this).find(".additional_name").val();
			additionals = additionals + (additional_price * additional_units);
		}
	});
	return additionals;
}

function updateReservationDetails(){
	var checkin  = $("#checkin").val();
	var checkout = $("#checkout").val();
	var adults = 0;
	var under_age = 0;
	var units = 0;
	var units_description = "";
	var optionals = "";
	var promotional_code = "";
	$(".reservation_form_item_list").find("input[type='checkbox'][checked=true]").each(function(idx){
		adults+=parseInt($(this).parents("td").find(".reservation_form_guests.adults").val());
		under_age+=parseInt($(this).parents("td").find(".reservation_form_guests.under_age").val());
		units+=parseInt($(this).parents("td").find(".reservation_form_units").val());
		units_description+=$(this).parents("tr").find(".reservation_form_item").html()+" ("+$(this).parents("td").find(".reservation_form_units").val()+")<br />";
		
	});
	
	$(".additional_item").each(function(){
		if($(this).find("input[type='checkbox']").attr("checked")==true){
			optionals = optionals + $(this).find(".reservation_form_item").html()+" ("+$(this).find(".reservation_form_units").val()+")<br />";
		}
	});
	promotional_code = $("#promotional_code").val();
	$.ajax({
	   async: true,
	   type: "GET",
	   url:  "_ajax.php",
	   data:  "opc=getReservationReview&checkin="+checkin+"&checkout="+checkout+"&adults="+adults+"&under_age="+under_age+"&units="+units+"&units_description="+units_description+"&optionals="+optionals+"&promotional_code="+promotional_code,
	   success: function(data){
			
			$("#reservation_review").html(data);
			$("#form_reservas").removeAjaxLoader();
	   }	
	});
}

function showTermsAndConditions(){
	$.ajax({
		   async: true,
		   type: "GET",
		   url:  "_ajax.php",
		   data:  "opc=getTermsAndConditions",
		   success: function(data){
			 var html = '<div>'+data+'<div>';
			 MySimpleLightBox.loadHTML(html);
			 $("#lboxContent").css("top",($(document).scrollTop()+100)+"px");
		   }	
		});
}

function showItemDetails(el,code){
	el.parents('tr').find('img').parent().addAjaxLoader(true);
	$.ajax({
		   async: true,
		   type: "GET",
		   url:  "_ajax.php",
		   data:  "opc=getItemDetails&code="+code,
		   success: function(data){
			 el.parents('tr').find('img').parent().removeAjaxLoader();
			 var html = '<div>'+data+'<div>';
			 MySimpleLightBox.loadHTML(html);
			 $("#lboxContent").css("top",($(document).scrollTop()+100)+"px");
		   }	
	});	
}

function reservationStep2(){
	$("#form_reservas").addAjaxLoader(true);
	var selected = $(".reservation_form_item_list").find("input[type='checkbox'][checked=true]").length; 
	if($("#check_terms_and_conditions").attr("checked")){
		//if($("#checkin").val() !='' && $("#checkout").val()!='' && selected > 0){
		if($("#checkin").val() !='' && $("#checkout").val()!=''){
			$("#reservation_step_1").hide();
			$("#reservation_step_2").show();
			$(document).scrollTop($("#reservation_step_2").position().top);
			$("#form_reservas").removeAjaxLoader();
		}
		else{
			var message = "";
			if($("#checkin").val() =='' || $("#checkout").val()==''){
				message += getTranslateEntry('complete_reservation_dates')+"<br />";
			}
			/*
			if(selected == 0){
				message += getTranslateEntry('select_reservation_option')+"<br />";
			}
			*/
			$("#form_reservas").removeAjaxLoader();
			showAlertMessage(message);
			
		}
	}
	else{
		var callback = function(message){
			showAlertMessage(message);
			$("#form_reservas").removeAjaxLoader();
		};
		getTranslateEntry("must_agree_terms_and_conditions",true,callback,[]);
	}
}
function sendReservation(){
	if(checkFormFields('form_reservas2',1,0,'#444444','#FFFFFF')){
		var adults = 0;
		var under_age = 0;
		var vars = serializeForm('form_reservas2');
		var total = parseFloat($("#form_additional_services .reservation_form_subtotal").html());
		var promotional_code = $("#form_additional_services #promotional_code").val();
		var checkin  = $("#checkin").val();
		var checkout = $("#checkout").val();
		var reservation_details = $("#reservation_review").html();
		$(".reservation_form_item_list").find("input[type='checkbox'][checked=true]").each(function(idx){
			adults+=parseInt($(this).parents("td").find(".reservation_form_guests.adults").val());
			under_age+=parseInt($(this).parents("td").find(".reservation_form_guests.under_age").val());
		});
		
		
		$('#form_reservas2').addAjaxLoader(true);
		$.ajax({
		   async: true,
		   type: "POST",
		   url:  "_ajax.php",
		   data:  "opc=sendReservationForm&"+vars+"&reservation_adults="+adults+"&reservation_under_age="+under_age+"&reservation_total="+total+"&reservation_checkin="+checkin+"&reservation_checkout="+checkout+"&reservation_details="+reservation_details+"&reservation_promotional_code="+promotional_code,
		   success: function(data){
			 $('#form_reservas2').removeAjaxLoader();
			 $('#reservation_step_2').html("<h2>"+getTranslateEntry('reservation_sended')+"</h2>");
		   }	
		});
	}
}
//************************************END OF RESERVATION***********************************************


function showRecommendForm(description,href){
	$.ajax({
	   async: true,
	   type: "POST",
	   url:  "_ajax.php",
	   data:  "opc=showRecommendForm&href="+href+"&description="+encodeURIComponent(description),
	   success: function(data){
			MySimpleLightBox.loadHTML(data);
	   }	
	});
}

function sendRecommend(description,href){
	if(checkFormFields('recommend_form',1,0,'#5A5A5A','#FFFFFF')){
		addAjaxLoader('recommend_form');
		var name  = $("#recommend_name").val();
		var email = $("#recommend_email").val();	
	
		$.ajax({
		   async: true,
		   type: "POST",
		   url:  "_ajax.php",
		   data:  "opc=sendRecommend&href="+href+"&description="+encodeURIComponent(description)+"&name="+encodeURIComponent(name)+"&email="+encodeURIComponent(email),
		   success: function(data){
				MySimpleLightBox.close();
		   }	
		});
	}
}


function showNewsletterSubscriptionForm(){
	$.ajax({
	   async: true,
	   type: "POST",
	   url:  "_ajax.php",
	   data:  "opc=showNewsletterSubscriptionForm",
	   success: function(data){
			MySimpleLightBox.loadHTML(data);
	   }	
	});
}
function sendNewsletterSubscription(){
	
	if(checkFormFields('newsletter_form',1,0,'#5A5A5A','#FFFFFF')){
		addAjaxLoader('newsletter_form');
		var name  = encodeURIComponent($("#newsletter_name").val());
		var surname  = encodeURIComponent($("#newsletter_surname").val());
		var email = encodeURIComponent($("#newsletter_email").val());	
		
		$.ajax({
		   async: true,
		   type: "POST",
		   url:  "_ajax.php",
		   data:  "opc=sendNewsletterSubscription&name="+name+"&surname="+surname+"&email="+email,
		   success: function(data){
				
				switch(parseInt(data)){
					case 1:
						alert(getTranslateEntry('existent_account'));
						removeAjaxLoader('newsletter_form');
						break;
					case 2:
						MySimpleLightBox.loadHTML('<div style="padding: 10px;background-color: #FFF;border:1px solid #999999;width:483px;">'+getTranslateEntry('newsletter_registration_successfull')+'</div>');
						//$("#newsletter_form").html(getTranslateEntry('newsletter_registration_successfull'));
						break;
					
				}
			
		   }	
		});
	}
}