var finder_amounts = new Array();
var finder_amount=0;
var finder_cities ="";
var finder_checkin="";
var finder_checkout="";
var finder_bedrooms ="";
var finder_studio ="0";
var finder_lang = getLanguage();

function isBooked(id,checkin,checkout){
	var booked=false;
	$.ajax({
	   async: false,
	   type: "GET",
	   url: "_ajax.php",
	   data: "opc=isBooked&checkin="+checkin+"&checkout="+checkout+"&id="+id,
	   success: function(data){
		  if(data==1){
			booked=true;
		  }
		  else{
			booked=false;
		  }
   	   }
	});
	
	return booked;
}

function getFinderSessionValues(){
	showAjaxLoading($("#finder"));
	$.ajax({
	   async: false,
	   type: "GET",
	   url: "_ajax.php",
	   data: "opc=finder_session_values",
	   success: function(data){
			
			if(data!=''){
				
				var i;
				eval("var values="+data);
				for(key in values) {
				 	eval("finder_"+[key]+" = '"+values[key]+"'");
				}
				if(finder_checkin!=''){
					$("#checkin").val(finder_checkin);
					toggleDateStyle(finder_checkin,$("#checkin"));
					$('#checkout').datepicker('option',{minDate:$('#checkin').datepicker('getDate')});
				}
				if(finder_checkout!=''){
					$("#checkout").val(finder_checkout);
					toggleDateStyle(finder_checkout,$("#checkout"));
					$('#checkin').datepicker('option',{maxDate:$('#checkout').datepicker('getDate')});
				}
				
				var rooms = finder_bedrooms.split(",");
				for(i=0;i<rooms.length;i++){
					if(rooms[i]!='' && $('#finder .numrooms #b'+rooms[i]).length>0){
						$('#finder .numrooms #b'+rooms[i]).addClass("selected");
					}
				}
				if(finder_studio=="1"){
					$('#finder .numrooms #bs').addClass("selected");
				}
				if(window.location.href.indexOf("find-your-apartment.php")==-1){
					finderSearch(1,1,false);
				}
				$(".ajax_loader").remove();
			}
	   }
	});
}

function toggleDateStyle(date,calendar){
	
	$('#ui-datepicker-div').removeAttr("style");												  
	
	if(date == $(calendar).val() && date != ""){ 
		$(calendar).parent().removeClass("editing");
		$(calendar).parent().addClass("modified");
		
		
	}else if(date == ""){
		$(calendar).parent().removeClass("editing");
	}
    $(calendar).removeClass('autovalue');
}

function clearSearch(){
	showAjaxLoading($("#finder"));
	finder_amounts = new Array();
	finder_amount=0;
	finder_cities ="";
	finder_checkin="";
	finder_checkout="";
	finder_bedrooms ="";
	finder_studio ="0";
	$("#finder .list_places , #finder .numrooms").find("li.selected").removeClass("selected");
	$('#checkin').datepicker('option',{maxDate:false});
	$('#checkout').datepicker('option',{minDate:false});
	$("#finder .caloptions").find(".modified").removeClass("modified");
	$("#finder .caloptions").find(".editing").removeClass("editing");
	$("#finder .ui-slider-handle").css({"left":"0"});
	$("#finder .caloptions input").val("");
	$("#finder #amount").val("");
	$.ajax({
	   async: true,
	   type: "GET",
	   url: "_ajax.php",
	   data: "opc=clearSearch&checkin="+finder_checkin+"&checkout="+finder_checkout+"&cities="+finder_cities+"&amount="+finder_amount+"&bedrooms="+finder_bedrooms+"&studio="+finder_studio,
	   success: function(data){
			if(window.location.href.indexOf("find-your-apartment.php")==-1){
				window.location.href = "find-your-apartment.php";
			}
			else{
				finderSearch();
			}
	   }
	});
}

function finderSearch(page,top,search){
	search = search==null || search == undefined?true:false;
	showAjaxLoading($(".search-result"));
	showAjaxLoading($("#finder"));
	page = page==''|| page==undefined?1:page;
	getChainFinderSearch(page,top,search);
}


/*****************************UPDATE FINDER VALUES*******************************************/
function updateFinderRooms(){
	finder_bedrooms="";
	$('#finder .numrooms li').not("li:first").each(function(){
		if($(this).hasClass("selected")){
			finder_bedrooms+=(finder_bedrooms!=""?",":"")+new String($(this).attr('id').replace("b",""));
		}
	});
	finder_studio=$(".numrooms #bs ").hasClass("selected")?"1":"0";
	
	
}

function updateFinderDates(){
	finder_checkin  = $("#checkin").val();
	finder_checkout = $("#checkout").val();
	
}

function updateFinderCities(){
	var values="";
	$(".list_places li").each(function(){
		if($(this).hasClass("selected")){
			values+=(values!=""?",":"")+$(this).attr("id");
		}
	});
	finder_cities = values;
	
}

function updateFinderAmount(){
	finder_amount = $("#amount_slider").val()==null || $("#amount_slider").val()==undefined?0:$("#amount_slider").val();
}
/*****************************END OF UPDATE FINDER VALUES*******************************************/

function getFinderBedrooms(){
	
	$.ajax({
		   async: true,
		   type: "GET",
		   url: "_ajax.php",
		   data: "opc=finderBedrooms&checkin="+finder_checkin+"&checkout="+finder_checkout+"&amount="+finder_amount+"&cities="+finder_cities+"&studio="+finder_studio,
		   success: function(data){
				auxvalues = new Array(1,2,3,'s');
				auxrooms = data.split(",");
				for(var i=0;i<auxvalues.length;i++){
					if(!in_array(auxrooms,auxvalues[i])){
						$("#b"+auxvalues[i]).removeClass("selected");
						$("#b"+auxvalues[i]).addClass("disabled");
					}
					else{
						$("#b"+auxvalues[i]).removeClass("disabled");
					}
				}
				updateFinderRooms();
		   }
		});
}
function getFinderCities(){
	
	$.ajax({
	   async: false,
	   type: "GET",
	   url: "_ajax.php",
	   data: "opc=finderCities&checkin="+finder_checkin+"&checkout="+finder_checkout+"&amount="+finder_amount+"&bedrooms="+finder_bedrooms+"&studio="+finder_studio,
	   success: function(data){
			$(".places").html(data);
			var cities = finder_cities.split(",");
			for(i=0;i<cities.length;i++){
				if(cities[i]!='' && $("#finder .list_places #"+cities[i]).length > 0){
					$("#finder .list_places #"+cities[i]).toggleClass("selected");
				}
			}
	   }
	});
}




function getChainFinderSearch(page,top,search){
	
	
	//start with cities
	$.ajax({
	   async: true,
	   type: "GET",
	   url: "_ajax.php",
	   data: "opc=finderCities&checkin="+finder_checkin+"&checkout="+finder_checkout+"&amount="+finder_amount+"&bedrooms="+finder_bedrooms+"&studio="+finder_studio,
	   success: function(data){
			$(".places").html(data);
			var cities = finder_cities.split(",");
			for(i=0;i<cities.length;i++){
				if(cities[i]!='' && $("#finder .list_places #"+cities[i]).length > 0){
					$("#finder .list_places #"+cities[i]).toggleClass("selected");
				}
			}
			updateFinderCities();
		
			//call get bedrooms
			$.ajax({
				   async: true,
				   type: "GET",
				   url: "_ajax.php",
				   data: "opc=finderBedrooms&checkin="+finder_checkin+"&checkout="+finder_checkout+"&amount="+finder_amount+"&cities="+finder_cities+"&studio="+finder_studio,
				   success: function(data){
						
						auxvalues = new Array(1,2,3,'s');
						auxrooms = data.split(",");
						for(var i=0;i<auxvalues.length;i++){
							
							if(!in_array(auxrooms,auxvalues[i])){
								$("#b"+auxvalues[i]).removeClass("selected");
								$("#b"+auxvalues[i]).addClass("disabled");
							}
							else{
								$("#b"+auxvalues[i]).removeClass("disabled");
							}
						}
						updateFinderRooms();
						
						
						//call get amounts
						$.ajax({
						   async: true,
						   type: "GET",
						   url: "_ajax.php",
						   data: "opc=finderAmounts&checkin="+finder_checkin+"&checkout="+finder_checkout+"&cities="+finder_cities+"&bedrooms="+finder_bedrooms+"&studio="+finder_studio,
						   success: function(data){
								finder_amounts=data.split(";");
								if($('#amount_slider').length>0){
									$('.slider .ui-slider').remove();
									$('#amount_slider').html("");
									$('#amount_slider').append("<option value='0'></option>");
									for(var i=0;i<finder_amounts.length;i++){
										$('#amount_slider').append("<option "+(parseInt(finder_amounts[i])==finder_amount?"selected":"")+" value='"+parseInt(finder_amounts[i])+"'>$ "+finder_amounts[i]+"</option>");
									}
									
									startAmountSlider();
									if($("#amount_slider").val()>0){
										$("#finder #amount").val("$ "+$("#amount_slider").val());
									}
									else{
										$("#finder #amount").val("");
									}
									
									if(navigator.userAgent.indexOf("MSIE 6")!=-1){
										
										var bgIMG = $("#handle_amount_slider").css('background-image');
										//var iebg = bgIMG.split('url("')[1].split('")')[0];
										var iebg="images/bg/handle_slider_icon_ie6.png";
										$("#handle_amount_slider").css('background-image','none');
										$("#handle_amount_slider").get(0).runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + iebg + "',sizingMethod='scale')";
										$("#handle_amount_slider").mouseover(function(){
											var iebg="images/bg/handle_slider_icon_ie6_off.png";
											$("#handle_amount_slider").css('background-image','none');
											$("#handle_amount_slider").get(0).runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + iebg + "',sizingMethod='scale')";
										});
										$("#handle_amount_slider").mouseout(function(){
											var iebg="images/bg/handle_slider_icon_ie6.png";
											$("#handle_amount_slider").css('background-image','none');
											$("#handle_amount_slider").get(0).runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + iebg + "',sizingMethod='scale')";
										});
										
									}
									else{
										$("#handle_amount_slider").css('background-image','url(images/bg/handle_slider_icon.png)');
									}
									
								}
								updateFinderAmount();
								if(search){
									//START SEARCH
									//alert("opc=finderSearch&checkin="+finder_checkin+"&checkout="+finder_checkout+"&cities="+finder_cities+"&amount="+finder_amount+"&bedrooms="+finder_bedrooms+"&studio="+finder_studio+"&page="+page);
									$.ajax({
									   async: true,
									   type: "GET",
									   url: "_ajax.php",
									   data: "opc=finderSearch&checkin="+finder_checkin+"&checkout="+finder_checkout+"&cities="+finder_cities+"&amount="+finder_amount+"&bedrooms="+finder_bedrooms+"&studio="+finder_studio+"&page="+page,
									   success: function(data){
											if(window.location.href.indexOf("find-your-apartment.php")==-1){
												window.location.href = "find-your-apartment.php";
											}
											else{
												$(".search-result").html(data);
												$(".ajax_loader").remove();
												if(top==true){
													window.location.href="#top";
												}
												else{
													//$(document).scrollTop(0);
												}
											}
												
									   }
									});
								}//END IF SEARCH
								
								$(".ajax_loader").remove();
						   }//END OF SUCCESS AMOUNTS
						});
						
						
				   }//END OF SUCCESS BEDROOMS
			});
	   }//END OF SUCCESS CITIES
	});
}


function startAmountSlider(){
	$('#amount_slider').selectToUISlider(
			{
			labels:0,
			tooltip:false,
			sliderOptions: {
					stop: function(e,ui) {
						/*DO NOT MODIFY*/
						var thisHandle = jQuery(ui.handle);
						//handle feedback 
						var textval = (ui.value);
						thisHandle
							.attr('aria-valuetext', textval)
							.attr('aria-valuenow', ui.value)
							.find('.ui-slider-tooltip')
								.text( textval );
		
						//control original select menu
						var currSelect = jQuery('#' + thisHandle.attr('id').split('handle_')[1]);
						currSelect.find('option').eq(ui.value).attr('selected', 'selected');
						/*END OF DO NOT MODIFY*/	
						
						
						
						
						/*
						$("#amount_slider").html('<option value=""></option><option value="'+finder_amount+'"> $'+finder_amount+'</option>');
						startAmountSlider();
						*/
						updateFinderAmount();
						finderSearch();
						
					},
					slide: function(e,ui){
						
						if(ui.value==0){ //First amount $0
							$("#finder #amount").val("");
						}
						else{
							$("#finder #amount").val("$ "+$("#amount_slider option:eq("+ui.value+")").val());	
						}
					}
				}
			}
	);
	
}

function getFinderAmounts(){
	
	$.ajax({
	   async: true,
	   type: "GET",
	   url: "_ajax.php",
	   data: "opc=finderAmounts&checkin="+finder_checkin+"&checkout="+finder_checkout+"&cities="+finder_cities+"&bedrooms="+finder_bedrooms+"&studio="+finder_studio,
	   success: function(data){
			finder_amounts=data.split(";");
			if($('#amount_slider').length>0){
				$('.slider .ui-slider').remove();
				$('#amount_slider').html("");
				$('#amount_slider').append("<option value='0'></option>");
				for(var i=0;i<finder_amounts.length;i++){
					$('#amount_slider').append("<option "+(parseInt(finder_amounts[i])==finder_amount?"selected":"")+" value='"+parseInt(finder_amounts[i])+"'>$ "+finder_amounts[i]+"</option>");
				}
				startAmountSlider();//INITIALIZE AMOUNTS SLIDER 
				if($("#amount_slider").val()>0){
					$("#finder #amount").val("$ "+$("#amount_slider").val());
				}
				else{
					$("#finder #amount").val("");
				}
				
				if(navigator.userAgent.indexOf("MSIE 6")!=-1){
					
					var bgIMG = $("#handle_amount_slider").css('background-image');
					//var iebg = bgIMG.split('url("')[1].split('")')[0];
					var iebg="images/bg/handle_slider_icon_ie6.png";
					$("#handle_amount_slider").css('background-image','none');
					$("#handle_amount_slider").get(0).runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + iebg + "',sizingMethod='scale')";
					$("#handle_amount_slider").mouseover(function(){
						var iebg="images/bg/handle_slider_icon_ie6_off.png";
						$("#handle_amount_slider").css('background-image','none');
						$("#handle_amount_slider").get(0).runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + iebg + "',sizingMethod='scale')";
					});
					$("#handle_amount_slider").mouseout(function(){
						var iebg="images/bg/handle_slider_icon_ie6.png";
						$("#handle_amount_slider").css('background-image','none');
						$("#handle_amount_slider").get(0).runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + iebg + "',sizingMethod='scale')";
					});
					
				}
				else{
					$("#handle_amount_slider").css('background-image','url(images/bg/handle_slider_icon.png)');
				}
				
			}
			
	   }
	});
}

$(document).ready(function(){
		if($("#finder").length>0){
			
			$('#finder .list_places').jScrollPane({showArrows:true});
			$('#finder .numrooms li a').each(function(){
				
				$(this).bind("click",function(){
					
					if(!$(this).parent().hasClass('disabled')){
						$(this).parent().toggleClass("selected");
						updateFinderRooms();
						finderSearch();
					}
					
				});
			});
			
		
			
			
			
			$('#finder .sbottom a').click(function(){
				clearSearch();
				return false;
			});
			
			
			
			$(".numrooms li a").hover(function(){
				$(this).siblings(".tip").remove();
				$(this).parent().css({"position":"relative"});
				$(this).parent().append(getTipHtml($(this).text()));
				if(!$(this).parent().hasClass("disabled")){
					$(this).css("cursor","pointer");
					$(this).siblings(".tip").fadeIn("fast");
				}
				else{
					$(this).css("cursor","default");
				}
				
			},function(){
				
				$(this).siblings(".tip").animate({opacity:0},function(){
					$(this).remove();
					$(this).parent().css({"position":""});												   
				});
				
			});
			
		
			$('.date-pick').datepicker({
				 onClose: function(date) { 
						$('#ui-datepicker-div').removeAttr("style");												  
						
						if(date == $(this).val() && date != ""){ 
							$(this).parent().removeClass("editing");
							$(this).parent().addClass("modified");
							if($(this).parents(".calc").length==0){
								//updateFinderDates();
							}
						}else if(date == ""){
							$(this).parent().removeClass("editing");
						}
	                    $(this).removeClass('autovalue');
				 },
				 onSelect: function(dateText) {		
					 	
						$('#ui-datepicker-div').removeAttr("style");
						
						 if(dateText != null){ 
								$(this).parent().removeClass("editing");
								$(this).parent().addClass("modified");
								
						 } 
									
				 							
				},
				 beforeShow: function(input) {
						$(this).parent().removeClass("modified");
						$(this).parent().addClass("editing");
												
						$(this).parent().append($('#ui-datepicker-div'));
						
						$('#ui-datepicker-div').find(".ui-datepicker-current-day").remove();
						
						$('#ui-datepicker-div').animate( { height:0, width:0},0 );
						$('#ui-datepicker-div').animate( { top:-225,left:-70,width:237,height:209},200 );
				 }
				
			});	

			$('#checkin').datepicker('option', {dateFormat: 'dd/mm/y',minDate: 0,hideIfNoPrevNext:true,onSelect:function(){
				var auxd = $('#checkin').datepicker('getDate');
				auxd.setDate(auxd.getDate()+1);
				$('#checkout').datepicker('option',{minDate:auxd});
				updateFinderDates();
				finderSearch();
			} 
			});
			$('#checkout').datepicker('option', {dateFormat: 'dd/mm/y',minDate: 0,onSelect:function(){
				var auxd = $('#checkout').datepicker('getDate');
				auxd.setDate(auxd.getDate()-1);
				$('#checkin').datepicker('option',{maxDate:auxd});
				updateFinderDates();
				finderSearch();
			} 
			});
			//$('.date-pick').datepicker('option', 'dayNamesMin',  ['M', 'T', 'W', 'T', 'F', 'S', 'S']);
			
			
		
			$("#finder .caloptions input").val(""); // LIMPIA INPUTS
			
			getFinderSessionValues(); //CARGA LAS OPCIONES SELECCIONADAS 
			if(window.location.href.indexOf("find-your-apartment.php")!=-1){
				finderSearch();//LANZA LA BÚSQUEDA
			}
		}
		
		//Find your apartment icon
			$(".finder #finderTop").mouseover(function(){
				var zidx = $(".finder #finderTopOver").css("zIndex");
				$(".finder #finderTopOver").css("zIndex",$(this).css("zIndex"));
				$(this).css("z-index",zidx);
			});
			$(".finder #finderTopOver").mouseout(function(){
				var zidx = $(".finder #finderTop").css("zIndex");
				$(".finder #finderTop").css("zIndex",$(this).css("zIndex"));
				$(this).css("z-index",zidx);
			});
			
			$(".finder .stop").css("cursor","pointer");
			$(".finder .stop").click(function(){
				
				window.location.href="find-your-apartment.php";
			});
		
		
		
	
	});

	function getTipHtml(t){		
		return 	'<div class="tip"><div class="w png"><div class="m png"><div class="t png"><div class="b png"><div class="arrow png"></div><div class="text">'+ t +'</div></div></div></div></div>';							
	}
