/**
 * @return
 * 
 * This is the base object for a search result set. It does the following:
 * 1)	Sets the basic filter object structure
 * 2)	Loads a filter object into the object
 * 3)	Gets the current "property" list of the data result set
 * 4)   Sorts Data
 * 5) 	Sets and Applies Filters
 * 6) 	draws selected Item (Needs object resultProperty)
 * 7)	Gets High and Low Prices
 * 8) 	Controls CRM selected items
 */

function resultBase (){
	this.testFn = function(){alert("test");};
	
	// Price variables
	this.min = 0;
	this.initMin = 0;
	this.max = 0;
	this.initMax = 0;
	this.arCurList = "";
	this.itemSelect = "div-item-select";
	
	this.myCrm = {};
	
	// This is the JSON filter base
	// The format is 
	// {
	//	'town': ## This is the name of the property
	//     	{'filterTown':[]}, ## This is the  where the ARRAY of values is stored
	//	'internet_room':  ## Again we have the propert
	//		{'filterStatInternet':[]} ## The word "stat" means that this is a static or just one value
	
	this.oFilter = {'town_label':{'filterTown':[]},
					'boards':{'arrFilterBoard':[]},
					'category_type':{'filterCategory':[]},
					'opt_less25_authorized':{'filterStatLess25':[]},
					'opt_handicapped':{'filterStatHandicapped':[]},
					'opt_payment_cc':{'filterStatPaymentCc':[]},
					'opt_payment_transfer':{'filterStatPaymentTransfer':[]},
					'opt_pets':{'filterStatPets':[]},
					'opt_bedrooms':{'filterBedrooms':[]},
					'district_label':{'filterDistrict':[]},
					'quality':{'filterQuality':[]},
					'opt_vtour':{'filterStatVirtualTour':[]},
					'opt_terrace':{'filterStatTerrace':[]},
					'opt_private_terrace':{'filterStatPrivateTerrace':[]},
					'opt_commun_terrace':{'filterStatCommunTerrace':[]},
					'opt_aircon':{'filterStatAirCon':[]},
					'opt_elevator':{'filterStatElevator':[]},
					'opt_internet':{'filterStatInternet':[]},
					'opt_wifi':{'filterStatWifi':[]},
					'opt_special':{'filterStatSpecial':[]},
					'opt_newyear':{'filterStatNewYear':[]},
					'opt_spa':{'filterStatSpa':[]},
					'opt_spa_golf':{'filterStatSpaGolf':[]},
					'opt_couples':{'filterStatCouples':[]},
					'opt_gastronomy':{'filterStatGastronomy':[]},
					'opt_excursion':{'filterStatExcursion':[]},
					'opt_ticket':{'filterStatTicket':[]},
					'opt_parking':{'filterStatParking':[]},
					'opt_free_parking':{'filterStatFreeParking':[]},
					'opt_garden':{'filterStatGarden':[]},
					'opt_garage':{'filterStatGarage':[]},
					'opt_tennis':{'filterStatTenis':[]},
					'opt_poolin':{'filterStatPoolIn':[]},
					'opt_poolout':{'filterStatPoolOut':[]},
					'opt_private_pool':{'filterStatPrivatePool':[]},
					'opt_wheelchair':{'filterStatHandicapped':[]},
					'opt_steam_bath':{'filterStatSteamBath':[]},
					'opt_sauna':{'filterStatSauna':[]},
					'opt_baby_cot':{'filterStatBabyCot':[]},
					'opt_massage':{'filterStatMassage':[]},
					'opt_whirlpool':{'filterStatWhirlpool':[]},
					'opt_heated_pool':{'filterStatHeatedPool':[]},
					'opt_gym':{'filterStatGym':[]},
					'opt_washmachine':{'filterStatWashMachine':[]},
					'opt_miniclub':{'filterStatMiniclub':[]},
					'opt_tv':{'filterStatTv':[]},
					'opt_heating':{'filterStatHeating':[]}
					};
	this.setFilter = function (oFilter){
		if(oFilter != 'undefined' && oFilter != null && oFilter != ''){this.oFilter = oFilter;}
	};
	
	// Loop through filters and select the ones that are loaded
	this.loadFilter = function (){
		var isFound = false;
		var i;
		var j;
		var filterTxt= "";

		for(var i in this.oFilter){
			var isArray = false;
			for(var j in this.oFilter[i]){
				
				for(var jj in this.oFilter[i][j]){
					value = this.oFilter[i][j][jj];
					$('input[name="'+j+'"]').filter(
							function(index){
								if($(this).val() == value){
									$(this).attr('checked','checked');
								}
						
							}
					
					);
				}
			}
		}
		
		
	};
	
	// Set the current property list
	this.getCurrent = function(data){
		var arr = new Array();
		for(i in data.result.property){
			arr[i] = data.result.property[i];
		}
		//return data.result.property;
		return arr;
	};
	
	// Select of availble items
	this.drawAvailableSelectItems = function (){
		var data = this.getCurrent(this.data);
		var html = "";
		var arrMod = new Array;
		
		arr = (this.type == 'apartment') ? this.sort(data,'asc|id') : this.sort(data,'asc|title');
		for(i=0; i<arr.length;i++){
			isFound = 0;
			var obj = arr[i];
			var title = (this.type == 'apartment') ? obj['id'] + " - " + obj['title'] : obj['title'];
			html += "<option value='"+ obj['id']+"'>"+title+"</option>";
		}
//		$(arr).each(function(i){
//				html += "<option value='"+ i['id']+"'>"+i['title']+"</option>";
//					});
		html = "<select id='item-sel-list' name='item-sel-list' onchange=\""+this.objName+".drawSelectedDropDownItem();\"><option value=''> - </option>"+html+"</select>";

		$("#"+this.itemSelect).html(html);
		$("#"+this.itemSelect).parent().show();
	};
	
	this.drawSelectedDropDownItem = function(){
		var id = $("#item-sel-list").val();
		var html = "";
		if(id != ''){
			var data = this.getCurrent(this.data);
			for(i=0; i<data.length;i++){
				isFound = 0;
				var obj = data[i];
				if(id == data[i]['id']){
					html = this._drawItem(data[i],this.data.result.params);
					$("#"+this.divSelectedItem).html(html);
					$("#"+this.divSelectedItemCont).show(25);
				}
			}
			
		}else{
			$("#"+this.divSelectedItemCont).hide(25);
			$("#"+this.divSelectedItem).html('');
		}
	};
	
	/**
	 *  Finds the highest price in the data set
	 * @param data object
	 * @return integer
	 */
	this.getMaxPrice = function(data){

		var high = 0;
		for(i=0;i<data.length;i++){
			var temp = parseInt(data[i]['price']);
			if(temp > high && (temp)){high = temp;}
		}
		
		return high;

	};
	
	/**
	 *  Finds the lowest price in the data set
	 * @param data object
	 * @return integer
	 */
	this.getLowPrice  = function(data){

		var low = 1000000;
		for(i=0;i<data.length;i++){
			temp = parseInt(data[i]['price']);
			if(temp < low && (temp)){low = temp;}
		}

		return low;

	};
	
	/**
	 *  Sets the HTML filter checkboxes according to the object oFilter
	 * @return null
	 */
	this.setFilterCheckBoxes = function (){
		var i;
		var j;
		var oFilter = this.oFilter;
		for(var i in oFilter){
			var isArray = false;
			for(var j in oFilter[i]){

				oFilter[i][j] = new Array();
				if($("input[name='"+j+"']:checked").length) {
				$("input[name='"+j+"']:checked").each(function(){
						isFound = true;
						filter = $(this).val();
						oFilter[i][j].push(filter);
						isArray = true;
					});
				}
			}
		}
		this.oFilter = oFilter;
		return null;

	};
	
	/**
	 *  Applies the supplied filters to a given array data set and then returns the filtered array
	 * @param arr array
	 * @param oFilter object
	 * @return array
	 */
	this.doApplyFilters = function (arr,oFilter){
		var arrResult 	= new Array();
		var isFound 	= 0;
		var intCount 	= 0;
		var intFilter = 0;
		var filterTxt = "";
		var isArray = false;
		var hasArray = false;

		// Check for the number of filters that exist
		for(var j in oFilter){
			// Loop through the HTML fields that correspond to the data field
			for(var jj in oFilter[j]){
				if(oFilter[j][jj].length > 0){
//					intFilter = intFilter + oFilter[j][jj].length;
					intFilter++;
				}
			}
		}
		
		// Loop through current record set
		for(i=0; i<arr.length;i++){
			isFound = 0;
			hasArray = false;
			
			var obj = arr[i];
			
			// Loop through data fields that are to be searched for 
			for(var j in oFilter){
				// Loop through the HTML fields that correspond to the data field
				for(var jj in oFilter[j]){
					
					if(oFilter[j][jj].length > 0){
						
						for(f=0;f< oFilter[j][jj].length; f++){
							
							// Check if the filter name has "arr" at the front
							// If it does this means that the filter is an array in the data set
							// This is really useful for board types
							isArray = (obj[j] instanceof Array) ? true : false;
							if(!isArray){
								if( obj[j] == oFilter[j][jj][f] && obj[j] != '' && oFilter[j][jj][f] != ''){
									isFound++;
								}
							}else{
								
								var arrValue = obj[j].valueOf();
								var regEx = new RegExp(oFilter[j][jj][f], "i");
								if(regEx.test(arrValue) && hasArray == false){
									isFound++;
									hasArray = true;
								}
							}
						}
					}
		
				}
			}
			
			// if all the filters were found for that row / record
			// This number must match the number of filters (intFilter)
			
			if(intFilter == isFound){
				
				arrResult[intCount] = arr[i];
				intCount++;
				var obj = arr[i];
			}
			
			
		}  // End loop of Records
		
		if(intFilter == 0){
			arrResult = arr;
			
		}
		
		// set current Min and Max price values
		this.min = (arrResult.length == 0) ? this.initMin : this.getLowPrice(arrResult);
		this.max = (arrResult.length== 0) ? this.initMax : this.getMaxPrice(arrResult);
		
		// set the current list
		this.arCurList = arrResult;
		
		return arrResult;
	};

	// Very useful for dom / advanced JSON and array / objects containers
	this.getElAttrValue = function (el,attr,type){
		
		switch(type){
			case('dom'):
				return el.getAttribute(attr);
			break;
			case("array"):
				return el[attr];
			break;
			default:
				return el[attr];
			break;
		}
		
	};
	
	// Sort the result array
	this.sort = function (arr,sortOption){
		var arrMod = new Array();
		if(sortOption == 'undefined' || sortOption == null || sortOption == '' || sortOption == false){
			sortOption = "asc|price";
		}
		
		if(sortOption != 'undefined' && sortOption != null && sortOption != ''){
			var arFilter = sortOption.split("|");
			var fTxt = "";
//			alert(arFilter.length + ' ' + filterType);
			for(i=0;i<arFilter.length; i++){
				fTxt += arFilter[i] + " ";
			}

			for (i=0;i<arr.length;i++){
				arrMod[i] = arr[i];
			}

			for (i=0;i<arrMod.length;i++){

				var temp = arrMod[i];
				for (j=0;j<arrMod.length;j++){
					if(arFilter[1] == 'price' || arFilter[1] == 'internal_rating_calc'){
						var sortValue1 = parseInt(arrMod[i][arFilter[1]]);
						var sortValue2 = parseInt(arrMod[j][arFilter[1]]);
					}else{
						var sortValue1 = arrMod[i][arFilter[1]];
						var sortValue2 = arrMod[j][arFilter[1]];
					}

					if(arFilter[0] == 'asc'){
						if(arFilter[1] == 'price'  || arFilter[1] == 'internal_rating_calc'){
							var sortValue1 = parseInt(arrMod[i][arFilter[1]]);
							var sortValue2 = parseInt(arrMod[j][arFilter[1]]);
						}else{
							var sortValue1 = arrMod[i][arFilter[1]];
							if(typeof sortValue1 == 'string')
							sortValue1 = sortValue1.toLowerCase();
							var sortValue2 = arrMod[j][arFilter[1]];
							if(typeof sortValue2 == 'string')
							sortValue2 = sortValue2.toLowerCase();
						}
						if(sortValue1 < sortValue2){
							temp 			= arrMod[i];
							arrMod[i] 		= arrMod[j];
							arrMod[j] 		= temp;
						}else{

							if(arFilter.length > 2){
								if(arFilter[3] == 'price'  || arFilter[1] == 'internal_rating_calc'){
									var sortValue3 = parseInt(arrMod[i][arFilter[3]]);
									var sortValue4 = parseInt(arrMod[j][arFilter[3]]);
								}else{
									var sortValue3 = arrMod[i][arFilter[3]];
									var sortValue4 = arrMod[j][arFilter[3]];
								}
								if(sortValue3 < sortValue4 && sortValue1 == sortValue2){
									temp 			= arrMod[i];
									arrMod[i] 		= arrMod[j];
									arrMod[j] 		= temp;
								}
							}

						}
					}

					if(arFilter[0] == 'desc'){
						if(sortValue1 > sortValue2){
							temp 			= arrMod[i];
							arrMod[i] 		= arrMod[j];
							arrMod[j] 	= temp;
						}
					}
				}


			}
			
			if(arrMod.length == 0){
				arrMod = arr;
			}
			
			// alert(sortOption + " : " +arr.length);
		}else{
			arrMod = arr;
		}
//		arrMod.sort(sortCallBack)

		return arrMod;
	};
	
	this.setMyCrm = function(type,key,el){
		if(el.checked){
			this.addMyCrm(type,key);
		}else{
			this.deleteMyCrm(type,key);
		}
		
	};
	
	this.addMyCrm = function(type, key){
		if(!this.myCrm[type]){
			this.myCrm[type] = {};
			this.myCrm[type][key] = true;
		}else{
			this.myCrm[type][key] = true;
		}
	};
	
	this.deleteMyCrm = function(type,key){
		
		for(var i in this.myCrm[type]){
			if(key == i && this.myCrm[type][i] == true)
//				alert(i);
				delete this.myCrm[type][i];
		}
	};
	
	this.checkMyCrm = function(type,key){
		if(this.myCrm[type]){
			if(this.myCrm[type][key] == true){return true;}
		}
		
		return false;
	};
}
