var listingType = null;
var pType = null;
var rType = null;
var showPhoto = false;
var showOpenHouse = false;
var mapCity = null;
var mapAarea = null;
var bedrooms = null;
var bathrooms = null;
var price = null;
var surface = null;
var propertyLength = 0;
var readinessTypeLength = 0;
var startPage = 0;
var currentNavigation = 0;
var isNavigation = false;
var entityType = 0;
var tabs = new Array($('entitySize').value);
var currentTab = 0;

function showPopupFailed() {
	var popupId = "popupMessageFailed";
	jQuery('.detailsInformationBox').children().remove();
	jQuery('.detailsInformationBox').append('<span style="position: relative;top:8px;">You must be logged in to do this... Please login from <a href="index.jsp">here</a> or register <a href="javascript:closePopUp(\''+popupId+'\');showPopupRegister();">here</a></span>');
	showModal("popupMessageFailed");
}

function checkBoxesLength(_propertyLength,_readinessTypeLength){
	propertyLength = _propertyLength;
	readinessTypeLength = _readinessTypeLength;
}

function nextPage(navigationNo_) {
	/* tuxpiper: as per client request, disable this restriction
	if (!isOnline()) {	/* disallow navigating to next page if anonymous user
			showPopupFailed();
			return;
	}
	*/

	for (var i = 0; i <= parseInt($('entitySize').value); i++) {
 		if (parseInt(i) === parseInt(currentTab)) {
 			tabs[i] = startPage = navigationNo_ * 10;
 		}
	}
	
	isNavigation = true;
	mapSearchAjax();
	isNavigation = true;
}

function setEntityType(_type) {
	entityType = _type;

	for (var i = 0; i <= parseInt($('entitySize').value); i++) {
 		if (parseInt(i) === parseInt(_type)) {
 			if (typeof(tabs[i])=="undefined")
 				startPage = 0;
 			else
 				startPage = tabs[i];
 		}
	}
	setAllParams();
	mapSearchAjax();
	changePagination(_type);
	currentTab = _type;
}

function setAllParams(){
	// set package type
	pType ='';
	for (var i = 1 ; i <= propertyLength ; i++){
		if ($('pType'+i) != null) {
			if ($('pType'+i).checked){
				pType +=i+',';
			}
		}
	}
	pType = pType.substring(0,pType.length-1);
	if (pType.length<1)
		pType = null;

	//set listing type

	listingType ='';
	for (var i=1; i<=6; i++){
		if ($('listingType'+i) != null) {
			if ($('listingType'+i).checked){
				listingType +=i+',';
			}
		}
	}
	listingType = listingType.substring(0,listingType.length-1);
	if (listingType.length<1)
		listingType = null;

	//set readiness type

	rType ='';
	for (var i = 1 ; i <= readinessTypeLength ; i++){
		if ($('rType'+i) != null) {
			if ($('rType'+i).checked){
				rType +=i+',';
			}
		}
	}
	rType = rType.substring(0,rType.length-1);
	if (rType.length<1)
		rType = null;

	//set show photo

	showPhoto = $('showPhoto').checked;

	//set show open house only

	showOpenHouse = $('showOpenHouse').checked;

	//set city

	mapCity = $('city').options[$('city').selectedIndex].value;
	if (mapCity == 0)
		mapCity = null;	
	//mapAarea = null;	

	//set area
	if ($('neighborhood').selectedIndex < 0)
		mapAarea = null;
	else
		mapAarea = $('neighborhood').options[$('neighborhood').selectedIndex].value;
	
	if (mapAarea == 0)
		mapAarea = null;
	startPage = 0;
	isNavigation = false;
}

//sets package type
function setPackageType(){
	setAllParams();
	mapSearchAjax();
}
//sets listing type
function setListingType(){
	setAllParams();
	mapSearchAjax();
}

//sets readinesstype
function setReadinessType(){
	setAllParams();	
	mapSearchAjax();
}

//set show photo
function setShowPhoto(){
	setAllParams();	
	mapSearchAjax();
}
//sets show open house
function setShowOpenHouse(){
	setAllParams();	
	mapSearchAjax();
}
//sets city value
function setCityValue(_value){
	setAllParams();		
	mapSearchAjax();
}
//sets area value
function setAreaValue(_value){
	setAllParams();		
	mapSearchAjax();
}

//sets quick search
function setQuickSearch(cityValue,areaValue){
	mapCity = cityValue;
	if (mapCity == 0)
		mapCity = null;
	mapAarea = areaValue;	
	if (mapAarea == 0)
		mapAarea = null;	
	
	for (var i=0; i<$('city').options.length; i++){
		var _city = $('city').options[i].value.split("-");
		 if (_city[0]==mapCity){
		 	$('city').options[i].selected=true;
		 	break;
		 }
	}
	
	showArea($('city').value,true);
	 
}
//sets quick search
function setQuickSearchArea(){
	if (mapAarea==null)
		return;
	for (var i=0; i<$('neighborhood').options.length; i++){
		var areaId = $('neighborhood').options[i].value.substring(0,$('neighborhood').options[i].value.indexOf("-"));
		 if (areaId==mapAarea){
		 	$('neighborhood').options[i].selected=true;
		 	break;
		 }
	}
}
//redirects to map_search to show quick search results
function showQuickSearchResult(path){
	var cityId = $('city').value;
	var areaId = $('neighborhood').value
	var searchType = '';
	
	for (var i=1;i<3;i++) {
		if ($('searchType'+i).checked){
 			searchType = $('searchType'+i).value
		}
	}
	if (areaId!=0)
		areaId = $('neighborhood').value.substring(0,$('neighborhood').value.indexOf("-"));
	window.location=path+"/"+searchType+"?city="+ cityId+"&area="+areaId;
}
//sets bedrooms
function setBedrooms(min,max){
	var _min = min;
	var _max = max;
	if (_min == "Studio") {
		_min = 0;
	}
	if(isEmpty(_min)){
		if(isEmpty(_max)){
			bedrooms = null;
		}else{
			bedrooms = "0,"+_max;
		}
	}else{
		if(isEmpty(_max)){
			bedrooms = _min +","+_min;
		}else{
			bedrooms = _min +","+_max;
		}
	}
	startPage = 0;
	isNavigation = false;
	setAllParams();
	mapSearchAjax();
}
//sets bathrooms
function setBathrooms(min,max){
	var _min = min;
	var _max = max;
	if(isEmpty(_min)){
		if(isEmpty(_max)){
			bathrooms = null;
		}else{
			bathrooms = "0,"+_max;
		}
	}else{
		if(isEmpty(_max)){
			bathrooms = _min +","+_min;
		}else{
			bathrooms = _min +","+_max;
		}
	}
	startPage = 0;
	isNavigation = false;
	setAllParams();
	mapSearchAjax();
}
//sets price
function setPrice(min,max){
	var _min = min;
	var _max = max
	if(isEmpty(_min)){
		if(isEmpty(_max)){
			price = null;
		}else{
			price = "0,"+_max;
		}
	}else{
		if(isEmpty(_max)){
			price = _min +","+_min;
		}else{
			price = _min +","+_max;
		}
	}
	startPage = 0;
	isNavigation = false;
	setAllParams();
	mapSearchAjax();
}
//sets surface
function setSurface(min,max){
	var _min = min;
	var _max = max
	if(isEmpty(_min)){
		if(isEmpty(_max)){
			surface = null;
		}else{
			surface = "0,"+_max;
		}
	}else{
		if(isEmpty(_max)){
			surface = _min +","+_min;
		}else{
			surface = _min +","+_max;
		}
	}
	startPage = 0;
	isNavigation = false;
	setAllParams();
	mapSearchAjax();
}
//hides content data
function setHideContentData(_id){
	if ($(_id)==null){
		$(_id).style.display = 'block';
		$(_id).innerHTML='<div class="map_inner-body"><div style="clear: both;"></div></div>';
		$(_id).style.display = 'none';
		return;
	}
	$(_id).innerHTML='<div class="map_inner-body"><div style="clear: both;"></div></div>';
}

function saveFavoriteSearch(){
	setAllParams();
	alert(getCompleteParams()+'&saveSearch=true');
	new Ajax.Request(mapSearch, {
		asynchronous:true, method: 'post', 
		parameters: getCompleteParams()+'&saveSearch=true',
			onComplete: function(transport){
			alert('done');	
			/*var json = transport.responseText.evalJSON();
				for (var i=0; i<json.readinessCollection.length;i++){
					    $('readType').options.add(new Option(json.readinessCollection[i].name,json.readinessCollection[i].id));
				}				
				loadReadinessType($('readType').value);*/
			}
	});

}

//gets the results of map search
function mapSearchAjax(){

	var info = '<div class="informationBox">';
		info +=	   '<img src="css/images/info.png" class="infoImg" width="50" height="50">Your search did not produce any results under this category. Please change your search criteria or look at other result tabs.';
		info += '</div>';
						
	if (!$('allResults'))
		return;
		
	for (var i=0;i<=4;i++){
		if (i==0){
			$('allResults').innerHTML='<div class="map_inner-body" style="text-align:center;height:100px;"><img id="searchLoader" src="css/images/loader-bluebg.gif" style="margin-top:30px;"><div style="clear: both;"></div></div>';
			continue;
		}
		if ($('propertyList'+i)){
			$('propertyList'+i).innerHTML='<div class="map_inner-body" style="text-align:center;height:100px;"><img id="searchLoader" src="css/images/loader-bluebg.gif" style="margin-top:30px;"><div style="clear: both;"></div></div>';
		}
	}
	
	new Ajax.Request(mapSearch, { 
		asynchronous:true, method: 'post', 
			parameters: getCompleteParams(),
			onComplete: function(transport){
				var json = transport.responseText.evalJSON();
				
				if (!isNavigation){
					for (var i=0;i<json.tabs.length;i++){
						var tabObj = json.tabs[i];
						if (i == 0){
							$('searchTab'+i).innerHTML=tabObj.name + '('+json.totalResults+')';
							setPager(json.totalResults, i);
							continue;
						}
						$('searchTab'+i).innerHTML=tabObj.name + '('+tabObj.size+')';
						setPager(tabObj.size, i);
					}
				}
				
				if (json.noRecord == 0){
					
					if (!isNavigation){
						currentNavigation = 0;
						jQuery('#buyPager').hide();
					}
						
					noResults = true;
					
					for (var i=0;i<=4;i++){
						if (i==0){
							$('allResults').innerHTML='<div class="map_inner-body"><div style="clear: both;">'+info+'</div></div>';
						}
						if ($('propertyList'+i)){
							$('propertyList'+i).innerHTML='<div class="map_inner-body"><div style="clear: both;">'+info+'</div></div>';
						}
					}

					if (initialize){
     					map.clearOverlays();
     					if (mapAarea){
	     					if (mapAarea && mapAarea.match("-")){
	     						var coordinates = mapAarea.substring(mapAarea.indexOf("-")+1).split("|");
	     						var point = new GLatLng(coordinates[0].toDecimalFormat(),coordinates[1].toDecimalFormat());
								map.setCenter(point,17);
	     					}
     					}else{
     						if (mapCity && mapCity.match("-")){
	     						var coordinates = mapCity.substring(mapCity.indexOf("-")+1).split("|");
	     						var point = new GLatLng(coordinates[0].toDecimalFormat(),coordinates[1].toDecimalFormat());
								map.setCenter(point,17);
	     					}
     					}
     				}
					return;
				}
				noResults = false;
				
				mapPoints2Collection = new Array();
				
				var str='';
				
				for (var i=0;i<json.propertyList.length;i++){
					var contentObj = json.propertyList[i];
					
					if (i == 0){
						$('allResults').innerHTML=contentObj.content;
						continue;
					}
					if ($('propertyList'+i)){
						if (contentObj.content==""){
							$('propertyList'+i).innerHTML=info;
						} else { $('propertyList'+i).innerHTML=contentObj.content;}
					}
				}

				//load map points 
				loadPoints(json.points);
				jQuery('#buyPager').show();
				
				/*if (!isNavigation){
					currentNavigation = 0;
					jQuery('#buyPager').pagination(parseInt(json.totalResults), {
						items_per_page:10, 
						num_edge_entries: 3,
						num_display_entries: 10,
						callback: nextPage
	                });
				}*/
				
				var _cityId = 0;
				var _areaId = 0;
				var _title = -1;
				var _size = -1;
				var _price = -1;
				var _bedrooms = -1;
				var _bathrooms = -1;
				var _imageLocation = -1;
				if (mapCity != null && mapCity!=0){
					var _idMapCity = mapCity.split("-");
					_cityId = _idMapCity[0];
				}
				if (mapCity != null)
					_cityId = mapCity;
				if (mapAarea != null && mapAarea!=0){
					var _idArea = mapAarea.split("-");
					_areaId = _idArea[0];
				}
				//$('open_map').setAttribute("onClick","loadSearchMap('"+_cityId+"','"+_areaId+"','-1',null)"); 
				
				isJspLoaded = false;
				selectedId = null;
				myBounds =new Array();
				
				mapPointsCollection =null
				loadToCollections();
			}
	});
}
//redirect to property details if property on map search is clicked
function loadToDetails(path){
	window.location = path;
}
//load the map points to a temporary array
function loadPoints(points){
	for (var i=0; i<points.length;i++){
		var id =  points[i].id;
		var _title = points[i].title;
		var _size = points[i].size;
		var _price = points[i]._price;
		var _bedrooms = points[i].bedrooms;
		var _bathrooms = points[i].bathrooms;
		var _imageLocation = points[i].primaryPhoto;
		var _type =  points[i].type;
		var _typeName = points[i].typeName;
		var _location = points[i].location;
		var mapPoints_ = new MapPoints2(id,points[i].latitude,points[i].longtitude,'\''+points[i].address+'\'',_title,_size,_price,_bedrooms,_bathrooms,_imageLocation,_type,_typeName,_location);
		mapPoints_.addUrl(points[i].validUrl);
		
		mapPoints2Collection[mapPoints2Collection.length] = mapPoints_;
	}
}
//returns the complete params of filters that is need by mapSearchAjax
function getCompleteParams(){
	
	var params = new Array();
	var str='';
	if (mapCity!=null)
		params["cityId"]=mapCity;
	if (mapAarea!=null)
		params["areaId"]=mapAarea;
	if (pType!=null)
		params["pType"]=pType;
	if (rType!=null)
		params["rType"]=rType;
	if (listingType!=null)
		params["listType"]=listingType;
	if (bedrooms!=null)
		params["bedRooms"]=bedrooms;
	if (bathrooms!=null)
		params["bathRooms"]=bathrooms;
	if (price!=null)
		params["price"]=price;
	if (surface!=null)
		params["surface"]=surface;
	if (entityType!=null)
		params["entity_type"]=entityType;	
		
	params["start_page"]=startPage;
	
	for (var _param in params){
		 if (_param == "cityId" || _param  == "areaId" || _param  == "pType" || _param  == "rType" || _param == "listType"
		 		|| _param == "bedRooms" || _param == "bathRooms" || _param == "surface" || _param == "price" || _param == "start_page" || _param == "entity_type"){ 
		 	var key = _param;
		 	var value = params[_param];
		 	if (str.length==0){
		 		str+=key+'='+value;
		 		continue;
		 	}
		 	str+='&'+key+'='+value;
		 }
	}
	
	var isBuy = true;
	
	if (!(String(window.location).match("buy.jsp"))){
		isBuy = !isBuy;
	}
	str+='&photo='+showPhoto+'&openHouse='+showOpenHouse+'&isBuy='+isBuy;
	return str;
}
//saves property as favorite
function saveToFavorite(_id){
	closeMark();
	new Ajax.Request(saveAsFavorite, { 
		asynchronous:true, method: 'post', 
			parameters: 'infoId='+_id,
			onComplete: function(transport){
				jQuery('#popupLoader').css('display','none');
				//if (transport.responseText == null || transport.responseText == ""){
				//	var str = '<div class="detailsInformationBox" style="margin: 0;width:200px;">';
				//		str += '<span style="position: relative;top:8px;">You must be logged in to do this... Please login from <a href="index.jsp">here</a></span>';
				//		str += '</div>';	
				//	$('popupMsgContent').innerHTML =str;
				//	showModal('popupFavorite2');
				//	return;
				//}
				
				if (transport.responseText == "exists"){
					$('popupMsgContent').innerHTML ='The Listing was Already Saved As Favorite.<br>You can view it on <a href="'+baseUrl+'my_beeyoot.jsp" style="color: #285493">My beeyoot</a> page';
				}else{
					$('popupMsgContent').innerHTML ='The Listing was saved.<br>You can view it on <a href="'+baseUrl+'my_beeyoot.jsp" style="color: #285493">My beeyoot</a> page';
				}
				showModal('popupFavorite2');
			}
	});
}

//opens a popup for confirmation to save property as favorite
function confirmedSaveToFavorite(_id){
	if(!isOnline()) {
		showModal("popupMessageFailed");
		return;
	}
	$('popupHeaderCommon').innerHTML = 'Save As Favorite <a href="javascript:closeMark();" class="popupClose"><img alt="close" src="css/images/popup_close.gif" width="14" height="16"></a>';
	$('popupContent').innerHTML = 'Save As Favorite?<br><a id="confirmDelete" onClick="javascript:showLoaderPopup(\'Saving as Favorite...\')" href="javascript:saveToFavorite('+_id+');" class="deleteConfirm yes">YES</a><a href="javascript:closeMark();" class="deleteConfirm">CANCEL</a>';
	showModal("popup");
}
//removes property as favorite
function removeFromFavorite(_id,path){
	alert("alert");
	$('confirmDelete').href=path+"/my_beeyoot.jsp?infoId="+_id;
}
//opens a pop up confirmation for property deletion on my beeyoot
function popupConfirmation(path,title,markType){
	var headerTitle = "Unmarking as ";
	if (title.match("Unmark") == null) {
		headerTitle = "Marking as ";
	}
	
	headerTitle = headerTitle + markType;
	
	$('popupHeaderCommon').innerHTML = title+' <a href="javascript:closeMark();" class="popupClose"><img alt="close" src="css/images/popup_close.gif" width="14" height="16"></a>';
	$('popupContent').innerHTML = title+'?<br><a id="confirmDelete" href="'+path+'" onClick="javascript:showLoaderPopup(\''+headerTitle+'\')" class="deleteConfirm yes">YES</a><a href="javascript:closeMark();" class="deleteConfirm">CANCEL</a>';
	showModal("popup");
}
//opens a pop up confirmation for property deletion
function confirmationRemoveListing(_id){
	$('popupHeaderCommon').innerHTML = 'Remove Listing <a href="javascript:closeMark();" class="popupClose"><img alt="close" src="css/images/popup_close.gif" width="14" height="16"></a>';
	$('popupContent').innerHTML = 'Are your sure you want to remove this listing?<br><a onClick="javascript:showLoaderPopup(\'Removing Listing...\')" id="confirmDelete" href="remove.jsp?infoId='+_id+'" class="deleteConfirm yes">YES</a><a href="javascript:closeMark();" class="deleteConfirm">CANCEL</a>';
	showModal("popup");
}
//opens a pop up confirmation for property deletion on my beeyoot for removing as favorite
function confirmationPopup(_id,path){
	$('popupHeaderCommon').innerHTML = 'Remove Listing From Favorite<a href="javascript:closeMark();" class="popupClose"><img alt="close" src="css/images/popup_close.gif" width="14" height="16"></a>';
	$('popupContent').innerHTML = 'Are you sure you want to remove this listing from your favorites?<br><a id="confirmDelete" onClick="javascript:showLoaderPopup(\'Removing Listing From Favorite\')" href='+path+'/my_beeyoot.jsp?infoId='+_id+' class="deleteConfirm yes">YES</a><a href="javascript:closeMark();" class="deleteConfirm">CANCEL</a>';
	showModal("popup");
}
//switch view to show map
function openPropertyMap(latitude, longitude, _title, _size, _price,_bedrooms, _bathrooms, _imageLocation,_type, _typeName, _location){
	document.getElementById('summary').style.display="none";
	document.getElementById('map').style.display="block";
	document.getElementById('tabPropertyMap').className ="tabActive2";
	document.getElementById('tabSummary').className ="tab";
	
	loadMap(latitude, longitude, _title, _size, _price,_bedrooms, _bathrooms, _imageLocation,_type, _typeName, _location);
}

function changePagination(_id) {

	for (var i = 0; i < parseInt($('entitySize').value) + 1; i++) {
	 		if (parseInt(_id) === parseInt(i))
	 			elementShow('pager_'+i);
	 		else
	 			elementHide('pager_'+i);
	}
}
