if(typeof(Fangbole) == 'undefined')Fangbole = {};

//为prototype.js扩展的方法
Fangbole.prototypMethod = {
	//模拟触发原生的浏览器事件
	fireNative: function(element, evt, type){
		type = type || 'Mouse';
		element = $(element)
		if(Prototype.Browser.IE){ 
			element.fireEvent('on'+evt);   
		}else{   
			var e = document.createEvent(type + 'Events');   
			e.initEvent(evt, true, true);   
			element.dispatchEvent(e); 
		}
		return element;
	}
}

Element.addMethods(Fangbole.prototypMethod);

Fangbole.imageResize = function(img, w, h){
	var img = $(img);
	var maxWidth = w;
	var maxHeight = h || w;
	var dim = img.getDimensions();
	if(dim.width > dim.height && dim.width > maxWidth){
		img.style.width = maxWidth + "px";
		img.style.height = dim.height / dim.width * maxWidth + "px";
	}else if(dim.height > dim.width && dim.height > maxHeight){
		img.style.height = maxHeight + "px";
		img.style.width = dim.width / dim.height * maxHeight + "px";
	}
}

Fangbole.imageReposition = function(img){
	var img = $(img);
	var dim = img.getDimensions();
	img.setStyle({
		position:"absolue",
		top:"50%",
		left:"50%",
		marginTop:"-"+dim.height/2+"px",
		marginLeft:"-"+dim.width/2+"px"
	})
}

Fangbole.Image = {
	zoom: function(img, maxWidth, maxHeigth) {
		var mw = maxWidth || 9999,
		mh = maxHeigth || 9999;
		var _img = new Image();
		_img.src = img.src;
		
		if (_img.width > 0 && _img.height > 0) {
			if (_img.width / _img.height >= mw / mh) {
				if (_img.width > mw) {
					img.width = mw;
					img.height = (_img.height * mw) / _img.width;
				} else {
					img.width = _img.width;
					img.height = _img.height;
				}
			} else {
				if (_img.height > mh) {
					img.height = mh;
					img.width = (_img.width * mh) / _img.height;
				} else {
					img.width = _img.width;
					img.height = _img.height;
				}
			}
		}
	},
	zoom2: function(el, options){
		if(el.width > options.maxWidth){
			el.width = options.maxWidth;
			el.height = options.maxWidth * el.height / el.width;
		}else{
			el.width = el.width;
			el.height = el.height;
		}
	}
}

Fangbole.utils = {
  getPageSize: function(parent){
    parent = parent || document.body;              
    var windowWidth, windowHeight;
    var pageHeight, pageWidth;
    if (parent != document.body) {
      windowWidth = parent.getWidth();
      windowHeight = parent.getHeight();                                
      pageWidth = parent.scrollWidth;
      pageHeight = parent.scrollHeight;                                
    } 
    else {
      var xScroll, yScroll;
      if (window.innerHeight && window.scrollMaxY) {  
        xScroll = document.body.scrollWidth;
        yScroll = window.innerHeight + window.scrollMaxY;
      } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
        xScroll = document.body.scrollWidth;
        yScroll = document.body.scrollHeight;
      } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
        xScroll = document.body.offsetWidth;
        yScroll = document.body.offsetHeight;
      }


      if (self.innerHeight) {  // all except Explorer
        windowWidth = self.innerWidth;
        windowHeight = self.innerHeight;
      } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
        windowWidth = document.documentElement.clientWidth;
        windowHeight = document.documentElement.clientHeight;
      } else if (document.body) { // other Explorers
        windowWidth = document.body.clientWidth;
        windowHeight = document.body.clientHeight;
      }  

      // for small pages with total height less then height of the viewport
      if(yScroll < windowHeight){
        pageHeight = windowHeight;
      } else { 
        pageHeight = yScroll;
      }

      // for small pages with total width less then width of the viewport
      if(xScroll < windowWidth){  
        pageWidth = windowWidth;
      } else {
        pageWidth = xScroll;
      }
    }             
    return {pageWidth: pageWidth ,pageHeight: pageHeight , windowWidth: windowWidth, windowHeight: windowHeight};
  },
  //获取查询字符串
  getUrlParms:function(){
	  var args = {};   
	  var query=location.search.substring(1);//获取查询串   
	  var pairs=query.split("&");//在逗号处断开   
	  for(var i=0;i<pairs.length;i++)   
	  {   
	      var pos=pairs[i].indexOf('=');//查找name=value   
	      if(pos==-1)   continue;//如果没有找到就跳过   
	      var argname=pairs[i].substring(0,pos);//提取name   
	      var value=pairs[i].substring(pos+1);//提取value   
	      args[argname]=unescape(value);//存为属性   
	  }
	  return args;
  },
  copyToClipboard: function(txt) {   
         if(window.clipboardData) {   
                 window.clipboardData.clearData();   
                 window.clipboardData.setData("Text", txt);
                 alert("复制成功！")
         } else if(navigator.userAgent.indexOf("Opera") != -1) {   
              window.location = txt;
              alert("复制成功！")
         } else if (window.netscape) {
         	try {   
                   netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");   
             } catch (e) {   
                  alert("要开启复制功能，请在浏览器地址栏输入'about:config'并回车\n然后将'signed.applets.codebase_principal_support'设置为'true'");   
             }   
             var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);   
             if (!clip)   
                  return;   
             var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);   
             if (!trans)   
                  return;   
             trans.addDataFlavor('text/unicode');   
             var str = new Object();   
             var len = new Object();   
             var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);   
             var copytext = txt;   
             str.data = copytext;   
             trans.setTransferData("text/unicode",str,copytext.length*2);   
             var clipid = Components.interfaces.nsIClipboard;   
             if (!clip)   
                  return false;   
             clip.setData(trans,null,clipid.kGlobalClipboard);   
             alert("复制成功！")
        }   
   }  

 
}

/*
 * 对于显示/隐藏类型的层的统一管理
 */
Fangbole.LayerManager = {
	layers: [],
	actives: [],
	register: function(element, options){
		var element = $(element);
		layer = Object.extend({
			element: element,
			close: function(){
				element.hide();
			},
			rootElement: null
		}, options || {})
		Fangbole.LayerManager.layers.push(layer);
	},
	unregister: function(elLayer){
		Fangbole.LayerManager.layers = layers.reject(function(layer){return layer.element = elLayer})
	},
	active: function(elLayer){
		var layer = Fangbole.LayerManager.findLayerByElement(elLayer);
		actives.push(layer);
	},
	close: function(){
		Fangbole.LayerManager.layers.each(function(layer){
			layer.close(layer.element)
		});
	},
	findLayerByElement: function(element){
		return Fangbole.LayerManager.layers.find(function(layer){layer.element == element});
	},
	onClick: function(e){
		var elm = e.element();
		if(Fangbole.LayerManager.isClickOnBlank(elm))
			Fangbole.LayerManager.close();
	},
	isClickOnBlank: function(elm){
		return !Fangbole.LayerManager.layers.any(function(layer){
			if(!layer.rootElement){
				return elm == layer.element;
			}else{
				return elm == layer.rootElement || elm.descendantOf(layer.rootElement);
			}
		})
	},
	initialize: function(){
		document.observe('click', Fangbole.LayerManager.onClick.bindAsEventListener(this));
	}
}

Fangbole.LayerManager.initialize();

/*
 * @class Fangbole.Suggest
 * @param element {HTMLElement} DOM element reference of whole container
 * @param url {String} url to request result
 * 		**ATTENTION** if a local suggest, this param act as a database initialize url
 * @param options {Object} (optional) Object of configuration params.
 */
Fangbole.Suggest = Class.create({
	initialize: function(element, data, options){
		this.element = $(element);
		this.elInput = this.element.down('input');
		this.oData = data;
		var defaultConfig = {
			checkInterval: 200,
			requestTimeout: 600,	
			minChars: 1,
			multiSelect: false,
			afterInit: Prototype.emptyFunction,
			beforeRequest: Prototype.emptyFunction,
			onSuccess: Prototype.emptyFunction,
			onFailure: Prototype.emptyFunction,
			onTooMuchResult: function(){
				this.elResult.update('太多结果，请输入更多文字缩小范围。');
				this.elResult.show();
			},
			onNoResult: function(){
				this.elResult.update('没有结果。');
				this.elResult.show();
			},
			onNormalResult: Prototype.emptyFunction,
			onSelect: Prototype.emptyFunction,
			
			local: false,
			localQuery: Prototype.emptyFunction			
		}
		this.options = Object.extend(defaultConfig, options || {});
		this.checkTimer = null;
		this.requestTimer = null;
		this.lastKey = null;
		this.elResult = new Element('div', {className: 'g_suggest_result', style: 'display: none;'});
		this.elInput.setAttribute('autocomplete','off');
		this.elInput.insert({after: this.elResult});
		Fangbole.LayerManager.register(this.elResult);
		
		this.onFocusInput = this._onTyping.bindAsEventListener(this);
		this.onBlurInput = this.endType.bindAsEventListener(this);
		this.onClickResult = this._onClickResult.bindAsEventListener(this);
		
		this.elInput.observe('focus', this.onFocusInput);
		this.elInput.observe('blur', this.onBlurInput);
		this.elResult.observe('click', this.onClickResult);
		
		if(this.options.local){
			if(this.options.localQuery === Prototype.emptyFunction)
				throw 'method localQuery must be implement';
			this._initLocalDatabase();
		}else{
			this.options.afterInit();
		}
		Fangbole.Suggest.instances.push(this);
	},
	_initLocalDatabase: function(){
		if(Object.isString(this.queryUrl)){
			new Ajax.Request(this.queryUrl, {
				method: 'GET',
				onSuccess: function(transport){
					this.options.afterInit(transport);
				}.bind(this)
			})			
		}else{
			this.db = this.queryUrl;
		}

	},
	_onClickResult: function(e){
		e.stop();
		var elm = e.element();
		this.options.onSelect.bind(this)(elm);
		this.endType();
		if(!this.options.multiSelect)
		this.elResult.hide();
	},
	_onTyping: function(){
		if(this.checkTimer)
			window.clearInterval(this.checkTimer);
		this.checkTimer = window.setInterval(function(){this._check()}.bind(this), this.options.checkInterval);		
	},
	endType: function(){
		if(this.checkTimer)
			window.clearInterval(this.checkTimer);
		if(this.requestTimer)
			window.clearTimeout(this.requestTimer);
	},
	_check: function(){
		var currentKey = this.elInput.getValue();
		if(currentKey != this.lastKey){
			if(this.requestTimer)
				window.clearTimeout(this.requestTimer);
			this.requestTimer = window.setTimeout(function(){this._query()}.bind(this), this.options.requestTimeout);
			this.lastKey = currentKey;
		}
	},
	_query: function(){
		var key = this.elInput.getValue();
		//if(key.empty())return;
		if(key.length < this.options.minChars){
			return;
		}
		this.requestObject = {
			key: key
		}
		this.options.beforeRequest.bind(this)(key);
		if(this.options.local){
			this.options.localQuery(this, this.requestObject);
		}else{
			new Ajax.Request(this.queryUrl + '&' + Object.toQueryString(this.requestObject), {
				method: 'GET',
				onSuccess: function(transport){
					if(this.options.onSuccess !== Prototype.emptyFunction)
						this.options.onSuccess(transport);
					else{
						try{
							var result = transport.responseText.evalJSON();
							switch(result.status){
								case '-1'://to much result
									this._onTooMuchResult();
									break;
								case '0'://no result
									this._onNoResult();
									break;
								case '1'://normal
									this._onNormalResult(result.list);
									break;
								default:
									throw 'unknow type of result from server.';
									break;
							}
						}catch(e){
							throw 'invalid result from server.';
						}
					}
				}.bind(this),
				onFailure: function(){
					this.options.onFailure();
				}.bind(this)
			})
		}
	},
	_onTooMuchResult: function(){
		this.options.onTooMuchResult.bind(this)();
	},
	_onNoResult: function(){
		this.options.onNoResult.bind(this)();
	},
	_onNormalResult: function(result){
		this.options.onNormalResult.bind(this)(result);
	}
})

Object.extend(Fangbole.Suggest, {
	instances: [],
	template: {
		resultItem: new Template('<a href="javascript:;">#{name}</a>')
	}
})


var Data = Class.create({
	initialize: function(data, options){
		this.data = data;
		this.options = Object.extend({
			cache: false,
			dataType: 'text'
		}, options || {})
		this._cacheData = '';
	},
	flushCache: function(){
		this._cacheData = '';
	}
})

Object.extend(Data, {

})


var XHRData = Class.create(Data, {
	initialize: function($super, url, options){
		if(!options.onSuccess || !options.onFailure)
			throw 'callback must be defined @ XHRData::initialize';
		$super(url, options);
		Object.extend(this.options, options);
	},
	update: function(oQuery, force){
		if(!this.options.cache || force){
			this._request(oQuery);
		}else{
			this.options.onSuccess(this._cacheData);
		}
	},
	_request: function(oQuery){
		var parameters = (this.data.indexOf('?') > -1 ? '&'  : '?') + Object.toQueryString(oQuery);
		new Ajax.Request(this.data, {
			method: 'GET',
			parameters: parameters,
			onSuccess: this._onSuccess.bind(this),
			onFailure: this._onFailure.bind(this)
		})	
	},
	_onSuccess: function(transport){
		var result = transport.responseText;
		if(this.options.cache)
			this._cacheData = result;
		this.options.onSuccess(result);
	},
	_onFailure: function(){
		this.options.onFailure();
	}
})



Fangbole.Tag = Class.create();

Object.extend(Fangbole.Tag.prototype, {
    initialize: function(element, options) {
      this.element = $(element);
	  this.input = this.element.down("input");
      this.maxlength = this.input.getAttribute("maxLength");
      this.options = Object.extend({
		mode: "extended"
      }, options || {});
      this.listElements = this.element.down(".fbl-tag-list").select("*");
	  if(this.options.mode == "extended"){
	  	this.more = this.element.down(".fbl-tag-more");
	  	this.completeList = this.element.down(".fbl-tag-flist");		  
		this.completeListElements = this.completeList.select("*");
	  }else{
		this.options.mode = "normal";  
	  }
      this.stockTags = this.parseStockTags();
    	this.input.observe("focus", this.onFocus.bind(this));
    	this.input.observe("blur",  this.onBlur.bind(this));
		new Field.Observer(this.input, 0.1, this.updateRecordTagsClassName.bind(this));
	var w = this.input.getWidth();
	this.completeList.style.width = w - 2 + "px";
      this.prepare();
    },
    
    prepare: function() {
		Object.extend(this.more, {
			showFullList: function(){
				Fangbole.util.hideSelects();
				this.completeList.show();
				Event.observe(document, "keydown", function(e){
					if(e.keyCode == Event.KEY_ESC){this.completeList.hide(); Fangbole.util.showSelects();}											
				}.bind(this))
				Event.observe(document, "mousedown", function(e){
					if(Fangbole.util.hideDiv('fbl-tag-flist', e)){this.completeList.hide(); Fangbole.util.showSelects();}
				}.bind(this))					
			}			  
		})
		
			this.listElements.each(function(element){
				if(!element.hasClassName("fbl-tag-more")){
					element.update(new Element("a", { href: "javascript:;", className: "ab" }).update(element.innerHTML.strip()));
					element.down("a").observe("click", this.onClickStockTag.bind(this));
				}
			}, this);

			if(this.options.mode == "extended"){
				this.completeListElements.each(function(element) {
					element.update(new Element("a", { href: "javascript:;", className: "ab" }).update(element.innerHTML.strip()));
					element.down("a").observe("click", this.onClickStockTag.bind(this));
				}, this);		
			}
			this.more.observe("mouseover", function(){this.timer = setTimeout(this.more.showFullList.bind(this), 400)}.bind(this))
			this.more.observe("mouseout", function(){clearTimeout(this.timer)}.bind(this))
    	this.updateRecordTagsClassName();
    },
    
    onFocus: function(e) {
    	if (!e.element().present()) { return; }
			while (/\s/.test($F(e.element()).charAt($F(e.element()).length-1))) {
				e.element().setValue($F(e.element()).substring(0, ($F(e.element()).length-1)));
			}
			e.element().setValue($F(e.element())+" ");
			if (e.element().createTextRange) { 
				var range = e.element().createTextRange(); 
				range.moveStart("character", $F(e.element()).length); 
				range.moveEnd("character", 0);      
				range.select(e.element());
			}
		this.input.setAttribute("maxLength", 0);
    },
    
    onBlur: function(e) {
		this.input.setAttribute("maxLength", this.maxlength);
		var recordTags = this.getRecordTags();
			recordTags.each(function(tag){											
				if(!this.stockTags[1].include(tag)){
					recordTags = recordTags.without(tag)
				}
			}, this)
			this.input.setValue(recordTags.join(" "));
			while (/\s/.test($F(e.element()).charAt($F(e.element()).length-1))) {
				e.element().setValue($F(e.element()).substring(0, ($F(e.element()).length-1)));
			}
    },

    parseStockTags: function() {
    	var stockTags = [[],[]];
    	this.listElements.each(function(li) {
			if(!li.hasClassName("fbl-tag-more")){
				var tag = li.innerHTML.strip();
				if (!tag.blank()) { stockTags[0].push(tag); }
			}
    	}, this);
		if(this.options.mode == "extended"){
			this.completeListElements.each(function(li) {
				var tag = li.innerHTML.strip();
				if (!tag.blank()) { stockTags[1].push(tag); }
			}, this);
		}
    	return stockTags;
    },
    
    getRecordTags: function() {
    	return (this.input.present() ? $F(this.input).split(" ").invoke("strip") : []);
    },
	
	getRecordTagsLength: function(){
		return (this.input.present() ? $F(this.input).split(" ").invoke("strip").join("").length : 0);
	},
    
    onClickStockTag: function(e) {
    	e.stop();
    	if (this.input.disabled){ return false; }
    	var tag = e.element().innerHTML.strip();
    	var recordTags = this.getRecordTags();
    	if (recordTags.include(tag)) {
    		recordTags = recordTags.without(tag);
    	}else if(this.getRecordTagsLength() + tag.length <= this.maxlength) {    		
   			recordTags.push(tag);
    	}
    	this.input.setValue(recordTags.join(" "));
    	this.updateRecordTagsClassName();
    },
    
    updateRecordTagsClassName: function(){
      var recordTags = this.getRecordTags();
    	this.stockTags[0].each(function(tag, i){
    		this.listElements[i].firstChild.className = recordTags.include(tag) ? "abh" : "ab";
    	}, this);
		if(this.options.mode == "extended"){
			this.stockTags[1].each(function(tag, i){
				this.completeListElements[i].firstChild.className = recordTags.include(tag) ? "abh" : "ab";
			}, this);
		} 		
	}
							
})

/*************** initialize packages **************/

Fangbole.Initialize = {
	location: function(options){
		var d = {
			mode: 'city-area',
			render: ['', ''],
			style: 'native',
			id: ['', ''],
			name: ['', ''],
			data: ['Fangbole.DB.option.city', ''],
			submitElement: ['', ''],
			selected: [0, 0]
		}
		Object.extend(d, options || {});

		if(d.mode != 'city-area' && d.mode != 'city')
			throw 'unsupport mode @ Fangbole.Initialize.location';
			
		if(d.mode.indexOf('area') > -1){
			var areaSelect = new Fangbole.Selector(d.data[1], {hasNullOption: true, submitElement: d.submitElement[1], id: d.id[1] || ''})
			areaSelect.render();
			var citySelect = new Fangbole.Selector(d.data[0], {hasNullOption: true, relative: areaSelect, submitElement: d.submitElement[0], id: d.id[0]});
		}else{
			var citySelect = new Fangbole.Selector(d.data[0], {hasNullOption: true, submitElement: d.submitElement[0], id: d.id[0]});
		}
		citySelect.render();

		return {
			city: citySelect,
			area: areaSelect
		}
	},
	/*
	room: function(options){
		var d = {
			render: ['', '', ''],
			style: 'native',
			id: ['', '', ''],
			name: ['', '', ''],
			data: ['Fangbole.DB.option.bedroom', 'Fangbole.DB.option.livingroom', 'Fangbole.DB.option.bathroom'],
			selected: [0, 0, 0]
		}
		Object.extend(d, options || {});
		var baSelect = new Fangbole.Select(d.id[2], {data: d.data[2], style: d.style, name: d.name[2]});
		baSelect.render(d.render[2] || d.render[0]);
		var livSelect = new Fangbole.Select(d.id[1], {data: d.data[1], style: d.style, name: d.name[1]});
		livSelect.render(d.render[1] || d.render[0]);
		var brSelect = new Fangbole.Select(d.id[0], {data: d.data[0], style: d.style, name: d.name[0]});
		brSelect.render(d.render[0]);
		if(d.selected[0])
			brSelect.select(d.selected[0]);
		if(d.selected[1])
			livSelect.select(d.selected[1]);
		if(d.selected[2])
			baSelect.select(d.selected[2]);	
		return {
			br: brSelect,
			liv: livSelect,
			ba: baSelect
		}
	},
	*/
	tag: function(input, tag){
		var elInput = $(input),
			elTag = $(tag);
		elTag.observe('click', function(e){
			var elt = e.element();
			if(elt.tagName.toUpperCase() != 'A')return;
			var selectedTags = elInput.value.strip().split(' ');
			var tag = elt.innerHTML;
			if(selectedTags.indexOf(elt.innerHTML) == -1){
				selectedTags.push(tag); 
				elInput.value = selectedTags.join(' ').replace(/^\s/, '');
			}
		})
	},
	gSearchUnits: function(){

		//init filter

		var filterArea = new Fangbole.Filter({enableSelectAll: true, data: Fangbole.DB.option.area.shanghai, title: '区域：'})
		filterArea.render('filter');
		
		var filterRooms = new Fangbole.Filter({data: Fangbole.DB.option.bedroom, title: '户型：'})
		filterRooms.render('filter');

		var filterSaleStatus = new Fangbole.Filter({data: Fangbole.DB.option.saleStatus, title: '销售：'});
		filterSaleStatus.render('filter');
		
		var filterTotalPrice = new Fangbole.Filter({data: Fangbole.DB.option.pirce, title: '价格：'});
		filterTotalPrice.render('filter');		

		var pagi = new Fangbole.Paginator();
		pagi.render('p1_wrap');
		pagi.render('p2_wrap');
		
		var query = new Fangbole.Query({
			itemId: 1,
			salesStatus: filterSaleStatus,
			area: filterArea,
			room: filterRooms,
			price: filterTotalPrice,
			pageNo: pagi,
			sortProperty: null,
			isAsc: true
		});

		var prUnit = new Fangbole.PageRequest('units', 'houseStyles.html?method=searchHouseStyleList', query, Fangbole.Template.newHouse.defaults.searchUnit, {
			onSuccess: function(result){
				pagi.update({page: result.page, total: result.total})
				$('total_result').update(result.result);
			},
			adapter: function(result){
				result.data.each(function(d){
					//户型
					d.architecture = Fangbole.DB.option.houseType[parseInt(d.architecture) - 1];
					if(d.projectArch)
						d.projectArch = '[' + Fangbole.DB.option.houseType[parseInt(d.projectArch) - 1] + ']';
				})
				return result;
			}
		})
		
		prUnit.listen('salesStatus');
		prUnit.listen('area');
		prUnit.listen('room');
		prUnit.listen('price');
		prUnit.listen('pageNo');
		
		prUnit.refresh()
		
	},
	//market_search_list.jsp
	searchUnits: function(){
		//init filter
		var filterData = $F('filter_data').evalJSON();
		
		var filterRooms = new Fangbole.Filter({data: filterData.rooms.collect(function(item){return [item, item]}), title: '物业类型：'})
		filterRooms.render('filter');

		var filterTotalPrice = new Fangbole.Filter({data: filterData.totalPrice.collect(function(item){
			if(item.indexOf('万') > -1){
				if(item == '50万以下')
					return [item, '1,50'];
				if(item == '1000万以上')
					return [item, '1000,1000000'];
			}else
				return [item + '万', item.replace('~', ',')]
		}), title: '户型价格：'});
		filterTotalPrice.render('filter');

		var filterTag = new Fangbole.Filter({data: filterData.tag.collect(function(item){return [item, item]}), title: '户型标签：'});
		filterTag.render('filter');
		
		var pagi = new Fangbole.Paginator();
		pagi.render('p1_wrap');
		pagi.render('p2_wrap');
		
		var query = new Fangbole.Query({
			itemId: null,
			houseType: filterRooms,
			tagLabel: filterTag,
			price: filterTotalPrice,
			pageNo: pagi,
			sortProperty: null,
			isAsc: true
		});
		
		var urlParams = document.location.href.parseQuery();
		for(var p in urlParams){
			if(p == 'pageNo')
				urlParams.pageNo = {page: urlParams.page}
			query.setParam(p, urlParams[p]);
		}
		
		var prUnit = new Fangbole.PageRequest('units', 'houseStyles.html?method=searchHouseStylesInItem&backOrFront=1', query, Fangbole.Template.newHouse.defaults.searchUnit, {
			onSuccess: function(result){
				pagi.update({page: result.page, total: result.total})
				$('total_result').update(result.result);
				$('units').select('tr').each(function(itm){
					itm.observe('click',function(e){
						if(e.element()!=$(this.down('.project_name').down('a'))){
							e.stop();
							url=this.down('a.photo').href;
							window.open(url);
						}
					}.bind(itm))
					itm.observe('mouseover',function(e){
						this.bgColor='#f7f7f7';
						//alert(this.bgColor)
					}.bind(itm))
					itm.observe('mouseout',function(e){
						this.bgColor='';
						//alert(this.bgColor)
					}.bind(itm))
				})
			},
			adapter: function(result){
				result.data.each(function(d){
					//户型
					d.architecture = Fangbole.DB.option.houseType[parseInt(d.architecture) - 1][0];
					if(d.projectArch)
						d.projectArch = '[' + Fangbole.DB.option.houseType[parseInt(d.projectArch) - 1][0] + ']';
				})
				return result;
			}
		})
	
		prUnit.listen('houseType');
		prUnit.listen('tagLabel');
		prUnit.listen('price');
		prUnit.listen('pageNo');		
		
		prUnit.refresh();
	},
	
	manageUnits: function(){
		var urlParams = document.location.href.parseQuery();
		//init filter
		var filterData = $F('filter_data').evalJSON();
		
		var deleteUrl, recommendUrl, editUrl, itemId = urlParams.itemId;
		
		//var filterRooms = new Fangbole.Filter({data: filterData.rooms.collect(function(item){return [item[0] + '(' + item[1] + ')', item[0]]}), title: '物业类型：'})
		var filterRooms = new Fangbole.Filter({data: filterData.rooms.collect(function(item){return [item[0], item[0]]}), title: '物业类型：'})
		filterRooms.render('units_filter');
		//var filterSaleStatus = new Fangbole.Filter({data: filterData.saleStatus.collect(function(item){return [item[0] + '(' + item[1] + ')', item[0]]}), title: '销售状态：'});
		var filterSaleStatus = new Fangbole.Filter({data: filterData.saleStatus.collect(function(item){return [item[0], item[0]]}), title: '销售状态：'});
		filterSaleStatus.render('units_filter');

		var pagi = new Fangbole.Paginator(),
			elList = $('unit_result_list').down('.unit_t1_l2');
		//pagi.render(elList, 'before');
		pagi.render('p1_wrap');
		pagi.render('p2_wrap');
		//pagi.render(elList, 'after');
		
		var query = new Fangbole.Query({
			itemId: null,
			houseType: filterRooms,
			salesStatus: filterSaleStatus,
			pageNo: pagi,
			sortProperty: null,
			isAsc: true
		});
		
		for(var p in urlParams){
			switch(p){
				case 'pageNo':
					urlParams.pageNo = {page: urlParams.page}
					break;
			}
			
			query.setParam(p, urlParams[p]);
		}
		
		
		var prUnit = new Fangbole.PageRequest(elList, 'houseStyles.html?method=searchHouseStylesInItem&backOrFront=0&rand='+Math.random(), query, Fangbole.Template.newHouse.defaults.manageUnit, {
			onSuccess: function(result){
				pagi.update({page: result.page, total: result.total})
				$('total_result').update(result.result); 
				if(!deleteUrl){
					deleteUrl = result.deleteUrl;
					recommendUrl = result.recommendUrl;
					editUrl = result.editUrl;
				}
			},
			adapter: function(result){
				result.data.each(function(d){
					d.architecture = Fangbole.DB.option.houseType[parseInt(d.architecture) - 1][0];
					if(d.recommend){
						d.recommend = '取消推荐';
						d.recommendIco = '<span class="recommended">荐</span>';
					}else{
						d.recommend = '推荐';
						d.recommendIco = '';
					}
				})
				return result;
			}
		})
		
		
		
		$('units').observe('click', function(e){
			var elt = e.element();
			if(elt.tagName.toUpperCase() == 'A'){
				var uid = elt.up('li').id.replace('unit_', '');
				
				if(elt.hasClassName('delete')){
					location.href = deleteUrl + '&itemId=' + itemId + '&houseStyleId=' + uid;
				}
				if(elt.hasClassName('edit')){
					location.href = editUrl + '&itemId=' + itemId + '&houseStyleId=' + uid;
				}
				if(elt.hasClassName('recommend')){
					location.href = recommendUrl + '&itemId=' + itemId + '&houseStyleId=' + uid + '&topType=' + (elt.innerHTML == '推荐' ? 1 : 0);
				}
				
				
				
			}
			
		})
		
		prUnit.listen('houseType');
		prUnit.listen('salesStatus');
		prUnit.listen('pageNo');		
		prUnit.refresh();
			
	},
	
	indicate: function(element, percentage){
		if(Effect)
			new Effect.Scale(element, percentage, {
				scaleX: true,
				scaleY: false
			});
		
	},
	
	clientCateTree: function(){
		
		var subs = $('client_category').select('.sub');
		subs.each(function(el){
			if(el.down('li'))
				el.up('li').addClassName('has_sub');
			el.hide();
		})
		
		
		$('client_category').observe('click', function(e){
			var elt = e.element(),
				handle = elt.up('.has_sub'),
				sub = elt.next('.sub');		
			if(handle && sub){
				sub.toggle();
				handle.toggleClassName('exp');
			}
		})
		
		
		var urlParam = location.href.toQueryParams();
		if(urlParam.cusSortId){
			var a = $('cusSort_' + urlParam.cusSortId)
			if(a)
				a.up().addClassName('current');
				a.up('.has_sub').addClassName('exp');
				a.up('.sub').show();
		}
		if(urlParam.cusType){
			var b = $('cusType_' + urlParam.cusType);
			if(b)
				b.up().addClassName('current');
				b.up('.has_sub').addClassName('exp');
				b.up('.sub').show();
		}
	}
	
}


Fangbole.Columns = {
	'project-overview-basic': ['project-overview-basic', 'project-overview-intro', 'project-overview-map', 'project-overview-planning-diagram-1', 'project-overview-planning-diagram-2', 'project-overview-planning-diagram-3', 'view-sandBox','project-overview-teams'],
	'project-feature': ['project-feature', 'project-add-feature', 'project-feature-category-management'],
	'project-news': ['project-news', 'project-add-news', 'project-news-category-management'],
	'vedio-manage': ['vedio-manage', 'add-video'],
	'album-management': ['album-management', 'edit-album', 'photo-content', 'upload-photo', 'add-album'],
	'account-setting': ['account-setting', 'account-status', 'modify-contact', 'modify-email', 'modify-password'],
	'sub-account-setting': ['sub-account-setting'],
	'product-management': ['add-unit-1', 'add-unit-2', 'add-unit-3', 'add-unit-4', 'add-unit-4-1', 'product-management'],
	'edm-management':['edm_1','edm_2_1','edm_2_2','edm_2_3','edm_2_4','edm_3','edm_4'],
	'visual-setting-1': ['visual-setting-1', 'visual-setting-2'],
	'visual-setting-3': ['visual-setting-3'],
	'visual-setting-4': ['visual-setting-4'],
	'layout-setting-1': ['layout-setting-1', 'layout-setting-2'],
	'domain-manage': ['domain-manage', 'domain-bind-1', 'domain-bind-2', 'domain-bind-3', 'domain-bind-4'],
	'head-conf-manage': ['head-conf-manage'],
	'project-terminus': ['project-terminus']
}

if($('client_category')){
	Fangbole.Initialize.clientCateTree();
}

var currentPageId = $(document.body).readAttribute('id') || '';

if($('sub_nav')){
	var pageNav
	for(var p in Fangbole.Columns){
		if(Fangbole.Columns[p].indexOf(currentPageId) > -1)
			pageNav = $('nav-' + p);
	}
	if(pageNav){
		pageNav.addClassName('current');
		//pageNav.down().replace(new Element('span').update(pageNav.down().innerHTML))
	}
}

if($('project_overview_tab')){
	//3 pages @ planning diagram
	if(['project-overview-planning-diagram-1', 'view-sandBox','project-overview-planning-diagram-2', 'project-overview-planning-diagram-3'].indexOf(currentPageId) > -1)
		currentPageId = 'project-overview-planning-diagram-1';
	var pageNav = $('nav-po-' + currentPageId);
	if(pageNav){
		pageNav.addClassName('current');
		//pageNav.down().replace(new Element('span').update(pageNav.down().innerHTML))
	}
}

//show server process message
(function(){
	var MESSAGE_SUCCESSFUL = '操作成功。',
		MESSAGE_FAILED = '操作失败。';
	
	var urlParams = location.href.toQueryParams();
	if(urlParams.sps){
		var status = parseInt(urlParams.sps),
			message = urlParams.spm || (status ? MESSAGE_SUCCESSFUL : MESSAGE_FAILED);
		var elMessage = new Element('p', {className: 'server_process_message v-info ' + (status ? 'v-ok' : 'v-error')}).update(message);
		var elContent = $('content');
		if(elContent){
			if(elContent.down('h1.std')){
				elContent.down('h1.std').insert({after: elMessage});
			}else
				elContent.insert({top: elMessage});
		}else{
			alert(message);
		}
	}
})()

Fangbole.maxLength = Class.create({
	initialize: function(obj,length){
		this.element = $(obj);
		this.detect = navigator.userAgent.toLowerCase();
		this.maxLength = length;
		this.element.observe('keydown', this.doKeyPress.bindAsEventListener(this));
		this.element.observe('paste', this.doPaste.bindAsEventListener(this));
		this.element.observe('keyup', this.doKeyUp.bindAsEventListener(this));
		this.element.observe('blur ', this.doKeyUp.bindAsEventListener(this));
	},

	doKeyPress:function(evt){
   		maxLength = this.maxLength;
	    var e = window.event ? event.keyCode : evt.which;
	    if ( (e == 32) || (e == 13) || (e > 47)) { //IE
	        if(maxLength && (this.element.value.length > maxLength-1)) {
	            if (window.event) {
	                window.event.returnValue = null;
	            } else {
	                evt.preventDefault();
	                return false;
	            }
	        }
	    }
	},
	doKeyUp:function(){
	    maxLength = this.maxLength;
	     if(maxLength && this.element.value.length > maxLength){
	           this.element.value = this.element.value.substr(0,maxLength);
	     }
	},

	doPaste:function(){
		maxLength = this.maxLength;
	     if(maxLength){
	        if ((window.event) && (this.detect.indexOf("safari") + 1 == 0)) { //IE
	          var oTR = this.element.document.selection.createRange();
	          var iInsertLength = maxLength - this.element.value.length + oTR.text.length;
	          try {
	          var sData = window.clipboardData.getData("Text").substr(0,iInsertLength);
	          oTR.text = sData;
	          }
	          catch (err) {
	          }
	          if (window.event) { //IE
	            window.event.returnValue = null;
	     } else {
	            //not IE
	            this.element.value = this.element.value.substr(0,maxLength);
	            return false;
	        }
	       }
	     }
	}

})
Fangbole.strReplace=function(str){
//(com|COM|cn|CN|net|NET|org|ORG|edu|EDU|info|INFO|gov|GOV|tv|TV|ws|WS)
	str=str.replace(/<a[^>]*>/g,"");
	str=str.replace(/<A[^>]*>/g,"");
	str=str.replace(/<\/a>/g,"");
	str=str.replace(/<\/A>/g,"");
	str=str.replace(/\&amp;/g,"&");
 	return str.replace(/(http(s)?:\/\/)?(w{3}\.)+([a-z0-9A-Z_\-:]+\.)+([a-z0-9A-Z_\-\?\&\=\.\/\$\?\#\@\\]+)/g,function(word){
 		//var i=str.indexOf(word)
 		//var l=word.length;
 		//if(i>2&&(str.substring(i-2,i)=='="'||str.substring(i-l-3,i)==word+"\">")){
 			//return word;
 		//}else
 		if(word.indexOf(".gif")!=-1||word.indexOf(".png")!=-1||word.indexOf(".jpeg")!=-1||word.indexOf(".jpg")!=-1||word.indexOf(".swf")!=-1){
 			return word;
 		}else if(word.indexOf("http://")!=-1)
 			return '<a href="'+word+'">'+word+'</a>'
 		else
 			return '<a href="http://'+word+'">'+word+'</a>'
 	})
}
