var drag_start_listener = null;
var drag_end_listener = null;
var PropertySearchPageController = Class.create();
PropertySearchPageController.prototype = {
	initialize : function()
	{
		var today = new Date();
		var expire_date = new Date(today.getTime()+3600000*24*100);		
		setCookie("HKH_MHC_map", "", expire_date, "/");
		this.use_ajax = true;
		this.history_key = null;
		this.history_val = null;
		this.first_history = true;
		this.history_cnt = 0;
		this.history_processing = false;
		
		this.auto_set_property_info = false;
		this.auto_set_property_info_action = 0;
		
		this.num_of_rec = 0;
		this.max_page = 0;
		this.map_panel = null;
		this.map_point_loaded = false;
		
		this.map_point_lib = [];
		this.map_point_lib_pointer = 0;
		this.map_point_cnt = 0;
		this.add_map_point_timeout = null;
		this.map_point_load_history = null;
		this.resources_on_map = null;
		this.first_fetch_action = true;
		this.form = $("ps_search_form");
		
		var url = parseUri(window.location.href);
		this.search_parameters = url.query.toQueryParams();
		this.item = toolbar.searchItem("property_search");

		Event.stopObserving(window, "resize", fitScreenAction);
		Event.observe(window, "resize", this.resize.bindAsEventListener(this));
		Event.observe(window, "unload", this.unloadProcess.bindAsEventListener(this));

		this.is_map_compatible = false; // not show map
		if(!(is_ie6||is_ie6up||agt.indexOf("gecko/2004")!=-1||agt.indexOf("gecko/2005")!=-1||agt.indexOf("gecko/2006")!=-1||agt.indexOf("gecko/2007")!=-1||agt.indexOf("opera/9")!=-1||agt.indexOf("firefox")!=-1||agt.indexOf("netscape/7")!=-1))
		{
			this.is_map_compatible = false;
		}	
		if(this.item != null && typeof(this.item.setResource) == "function")
		{
			this.item.setResource(this.search_parameters);
		}			
		
		this.map_loading_cover = document.createElement("DIV");
		this.map_loading_cover.style.display = "none";
		this.map_loading_cover.style.position = "absolute";
		this.map_loading_cover.style.zIndex = "800000";
		this.map_loading_cover.style.backgroundColor = "#FFFFFF";
		this.map_loading_cover.innerHTML = "<table class='general_tbl'><tr><td vAlign='middle' align='center'><img align='absmiddle' src='"+sRelativePath+"images/spinner.gif'>&nbsp;<span id='map_panel_loading_message'>Loading Map Point...</span></td></tr></table>";
		document.body.appendChild(this.map_loading_cover);
		Element.setOpacity(this.map_loading_cover, 0.7);				
	},
	setResource : function ()
	{
		if(this.form == null)
			return false;
			
			
	},
	unloadProcess : function ()
	{
		try{
		while($("mode1").childeNodes.length > 0)
		{
			$("mode1").removeChild($("mode1").childeNodes[0]);
		}
		while($("mode2").childeNodes.length > 0)
		{
			$("mode2").removeChild($("mode1").childeNodes[0]);
		}		
		while(document.body.childeNodes.length > 0)
		{
			document.body.removeChild(document.body.childeNodes[0]);
		}
		}
		catch(e){}
	},
	setFirstHistory : function()
	{
		if(window.dhtmlHistory.isFirstLoad() && this.use_ajax)
		{
			var form_serialize = $(this.item.form).serialize();
			this.setHistory("", form_serialize);
		}		
	},
	resize : function()
	{
		if(property_info_viewer != null && typeof(property_info_viewer.quickHide) == "function" )
			property_info_viewer.quickHide();
		toolbar.closeOthers(null);
		fitScreen();
		if(	this.map_panel != null && this.map_container != null)
		{
			this.map_panel_left = getOffset(this.map_container, true);
			this.map_panel_top = getOffset(this.map_container, false);
					
			this.map_panel.style.left = (this.map_panel_left+1)+"px";
			this.map_panel.style.top = (this.map_panel_top+1)+"px";				
		}

	},
	initializeHistory : function()
	{
		//window.dhtmlHistory.initialize();	
		//window.dhtmlHistory.addListener(this.historyChangeListener.bind(this));
	},
	historyChangeListener : function(history_code, history_data)
	{
		this.processHistory(history_code, history_data);
	},
	showLoading : function()
	{
		this.loading_panel.style.display = "block";
		this.loading_panel_b.style.display = "block";
		if($("mode1") != null)
		{
			var left = getOffset($("mode1"), true);	
			var top = getOffset($("mode1"), false);
			var width = $("mode1").offsetWidth;
			var height = $("mode1").offsetHeight;
			this.loading_shad.style.left = left+"px";
			this.loading_shad.style.top = top+"px";
			this.loading_shad.style.width = width+"px";
			this.loading_shad.style.height = height+"px";
			this.loading_shad.style.display = "block";
		}
	},	
	hideLoading : function()
	{
		this.loading_shad.style.display = "none";
		this.loading_panel.style.display = "none";
		this.loading_panel_b.style.display = "none";
	},	
	initializePageComponents : function()
	{
		if($("search_property_sort_by_select") != null && typeof($("search_property_sort_by_select")) != "undefined")
		{
			//Event.observe($("search_property_sort_by_select"), "change", this.changeSortBySetting.bindAsEventListener(this));
			$("search_property_sort_by_select").onchange = this.changeSortBySetting.bindAsEventListener(this);
		}
		if($("search_property_result_per_page_select") != null && typeof($("search_property_result_per_page_select")) != "undefined")
		{
			//Event.observe($("search_property_result_per_page_select"), "change", this.changeResultPerPageSetting.bindAsEventListener(this));
			$("search_property_result_per_page_select").onchange = this.changeResultPerPageSetting.bindAsEventListener(this);
		}	
		
		if($("property_search_toolbar_top_right") != null && typeof($("property_search_toolbar_top_right")) != "undefined")
		{
			var as = $("property_search_toolbar_top_right").getElementsByTagName("a");
			var max = 0;
			for(var i=0; i<as.length; i++)
			{
				if($(as[i]).readAttribute("action") != null && $(as[i]).readAttribute("action").indexOf("page") != -1)	
				{
					var page = as[i].readAttribute("action").replace("page_", "");
					
					if(is_opera != null && is_opera)
					{
						var page_split = page.split("/");
						page = parseInt(page_split[page_split.length-1]);
					}
					as[i].href = "javascript:controller.changePageSetting("+page+");";
					if(parseInt(page) > max)
						max = parseInt(page);
				}
			}
			this.setMaxPage(max);
			var as = $("property_search_toolbar_top_right").getElementsByTagName("img");
			for(var i=0; i<as.length; i++)
			{
				if($(as[i]).readAttribute("action") != null && $(as[i]).readAttribute("action").indexOf("prev_page") != -1)		
				{
					as[i].style.cursor = "pointer";
					as[i].onclick = this.prevPage.bindAsEventListener(this);
				}
				if($(as[i]).readAttribute("action") != null && $(as[i]).readAttribute("action").indexOf("next_page") != -1 )		
				{
					as[i].style.cursor = "pointer";
					as[i].onclick = this.nextPage.bindAsEventListener(this);
				}			
			}		
		}	
		if($("property_search_toolbar_bottom") != null && typeof($("property_search_toolbar_bottom")) != "undefined")
		{
			var as = $("property_search_toolbar_bottom").getElementsByTagName("img");
			for(var i=0; i<as.length; i++)
			{
				if($(as[i]).readAttribute("action") != null && $(as[i]).readAttribute("action").indexOf("prev_page") != -1)		
				{
					as[i].style.cursor = "pointer";
					//Event.observe($(as[i]), "click", this.prevPage.bindAsEventListener(this));
					as[i].onclick = this.prevPage.bindAsEventListener(this);
				}
				if($(as[i]).readAttribute("action") != null && $(as[i]).readAttribute("action").indexOf("next_page") != -1)		
				{
					as[i].style.cursor = "pointer";
					//Event.observe($(as[i]), "click", this.nextPage.bindAsEventListener(this));
					as[i].onclick = this.nextPage.bindAsEventListener(this);
				}			
			}		
		}		
		if($("search_property_page_bottom_form") != null && typeof($("search_property_page_bottom_form")) != "undefined")
		{
			//Event.observe($("search_property_page_bottom_form"), "submit", this.pageBottomSubmitListener.bindAsEventListener(this));	
			$("search_property_page_bottom_form").onsubmit = this.pageBottomSubmitListener.bindAsEventListener(this);
		}
		if(this.num_of_rec == 0)
		{
			if($("result_num_of_rec") != null)
				this.num_of_rec = parseInt($("result_num_of_rec").innerHTML);
		}
		

	},
	showMapLoadingCover : function()
	{
		if(this.map_panel == null)
			return false;
		if(this.map_panel.style.display == "none")
			return false;
			
		var left = getOffset(this.map_panel, true);
		var top = getOffset(this.map_panel, false);
		var width = this.map_panel.offsetWidth;
		var height = this.map_panel.offsetHeight;
		
		this.map_loading_cover.style.display = "";
		this.map_loading_cover.style.left = left+"px";
		this.map_loading_cover.style.top = top+"px";
		this.map_loading_cover.style.width = width+"px";
		this.map_loading_cover.style.height = height+"px";
		this.map_loading_cover.childNodes[0].style.width= width+"px";
		this.map_loading_cover.childNodes[0].style.height= height+"px";
		
	},
	hideMapLoadingCover : function()
	{
		this.map_loading_cover.style.display = "none";	
	},
	initializeTagMenu : function(container)
	{
		while(container.childNodes.length > 0)
			container.removeChild(container.childNodes[0]);
			
		this.result_in_list = document.createElement("IMG");
		this.result_in_list.mode = "1";
		this.result_in_list.align = "absbottom";
		this.result_in_list.style.cursor = "pointer";
		this.result_in_list.style.marginRight = "5px";
		this.result_in_list.src = "../images/property/tag_result_list_on.gif";
		//Event.observe(this.result_in_list, "click", this.tagItemClickListener.bindAsEventListener(this));
		this.result_in_list.onclick = this.tagItemClickListener.bindAsEventListener(this);
		container.appendChild(this.result_in_list);

		if(this.is_map_compatible)
		{
		this.result_in_map = document.createElement("IMG");
		this.result_in_map.mode = "2";
		this.result_in_map.align = "absbottom";
		this.result_in_map.style.cursor = "pointer";	
		this.result_in_map.style.marginRight = "5px";	
		this.result_in_map.src = "../images/property/tag_result_map_off.gif";
		//Event.observe(this.result_in_map, "click", this.tagItemClickListener.bindAsEventListener(this));
		this.result_in_map.onclick = this.tagItemClickListener.bindAsEventListener(this);
		container.appendChild(this.result_in_map);
		}
		else
		{
			this.result_in_map = null;
		}
		this.loading_panel = document.createElement("DIV");
		this.loading_panel.style.display = "none";
		this.loading_panel.innerHTML = "<img src='../images/spinner.gif' align='absmiddle'>&nbsp;Loading...";
		$("loading_toolbar").appendChild(this.loading_panel);
		
		this.loading_panel_b = document.createElement("DIV");
		this.loading_panel_b.style.display = "none";
		this.loading_panel_b.innerHTML = "<img src='../images/spinner.gif' align='absmiddle'>&nbsp;Loading...";
		$("loading_toolbar_b").appendChild(this.loading_panel_b);
				
		this.loading_shad = document.createElement("DIV");
		this.loading_shad.style.display = "none";
		this.loading_shad.style.position = "absolute";
		$("loading_toolbar").appendChild(this.loading_shad);
		this.loading_shad.style.backgroundImage = "url(../images/nbsp.gif)";
	},
	pageBottomSubmitListener : function(evt)
	{
		var ele = Event.element(evt);
		//alert(ele.id);
		this.changePageSetting(parseInt($("search_property_page_bottom").value));
		return false;
	},
	tagItemClickListener : function(evt)
	{
		var obj = Event.element(evt);

		this.tagItemClickAction(obj);
	},
	tagItemClickAction : function(obj)
	{
		switch(obj.mode)
		{
			case "1":
				this.result_in_list.src = "../images/property/tag_result_list_on.gif";
				if(this.result_in_map != null)
					this.result_in_map.src = "../images/property/tag_result_map_off.gif";
				$("mode2").style.display = "none";
				$("loading_toolbar_b").style.display = "";
				$("mode1").style.display = "";
				if(this.map_panel != null)
					this.map_panel.style.display = "none";
				this.item.form.mode.value = 1;
				break;
			case "2":
				this.result_in_list.src = "../images/property/tag_result_list_off.gif";
				if(this.result_in_map != null)
					this.result_in_map.src = "../images/property/tag_result_map_on.gif";
				$("mode2").style.display = "";
				$("mode1").style.display = "none";
				$("loading_toolbar_b").style.display = "none";
				if(this.map_panel != null)
				{
					this.map_panel.style.display = "";	
					try{
					if(	this.map_panel != null && this.map_container != null)
					{
						this.map_panel_left = getOffset(this.map_container, true);
						this.map_panel_top = getOffset(this.map_container, false);
								
						this.map_panel.style.left = (this.map_panel_left+1)+"px";
						this.map_panel.style.top = (this.map_panel_top+1)+"px";				
					}	
					}catch(e){}							
				}
				else
				{
					// this.initializeMapComponent($("mode2_map_panel"));	
					this.initializeMapComponent();
				}
				//var form_serialize = $(this.item.form).serialize(true);
				var tmp_map_point_history_val = $(this.item.form).serialize(true);
				var tmp_map_point_history_h = $H(tmp_map_point_history_val);
				tmp_map_point_history_h.remove("page");
				tmp_map_point_history_h.remove("rec_per_page");
				var tmp_map_point_history = tmp_map_point_history_h.toQueryString();

				if(this.map_point_load_history == null || this.map_point_load_history != tmp_map_point_history)
				{
					//alert("x");
					this.getListingMapPoint();
					this.map_point_loaded = true;
					this.map_point_load_history = tmp_map_point_history;
				}
				this.item.form.mode.value = 1;
				break;	
			
		}		
	},
	setDefaultMode : function()
	{
		this.mode = this.item.form.mode.value;
		if(!this.is_map_compatible)
		{
			this.mode = "1";
			this.item.form.mode.value = "1";
		}
		switch(this.mode)
		{
			case "1":
				this.tagItemClickAction(this.result_in_list);
				break;
			case "2":
				if(this.result_in_map != null)
					this.tagItemClickAction(this.result_in_map);
				break;	
		}
	},
	initializeMapPanel : function(container)
	{
		var size = getPageSize();
		var offset = getOffset($("mode2").parentNode,false);
		//$("mode2").style.border = "1px #000 solid";
		$("mode2").style.width = "100%";
		var h = size[3]-offset-150;
		if(h < 0)
			h = 500;
		$("mode2").style.height = h+"px";
		$("mode2_map_panel").style.height = (h)+"px";
		$("mode2_map_panel").style.border = "1px #B4B4A0 solid";
	},
	initializeMapComponent : function(container)
	{
		initMap();
	},
	onDragListener : function()
	{
		try{
			if(is_ie != null && !is_ie && typeof($("pb_content_extra_div")) != "undefined" && this.target_point.topping.style.display != "none")
			{
				$("pb_content_extra_div").style.display = "none";
			}
		}catch(e){}
	},
	onDragEndListener : function()
	{
		try{
			if(is_ie != null && !is_ie && typeof($("pb_content_extra_div")) != "undefined" && this.target_point.topping.style.display != "none")
			{
				$("pb_content_extra_div").style.display = "";
			}
		}catch(e){}
	},	
	onZoomListener : function()
	{
		
	},
	targetPointClick : function(evt)
	{
		
	},
	targetPointOver : function(evt)
	{
		this.target_point.div.zIndex = "50000";
	},
	targetPointOut : function(evt)
	{
		this.target_point.div.zIndex = "50000";
	},	
	switchTagMenu : function(obj)
	{
		
	},
	changeResultPerPageSetting : function (evt)
	{
		var obj = Event.element(evt);
		var current_rec_per_page = this.item.form.rec_per_page.value;
		this.item.form.rec_per_page.value = obj.options[obj.selectedIndex].value;
		this.item.form.page.value = 1;		
		if(this.use_ajax)
		{
			/*if(window.dhtmlHistory.isFirstLoad())
			{
				this.setHistory("", $(this.item.form).serialize());
			}*/
			//this.item.form.page.value = val;
			var form_serialize = $(this.item.form).serialize();
			var url = "xml/getResult.php?"+form_serialize;
			this.history_key = "";
			this.history_val = form_serialize;	
			//this.setHistory("rec_per_page", this.item.form.rec_per_page.value);
			this.makeResultRequest(url);
			
			return;
		}

		this.item.form.submit();
	},
	changeSortBySetting : function (evt)
	{
		var obj = Event.element(evt);
		var current_sort = this.item.form.sort_by.value;
		this.item.form.sort_by.value = obj.options[obj.selectedIndex].value;
		this.item.form.page.value = 1;		
		if(this.use_ajax)
		{
			/*if(window.dhtmlHistory.isFirstLoad())
			{
				this.setHistory("", $(this.item.form).serialize());
			}*/
			//this.item.form.page.value = val;
			var form_serialize = $(this.item.form).serialize();
			var url = "xml/getResult.php?"+form_serialize;
			this.history_key = "";
			this.history_val = form_serialize;			
			//this.setHistory("sort", this.item.form.sort_by.value);
			this.makeResultRequest(url);		
			return;
		}		

		this.item.form.submit();
	},
	changePageSetting : function (val)
	{
		if(val == null || isNaN(val) || val > parseInt($("search_property_max_page").innerHTML))
		{
			try{
				$("search_property_page_bottom_form").reset();	
			}catch(e)
			{
			}
			return false;
		}
		var current_page = this.item.form.page.value;
		
		if(this.use_ajax)
		{
			/*if(window.dhtmlHistory.isFirstLoad())
			{
				this.setHistory("", $(this.item.form).serialize());
			}*/
			this.item.form.page.value = val;
			var form_serialize = $(this.item.form).serialize();
			var url = "xml/getResult.php?"+form_serialize;
			//alert(url);
			this.history_key = "";
			this.history_val = form_serialize;			
			//this.setHistory("page", val);
			this.makeResultRequest(url);
			return;
		}			
		this.item.form.page.value = val;
		this.item.form.submit();
	},
	processHistory : function (history_code, history_data)
	{
		if(this.item != null && typeof(this.item.setResource) == "function")
		{
			if(history_data != null)
			{
				if(property_info_viewer != null && typeof(property_info_viewer.hide) == "function")
					property_info_viewer.hide(true);
				//alert(history_data);
				this.item.setResource(history_data.toQueryParams());
				this.processHistoryAction();
				this.map_point_load_history = null;
				this.map_point_loaded = false;
			}
			else
			{

					
			}
		}	
	},
	processHistoryAction : function()
	{
		var url = "xml/getResult.php?"+$(this.item.form).serialize();
		//alert(url);
		this.makeResultRequest(url);
	},
	setHistory : function(history_code, history_data)
	{
		this.history_code = "history_"+this.history_cnt;
		this.history_cnt++;
		this.history_data = history_data;
		window.dhtmlHistory.add(this.history_code, this.history_data);		
	},
	makeResultRequest : function(url)
	{
		try{
		if(url == null  && this.history_processing)
			return false;
		this.history_processing = true;
		//this.loading_panel.style.display = "";
		this.showLoading();
		this.result_ajax_request = new Ajax.Request(
			url,
			{
				method: 'get', 
				onComplete: this.getResultResponse.bind(this)
			}
		)
		}catch(e){
			//this.loading_panel.style.display = "none";	
			this.hideLoading();
		}
	},
	getPropertyInforViewerPagingHTML : function (from, to)
	{
		return from+" of "+to+" listings";
	},
	getResultResponse : function(req)
	{
		try{
		var xml = req.responseXML;
		
		var top = xml.getElementsByTagName("top")[0].firstChild.nodeValue;
		var middle = xml.getElementsByTagName("middle")[0].firstChild.nodeValue;
		var bottom = xml.getElementsByTagName("bottom")[0].firstChild.nodeValue;
		var nor = xml.getElementsByTagName("num_of_rec")[0].firstChild.nodeValue;
		var url = xml.getElementsByTagName("url")[0].firstChild.nodeValue;
		
		if (typeof(urchinTracker) == "function" && url != "")
			urchinTracker(url);
			
		//alert(nor);
		this.num_of_rec = parseInt(nor);
		
		$("mode1").innerHTML = top+middle+bottom;
		this.initializePageComponents();
		if(this.history_key != null && this.history_val != null)
		{
			this.setHistory(this.history_key,this.history_val);	
			this.history_key = null;
			this.history_val = null;
		}

		//this.loading_panel.style.display = "none";
		this.getAllListingObject();
		this.hideLoading();
		this.history_processing = false;
		if(this.auto_set_property_info)
		{
			this.auto_set_property_info = false;
			var trs = $("mode1").getElementsByTagName("TR");
			
			var tmp = null;
			var tmp_arr = [];
			for(var i=0; i<trs.length; i++)
			{
				if($(trs[i]).readAttribute("obj") != null && trs[i].id.indexOf("property_item_") != "-1" )	
				{
					tmp = null;
					eval(" tmp = "+unescape($(trs[i]).readAttribute("obj")));
					//this.showListingDetail(tmp.id, tmp.bid, tmp.type, false)
					///break;
					tmp_arr.push(tmp);
				}
			}			
			//alert(this.auto_set_property_info_action);
			if(this.auto_set_property_info_action == 1)
			{
				this.showListingDetail(tmp_arr[tmp_arr.length-1].id, tmp_arr[tmp_arr.length-1].bid, tmp_arr[tmp_arr.length-1].type, false);
				this.current_posx = ((parseInt(this.item.form.page.value)-1)*parseInt(this.item.form.rec_per_page.value))+parseInt(this.item.form.rec_per_page.value);
				$("property_info_viewer_buffer_paging").innerHTML = this.getPropertyInforViewerPagingHTML(this.current_posx,this.num_of_rec);
			}
			else if( this.auto_set_property_info_action == 2)
			{
				this.showListingDetail(tmp_arr[0].id, tmp_arr[0].bid, tmp_arr[0].type, false);
				this.current_posx = ((parseInt(this.item.form.page.value)-1)*parseInt(this.item.form.rec_per_page.value))+1;
				$("property_info_viewer_buffer_paging").innerHTML = this.getPropertyInforViewerPagingHTML(this.current_posx,this.num_of_rec);
			}


		}
		switchOnClipSaveButton();
		}catch(e){
			//this.loading_panel.style.display = "none";	
			this.hideLoading();
			this.history_processing = false;
		}

	},
	setMaxPage : function(val)
	{
		if(val == null || isNaN(val))
			return;
		this.max_page = val;
	},
	nextPage : function ()
	{
		if(this.max_page == 0)
			return;
		var current_page = parseInt(this.item.form.page.value);
		current_page++;
		if(current_page > this.max_page)
			return;
		this.changePageSetting(current_page);
	},
	prevPage : function ()
	{
		if(this.max_page == 0)
			return;
		var current_page = parseInt(this.item.form.page.value);
		current_page--;
		if(current_page < 1)
			return;
		this.changePageSetting(current_page);		
	},
	makeEnquiry : function(id)
	{
		/*http://www.hongkonghomes.com/hong_kong_property/eng/email/email.php?pro_id_set=35667,&action=tellMore&type=1*/
		var type = this.item.getSearchType();
		//var url = "http://www.hongkonghomes.com/hong_kong_property/eng/email/email.php?pro_id_set="+id+",&action=tellMore&type="+type;
		//var url = sRelativePath+"email/email.php?pro_id_set="+id+",&action=tellMore&type="+type;
		var url = sRelativePath+"email/tell_me_more.php?pid="+id+"&type="+type;
		var win = newWindowFixed(url,'',700,750)
		try{
			win.focus();
		}catch(e){}		
	},
	sendEmail : function(id)
	{
		/*http://www.hongkonghomes.com/hong_kong_property/eng/email/email2.php?pro_id_set=35667,&action=tellFriend&type=1*/
		var type = this.item.getSearchType();
		//var url = "http://www.hongkonghomes.com/hong_kong_property/eng/email/email2.php?pro_id_set="+id+",&action=tellFriend&type="+type;
		//var url = sRelativePath+"email/email2.php?pro_id_set="+id+",&action=tellFriend&type="+type;
		var url = sRelativePath+"email/tell_a_friend.php?pid="+id+"&type="+type;
		var win = newWindowFixed(url,'',580,500)
		try{
			win.focus();
		}catch(e){}
	},
	saveListing : function(pro_id)
	{
		if(clipboard != null && pro_id)
		{
			var item_type = this.item.getSearchType();
			if (item_type == 1)
				item_type = 'rent';
			else
				item_type = 'buy';
				
			clipboard.addClipItem(this.onListingClipped.bind(this), 'property', pro_id, item_type);
		}
	},
	onListingClipped: function (resp, req_id)
	{
		if (resp == null)
			return false;
		
		var resp = eval('('+resp+')');
		var pro_id = resp.item_id;
		var save_btn = $('save_property_clipboard_'+pro_id);
		if (save_btn != null)
		{
			save_btn.clip_item_id = resp.clip_item_id;
			save_btn.src = sRelativePath+'images/property/btn_clip_on.gif';
			save_btn.onclick = this.removeListing.bind(this, pro_id);
		}
		
		clipboard.increaseCategoryItemCount('prop');
	},
	removeListing : function(pro_id)
	{
		if(clipboard != null && pro_id)
		{
			var clip_item_id = $('save_property_clipboard_'+pro_id).clip_item_id;
			clipboard.removeClipItem(this.onListingUnclipped.bind(this), clip_item_id);
		}
	},
	onListingUnclipped: function (resp, req_id)
	{
		if (resp == null)
			return false;
		
		var resp = eval('('+resp+')');
		var pro_id = resp.item_id;
		var save_btn = $('save_property_clipboard_'+pro_id);
		if (save_btn != null)
		{
			save_btn.clip_item_id = resp.clip_item_id;
			save_btn.src = sRelativePath+'images/property/btn_clip_off.gif';
			save_btn.onclick = this.saveListing.bind(this, pro_id);
		}
		
		clipboard.decreaseCategoryItemCount('prop');
	},
	getAllListingObject : function ()
	{
		this.buffer = [];
		var trs = $("mode1").getElementsByTagName("TR");
		var tmp = null;
		for(var i=0; i<trs.length; i++)
		{
			if($(trs[i]).readAttribute("obj") != null && trs[i].id.indexOf("property_item_") != "-1" )	
			{
				tmp = null;
				eval(" tmp = "+unescape($(trs[i]).readAttribute("obj")));
				this.buffer.push(tmp);
			}
		}
		//alert(this.buffer.length);
	},
	propertyInfoViewerChnageListener : function(p)
	{
		//alert(p);	
		try{
		var actual_pos = p+1;
		
		if( actual_pos < 1 )
		{
			if(this.item.form.page.value > 1)
			{
				this.auto_set_property_info = true;
				this.auto_set_property_info_action = 1;
				//property_info_viewer.processHistory();
				this.changePageSetting(parseInt(this.item.form.page.value)-1);
			}
		}
		else if( actual_pos > this.item.form.rec_per_page.value )
		{
			if( this.item.form.page.value < this.max_page )
			{
				this.auto_set_property_info = true;
				this.auto_set_property_info_action = 2;
			
				//property_info_viewer.processHistory();
				//alert(property_info_viewer.history_cnt);
				this.changePageSetting(parseInt(this.item.form.page.value)+1);
			}
		}
		else
		{
			this.auto_set_property_info_action = 0;
			this.current_posx = ((parseInt(this.item.form.page.value)-1)*parseInt(this.item.form.rec_per_page.value))+actual_pos;
			if(this.current_posx > this.num_of_rec)
				$("property_info_viewer_buffer_paging").innerHTML = this.getPropertyInforViewerPagingHTML(this.num_of_rec,this.num_of_rec);	
			else
				$("property_info_viewer_buffer_paging").innerHTML = this.getPropertyInforViewerPagingHTML(this.current_posx,this.num_of_rec);	
		}
		}catch(e)
		{
			//alert(e.message);	
		}
	},
	showListingDetail : function(pro_id, bid, type, clip)
	{
		if(property_info_viewer != null)
		{
			var obj = $("property_item_"+pro_id);
			
			if(obj == null)
				return;
			var obj_str = obj.readAttribute("obj");
			var pobj = null;
			eval(" pobj = "+unescape(obj_str));
			
			if(this.buffer == null)
				this.getAllListingObject();
				
			//property_info_viewer.hideMap();
			property_info_viewer.cleanBuffer();
			
			property_info_viewer.show(pobj);
			
			property_info_viewer.setBuffer(this.buffer, {from:""});
			property_info_viewer.cleanChangeListener();
			property_info_viewer.addChangeListener(this.propertyInfoViewerChnageListener.bind(this));			
			//window.dhtmlHistory.add("property_info_"+pro_id, "");
			this.current_posx = ((parseInt(this.item.form.page.value)-1)*parseInt(this.item.form.rec_per_page.value))+(property_info_viewer.current_buffer_pos+1);
			$("property_info_viewer_buffer_paging").innerHTML = this.getPropertyInforViewerPagingHTML(this.current_posx,this.num_of_rec);
			// if(clipboard != null)
			// {
				// if(clip == null || clip != false)
					// clipboard.addProperty(pobj, 3);
			// }
		}
		
	},
	showMapDisclaimer : function()
	{
		var x = newWindowFixed('http://map.hongkonghomes.com/map1/disclaimer.html','',580,500);
	},
	getListingMapPoint : function()
	{
		/*var h = $H(this.search_parameters);
		h.remove("page");
		h.remove("rec_per_page");
		
		var url = "../xml/getListingMapPoint.php?"+h.toQueryString();*/
		this.showMapLoadingCover();
		var form_serialize = $(this.item.form).serialize(true);
		var h = $H(form_serialize);
		h.remove("page");
		h.remove("rec_per_page");
		var url = "../xml/getListingMapPoint.php?"+h.toQueryString();
		//window.prompt("URL", url);
		//alert(this.item.form.sl.value+" "+url);
		this.map_point_ajax_request = new Ajax.Request(
			url,
			{
				method: 'get', 
				// onComplete: this.parseListingRecord.bind(this)
				onComplete: markResultsOnMap
			}
		)	
	},
	mapPointClickListener : function(evt)
	{
		try{
		var obj = Event.element(evt);
		
		obj.parentNode.style.zIndex = "900";
		
		this.target_point.ln = obj.ln;
		this.target_point.la = obj.la;
		
		this.target_point.div.style.zIndex = "50000";
		this.target_point.div.style.cursor = "pointer";
		if(this.target_point.div.childNodes.length > 0)
			this.target_point.div.childNodes[0].style.cursor = "pointer";
					
		this.target_point.no_reset = false;
		this.target_point.setPosition(true);

		this.getTargetContent(obj.bid);
		}catch(e)
		{}
	},
	getTargetContent : function(bid)
	{
		// this.target_point.topping.innerHTML = '<table border="0" cellspacing="0" cellpadding="2" class="general_tbl"><tr><td width="18" nowrap><img src="../images/spinner.gif" width="16" height="16"></td><td nowrap>Loading...</td></tr></table>';
		// this.target_point.topping.style.display = "none";
		
		// this.target_point.toppingToggleDiv();
		// this.target_point.topping.style.width = (this.target_point.topping.childNodes[0].offsetWidth)+"px";
		// this.target_point.setToppingPosition();
				
		/*var h = $H(this.search_parameters);
		h.remove("page");
		h.remove("rec_per_page");
		h.merge({"bid":bid});*/
		var h = $H(this.item.form.serialize(true));
		h.remove("page");
		h.remove("rec_per_page");
		h.merge({"bid":bid});		
		//var url = "../xml/searchTargetBuilding.php?"+h.toQueryString();		
		var url = "../xml/searchTargetBuilding.php?"+h.toQueryString();;		
		//window.prompt("URL", url);
		this.target_point_ajax_request = new Ajax.Request(
			url,
			{
				method: 'get', 
				onComplete: loadBuildingInfo
			}
		)		
	},
	setTargetContent : function(req)
	{
		try{
		var xml = req.responseXML;
		var listing = xml.getElementsByTagName("p");
		var bldg = xml.getElementsByTagName("b")[0].firstChild.nodeValue.split("##");
		//var h = $H(this.search_parameters);
		var htm_src = [];
		for(var i=0; i < listing.length; i++)
		{
			
			var item = listing[i].firstChild.nodeValue.split("**");
			build_id = item[1];
			var obj_str = escape('{id:"'+item[0]+'",type:"'+item[9]+'",price:"'+((this.item.getSearchType() == "2")?item[5]:item[4])+'",bname:"'+bldg[3]+'",br:"'+item[7]+'",size:"'+item[6]+'",photo:"'+item[8]+'",bid:"'+bldg[2]+'",bln:"'+bldg[0]+'",bla:"'+bldg[1]+'"}');
			var h = '<table obj="'+obj_str+'" sch_type="'+item[9]+'" bid="'+build_id+'" pid="'+item[0]+'" width="100%" class="general_tbl" border="0" cellspacing="0" cellpadding="0" style="padding-top:2px;border-bottom:1px solid #999999">';
			h += '  <tr>';
			h += '	<td vAlign="top" class="generalDesc" isdraggable="0">&nbsp;</td>';
			h += '	<td vAlign="top" class="generalDesc" isdraggable="0"><b>'+(i+1)+'.</b></td>';
			
			h += '    <td width="45" vAlign="top" isdraggable="0">';
			h += '<img src="http://map.hongkonghomes.com/map/tmp/pro_info/'+item[0]+'/'+item[8]+'" width="40px" height="30px">';
			h += '		</td>';			
			h += '    <td vAlign="top" class="generalDesc" isdraggable="0">';
			h += item[6]+"s.f.&nbsp;/&nbsp;";
			h += item[7]+"br.<br>";
			//alert(h.sch_type);
			if(this.item.getSearchType() == "2")
				h += "HK$ "+this.addCommas(item[5])+"&nbsp;";
			else
				h += "HK$ "+this.addCommas(item[4])+"&nbsp;";	
					
			h += '	</td>';
			h += '  </tr>';
			h += '</table>';			
			htm_src.push(h);			
		}
		
		this.target_point.topping.style.width = "0px";
		var htm = '<table width="100%" height="100%"  border="0" cellpadding="0" cellspacing="0" class="general_tbl">';
		htm += '  <tr height="4px">';
		htm += '    <td width="4px" height="4px" background="../images/pb/lt.gif"></td>';
		htm += '    <td bgcolor="#E80153" colspan="2"></td>';
		htm += '    <td width="4px" height="4px" background="../images/pb/rt.gif"></td>';
		htm += '  </tr>';
		htm += '  <tr height="18px">';
		htm += '    <td width="4px" bgcolor="#E80153"></td>';
		htm += '    <td align="left" class="generalDesc" nowrap verticalAlign="top" bgcolor="#E80153" style="color:#FFFFFF" id="pb_content_header_target">';
		htm += "<span id='pb_content_header_target_val'>"+bldg[3]+"</span>";
		htm += '	</td>';
		htm += '    <td id="pb_content_extra_toggler" width="15px" bgcolor="#E80153" align="right" style="cursor:pointer; background-repeat:no-repeat; background-position:center right; background-image:url(../images/plus/close.gif);"></td>';		
		htm += '    <td width="4px" bgcolor="#E80153"></td>';
		htm += '  </tr>';	
		htm += '  <tr height="3px">';
		htm += '    <td width="4px" bgcolor="#E80153"></td>';
		htm += '	<td colspan="2" bgcolor="#E80153"></td>';
		htm += '    <td width="4px" bgcolor="#E80153"></td>';
		htm += '  </tr>';			
		htm += '  <tr id="pb_content_extra_header1" height="3px">';
		htm += '    <td width="4px" background="../images/pb2/l.gif"></td>';
		htm += '	<td colspan="2" bgcolor="#FFFFFF"></td>';
		htm += '    <td width="4px" background="../images/pb2/r.gif"></td>';
		htm += '  </tr>';												
		htm += '  <tr id="pb_content_extra_header">';
		htm += '    <td width="4px" background="../images/pb2/l.gif"></td>';
		htm += '    <td colspan="2" height="90px" align="left" class="generalDesc" id="pb_content_extra" vAlign="top" bgcolor="#FFFFFF" style="color:#333333; height:90px;">';
		htm += "<div style='height:"+(90)+"px; width:100%; overflow:auto;' isdraggable='0' id='pb_content_extra_div' class='plist'>"+htm_src.join("")+"</div>";
		htm += '	</td>';

		htm += '    <td width="4px" background="../images/pb2/r.gif"></td>';
		htm += '  </tr>';	
		htm += '  <tr id="pb_content_extra_header2" height="3px">';
		htm += '    <td width="4px" background="../images/pb2/l.gif"></td>';
		htm += '	<td colspan="2" bgcolor="#FFFFFF"></td>';
		htm += '    <td width="4px" background="../images/pb2/r.gif"></td>';
		htm += '  </tr>';							
		htm += '  <tr height="30px">';
		htm += '    <td width="4px" height="30px" background="../images/pb/lb3.gif"></td>';
		htm += '    <td colspan="2" height="30px" background="../images/pb/b3.gif" align="center"><img src="../images/pb/cb3.gif"></td>';
		htm += '    <td width="4px" height="30px" background="../images/pb/rb3.gif"></td>';
		htm += '  </tr>';
		htm += '</table>';		
		
		this.target_point.topping.innerHTML = htm;
		htm = null;
		htm_src = null;
		this.target_point.topping.style.display = "none";
		this.target_point.toppingToggleDiv();
		var xxwidth = $("pb_content_header_target").offsetWidth+10+25;
		this.target_point.topping.style.width = (xxwidth)+"px";
		
		this.target_point.setToppingPosition();

		var xxwidth = $("pb_content_header_target").offsetWidth+10+25;		
		if(xxwidth < 220)
			xxwidth = 220;		
		this.target_point.topping.style.width = (xxwidth)+"px";
		this.target_point.setToppingPosition();	
		this.target_point.fitToScreen();	
		$("pb_content_extra_toggler").onclick = this.closeTargetTopping.bindAsEventListener(this);
		this.target_point.div.childNodes[0].onclick = this.openTargetTopping.bindAsEventListener(this);
		var tbls = $('pb_content_extra_div').getElementsByTagName("TABLE");
		for(var i=0; i<tbls.length; i++)
		{
			tbls[i].onclick = this.tblItemClickLitener.bind(this, tbls[i]);
		}	
		}catch(e)
		{
			this.target_point.topping.style.display = "none";
		}
	},
	getAllListingObjectOnMap : function(container)
	{
		this.map_buffer = [];
		if(container == null)
			return false;
		var trs = container.getElementsByTagName("TABLE");

		var tmp = null;
		for(var i=0; i<trs.length; i++)
		{
			if($(trs[i]).readAttribute("obj") != null)	
			{
				tmp = null;
				eval(" tmp = "+unescape($(trs[i]).readAttribute("obj")));
				this.map_buffer.push(tmp);
			}
		}		
	},	
	tblItemClickLitener : function(obj)
	{
		try{
		var pobj = null;
		eval(" pobj = "+unescape($(obj).readAttribute("obj")));			
		if(property_info_viewer != null && pobj != null)
		{
			this.getAllListingObjectOnMap(obj.parentNode);	
			//property_info_viewer.hideMap();
			property_info_viewer.cleanBuffer();
			
			property_info_viewer.show(pobj);
			
			property_info_viewer.setBuffer(this.map_buffer, {from:" listings in "+pobj.bname});
			property_info_viewer.cleanChangeListener();
			/*if(pobj != null)
			{
				property_info_viewer.show(pobj);			
			}*/
		}
		if(clipboard != null && pobj != null)
		{
			clipboard.addProperty(pobj, 3);
		}
		}catch(e){}
	},	
	openTargetTopping : function(evt)
	{
		if(this.target_point.topping.style.display == "none")
		{
			this.target_point.topping.style.display = "";
			this.target_point.setToppingPosition();	
			this.target_point.fitToScreen();
		}
		else
		{
			this.target_point.topping.style.display = "none";
		}		
	},
	closeTargetTopping : function(evt)
	{
		//this.target_point.toppingToggleDiv();
		this.target_point.topping.style.display = "none";
	},
/*	mapPointMouseoverListener : function(evt)
	{
		
	},
	mapPointMouseoutListener : function(evt)
	{
		
	},*/
	addCommas : function(nStr)
	{
		nStr += '';
		x = nStr.split('.');
		x1 = x[0];
		x2 = x.length > 1 ? '.' + x[1] : '';
		var rgx = /(\d+)(\d{3})/;
		while (rgx.test(x1)) {
			x1 = x1.replace(rgx, '$1' + ',' + '$2');
		}
		return x1 + x2;
	},	
	makeMapPoint : function ()
	{
		if(this.map_point_lib[this.map_point_lib_pointer].change_pos == false)
		{
			this.map.addPoint(this.map_point_lib[this.map_point_lib_pointer]);
		}
		else
		{
			
			this.map_point_lib[this.map_point_lib_pointer].setPosition(true);
		}		
		this.map_point_lib_pointer++;
		if(this.map_point_lib_pointer >= this.map_point_cnt && this.add_map_point_timeout != null && typeof(this.add_map_point_timeout.stop) == "function")
		{
			//alert("stop");
			this.add_map_point_timeout.stop();		
			//alert(this.map_point_lib_pointer+" "+this.map_point_lib.length);
			for(var i=(this.map_point_cnt); i<this.map_point_lib.length; i++)
			{
				this.map_point_lib[i].no_reset = true;
				this.map_point_lib[i].hide();
			}
		}
	},
	getCoorBoundaryConfig : function(coor_boundary)
	{
		try{
		if(coor_boundary == null && coor_boundary.length != 4)
			return;	
		
		this.map.optimizeMapViewByCoorBoundary(coor_boundary);
		return;
	//if(max_ln != 0 || max_la != 0)
	//{
		/*var min_ln = coor_boundary[0];
		var max_ln = coor_boundary[2];
		var min_la = coor_boundary[3];
		var max_la = coor_boundary[1];
		
		var ln_margin = (max_ln-min_ln);
		var la_margin = (max_la-min_la);		
		
		var center_ln = Math.ceil((ln_margin)/2);
		var center_la = Math.ceil((la_margin)/2);
		

		var zoom_case = 0;
		
		
		var ln_ratio = ln_margin/this.map.container.offsetWidth;
		var la_ratio = la_margin/this.map.container.offsetHeight;
		
		if(ln_margin > la_margin)
			zoom_case = 1;
		else if(la_margin > ln_margin)
			zoom_case = 2;
		
		var possible_level = [];
		var possible_rate = [];
		var rate = 1;
		
		// Find out possible zoom level
		for(var i=0; i<CONST_ALL_ZOOM.length; i++)
		{
			switch(zoom_case)
			{
				case 1:
				case 0:
					if(parseFloat(CONST_ALL_ZOOM[i].glg1_per_px) > ln_ratio)
					{
						possible_level.push(parseInt(CONST_ALL_ZOOM[i].level));	
						possible_rate.push(parseFloat(CONST_ALL_ZOOM[i].glg1_per_px));			
						rate = ln_ratio;
					}
					break;
				case 2:
					if(parseFloat(CONST_ALL_ZOOM[i].gla1_per_px) > la_ratio)
					{
						possible_level.push(parseInt(CONST_ALL_ZOOM[i].level));
						possible_rate.push(parseFloat(CONST_ALL_ZOOM[i].gla1_per_px));
						rate = la_ratio;	
					}
					break;
			}
		}
		
		// Select suitable zoom level
		var min_zoom = 0;
		var pos = -1;
		var plus = 0;
		if(possible_level.length > 0)
		{
			min_zoom = 100;
			for(var i=0; i<possible_level.length; i++)
			{
				if(	possible_level[i] < min_zoom )
				{
					min_zoom = possible_level[i];
					pos = i;
				}
			}
		}
		
		if((rate/possible_rate[pos]) > 0.5)
			plus = 1;
		
		// Config Map
		this.map.changeZoomLevel((min_zoom+plus), false);

		if(this.map.map_control != null)
			this.map.map_control.setZoomLevel(this.map.zoom);
		this.map.centMapByLnLa(parseInt(min_ln)+parseInt(center_ln), parseInt(max_la)-parseInt(center_la), false);*/
	//}		
		}catch(e)
		{
			//alert(e.message);
		}
	},
	parseListingRecord : function(req)
	{
		try{
			this.target_point.hide();
			var xml = req.responseXML;
			
			//Get Map point boundary
			var boundary = xml.getElementsByTagName("coor_boundary");

			
			//Setup MapPoint
			this.map_point_lib_pointer = 0;
			this.map_point_cnt = 0;			
			var rec = xml.getElementsByTagName("i");
			for(var i=(this.map_point_cnt); i<this.map_point_lib.length; i++)
			{
				this.map_point_lib[i].no_reset = true;
				this.map_point_lib[i].hide();
			}			
			if(rec.length == 0)
			{
				
				this.hideMapLoadingCover();
				return;
			}
				
			var max = rec.length;

			
			if(this.add_map_point_timeout != null && typeof(this.add_map_point_timeout.stop) == "function")
				this.add_map_point_timeout.stop();
			var first_ln = null;
			var first_la = null;
			//alert(max);
			for(var i=0; i<max; i++)
			{
				var item_config = rec[i].firstChild.nodeValue;
				//alert(item_config);
				var item_arr = item_config.split("##");
	
				if(item_arr.length != 4)
				{
					continue;
				}
					
				var ln = parseInt(item_arr[0]);
				if(first_ln == null)
					first_ln = ln;
				var la = parseInt(item_arr[1]);
				if(first_la == null)
					first_la = la;
				var bid = parseInt(item_arr[2]);
				var build_name_eng = item_arr[3];
				
				if(isNaN(ln) || isNaN(la) || isNaN(bid))
				{
					continue;
				}
				
				if( i >= this.map_point_lib.length )
				{
					var tmp = new MapPoint2(this.map, ln, la, build_name_eng, "<img src='../images/map_point1.gif'>", null, null, null, {align:"center"});
					tmp.group = "building_map_point";
					tmp.change_pos = false;
					tmp.div.isdraggable = "0";
					if(tmp.div.childNodes.length > 0)
					{
						tmp.div.childNodes[0].bid = bid;
						tmp.div.childNodes[0].ln = ln;
						tmp.div.childNodes[0].la = la;
						tmp.div.childNodes[0].title = build_name_eng;
						tmp.div.childNodes[0].onclick = this.mapPointClickListener.bindAsEventListener(this);
						/*tmp.div.childNodes[0].onmouseover = this.mapPointMouseoverListener.bindAsEventListener(this);
						tmp.div.childNodes[0].onmouseout = this.mapPointMouseoutListener.bindAsEventListener(this);*/
						tmp.div.childNodes[0].isdraggable = "0";
					}		
					tmp.div.style.cursor = "pointer";
					this.map_point_lib[i] = tmp;
				}
				else
				{
					var obj = this.map_point_lib[i];
					obj.ln = ln;
					obj.la = la;
					obj.group = "building_map_point";
					obj.no_reset = false;
					obj.div.title = build_name_eng;
					obj.div.childNodes[0].bid = bid;
					obj.div.childNodes[0].ln = ln;
					obj.div.childNodes[0].la = la;
					obj.div.childNodes[0].title = build_name_eng;					
					
					//obj.div.childNodes[0].ctype = id;
					obj.div.style.display = "none";
					obj.change_pos = true;
				}		
				this.map_point_cnt++;	
			}
			
			if(boundary.length == 1)
			{
				this.getCoorBoundaryConfig(boundary[0].firstChild.nodeValue.split("_"));
			}
			else
			{
				this.map.centMapByLnLa(first_ln,first_la,true);		
			}
			this.add_map_point_timeout = new PeriodicalExecuter(this.makeMapPoint.bind(this), 0.01);
			this.resize();
			this.hideMapLoadingCover();
		}catch(e){
			//alert(e.message);
			this.hideMapLoadingCover();
		}		
	}
}

