
/** JSON Result Object Controller
 * The obj needs the following options:
 * data // Json Object
 * arText // multi-lingual texts
 * lang // current language
 * token
 * type
 * action
 * 
 * This class controls the actions of the result page.
 * Main functions:
 * 1) Get Apartment calendar HTML via AJAX
 * 2) Get Search Results via AJAX
 * 3) Gets Price for detail page (apartments)
 * 4) Draws Pagination
 * 5) Draws current list
 * 6) Creates Filter List. Note: The filter list must have the same elements as the oFilter created in resultBase
 * 7) Checks the Ajax Response
 * 8) Creates price Slider
 * 9) Saves current filter via AJAX

// Depends on JQuery 
//	1) To add content to HTML
//	2) Slider
//  3) Ajax
 */

function resultController(opts){
	
	Object.extend(this, new resultBase());
	Object.extend(this, new baseOptions());
	Object.extend(this, new resultProperty());
	Object.extend(this, new resultGMap());
	
	this.base = new resultBase();
	// set up variables
	this.objName= "oResult";
	this.oList;
	this.crm 	= false;
	this.search	= false;
	this.data 	= "";
	this.arCurList = "";
	this.lang  	= "";
	this.token 	= "";
	this.type 	= "";
	this.action = "";
	this.postcmd = "";
	this.calDate = "";
//	this.type = (type) ? type : 'apartment';
//	this.action = (action) ? action : 'search';
	// page
	this.page  	= 0;
	this.perPage= 10;
	
	// Texts
	this.arText = new Array;
	
	// Crm Array
	this.myCrm = {};
	
	// Display containers
	this.divTopDisplay = 'xcontent';
	this.divResults = 'resultado';
	this.divLoader = 'div-result-loader';
	this.divPageNav = 'pages';
	this.divPageNavBottom = 'pages_bottom';
	this.divTowns	= 'result-destinations';
	this.divCategories = 'div-cats';
	this.divOptions	   = 'div-options';
	this.divBedrooms = 'div-bedrooms';
	this.divDistrict = 'div-districts';
	this.spanTotal = "result-item-total";
	this.spanTotalCurrent = "current-item-total";
	this.divSelectedItem = "div-selected-item";
	this.divSelectedItemCont = "div-selected-item-container";
	this.divTourSort = "div-res-tour-sort";
	this.divLoading = "loading_div";
	this.divLoadingBig = "loading_div_big";
	this.divContentResult = "result-content";
	this.divResultDestinations = "result-destinations";
	
	// initial values
	this.initMax = "";
	this.initMin = "";
	this.maxPrice= "";
	this.minPrice= "";
//	this.sortOption = 'asc|price';
	this.sortOption = 'asc|internal_rating_calc|desc|price';
	this.initTown = "";
	this.initDistrict = "";
	
	this.test_1	= "";
	this.test_2 = "";
	// Set options
	this.setOpts(opts,this);
	// Set Object Name
	this.setObjectName = function(name){this.objName = name;};
	
	// For Rental Calendar
	this.getCal = function(obj,params,tar){
		
		// Check for starting date or "next/prev" command
		if(params['date'] == 'next'){
			if(this.calDate == ''){
				var d = new Date(); 
				
			}else{
				var cx = this.calDate.split('-');
				var d = new Date();
				if(parseInt(cx[1]) == 0 ){cx[1]=1;}
				d.setFullYear(cx[0],(parseInt(cx[1])+1),cx[2]);
			}
			
			params['date'] = d.getFullYear() + "-"+ d.getMonth() +"-01";
		}else if(params['date'] == 'prev'){
			if(this.calDate == ''){
				var d = new Date(); 
				
			}else{
				var cx = this.calDate.split('-');
				var d = new Date();
				cx[1] = parseInt(cx[1]) - 1;
				if(cx[1] == 0) {
					cx[1] = 12;
					cx[0] = parseInt(cx[0])-1;
				}
				d.setFullYear(cx[0],cx[1],cx[2]);
			}
//			params['date'] = d.getFullYear() + "-"+ d.getMonth() +"-01";
			params['date'] = cx[0] + "-"+ cx[1]+"-01";
		}
		
//		alert("calDate: "+ this.calDate + " , Param Date: " + params['date']);
		
		// set param link
		var strParams = this.createParamsString(params);
		
		// set current date
		this.calDate = params['date'];
		
		// set post cmd
		$.ajax({
			type: "GET",
			url: "/includes/service/ServiceRequest.php",
			data: "&action=getcal"+strParams,
			dataType: "text",
			success: function(data) {

				// Update Caledar
				$('#'+tar).html(data);

	  			}, // End Ajax Success Call
					error: function(xml, txtStatus, eText){
					// Remove page Loader

						var errorHtml;
						errorHtml = '<div id="ajax-error">';
						errorHtml += '<div class="client-msg">'+obj.arText['empty-response']+'</div>';
						errorHtml += '<div class="tech-msg">'+txtStatus+'</div>';
						errorHtml += '<div class="tech-msg">'+eText+'</div>';
						errorHtml += '</div>';

						$("#"+this.divResults).html(errorHtml);
						$("#share-result").hide();

					},
					complete: function(){
						$('#'+oResult.divLoader).hide();
					}


				});

	};
	
	// Start Ajax
	this.getResults = function(obj,params,postcmd){
		
		// set param link
		var strParams = this.createParamsString(params);
		// set post cmd
		obj.postcmd = postcmd;
		$.ajax({
			type: "GET",
			url: "/includes/service/ServiceRequest.php",
			data: "type="+this.type+"&lang="+this.lang+"&action="+this.action+"&token="+this.token+strParams+"&search="+this.search,
			dataType: "json",
			success: function(data) {
			$('#'+oResult.divLoader).hide();
				obj.checkResponse(data,obj.postcmd);

	  			}, // End Ajax Success Call
					error: function(data, txtStatus, eText){
					// Remove page Loader
	  				$('#'+this.divLoader).hide();
						var errorHtml;
						errorHtml = '<div id="ajax-error" class="result-filter-msg">';
						errorHtml += '<div class="client-msg">'+obj.arText['empty-response']+'</div>';
						errorHtml += '<div class="tech-msg">'+txtStatus+'</div>';
						errorHtml += '<div class="tech-msg">'+eText+'</div>';
						errorHtml += '</div>';

						$("#"+obj.divResults).html(errorHtml);
						$("#share-result").hide();

					},
					complete: function(){
						$('#'+oResult.divLoader).hide();
						
					}


				});

	};
	
	// do Detail Get price 
	this.doDetailGetPrice = function (obj,params,postcmd){
		$('#'+this.priceDivLoader).show();
		$('#'+this.priceDiv ).hide();
		this.getResults(obj,params,'updateprice');
	};
	
	// do Detail get Price and get all form variables to send 
	this.doDetailGetPriceAllFields = function (obj,params){
		
		if(searchForm == undefined){
			searchForm = new searchForm();
		}
		if(!searchForm.checkDates()){return false;}
		
		$('[id*='+this.divNoSearch+']').hide();
		$("[id*=div-additional-apts]").hide();
		$("[class*=apt-additional-title]").hide();
		if($('[id='+this.priceDivContainer+'1]').css('display') == 'block' || $('[id='+this.priceDivContainer+'1]').css('display') ==''){
			$('[id*='+this.priceDivLoader+']').show();
			$('[id*='+this.priceDivContainer+']').hide();
		}else{
			$('[id*='+this.priceDivLoader+']').show();
			$('[id='+this.priceDivLoader+'2]').show();
			$('[id*='+this.priceDivContainer+']').hide();
		}
		
		$('#'+this.priceDiv ).hide();
		if($('input[name=accommType]').val() == 'hotel'){
			var formFields = $("#"+this.requestForm + ' :input');
			//alert($("#"+this.requestForm + ' :input[name=numRooms]').val());
			// If it is a multi´room then send it automatically to the results page
			if($("#"+this.requestForm + ' :input[name=numRooms]').val() > 1){
				$('#'+this.requestForm ).attr('action','/results.php');
				$('#'+this.requestForm ).submit();
				
			}
		}else{
			var formFields = $("#"+this.requestForm).serializeArray();
		}
		
		
		$.each(formFields, function (i, field) { 
			params[this.name] = this.value; 
	    });
		
		this.getResults(obj,params,'updateprice');
	};
	
	// set data object
	this.setData = function(data){
		this.data = data;
	};
	
	// Check the response to see if there are any available apartments
	this.checkResponse = function (data){
		this.setData(data);
		var ok = false;
		
		if(typeof data != 'undefined' && data != null){
			// Status is "Y" or True to procced
			if(typeof data.result != 'undefined'){
				if(data.result.status.status == 'Y'){
					ok = true;
				}else{
					// Check valid dates
					if(data.result.status.validDate == 'N'){
						html = "<div class='result-filter-msg'>"+this.arText["invalid-dates"]+"</div>";
						$("#"+this.divResults).html(html);
						$("#share-result").hide();
					}else{
						html = "<div class='result-filter-msg'>"+this.arText["no-availability"]+"</div>";
						$("#"+this.divResults).html(html);
						$("#share-result").hide();
					}
					
				}
			}else{
				var errorHtml;
				errorHtml = '<div id="ajax-error" class="result-filter-msg">';
				errorHtml += '<div class="client-msg">'+this.arText['empty-response']+'</div>';
				errorHtml += '</div>';

				$("#"+this.divResults).html(errorHtml);
				$("#share-result").hide();
			}
			
			if(typeof data.status != 'undefined'){
				if(data.status == true){
					ok = true;
				}else{
					var errorHtml;
					errorHtml = '<div id="ajax-error" class="result-filter-msg">';
					errorHtml += '<div class="client-msg">'+this.arText['empty-response']+'</div>';
					errorHtml += '</div>';

					$("#"+this.divResults).html(errorHtml);	
					$("#share-result").hide();
				}
			}
			
			if(ok){
				// initial values
				if(this.action == 'search'){
					$('#'+this.divTopDisplay).show();
					if(data.result.params.vtour == 'Y') { $('#'+this.divTourSort).show(); }else{$(".sort-opt").css("padding","5px");}
					
					// this.arCurList = this.sort(this.getCurrent(data),'desc|internal_rating_calc');
					this.arCurList = this.getCurrent(data);
					// Update HTML Span total
					$('#'+this.spanTotal).html(this.arCurList.length);
					// alert("legnth : " + this.arCurList.length);
					this.initMax = this.getMaxPrice(this.arCurList);
					this.initMin = this.getLowPrice(this.arCurList);
					this.maxPrice = this.initMax;
					this.minPrice = this.initMin;
					this.drawInitialList();
					
					// Update Html Totals
					$('#'+this.spanTotalCurrent).html(this.arCurList.length);
					
					// Check for seelected items
//					alert(this.data.result.params.selected_hotel);
					var selItem = false;
					var list = this.getCurrent(this.data);
					var selItemValue;
					switch(this.type){
						case "hotel":
							selItemValue = this.data.result.params.selected_hotel;
							break;
						case "apartment":
							selItemValue = this.data.result.params.selected_property;
							break;
					}

					var itemIsSelected = false;
					if(selItemValue != '' && selItemValue != null){
						itemIsSelected = true;
						for(i in list){
							if(list[i].id == selItemValue){
								selItem = list[i];
							}
						}
					}
					
					if(selItem) {
						var selHtml = this._drawItem(selItem,this.data.result.params);
						$('#'+this.divSelectedItemCont).show('slide',400);
						$('#show-selected').hide();
						$('#hide-selected').show();
						$('#'+this.divSelectedItem).append(selHtml);
					}else if(itemIsSelected){
						$('#'+this.divSelectedItemCont).show();
						$('#show-selected').hide();
						$('#hide-selected').show();
						$('#'+this.divSelectedItem).append('<h3>'+this.arText['selected-not-available']+'</h3>');
					}
				}
				
			}
		}else{
			var errorHtml;
			errorHtml = '<div id="ajax-error" class="result-filter-msg">';
			errorHtml += '<div class="client-msg">'+this.arText['empty-response']+'</div>';
			errorHtml += '</div>';

			$("#"+this.divResults).html(errorHtml);
		}
		
		if(this.action == 'getprice'){
			switch(this.postcmd){
				case "updateprice":
					this.updatePrice(data);
					break;
			}
		}
	};
	
	// GEt next set from the specified array
	this.getNextPage = function (arr, p, perPage){

		var arrResult = new Array();
		var curIndex = 0;

		var sLimit = ((p-1) * perPage);
		var eLimit = ((p-1) * perPage) + perPage;
		if(sLimit < 0){sLimit = 0;eLimit = perPage;p=0;}
		if(arr.length < eLimit){ eLimit = arr.length;}
		
		for(i=sLimit; i< eLimit; i++){
			if( arr[i]['id'] != '' && arr[i]['id'] != 'null' && arr[i]['id'] != null ){
				arrResult[curIndex] = arr[i];
				curIndex++;
			}
		}
		
		// set current page
		this.page = (p == 0) ? 1 : p;
		
		return arrResult;
	};
	
	// Function to draw pagination
	this.drawPagination = function(){
		var total = this.arCurList.length;
		var tPages  = parseInt( total / this.perPage);
		if(tPages < (total/this.perPage) ){tPages++;}
		var html = "";
		var pClass = "";
		
		this.page = (this.page == 0) ? 1 : this.page;
		
		for(i=0; i<tPages; i++){
			//pClass = (i == (this.page-1)) ? "list-page-number" : "list-page-number";	
			//html += '<div class="'+pClass+'" id="p'+(i+1)+'"><a href="javascript:void(0)" onclick="'+this.objName+'.drawNextPage(' + (i+1) + ')"> ' + (i+1) + ' </a></div>';
			html += '<li><a href="javascript:void(0)" onclick="'+this.objName+'.drawNextPage(' + (i+1) + ')" class="'+pClass+'" name="p'+(i+1)+'"> ' + (i+1) + '</a><i>Â·</i></li>';
		}
		
		$("#"+this.divPageNav).html(html);
		$("#"+this.divPageNavBottom).html(html);
		
	};
	
	// draw the next set of results
	this.drawNextPage = function (p){
		
		var data = this.getNextPage(this.arCurList,p, this.perPage);
		$('a[name*="p"]').removeClass('active');
		if(p == this.page){
			$('a[name="p'+p+'"]').attr('class','active');
			
		}

		if(this.mapStatus == false){
			
			var html = "";
			for(i=0;i<data.length;i++){
				switch (this.type){
					case "apartment":
						html += this._drawItem(data[i],this.data.result.params);
						break;
					
					case "hotel":
						html += this._drawItem(data[i],this.data.result.params);
						break;
				}
			}
		}else{
			this.doShowResult('map');
		}
		
		if(data.length == 0){
			html = "<div class='result-filter-msg'>"+arTxt["filter-select-empty"]+"</div>";
		}
		
		$("#"+this.divResults).html(html);
		obj = this;
		$('a[title*="myList"]').each(function(){
			var found = oMyList.searchList(oResult.type,$(this).attr('name'));
			if(found){
				$(this).children('label').text(arTxt['remove from my list']);
				$(this).children('i').addClass('active');
			}
		});
		$('a[title*="myList"]').click(function(obj){
			
			oMyList.doItemControl(this,oResult.type,$(this).attr('name'),$(this).attr('id'),'add');
		});
	};
	
	// Switch between map and list view
	this.doShowResult = function(type){
		
		switch(type){
			case "map":
				$('#'+this.divResults).hide();
				$('#'+this.divPageNav).html("");
				$('#'+this.divPageNavBottom).html("");
				this.doShowMap(this.arCurList,this.data.result.params);
				break;
			case "list": 
				this.doHideMap();
				$('#'+this.divResults).show();
				this.doFilter();
				break;
		}
		
	};
	
	// Function to draw the current
	this.drawInitialList = function (){
		
		// Draw Page Navigation
		this.drawPagination();
		// Draw Towns
		this.drawTowns();
		
		// Draw Bedrooms
		if(this.type == 'apartment'){
			this.drawBedrooms();
			this.drawDistricts();
			this.drawAvailableSelectItems();
		}
		
		if(this.type=='hotel'){
			this.drawFilter('category_type', 'filterCategory', "div-type-specific-opt", "","opt_category");
			this.drawFilter('boards', 'arrFilterBoard', "div-type-board-opt", "");
			this.drawAvailableSelectItems();
		}
		
		// Get current limit
		this.drawNextPage(this.page);
		
		// Load slider
		this.loadSlider(this.initMin, this.initMax, this);
		
		// Load the filter values that have been set from the session token
		this.loadFilter();
		
		// apply filters if they have been loaded
		this.doFilter();
		
		// Load slider
//		this.loadSlider(this.min, this.max, this);
		
	};
	
	this.doSort = function (sort){
		this.arCurList = this.sort(this.arCurList,sort);
		this.sortOption = sort;
		this.drawNextPage(1);
		this.drawPagination();
	};
	
	this.resetSilder = function(){
		this.loadSlider(this.initMin, this.initMin, this);
	};
	
	this.loadSlider = function(min,max,obj){
		$("#slider-range").slider( 'destroy' );
		$("#slider-range").slider({
			range: true,
			min: this.initMin,
			max: (this.initMax + 1),
			values: [min, max],
			step: 3,
			obj: obj,
			slide: function(event, ui) {
				$("#amount").html(ui.values[0] + ' &euro; - ' + ui.values[1]+' &euro;');
			},
			stop: function(event, ui){
				// Apply price filter to the current list
//				obj.doFilter(false);
				
				// Check if slider has been moved
				if($("#slider-range").slider("values", 0) != obj.min || $("#slider-range").slider("values", 1) != obj.max){
					obj.disableSearcher(true); // Disable all inputs before filtering ...
					var min = $("#slider-range").slider("values", 0);
					var max = $("#slider-range").slider("values", 1);

					obj.setFilterCheckBoxes();
					obj.arCurList = obj.doApplyFilters(obj.getCurrent(obj.data), obj.oFilter);
					obj.arCurList = obj.sort(obj.arCurList, obj.sortOption);
					
					obj.doPriceFilter(obj.arCurList,min,max );
					obj.drawNextPage(1);
					obj.drawPagination();
					$('#'+obj.spanTotalCurrent).html(obj.arCurList.length);
					obj.disableSearcher(false); // Enable all inputs after filtering ...
				}
			}
		});
		$("#amount").html( $("#slider-range").slider("values", 0) + ' &euro; -' + $("#slider-range").slider("values", 1)+' &euro;');
	};

	// Draw Bedroom list
	this.drawFilter = function (resultOptName,filterName,divId,textKey,optDisplayField){

		var arOpt 		= new Array();
		var town		= "";
		var html 		= "";
		var list = this.getCurrent(this.data);
		var isFound = false;
		var sortByCode = false;
		var alertTxt = "";
		var showCount = true;
		
		if(optDisplayField == '' || optDisplayField == 'undefined'){
			optDisplayField = resultOptName;
		}
//		alert(resultOptName+ " : " +filterName+ " : " +divId+ " : " +textKey);
		if(resultOptName != 'boards'){
		for(i in list){
			isFound = false;
			optValue = list[i][resultOptName];
			optDisplay = list[i][optDisplayField];
			// check for duplicates
			for(var j in arOpt){
				if(arOpt[j]['opt'] == optValue){
					arOpt[j]['count']++;
					isFound = true;

				}
			}
			
			if(!isFound){
				if(resultOptName == 'category_type'){
					sortByCode = true;
					if(optValue.match(/^\d[a-z]{2,}/i) && !optValue.match(/^\dlux/i)){
						code = optValue.replace(/(^\d)([a-z]{2,})/i, "$2$1");
					}else if(optValue.match(/^\dlux/i)){
						code = optValue.replace(/(^\d)(lux)/i, "EST$1$2");
					}else{
						code = optValue;
					}
					
				}
				
				
//				alertTxt += optValue + " : " + code + "\n";
				arOpt.push({'opt':[optValue],'display': [optDisplay], 'count':[1],'code':[code]});
			}
			
			
		}
		}
		
		if(resultOptName == 'boards'){
			var arOpt 		= new Array();
			sortByCode = false;
			showCount = false;
			
			var oBoardHack = {"Solo Habitaciï¿½n":"Solo Habitacion",'Solo Alojamiento':'Solo Habitacion','Alojamiento Y Desayuno':'Habitacion y Desayuno'};
			// Loop through list
			for(i in list){
				
				// find boards
				var opts = list[i]['opts'];
				// loop through boards
				for(b in opts){
					isFound = false;
					// Check so that there are no duplicate boards
					var optValue = opts[b]['board'];
					var optDisplay = opts[b]['board'];
					
					// Check for language problem hack
					if(oBoardHack[optValue] != 'undefined' && oBoardHack[optValue] != '' && oBoardHack[optValue] != null ){
//						alert(optValue + " : " +oBoardHack[optValue]);
//						return;
						
						this.data.result.property[i]['opts'][b]['board'] = optValue;
						
						jQuery.each(list[i]['boards'],function(index, value){
							var str = value;
							value = str.replace(optValue, oBoardHack[optValue]);
							oResult.data.result.property[i]['boards'][index] = value;
						});
						
						optValue = oBoardHack[optValue];
						optDisplay = oBoardHack[optValue];
					}
					if(optValue != 'undefined' && optValue != '' && optValue != null ){
						for(var j in arOpt){
							if(arOpt[j]['opt']){
								var textRegEx = new RegExp(jQuery.trim( arOpt[j]['opt'].toString() ),"i");
								var test = textRegEx.test(optValue);
		//						if(arOpt[j]['opt'] == optValue){
								if(test){
									arOpt[j]['count']++;
									isFound = true;
									break;
								}
							}
						}
					}else{
						isFound = true;
					}
					
					// Add board to filter list
					if(!isFound){
//						alertTxt += optValue + " : " + code + "\n";
						arOpt.push({'opt':[optValue],'display': [optValue],'count':[1],'code':[code]});
//						break;
					}else{
//						continue;
					}
					
				}
			}
			
//			alert(alertTxt);
			
		}
		
//		alert(alertTxt);
		var sortTag = (sortByCode) ? 'code' : 'opt';
		
		// Sort Bedrooms list Numerically decending
		arOpt = this.sort(arOpt,'asc|'+sortTag);
		
		// Create HTML
		var checked =  "";
		var txt = "";
		var html = "";
		jQuery.each(arOpt,function(index, value){
//			alert(value.display);
			var countHtml = (showCount) ? ' (' + value['count'] + ')' : "";
//			html += '<div><input type="checkbox" name="'+filterName+'" value="'+arOpt[i]['opt']+'" onclick="'+this.objName+'.doFilter();" '+ checked+'/> ' +  arOpt[i]['display'] + ' ' +txt + countHtml + '</div>';
			//html += '<div><input type="checkbox" id="chk'+resultOptName+index+'" onclick="oResult.doFilter()" name="'+filterName+'" value="'+value['opt']+'" '+ checked+'/><label for="chk'+resultOptName+index+'"> ' +  value['display'] + ' ' +txt + countHtml + '</label></div>';
			html += '<div class="contenido-filter border"><input type="checkbox" id="chk'+resultOptName+index+'" onclick="oResult.doFilter()" name="'+filterName+'" value="'+value['opt']+'" '+ checked+'/><label for="chk'+resultOptName+index+'">' +  value['display'] +  ' ' +txt +'</label><span>'+countHtml+'</span></div>';
					});

		// Draw in its container
		$("#"+divId).append(html);
	};
	
	// Draw Bedroom list
	this.drawBedrooms = function (){

		var arOpt 		= new Array();
		var town		= "";
		var html 		= "";
		var list = this.getCurrent(this.data);
		var isFound = false;
		
		for(i in list){
			isFound = false;
			optValue = list[i]['opt_bedrooms'];
			// check for duplicates
			for(var j in arOpt){
				if(arOpt[j]['opt_bedrooms'] == optValue){
					arOpt[j]['count']++;
					isFound = true;

				}
			}
//			alert(optValue);
			if(!isFound){
				arOpt.push({'opt_bedrooms':[optValue],'count':[1],'code':['']});
			}
		}
		
		// Sort Bedrooms list Numerically decending
		arOpt = this.sort(arOpt,'asc|opt_bedrooms');
		
		// Create HTML
		var checked =  "";
		var txt = "";
		var html = "";
		jQuery.each(arOpt,function(index, value){
			if (value) {
				//html += '<div><input type="checkbox" id="chkbedrooms'+index+'" name="filterBedrooms" value="'+value['opt_bedrooms']+'" onclick="oResult.doFilter();"'+ checked+'/><label for="chkbedrooms'+index+'">' +  value['opt_bedrooms'] + ' ' +arTxt['bedrooms']+ ' (' + value['count'] + ')</label></div>';
				html += '<div class="contenido-filter border"><input type="checkbox" id="chkbedrooms'+index+'" name="filterBedrooms" value="'+value['opt_bedrooms']+'" onclick="oResult.doFilter();"'+ checked+'/><label for="chkbedrooms'+index+'">' +  value['opt_bedrooms'] + " " +arTxt['bedrooms']+ '</label><span>(' + value['count'] +')</span></div>';
			}
			// html += '<div><input type="checkbox" name="filterBedrooms" value="'+arOpt[i]['opt_bedrooms']+'" onclick="'+this.objName+'.doFilter();" '+ checked+'/> ' +  arOpt[i]['opt_bedrooms'] + ' ' +arTxt['bedrooms']+ ' (' + arOpt[i]['count'] + ')</div>';
		});
		//		for(var i in arOpt){
		//			var checked =  "";
		//					
		//			if(arOpt[i]['opt_bedrooms'] != ''){
		//				html += '<div><input type="checkbox" name="filterBedrooms" value="'+arOpt[i]['opt_bedrooms']+'" '+ checked+'/> ' +  arOpt[i]['opt_bedrooms'] + ' ' +arTxt['bedrooms']+ ' (' + arOpt[i]['count'] + ')</div>';
		////				html += '<div><input type="checkbox" name="filterBedrooms" value="'+arOpt[i]['opt_bedrooms']+'" onclick="'+this.objName+'.doFilter();" '+ checked+'/> ' +  arOpt[i]['opt_bedrooms'] + ' ' +arTxt['bedrooms']+ ' (' + arOpt[i]['count'] + ')</div>';
		//			}
		//		}
		
		// Draw in its container
		$("#"+this.divBedrooms).append(html);
	};
	
	// Clear Check box type
	this.doClearFilters = function(filterName){
		if($("input:checked").length) {
			$("input:checked").each(function(){
				var regex = new RegExp("("+filterName+")", "i");
				var curInputName = $(this).attr('name');
					if(regex.test(curInputName)){
						$(this).attr('checked',false);
					}
				});
			}
		
		this.doFilter();
	};
	
	// Draw Districts
	this.drawDistricts = function (){
		var arr 		= new Array();
		var el		= "";
		var html 		= "";
		var list = this.getCurrent(this.data);
		var isFound = false;
		
		for(i in list){
			isFound = false;
			el = list[i]['district_label'];
			// check for duplicates
			for(var j in arr){
				if(arr[j]['label'] == el){
					arr[j]['count']++;
					isFound = true;

				}
			}
			
			if(!isFound){
				arr.push({'label':[el],'count':[1],'code':['']});
			}
		}
		
		// Sort District list alphabetically
		arr = this.sort(arr,'asc|label');
		var elSel = this.initDistrict;
		elSel = (this.initDistrict) ? elSel.toLowerCase() : "";
		// Create HTML
		var id_num=0;
		for(var i in arr){
			var checked =  "";
			if(arr[i]['label'] != '' && arr[i]['label'] != null){
				var cur = arr[i]['label'].toString() ;
				cur = cur.toLowerCase();
				var checked = (cur == elSel && elSel != '') ? 'checked' : "";
//				html += '<div class="filter-district"><input type="checkbox" name="filterDistrict" value="'+arr[i]['label']+'" onclick="'+this.objName+'.doFilter();" '+ checked+'/> ' + arr[i]['label'] + ' (' + arr[i]['count'] + ')</div>';
				//html += '<div class="filter-district"><input id="chk_distr_'+id_num+'" onclick="oResult.doFilter()" type="checkbox" name="filterDistrict" value="'+arr[i]['label']+'" '+ checked+'/><label for="chk_distr_'+id_num+'">' + arr[i]['label'] + ' (' + arr[i]['count'] + ')</label></div>';
				html += '<div class="contenido-filter border"><input id="chk_distr_'+id_num+'" onclick="oResult.doFilter()" type="checkbox" name="filterDistrict" value="'+arr[i]['label']+'" '+ checked+'/><label for="chk_distr_'+id_num+'">' + arr[i]['label'] + '</label><span>(' + arr[i]['count'] + ')</span></div>';
				
			}
			id_num++;
		}
		
		// Draw in its container
		$("#"+this.divDistrict).append(html);	
				
		return null;
	};
	
	// Draw the list of available towns
	this.drawTowns = function (){

		var arTown 		= new Array();
		var town		= "";
		var html 		= "";
		var list = this.getCurrent(this.data);
		var isFound = false;
		
		for(i in list){
			isFound = false;
			town = list[i]['town_label'];
			// check for duplicates
			for(var j in arTown){
				if(arTown[j]['town'] == town){
					arTown[j]['count']++;
					isFound = true;

				}
			}
			
			if(!isFound){
				arTown.push({'town':[town],'count':[1],'code':['']});
			}
		}
		
		// Sort Town list alphabetically
		arTown = this.sort(arTown,'asc|town');
		var selectedTown = this.initTown;
		selectedTown = (this.initTown) ? selectedTown.toLowerCase() : "";
		// Create HTML
		var id_num=0;
		for(var i in arTown){
			var checked =  "";
			if(arTown[i]['town'] != '' && arTown[i]['town'] != null){
				var currentTown = arTown[i]['town'].toString() ;
				currentTown = currentTown.toLowerCase();
				var checked = (currentTown == selectedTown && selectedTown != '') ? 'checked' : "";
				//html += '<div><input type="checkbox" id="chk_dest_'+id_num+'" onclick="oResult.doFilter()" name="filterTown" value="'+arTown[i]['town']+'" '+ checked+'/><label for="chk_dest_'+id_num+'"> ' + arTown[i]['town'] + ' (' + arTown[i]['count'] + ')</label></div>';
//				//html += '<div><input type="checkbox" name="filterTown" value="'+arTown[i]['town']+'" onclick="'+this.objName+'.doFilter();" '+ checked+'/> ' + arTown[i]['town'] + ' (' + arTown[i]['count'] + ')</div>';
				html += '<div class="contenido-filter border"><input type="checkbox" id="chk_dest_'+id_num+'" onclick="oResult.doFilter()" name="filterTown" value="'+arTown[i]['town']+'" '+ checked+'/><label for="chk_dest_'+id_num+'"> ' + arTown[i]['town'] + '</label><span>(' + arTown[i]['count'] + ')</span></div>';
			}
			id_num++;
		}
		
		// Draw in its container
		$("#"+this.divTowns).append(html);	
				
		return null;
	};
	
	// Do Filtering
	this.doFilter = function (doSave){
		
		// Disable all inputs before filtering ...
		if(this.mapStatus == false || !this.mapStatus){
			this.disableSearcher(true);
		}
		
		doSave = (doSave == '' || doSave == 'undefined') ? true : false;
		this.setFilterCheckBoxes();
		//console.debug(this.getCurrent(this.data));
		this.arCurList = this.doApplyFilters(this.getCurrent(this.data), this.oFilter);
		this.arCurList = this.sort(this.arCurList, this.sortOption);
		// Check if slider has been moved
		if($("#slider-range").slider("values", 0) != this.min || $("#slider-range").slider("values", 1) != this.max){
			min = $("#slider-range").slider("values", 0);
			max = $("#slider-range").slider("values", 1);
			this.doPriceFilter(this.arCurList,min,max );
		}
		
		if(this.mapStatus){
			this.doShowMap(this.arCurList,this.data.result.params);
		}else{
			this.drawNextPage(1);
			this.drawPagination();
			this.disableSearcher(false);
		}
		
		
		$('#'+this.spanTotalCurrent).html(this.arCurList.length);
		
		this.saveFilter(this);

		// Enable all inputs after filtering ...
		
		
	};

	// Private function in order to sleep for 1.5 seconds
	this._doFilter = function(){
		
	};
	
	// Enable / Disable Search zones
	this.disableSearcher = function (disable){
		
		var lopacity=0.8; //Layer opacity
		var ldelay=200; // Layer Delay in fade
		
		if (disable) {
			// Resize loading layer and fit to content layer
			loading_pad=($('#'+this.divOptions).height()/2)-31; // 31px width of loader ajax image 
			$('#'+this.divLoading).css('padding-top',loading_pad+'px'); // 'vertical align'
			$('#'+this.divLoading).width($('#'+this.divOptions).width()+1);
			$('#'+this.divLoading).height($('#'+this.divOptions).height()-loading_pad);

			// Resize big loading layer and fit to content big layer
			//loading_big_pad=($('#'+this.divContentResult).height()/2)-31; // 31px height loader ajax image
			loading_big_pad=300; // Fixed. Not in the middle.
			var min_height=0;
			if ($('#'+this.divContentResult).height()<800) 
				min_height=800; // set minimun heigh

			//$('#'+this.divLoadingBig).css('padding-top',loading_big_pad+'px'); // 'vertical align'
			//$('#'+this.divLoadingBig).width($('#'+this.divContentResult).width()+12);
			//$('#'+this.divLoadingBig).height($('#'+this.divContentResult).height()-loading_big_pad+min_height);
			
			// Show loading layers
			$('#'+this.divLoading).show();
			$('#'+this.divLoading).fadeTo(ldelay, lopacity);
			//$('#'+this.divLoadingBig).show();
			//$('#'+this.divLoadingBig).fadeTo(ldelay, lopacity);
		}
		else {
			// Hide loading layers
			$('#'+this.divLoading).stop(true, true).fadeOut(ldelay*2);
			//$('#'+this.divLoadingBig).stop(true, true).fadeOut(ldelay*3);
		}
		
		// Enable / Disable inputs in Search zones
		$('#'+this.divOptions+' :input').attr('disabled', disable);
		$('#'+this.divResultDestinations+' :input').attr('disabled', disable);
	};
	
	// Filter by price
	this.doPriceFilter = function (arr,minValue,maxValue){
		
		var arrResult = new Array();
		var intCount = 0;
		for(i=0;i<arr.length;i++){
			var obj = arr[i];
			temp = parseInt(arr[i]['price']);
			if(minValue == maxValue){
				if(temp == minValue || temp == maxValue){
					arrResult[intCount] = obj;
					intCount++;
				};
			}else if( (temp <= maxValue && temp >= minValue) || temp == minValue || temp == maxValue || minValue == maxValue){
				arrResult[intCount] = obj;
				intCount++;
				
			}
		}
		
		this.arCurList = arrResult;
		return arrResult;
	};
	
	this.saveFilter = function (obj){
		
		var filterJson = JSON.stringify(this.oFilter);
		$.ajax({
			type: "POST",
			url: "/includes/service/ServiceRequest.php?type="+this.type+ "&action=saveFilter",
			data: "&token=" + token + "&filter=" + filterJson,
			async: false
			});
	};
	
	// Add Selected Item From Result
	this.drawSelectedItem = function (){
	
		var isFound = false;
		// Find selected
		if(this.selectedItem != '' && this.selectedItem != 'undefined'){
			list = this.getCurrent(this.data);
			for(i in list){
				if(i['code'] == this.selectedItem){
					html = this._drawItem(i,this.data.result.params);
					$('#'+this.divSelectedItem).html(html);
				}
			}
		}
		
	};
	
}



