if(typeof(Seven) == 'undefined')Seven = {};

 /***************************************************/

Seven.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(Seven.prototypMethod);

/*****************************************************/

Seven.Tab = Class.create();

Object.extend(Seven.Tab, {
	instances: []
})

Object.extend(Seven.Tab.prototype, {
	initialize : function(element, options) {
		this.element = $(element);
		this.options = {
			defaultTab: 0,
			cnActive: 'current',
			cnDisabled: 'disabled',
			tnTab: 'li',
			beforeActivate: Prototype.emptyFunction,
			afterActivate: Prototype.emptyFunction
		};
		this.current = null;
		Object.extend(this.options, options || {});
		this.elTabs = this.element.select(this.options.tnTab);
		this.elContents = [];
		this.elTabs.each(function(tab){
			var content = $(this.tabID(tab));
			this.elContents.push(content);
			content && content.hide();
		}, this);
		this.activate(this.getInitialTab());
		this.elTabs.each(this.setupTab.bind(this));
		Seven.Tab.instances.push(this);
	},
	onclick: function(e){
		var elTab = Event.findElement(e, this.options.tnTab);
		e.stop();
		this.activate(elTab);
	},
	setupTab: function(elTab){
		if(!elTab.hasClassName(this.options.cnDisabled))
			elTab.observe('click', this.onclick.bindAsEventListener(this));
	},
	activate: function(elTab){
		if(elTab == this.current)return;
		this.options.beforeActivate(elTab, this.current);
		if(this.current)
			this.hide(this.current);
		this.show(elTab);
		this.current = elTab;
		this.options.afterActivate();
	},
	hide: function(elTab) {
		var elTab = $(elTab);
		var i = this.elTabs.indexOf(elTab);
		elTab.removeClassName(this.options.cnActive);
		this.elContents[i] && this.elContents[i].hide();
	},
	show: function(elTab) {
		var elTab = $(elTab)
		var i = this.elTabs.indexOf(elTab);
		elTab.addClassName(this.options.cnActive);
		this.elContents[i] && this.elContents[i].show();
	},
	tabID: function(elTab) {
		var elA = elTab.down('a');
		return elA ? elA.href.match(/#(\w.+)/) && elA.href.match(/#(\w.+)/)[1] : null;
	},
	getInitialTab : function(){
		return this.elTabs[this.options.defaultTab];
	}			  
})


//相册专辑浏览
Seven.PhotoViewer = Class.create();

Object.extend(Seven.PhotoViewer,{
	
});


Object.extend(Seven.PhotoViewer.prototype,{
	initialize: function(bigCtn, smallCtn, index, data, options){
		//原图容器
		this.bigCtn = $(bigCtn);
		//缩略图列表容器
		this.smallCtn = $(smallCtn);
		this.elPhotoIndex = $(index);
		//将data属性赋值为类的实例属性，代码清晰
		this.total = parseInt(data.total);
		this.start = data.start;
		this.list = data.list;
		
		
		this.options = Object.extend({
			updateYardInfo: true,
			updateIndex: true,
			updateInfo: [],
			afterChangePhoto: Prototype.emptyFunction
		}, options || {})
		
		//二级缓存图片对象
		this.bigImgCache = new Element('img');
		
		//原图对象
		this.bigImg = new Element('img');
		this.bigCtn.insert(this.bigImg);
		
		//为二级缓存图片注册onload事件监听
		this.bigImgCache.observe('load',this.loadImg.bindAsEventListener(this));
		
		//显示图片(默认start)
		if(this.list.length)
			this.viewPhoto(this.start);
		/*{
		"total":"6",//相册照片总数
		"start":0,//默认显示照片的索引，第一张索引为0
		"list":[
			//width:原图宽度、height:原图高度、big:原图url、small:缩略图url
			{"title":"01 李宇春001","ctime":"2008-10-05 21:00","width":"998","height":"749","big":"images/test1.jpg","small":"images/s_test1.jpg"},
			{"title":"01 李宇春002","ctime":"2008-10-05 21:00","width":"998","height":"749","big":"images/test2.jpg","small":"images/s_test2.jpg"},
			{"title":"01 李宇春003","ctime":"2008-10-05 21:00","width":"998","height":"749","big":"images/test3.jpg","small":"images/s_test3.jpg"},
			{"title":"01 李宇春004","ctime":"2008-10-05 21:00","width":"998","height":"749","big":"images/test4.jpg","small":"images/s_test4.jpg"},
			{"title":"01 李宇春005","ctime":"2008-10-05 21:00","width":"998","height":"749","big":"images/test5.jpg","small":"images/s_test5.jpg"},
			{"title":"01 李宇春006","ctime":"2008-10-05 21:00","width":"998","height":"749","big":"images/test6.jpg","small":"images/s_test6.jpg"}]
		}*/
	},
	//显示loading条
	showLoading: function(){
		$('loading').src = this.smallImg;
		var loading = $('loading');
		if(typeof(loading)!= 'undefined'){
			//loading.style.display='block';
		}
	},
	//隐藏loading条
	hideLoading: function(){
		$('loading').src = this.smallImg;
		var loading = $('loading');
		if(typeof(loading)!= 'undefined'){
			loading.style.display='none';
		}
	},
	//二级缓存图片加载完图片后调用
	loadImg: function(){
		this.hideLoading();
		this.bigImg.src = this.bigImgCache.src;
		this.bigImg.setStyle({cursor:'pointer'});
		this.bigImg.alt='下一张';
		this.bigImg.title='下一张';
		this.bigImg.onclick=function(){photoViewer.next()}
	    
	},
	//显示缩略图列表，满5张，当前图片为第3格，不满5张，当前图片为第2格，只有1张，默认显示。
	//当前图片不能点击
	//非当前图片被点击后，清空缩略图列表，并以点击图片为当前图片重新生成缩略图列表
	showSmallPhoto: function(photoIndex){
		this.smallCtn.update();
		//只有一张相片
		if(this.list.length == 1){
			var smallImg = new Element('div');
			smallImg.style.background = 'url('+this.list[0].small+') no-repeat center center';
			smallImg.style.backgroundRepeat = 'no-repeat';
			this.smallCtn.insert(smallImg);
			return;
		}
		
		if(this.list.length<5){
			//不满5张相片
			for(var j=0; j<this.total; j++){
				var itm = this.list[(this.currentIndex + j - 1 + this.total) % this.total];
				var smallImg = new Element('div');
				smallImg.style.background = 'url('+itm.small+') no-repeat center center';
				smallImg.style.cursor = 'pointer';
				this.smallCtn.insert(smallImg);
			}
			
			var smallImgs = this.smallCtn.select('div');
			$(smallImgs).each(function(itm, index){
				//alert(index);
				if(index == 1){
					itm.style.cursor="default";
					itm.style.backgroundRepeat = 'no-repeat';
					itm.style.border='1px solid #ccc';
				}else{
					itm.observe('click',function(){
						//alert((this.currentIndex + index - 1 + this.total) % this.total);
						this.viewPhoto((this.currentIndex + index - 1 + this.total) % this.total);
					}.bindAsEventListener(this));
				}
			},this);
		}else{
			//满足5张相片
			for(var j=0; j<5; j++){
				var itm = this.list[(this.currentIndex + j - 2 + this.total) % this.total];
				var smallImg = new Element('div');
				smallImg.style.background = 'url('+itm.small+') no-repeat center center';
				smallImg.style.cursor = 'pointer';
				this.smallCtn.insert(smallImg);
			}
			
			var smallImgs = this.smallCtn.select('div');
			$(smallImgs).each(function(itm, index){
				if(index == 2){
					itm.style.cursor="default";
					itm.style.backgroundRepeat = 'no-repeat';
					itm.style.border='1px solid #e1e1e1';
				}else{
					itm.observe('click',function(){
						this.viewPhoto((this.currentIndex + index - 2 + this.total) % this.total);
					}.bindAsEventListener(this));
				}
			},this);
		}
	},
	//加载原图，采用二级加载机制，即，原图根据传输的尺寸信息（data.list中包含的width、height）拉伸缩略图，等二级缓存图片加载完后，原图加载二级缓存图片。
	showBigPhoto: function(photoIndex){
		this.bigImg.src= this.list[this.currentIndex].small;
		var tmpWidth = this.list[this.currentIndex].width;
		var tmpHeight = this.list[this.currentIndex].height;
		
		this.bigImg.style.width = (this.list[this.currentIndex].width<660?this.list[this.currentIndex].width:660) + 'px';
		this.bigImg.observe('mousemove',function(event){
		}.bindAsEventListener(this));
		this.showLoading();
		/*
		var tempthis = this;
		window.setTimeout(function(){
			tempthis.bigImgCache.src = tempthis.list[tempthis.currentIndex].big;
		},1000);*/
		this.bigImgCache.src = this.list[this.currentIndex].big;
		if(this.options.updateIndex)
			this.updateIndex();
		if(this.options.updateYardInfo)
			this.updateYards();
		if(this.options.updateInfo && this.options.updateInfo.length)
			this.options.updateInfo.each(function(info){
				$(info[1]).update(this.list[info[0]])
			}, this)
	},
	//上一张照片
	previous: function(){
		this.viewPhoto((this.currentIndex + this.total - 1) % this.total);
	},
	//下一张照片
	next: function(){
		this.viewPhoto((this.currentIndex + 1) % this.total);
	},
	//显示照片附属信息，包含标题，作者，日期
	showPhotoInfo: function(photoIndex){
		var photoInfo = $('photoInfo');
		if(photoInfo){
			if($('currentIndex')) $('currentIndex').update(this.currentIndex+1);
			if($('total')) $('total').update(this.total);
			if(photoInfo){
				photoInfo.down('.tt') && photoInfo.down('.tt').update(this.list[this.currentIndex].title);
				photoInfo.down('.light') && photoInfo.down('.light').update(this.list[this.currentIndex].ctime);
				//photoInfo.down('#del_photo') && photoInfo.down('#del_photo').update('<a href=photos.html?method=delete&deletePhotoId='+this.list[this.currentIndex].pid+' class="blue_l">删除该照片</a>');
				$('loading') && $('loading').update('<img src='+this.list[this.currentIndex].small+' />');

				if(this.options.updateYardInfo && this.list[this.currentIndex].sharedYarddata.length)
					this.updateYards(this.list[this.currentIndex].sharedYarddata);
				if(photoInfo.down('#del_photo')){photoInfo.down('#del_photo').update('<a href=photos.html?method=delete&deletePhotoId='+this.list[this.currentIndex].pid+' class="blue_l">删除该照片</a>')}
				if(photoInfo.down('.do')){
					photoInfo.down('.do').update('<a href=albums.html?method=addToCoverpicURL&photoid='+this.list[this.currentIndex].pid+'>设为相册封面</a>')
				}
			}
		}
	},
	updateYards: function(yards){
		var photoInfo = $('photoInfo');
		var elYard = photoInfo.down('.share_yards');
		elYard.update();
		if(yards)
			this.list[this.currentIndex].sharedYarddata = yards;
		this.list[this.currentIndex].sharedYarddata.each(function(y){
			if(y.yardId in Seven.uYards)
				elYard.insert(new Element('a', {href: Seven.uYards[y.yardId].yardhref}).update(Seven.uYards[y.yardId].yardName));
				elYard.insert({after:' '})
		})
		var yard_size=$('photoInfo').down('.share_yards').innerHTML;
		
		if($('photoInfo').down('.yards_string')){
	    if(yard_size==""||yard_size.length<1){
		   $('photoInfo').down('.yards_string').update('点击"设置"分享相片');
	    }else{
	       $('photoInfo').down('.yards_string').update('分享至：');
	    }
	    }
	    if($('photoInfo').down('.yards_string_friend')){
	    if(yard_size==""||yard_size.length<1){
		    $('photoInfo').down('.yards_string_friend').update('');
		    $('photoInfo').down('.yards22_string_friend').update('');
	    }else{
	        $('photoInfo').down('.yards_string_friend').update('分享至： ');
	        $('photoInfo').down('.yards22_string_friend').update('等大院 ');
	    }
	    }
	},
	updateIndex: function(){
		var current = (this.currentIndex || 0) + 1,
			total = this.total || 0;
		this.elPhotoIndex.update(current  + '/' + total);
	},
	//显示照片
	viewPhoto: function(index){
		this.currentIndex = index;
		this.showSmallPhoto(index);
		this.showBigPhoto(index);
		this.showPhotoInfo(index);
		this.options.afterChangePhoto(this.list[index]);
		
	}
});


Seven.SimpleResize = Class.create({
	initialize: function(element, handle){
		this.element = $(element);
		this.elHandle = $(handle) || new Element('div', {className: 'g_sresize_handle'});
		this.element.appendChild(this.elHandle);
		this.elProxy = new Element('div', {className: 'g_sresize_proxy', style: 'display: none'});
		
		this.element.parentNode.appendChild(this.elProxy);
		
		
		this.funcCacheStart = this.start.bindAsEventListener(this);
		this.funcCacheStartResize = this.startResize.bindAsEventListener(this);
		this.funcCacheResize = this.resize.bindAsEventListener(this);
		this.funcCacheStop = this.stop.bindAsEventListener(this);

		this.originalWidth = 0;
		this.originalHeight = 0;		
		this.originalX = 0;
		this.originalY = 0;
		this.elHandle.observe('mousedown', this.funcCacheStart);
		Seven.SimpleResize.instances.push(this);
	},
	start: function(e){
		Event.stop(e);
		this.elHandle.stopObserving('mousedown', this.funcCacheStart);
		document.observe('mousemove', this.funcCacheResize);
		document.observe('mouseup', this.funcCacheStop);
		
		this.elProxy.clonePosition(this.element);
		//this.elProxy.setStyle({width: this.element.getWidth() + 'px', height: this.element.getHeight() + 'px', left: this.element.getStyle('left') + 'px', top: this.element.getStyle('top') + 'px'});
		this.elProxy.show();
		
		
		var dim = this.element.getDimensions();
		this.originalWidth = dim.width;
		this.originalHeight = dim.height;
		this.originalX = e.pageX;
		this.originalY = e.pageY;
		//var _dim = this.element.getInnDimensions();
		//this.minHeight = _dim.height;
		//this.minWidth = _dim.width;
		//取消文本选择效果
		//document.body.style['MozUserSelect'] = 'none';
	},
	startResize: function(e){

	},
	resize: function(e){
		Event.stop(e);
		var _w = this.originalWidth + e.pageX - this.originalX,
			_h = this.originalHeight + e.pageY - this.originalY;
		//if(_w >= this.minWidth)
			this.elProxy.style.width = _w + 'px';
		//if(_h >= this.minHeight)
			this.elProxy.style.height = _h + 'px';
	},
	stop: function(e){
		document.stopObserving('mousedown', this.funcCacheStop);
		document.stopObserving('mousemove', this.funcCacheStartResize);
		document.stopObserving('mousemove', this.funcCacheResize);
		this.elHandle.observe('mousedown', this.funcCacheStart);
		//document.body.style['MozUserSelect'] = '';
		
		//this.element.clonePosition(this.elProxy, {setLeft: false, setTop: false, setWidth: true, setHeight: true});
		this.element.setStyle({width: this.elProxy.style.width, height: this.elProxy.style.height});
		this.elProxy.hide();
	},
	destroy: function(){
		this.elHandle.remove();
	},
	disable: function(){
		this.elHandle.hide();
	},
	enable: function(){
		this.elHandle.show();
	}
})

Object.extend(Seven.SimpleResize, {
	instances: []			
})


var LayerManager = {
	layers: [],
	actives: [],
	register: function(element, options){
		var element = $(element);
		layer = Object.extend({
			element: element,
			close: function(){
				element.hide();
			},
			rootElement: null
		}, options || {})
		LayerManager.layers.push(layer);
	},
	unregister: function(elLayer){
		LayerManager.layers = layers.reject(function(layer){return layer.element = elLayer})
	},
	active: function(elLayer){
		var layer = LayerManager.findLayerByElement(elLayer);
		actives.push(layer);
	},
	close: function(){
		LayerManager.layers.each(function(layer){
			layer.close(layer.element)
		});
	},
	findLayerByElement: function(element){
		return LayerManager.layers.find(function(layer){layer.element == element});
	},
	onClick: function(e){
		var elm = e.element();
		if(LayerManager.isClickOnBlank(elm))
			LayerManager.close();
	},
	isClickOnBlank: function(elm){
		return !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', LayerManager.onClick.bindAsEventListener(this));
	}
}

LayerManager.initialize();


/******************************************/

Seven.Window = Class.create({
	initialize: function(){	
		var defaultOptions = {
			type: 'normal',//normal, alert, confirm
			id: '',
			element: null,
			title: '',
			content: '',
			mask: true,
			afterInit: Prototype.emptyFunction,
			beforeOpen: Prototype.emptyFunction,
			afterOpen: Prototype.emptyFunction,
			beforeClose: Prototype.emptyFunction,
			afterClose: Prototype.emptyFunction,
			position: 'centered',//centerd, {left: x, top: y}
			closeHandles: [],
			openHandles: [],
			onOK: Prototype.emptyFunction,
			onCC: Prototype.emptyFunction,
			onConfirm: Prototype.emptyFunction,
			//onPrompt: Prototype.emptyFunction,
			autoOpen: false,
			escClose: true,
			destroyAfterClose: false
		}
		this.options = Object.extend(defaultOptions, arguments[0] || {});
		Object.extend(this.options, Seven.Window.config[this.options.type]);
		
		this.type = this.options.type;
		this.title = this.options.title;
		this.content = this.options.content;
		if(!this.options.element){
			this.id = this.options.id || this._generateWindowId();
			this.element = new Element('div', {className: 'box box_pop', id: this.id}).update(Seven.Window.template[this.type].evaluate(this));	
			document.body.appendChild(this.element);
		}else{
			this.element = $(this.options.element);
			this.id = this.element.readAttribute('id') || this.options.id || this._generateWindowId();
		}
		this.element.hide();
		
		this.position = this.options.position;
		this.fixed = !(Prototype.Browser.IE && navigator.appVersion.indexOf('MSIE 6.0'));

		
		
		this.elDefaultClose = this.element.down('.box_pop_close') || null;
		this.elContent = this.element.down('.ct');
		this.elTitle = this.element.down('h2') || this.element.down('h3') || null;
		
		this._initMask();
		
		this.afterInit = this.options.afterInit;
		this.beforeOpen = this.options.beforeOpen;
		this.afterOpen = this.options.afterOpen;
		this.beforeClose = this.options.beforeClose;
		this.afterClose = this.options.afterClose;
		
		this.closeHandles = [];
		this.openHandles = [];
		this.options.openHandles.each(function(elm){
			this.addOpenHandle(elm);
		}, this)
		this.addCloseHandle(this.elDefaultClose);
		this.options.closeHandles.each(function(elm){
			this.addCloseHandle(elm);
		}, this)

		if(this.options.escClose){
			Event.observe(document, 'keypress', function(e){
				if(e.keyCode == Event.KEY_ESC)
					this.close();
			}.bindAsEventListener(this))
		}		
		Event.observe(window, 'resize', this._onResize.bind(this));
		if(Seven.Window.config[this.options.type].init)
			Seven.Window.config[this.options.type].init.bind(this)();
		this.afterInit();
		Seven.Window.instances.push(this);
		if(this.options.autoOpen)
			this.open();
	},
	_initMask: function(){
		if($('seven_mask')){
			this.elMask = $('seven_mask');
			return;
		}
		this.elMask = new Element('div', {id: 'seven_mask'});
		document.body.appendChild(this.elMask);
		this.elMask.hide();
	},
	_initMaskDimension: function(){
		
	},
	_initPositionAndDimensions: function(){
		var winSize = Seven.utils.getPageSize(document.body);
		this.elMask.setStyle({width: winSize.windowWidth + 'px', height: winSize.pageHeight + 'px'});
		/*
		var	winDim = this.element.getDimensions();
		var winScrollTop=document.documentElement.scrollTop;
		var berheight=document.documentElement.clientHeight;
		var berwidth=document.documentElement.clientWidth;
		//alert((berheight-winDim.height)/2)
		this.element.setStyle({position:'absolute !impotrant',top:(winScrollTop+(berheight-winDim.height)/2)+'px'})
		*/
		if(this.position == 'centered'){
			var	winDim = this.element.getDimensions();
			//alert(document.documentElement.scrollTop)
			this.element.setStyle({left: '50%', top: '50%'});
			if(this.fixed){
				this.element.setStyle({marginLeft: - winDim.width / 2 + 'px', marginTop: - winDim.height / 2 + 'px'})
			}else{
				if(parseFloat(navigator.appVersion.substr(navigator.appVersion.indexOf('MSIE')+5,3))==6){
					this.element.setStyle({marginTop: document.documentElement.scrollTop - (document.documentElement.clientHeight-winDim.height) / 2 + 200 + 'px', marginLeft: document.documentElement.scrollLeft - winDim.width / 2 + 'px'});
				}else{
					if(document.documentElement.scrollHeight>document.documentElement.clientHeight){
						this.element.setStyle({marginTop: '-150px', marginLeft: -(document.documentElement.scrollLeft + winDim.width / 2) + 'px'});
						}else{
							this.element.setStyle({marginTop: -(document.documentElement.scrollTop + winDim.height / 2)+ 'px', marginLeft: -(document.documentElement.scrollLeft + winDim.width / 2) + 'px'});
						}
				}
			}
		}else{
			this.element.setStyle({left: this.position.left + 'px', top: this.position.top + 'px'});	
		}
		
					
	},
	_generateWindowId: function(){
		return 'seven_window_' + (Seven.Window.instances.length + 1);
	},
	open: function(){
		this.beforeOpen();
		this._initPositionAndDimensions();
		this.element.show();
		if(this.options.mask)
			this.elMask.show();
		this.afterOpen();
	},
	close: function(){
		this.beforeClose();
		
		this.element.hide();
		this.elMask.hide();
		if(this.options.destroyAfterClose)
			this.destroy();
		this.afterClose();
	},
	addCloseHandle: function(element){
		var handle = $(element);
		handle.observe('click', function(){this.close()}.bind(this));
		this.closeHandles.push(handle);
	},
	addOpenHandle: function(element){
		var handle = $(element);
		handle.observe('click', function(){this.open()}.bind(this));
		this.openHandles.push(handle);		
	},
	update: function(oContent){
		
	},
	_onResize: function(){
		this._initPositionAndDimensions();
	},
	destroy: function(){
		this.element.remove();
	}
})

Object.extend(Seven.Window, {
	instances: [],
	template: {
		normal: new Template('\
			<div class="hd"><h2>#{title}</h2><a href="javascript:;" class="box_pop_close" hidefocus="true">关闭</a></div>\
			<div class="ct">#{content}<div class="do"><input type="button" class="g_btn g_btn_ok box_pop_ok" value="确定"><input type="button" class="g_btn g_btn_cc box_pop_cc" value="取消"></div></div>\
    	'),
    	alert: new Template('\
			<div class="hd"><h2>#{title}</h2><a href="javascript:;" class="box_pop_close" hidefocus="true">关闭</a></div>\
			<div class="ct"><div>#{content}</div><div class="do"><input type="button" class="g_btn g_btn_ok box_alert_ok" value="确定"></div></div>\
    	'),
    	confirm: new Template('\
			<div class="hd"><h2>#{title}</h2><a href="javascript:;" class="box_pop_close" hidefocus="true">关闭</a></div>\
			<div class="ct">\
				<div>#{content}</div>\
				<div class="do"><input type="button" class="g_btn g_btn_ok box_confirm_ok" value="是"><input type="button" class="g_btn g_btn_cc box_confirm_cc" value="否"></div>\
			</div>\
    	'),
    	showInf: new Template('\
			<div class="hd"><h2>#{title}</h2><a href="javascript:;" class="box_pop_close" hidefocus="true">关闭</a></div>\
			<div class="ct"><div>#{content}</div><div class="do" style="display:none;"><input type="button" class="g_btn g_btn_ok box_alert_ok" value="确定"></div></div>\
    	')
	},
	config: {
		normal: {
			init: function(){
				this.elOK = this.element.down('.box_pop_ok');
				this.elCC = this.element.down('.box_pop_cc');
				this.elOK.observe('click', function(){
					this.options.onOK();
					this.close();
				}.bind(this))
				this.elCC.observe('click', function(){
					this.options.onCC();
					this.close();
				}.bind(this))			
			}
		},
		alert: {
			mask: false,
			init: function(){
				this.element.addClassName('box_pop_alert');
				this.elSubmit = this.element.down('.box_alert_ok');
				this.addCloseHandle(this.elSubmit);
			},
			autoOpen: true,
			destroyAfterClose: true
		},
		confirm: {
			mask: false,
			init: function(){
				this.element.addClassName('box_pop_confirm');
				this.onConfirm = this.options.onConfirm;
				this.elConfirmYes = this.element.down('.box_confirm_ok');
				this.elConfirmNo = this.element.down('.box_confirm_cc');
				this.elConfirmYes.observe('click', this.onConfirm.bind(this, true));
				this.elConfirmNo.observe('click', this.onConfirm.bind(this, false));
				this.addCloseHandle(this.elConfirmYes);
				this.addCloseHandle(this.elConfirmNo);					
			},
			autoOpen: true,
			destroyAfterClose: true
		},
		showInf: {
			mask: false,
			init: function(){
				this.element.addClassName('box_pop_showInf');
			},
			autoOpen: true,
			destroyAfterClose: true
		}
	}
})

/*
var yearSelect = new Seven.Select('year_select', {
	data: Seven.DB.selectOptions.year,
	name: 'birthday_year', 
	selectedName: $F('birthday_year') - 0, 
	relative: daySelect, 
	relationship: getDayArray, 
	config: 'native'
});
*/
Seven.Select = Class.create({
	initialize: function(id, options){
		this.options = Object.extend({
			config: Seven.Select.config.DEFAULT,
			//联动的select， 可以为单个或者数组形式的多个
			relative: null,
			//数据集合
			data: null,		
			relationship: null,
			name: null,
			onselect: Prototype.emptyFunction,
			onChangeBefore:Prototype.emptyFunction,
			onChangeAfter:Prototype.emptyFunction
		},options||{});
		
		Object.extend(this.options, this.options.config);
		this.isNative = this.options.config == 'native';
		this.styleClass = this.options.styleClass || '';
		this.name = this.options.name || '';
		this.selectedIndex = 0;
		this.dataPath = null;
		this.relative = Object.isArray(this.options.relative) ? this.options.relative : [this.options.relative];
		this.isCollapsed = true;	
		this.element = $(id);
		if(!this.element){
			if(this.options.config == 'native'){
				this.element = new Element('select', {id: id, className: 'g_sel', name: this.name});
				this.element.observe('change', this.onChange.bindAsEventListener(this));
				this.selectedIndex = function(){
					return this.element.selectedIndex;
				}

				this.update(this.options.data, true);
				
			}else{
				this.element = new Element('div', {id: id, className: 'g_sel ' + this.styleClass}).update(this.options.template.evaluate({}));
				this.element.observe('click',this.onClick.bindAsEventListener(this));
				this.element.observe('Select:change',this.onChange.bind(this));				
				this.elInput = new Element('input', {type: 'hidden', name: this.name, value: this.options.currentSelected});
				this.elTitle = this.element.down('.sel_title');
				this.elOptsWrap = this.element.down('.sel_options_wrap');
				this.optItems = [];
				this.collapsedCN = this.options.styleClass + '_collapsed';
				this.expandedCN = this.options.styleClass + '_expanded';

				this.update(this.options.data, true);
				this.element.addClassName(this.collapsedCN);
				
				LayerManager.register(this.elOptsWrap, {close: this.collapse.bind(this), rootElement: this.element});
			}
		}
		Seven.Select.instances.push(this);
	},
	clear: function(){
		this.optItems = [];
		this.selectedIndex = 0;
		if(this.options.config == 'native'){
			this.element.update();
		}else{
			this.elOptsWrap.update();
			this.elTitle.update();
		}
		this.data = null;
		this.dataPath = null;
	},
	update: function(data, isIntialize){
		this.clear();
		if(Object.isString(data)){
			this.dataPath = data;
			this.data = eval(data);
		}else if(Object.isArray(data)){
			this.data = data;
		}else{
			return;
		}
		//format this.data
		if(!Object.isArray(this.data[0])){
			this.data = this.data.collect(function(dt, i){
				var temp = [];
				temp[0] = dt;
				temp[1] = i;
				return temp;
			})
		}

		if(isIntialize && this.options.currentSelected){
			for(var i = 0, j = this.data.length; i < j; i ++){
				if(this.data[i][1] == this.options.currentSelected)
					this.selectedIndex = i;
			}
		}
		for(var i = 0, j = this.data.length; i < j; i ++){
			var opt = new Seven.Option(this.data[i][0], this.data[i][1], i, i == this.selectedIndex, {isNative: this.isNative});
			this.optItems.push(opt);
			if(this.isNative){
				this.element.appendChild(opt.element);
			}else{
				this.elOptsWrap.appendChild(opt.element);
			}
		}
		if(this.isNative){
			this.element.selectedIndex = this.selectedIndex;
			this.element.fireNative('change');
		}else{
			this.elTitle.update(this.optItems[this.selectedIndex].name);
			this.element.fire('Select:change');		
		}
	},
	onClick: function(event){
		event.stop();
		var elm = Event.element(event);
		if(elm == this.elTitle){
			if(this.isCollapsed){
				this.expand();
			}else{
				this.collapse();
			}
		}else{
			var item = Event.element(event).up();
			if(item && item.hasClassName('sel_option')){
				var option = this.optItems.find(function(opt){return opt.element == item});
				this.select(option.value);
			}
		}
	},
	onChange: function(){
		if(this.options.onChangeBefore != Prototype.emptyFunction)
			this.options.onChangeBefore();	
		if(this.options.relative){
			this.relative.each(function(sel){
				var relationPath;
				if(this.options.relationship){
					sel.update(this.options.relationship());
				}else if(this.dataPath){
					var relationship = Seven.Select.getRelationPathByOptionPath(this.dataPath) + '[' + (this.isNative ? this.element.selectedIndex : this.selectedIndex) + ']';
					if(relationship)
						sel.update(relationship);
				}
			}, this)
		}
		//this.selectedIndex = this.element.selectedIndex;
		if(this.options.onChangeAfter != Prototype.emptyFunction)
			this.options.onChangeAfter();		
	},
	expand: function(){
		Seven.Select.instances.each(function(sel){
			if(!sel.isNative && !sel.isCollpased)
				sel.collapse();
		})
		this.isCollapsed = false;
		this.element.addClassName(this.expandedCN);
		this.element.removeClassName(this.collapsedCN);
		this.elOptsWrap.show();
	},
	collapse: function(){
		this.isCollapsed = true;
		this.element.removeClassName(this.expandedCN);
		this.element.addClassName(this.collapsedCN);
		this.elOptsWrap.hide();
	},
	select: function(optionValue){
		var option = this.optItems.find(function(opt){return opt.value == optionValue});
		if(this.isNative){
			this.element.selectedIndex = option.index;
			this.element.fireNative('change');
			//this.element.selectedIndex = this.optItems.find(function(opt){return opt.value == option});
		}else{
			if(option.index != this.selectedIndex){
				this.elTitle.update(option.name);
				option.element.addClassName('selected');
				this.optItems[this.selectedIndex].element.removeClassName('selected');
				this.selectedIndex = option.index;
			}
			this.collapse();
			this.element.fire('Select:change');
		}
		if(this.options.onselect != Prototype.emptyFunction)
			this.options.onselect(optionValue);		
	},
	render: function(element){
		$(element).insert({top: this.element});
	},
	getValue: function(type){
		var type = type || 'value',
			selectedIndex = this.isNative ? this.element.selectedIndex : this.selectedIndex;
		switch(type){
			case 'name':
				return this.isNative ? this.optItems[selectedIndex].element.innerHTML : this.optItems[selectedIndex].name;
				break;
			case 'index':
				return selectedIndex;
				break;
			case 'value':
				return this.isNative ? this.optItems[selectedIndex].element.value : this.optItems[selectedIndex].value;
				break;
			default:
				throw 'invalid type of value, must be "name", "value" or "index".';
				break;
		}
	},
	setRelationship: function(relationship){
		if(relationship)
			this.options.ralationship = relationship;
	}
});

Object.extend(Seven.Select,{
	instances: [],
	config: {
		DEFAULT: {
			template: new Template('<h4 class="sel_title"></h4><ul class="sel_options_wrap" style="display: none;"></ul>'),
			styleClass: 'g_sel_wGy'
		}
	},
	getRelationPathByOptionPath: function(optionPath){
		return optionPath.replace('selectOptions', 'optionRelationship');
	}
});

Seven.Option = Class.create({
	initialize: function(name, value, index, selected, options){
		if(arguments.length < 4)
			throw 'more arguments need when call Seven.Option';	
		this.name = name;
		this.value = value;
		this.index = index;
		this.selected = selected;
		this.options = Object.extend({
			tagName: 'li',
			className: 'sel_option',
			isNative: false
		}, options || {});
		if(this.options.isNative){
			this.element = new Element('option', {className: this.options.className, selected: (this.selected ? 'selected' : ''), value: this.value}).update(this.name)
		}else{
			this.element = new Element('li', {className: this.options.className + (this.selected ? ' selected' : '')}).update(Seven.Option.template.evaluate(this));
		}
		Seven.Option.instances.push(this);
	}
})

Object.extend(Seven.Option, {
	instances: [],
	template: new Template('<a href="javascript:;">#{name}</a>')
});


Seven.SRTE = Class.create({
	initialize: function(element, options){
		this.element = $(element);
		this.elTextarea = this.element.down('textarea');
		var defaultOptions = {
			tools: ['emoticon']
		}
		this.options = Object.extend(defaultOptions, options || {});
		this._initToolsWrap();
		
		this.options.tools.each(function(tool){
			var klass, options = {};
			if(Object.isString(tool)){
				klass = tool;
			}else if(Object.isArray(tool)){
				klass = tool[0];
				options = tool[1];
			}
			this.addTool(klass.capitalize(), options);
		}, this)
	},
	_initToolsWrap: function(){
		this.tools = {};
		this.elTool = new Element('ul', {className: 'tools'});
		this.elTextarea.insert({before: this.elTool});
	},
	addTool: function(tool, options){
		if(tool in Seven.SRTE){
			var oTool = new Seven.SRTE[tool](this, options);
			if(oTool){
				this.tools[tool] = oTool;
				this.elTool.insert(oTool.element);
			}			
		}else{
			throw 'Seven.SRTE Tool type Error @ Seven.SRTE.initialize: invalid tool class';
		}
	}
})

Object.extend(Seven.SRTE, {
	//use for Seven.SRTE.Image & Seven.SRTE.Grab upload complete
	onUploadComplete: function(type, id, src){
		
		if(arguments.length ==3&&id==-1){
			if(src==''){
				alert('不能上传空文件');
				Seven.SRTE.Image.instances[Seven.SRTE.Image.instances.length-1].cancel.bind(Seven.SRTE.Image.instances[Seven.SRTE.Image.instances.length-1])();
				return;
			}
			if(src=='errorPath'){
				alert('请上传图片类型的文件');
				Seven.SRTE.Image.instances[Seven.SRTE.Image.instances.length-1].cancel.bind(Seven.SRTE.Image.instances[Seven.SRTE.Image.instances.length-1])();
				return;
			}
		}
	
		if(arguments.length == 1&&type==-1)
			{
				alert('单张图片不得超过3M！');
				Seven.SRTE.Image.instances[Seven.SRTE.Image.instances.length-1].cancel.bind(Seven.SRTE.Image.instances[Seven.SRTE.Image.instances.length-1])();
				return;
			}
		if(arguments.length != 3)
			throw 'uploading error @ Seven.SRTE.onUploadComplete: arguments not match'; 
		switch(type){
			case 0:
				Seven.SRTE.Grab.instances[0] && Seven.SRTE.Grab.instances[0].onFinish(id, src);
				break;
			case 1:
				Seven.SRTE.Image.instances[0] && Seven.SRTE.Image.instances[0].onFinish(id, src);
				break;
			default:
				throw 'type error @ Seven.SRTE.onUploadComplete: unkown uploading type';
				break;
		}
	},
	insertAtCursor:function(myField, myValue,sel) {  
    //IE support  
	    if (document.selection&&sel!=null) {
	        //myField.focus();  
	        //sel = document.selection.createRange();  
	        sel.text = myValue;  
	        sel.select();  
	    }  
	    //MOZILLA/NETSCAPE support  
	    else if (myField.selectionStart || myField.selectionStart == '0') {  
	        var startPos = myField.selectionStart;  
	        var endPos = myField.selectionEnd;  
	        // save scrollTop before insert  
	        var restoreTop = myField.scrollTop;  
	        myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length);  
	        if (restoreTop > 0) {  
	        myField.scrollTop = restoreTop;  
	        }  
	        myField.focus();  
	        myField.selectionStart = startPos + myValue.length;  
	        myField.selectionEnd = startPos + myValue.length;  
	    } else {
	        myField.value += myValue;  
	        myField.focus();  
	    }  
	},
	onFieldKeyup:function(e){
		//var keyCode = e.keyCode
    	//if(keyCode==37||keyCode==38||keyCode==39||keyCode==40){
			this.currSel=document.selection.createRange();
		//}
	}
})


Seven.SRTE.Emoticon = Class.create({
	initialize: function(oSRTE){
		this.element = new Element('li', {className: 'emoticon'}).update(Seven.SRTE.Emoticon.html);
		this.oSRTE = oSRTE;
		this.elToggle = this.element.down('a');
		this.elEmoList = this.element.down('.emoticons');
		this.elToggle.observe('click', function(){this.elEmoList.toggle()}.bindAsEventListener(this));
		this.elEmoList.observe('click', this._onClickEmoList.bindAsEventListener(this));
		this.elEmoList.hide();
		LayerManager.register(this.elEmoList, {rootElement: this.element});
	},
	_onClickEmoList: function(e){
		e.stop();
		var elm = e.element();
		if(elm.tagName.toUpperCase() == 'LI'){
			this.select(elm.className);
		}
		this.elEmoList.hide();
	},
	select: function(emo){
		if(!(emo in this._map))
			throw new Error('Emoticon Type Error @ Seven.SRTE.Emoticon.select: Invalid emoticon name');
		var token = this._map[emo];
		this.oSRTE.elTextarea.value += token;
	},
	_map: {
		'emo1': '/:)',
		'emo2': '/:(',
		'emo3': '/:>',
		'emo4': '/:\'(',
		'emo5': '/:@',
		'emo6': '/:0',
		'emo7': '/:p',
		'emo8': '/:$',
		'emo9': '/;p',
		'emo10': '/:L',
		'emo11': '/:8',
		'emo12': '/:D',
		'emo13': '/:-D',
		'emo14': '/:!',
		'emo15': '/:-S',
		'emo16': '/;@',
		'emo17': '/:X',
		'emo18': '/:Z',
		'emo19': '/hug',
		'emo20': '/v',
		'emo21': '/cake',
		'emo22': '/showlove',
		'emo23': '/share',
		'emo24': '/rose'		
	}
})

Object.extend(Seven.SRTE.Emoticon, {
	html: '\
		<a href="javascript:;">表情</a>\
		<div class="emoticons" style="display: none;">\
			<ul>\
			<li title="微笑" class="emo1">微笑</li>\
			<li title="难过" class="emo2">难过</li>\
			<li title="憨笑" class="emo3">憨笑</li>\
			<li title="大哭" class="emo4">大哭</li>\
			<li title="发怒" class="emo5">发怒</li>\
			<li title="惊讶" class="emo6">惊讶</li>\
			<li title="调皮" class="emo7">调皮</li>\
			<li title="害羞" class="emo8">害羞</li>\
			<li title="偷笑" class="emo9">偷笑</li>\
			<li title="流汗" class="emo10">流汗</li>\
			<li title="折磨" class="emo11">折磨</li>\
			<li title="呲牙" class="emo12">呲牙</li>\
			<li title="可爱" class="emo13">可爱</li>\
			<li title="惊恐" class="emo14">惊恐</li>\
			<li title="咒骂" class="emo15">咒骂</li>\
			<li title="晕" class="emo16">晕</li>\
			<li title="闭嘴" class="emo17">闭嘴</li>\
			<li title="睡" class="emo18">睡</li>\
			<li title="拥抱" class="emo19">拥抱</li>\
			<li title="胜利" class="emo20">胜利</li>\
			<li title="蛋糕" class="emo21">蛋糕</li>\
			<li title="示爱" class="emo22">示爱</li>\
			<li title="握手" class="emo23">握手</li>\
			<li title="玫瑰" class="emo24">玫瑰</li>\
			</ul>\
		</div>'
})

/*
 * {
 *		id: 1,
 *		name: '<图片1>',
 *		src: '/7dian/images/tmp_50.gif',
 *		desc: 'test',
 *		pos: 1
 */
Seven.SRTE.Image = Class.create({
	initialize: function(oSRTE, options){
		this.options = options || {};
		this.oSRTE = oSRTE;
		this.aImages = [];
		this.oUploading = null;
		this.currSel=null;//实例光标当前位置
		this.element = new Element('li', {className: 'image'});
		this.elHandle = new Element('input', {type: 'button', value: '添加图片'});
		this.element.insert(this.elHandle);
		this.elImageList = new Element('ul', {className: 'g_srte_image'});
		this.oSRTE.element.insert(this.elImageList);
		if(options.window && $(options.window)){
			this.oWinFile = new Seven.Window({element: options.window, openHandles: [this.elHandle], onOK: function(){
				this.upload();
				//window.setTimeout(function(){this.onFinish(1, '/7dian/images/tmp_50.gif')}.bind(this), 2000)
			}.bind(this)});
		}else
			throw 'window initialize error @ Seven.SRTE.Image.initialize: file upload window template must be indicate';
			
		Seven.SRTE.Image.instances.push(this);
		if(this.options.textarea&&document.selection){
			$(this.options.textarea).observe('click', function(){
				this.currSel=document.selection.createRange();
			}.bindAsEventListener(this));
			$(this.options.textarea).observe('keyup',Seven.SRTE.onFieldKeyup.bindAsEventListener(this));
		}
	},
	load: function(oImage){
		//oImage.element = new Element('li', {className: 'g_srte_image_item'}).update(Seven.SRTE.Image.template.image.evaluate(oImage));
		oImage.element = new Element('li', {className: 'g_srte_image_item', id:'srteImage_'+oImage.id}).update(Seven.SRTE.Image.template.image.evaluate(oImage));
		//oImage.element.select('input[type="radio"]')[oImage.pos].checked = 'checked';
		oImage.elDelete = oImage.element.down('a');
		oImage.elDelete.observe('click', this._delete.bind(this, oImage.id));
		oImage.elPos = oImage.element.down('.position');
		oImage.elText=oImage.element.down('textarea');
		oImage.elText.value=oImage.text;
		oImage.elPos.observe('click', this.onSelectPosition.bindAsEventListener(this));
		this.elImageList.insert(oImage.element);
		oImage.element.select('input[type="radio"]')[oImage.pos].checked = 'checked';
		this.aImages.push(oImage);
	},
	save: function(){
		this.aImages.each(function(itm){
			itm.text=itm.element.down("textarea").value
			//itm.pos=itm.element.down("input").value
		})
		return this.aImages;
	},
	upload: function(){
		if(this.oUploading)return false;
		//var id = 'srteImage_' + (new Date()).getTime();
		var elImage = new Element('li', {className: 'g_srte_image_item'}).update('上传中...'),
			elCancel = new Element('a', {href: 'javascript:;'}).update('取消');
		elCancel.observe('click', this.cancel.bind(this));
		elImage.insert(elCancel);
		this.oUploading = {
			element: elImage,
			elCancel: elCancel,
			type:1	
		}
		this.elImageList.insert(elImage);
		this.disable();
	},
	onSelectPosition: function(e){
		var elt = e.element();
		if(elt.tagName.toUpperCase() == 'INPUT' && elt.type == 'radio'){
			var id = elt.up('.g_srte_image_item').id.replace('srteImage_', '');
			var oImage = this.getImageById(id);
			oImage.pos = parseInt($F(elt));
			
		}
	},
	onFinish: function(sId, sThumbSrc){
		if(!sId || !sThumbSrc)throw 'server error @ Seven.SRTE.Image.onFinish';
		//this.status = 0;
		this.oUploading.id = sId;
		this.oUploading.name = '<图片' + this.oUploading.id + '>';
		this.oUploading.src = sThumbSrc;
		this.oUploading.element.id = 'srteImage_' + this.oUploading.id;
		this.oUploading.element.update(Seven.SRTE.Image.template.image.evaluate(this.oUploading));
		this.oUploading.pos = 0;
		this.oUploading.elPos = this.oUploading.element.down('.position');
		this.oUploading.elPos.observe('click', this.onSelectPosition.bindAsEventListener(this));		
		this.oUploading.elDelete = this.oUploading.element.down('a');
		this.oUploading.elDelete.observe('click', this._delete.bind(this, this.oUploading.id));
		
		if(this.options.afterUpdate&&this.options.textarea){
			this.options.afterUpdate($(this.options.textarea),this.oUploading.name,this.currSel);
		}
		else
			this.oSRTE.elTextarea.value += this.oUploading.name;
		this.aImages.push(this.oUploading);	
		this.oUploading = null;
		this.enable();
	},
	cancel: function(){
		this.oUploading.element.remove();
		this.oUploading = null;
		this.enable();
	},
	_delete: function(sId){
		var oImage = this.getImageById(sId);
		if(oImage){
			oImage.element.remove();
			this.oSRTE.elTextarea.value = this.oSRTE.elTextarea.value.replace(oImage.name, '');
			this.aImages = this.aImages.without(oImage);
			oImage = null;
			this.currSel=null;
		}
	},
	enable: function(){
		this.elHandle.removeAttribute('disabled');
		//this.element.update('<a href="javascript:;">添加图片</a>');
		//this.element.observe('click', this.openFileWin.bindAsEventListener(this));
	},
	disable: function(){
		this.elHandle.setAttribute('disabled', 'disabled');
		//this.element.update('图片上传中...');
		//this.element.stopObserving();
	},
	getImageById: function(id){
		return this.aImages.find(function(oImage){if(oImage.id == id)return oImage});
	}
});

Object.extend(Seven.SRTE.Image, {
	instances: [],
	template: {
		image: new Template('\
			<div class="pic_inf">\
				<h4>#{name}</h4>\
				<img src="#{src}"/>\
				<a href="javascript:;" class="blue_l">删除</a>\
			</div>\
			<div class="hdl">\
				<label>图片描述(30字以内)</label>\
				<textarea>#{desc}</textarea>\
				<div class="tt">图片位置</div>\
				<ul class="position">\
					<li><label><input class="g_rad" name="pos_#{id}" type="radio" value="0" checked="checked" /><span class="left">左</span></label></li>\
					<li><label><input class="g_rad" name="pos_#{id}" type="radio" value="1" /><span class="center">中</span></label></li>\
					<li><label><input class="g_rad" name="pos_#{id}" type="radio" value="2" /><span class="right">右</span></label></li>\
				</ul>\
			</div>\
		')
	}
})


Seven.SRTE.Grab = Class.create({
	initialize: function(oSRTE, options){
		this.options = options || {};
		this.oSRTE = oSRTE;
		this.aGrabs = [];
		this.oUploading = null;
		this.currSel=null;//实例光标当前位置
		this.element = new Element('li', {className: 'Grab'});
		this.elHandle = new Element('input', {type: 'button', value: '采集网页'});
		this.element.insert(this.elHandle);
		this.elGrabList = new Element('ul', {className: 'g_srte_grab'});
		this.oSRTE.element.insert(this.elGrabList);
		if(options.window && $(options.window)){
			this.oWinFile = new Seven.Window({element: options.window, openHandles: [this.elHandle], onOK: function(){
				this.upload();
				//window.setTimeout(function(){this.onFinish(1,'/7dian/images/tmp_50.gif')}.bind(this), 2000)
			}.bind(this)});
		}else
			throw 'window initialize error @ Seven.SRTE.Grab.initialize: URL submitting window template must be indicate';
		Seven.SRTE.Grab.instances.push(this);
		if(this.options.textarea&&document.selection){
			$(this.options.textarea).observe('click', function(){
				this.currSel=document.selection.createRange();
			}.bindAsEventListener(this));
			$(this.options.textarea).observe('keyup',Seven.SRTE.onFieldKeyup.bindAsEventListener(this));
		}
	},
	load: function(oGrab){
		oGrab.element = new Element('li', {className: 'g_srte_image_item'}).update(Seven.SRTE.Grab.template.grab.evaluate(oGrab));
		//oGrab.element = new Element('li', {className: 'g_srte_image_item', id: oGrab.id}).update(Seven.SRTE.Grab.template.grab.evaluate(oGrab));
		//oGrab.element.select('input[type="radio"]')[oGrab.pos].checked = 'checked';
		oGrab.elDelete = oGrab.element.down('a');
		oGrab.elDelete.observe('click', this._delete.bind(this, oGrab.id));
		oGrab.elPos = oGrab.element.down('.position');
		oGrab.elText=oGrab.element.down('textarea');
		oGrab.elText.value=oGrab.text;
		oGrab.elPos.observe('click', this.onSelectPosition.bindAsEventListener(this));
		this.elGrabList.insert(oGrab.element);
		oGrab.element.select('input[type="radio"]')[oGrab.pos].checked = 'checked';
		this.aGrabs.push(oGrab);
	},
	save: function(){
		this.aGrabs.each(function(itm){
			itm.text=itm.element.down("textarea").value
		})
		return this.aGrabs;
	},
	upload: function(){
		if(this.oUploading)return false;
		var elGrab = new Element('li', {className: 'g_srte_image_item'}).update('上传中...'),
			elCancel = new Element('a', {href: 'javascript:;'}).update('取消');
		elCancel.observe('click', this.cancel.bind(this));
		elGrab.insert(elCancel);
		this.oUploading = {
			element: elGrab,
			elCancel: elCancel,
			type:0	
		}
		this.elGrabList.insert(elGrab);
		this.disable();
	},
	onFinish: function(sId, sThumbSrc){
		if(!sId || !sThumbSrc)throw 'server error @ Seven.SRTE.Grab.onFinish';
		this.oUploading.id = sId;
		this.oUploading.name = '<图片' + this.oUploading.id + '>';
		this.oUploading.src = sThumbSrc;
		this.oUploading.element.id = 'srteGrab_' + this.oUploading.id;
		this.oUploading.pos = 0;
		this.oUploading.element.update(Seven.SRTE.Grab.template.grab.evaluate(this.oUploading));
		this.oUploading.elPos = this.oUploading.element.down('.position');
		this.oUploading.elPos.observe('click', this.onSelectPosition.bindAsEventListener(this));
		this.oUploading.elDelete = this.oUploading.element.down('a');
		this.oUploading.elDelete.observe('click', this._delete.bind(this, this.oUploading.id));
		if(this.options.afterUpdate&&this.options.textarea)
			this.options.afterUpdate($(this.options.textarea),this.oUploading.name,this.currSel);
		else
			this.oSRTE.elTextarea.value += this.oUploading.name;
		this.aGrabs.push(this.oUploading);
		this.oUploading = null;
		this.enable();
	},
	cancel: function(){
		this.oUploading.element.remove();
		this.oUploading = null;
		this.enable();
	},
	onSelectPosition: function(e){
		var elt = e.element();
		if(elt.tagName.toUpperCase() == 'INPUT' && elt.type == 'radio'){
			var id = elt.up('.g_srte_image_item').id.replace('srteGrab_', '');
			var oGrab = this.getGrabById(id);
			oGrab.pos = parseInt($F(elt));
		}
	},
	_delete: function(sId){
		var oGrab = this.getGrabById(sId);
		if(oGrab){
			oGrab.element.remove();
			this.oSRTE.elTextarea.value = this.oSRTE.elTextarea.value.replace(oGrab.name, '');
			this.aGrabs = this.aGrabs.without(oGrab);
			oGrab = null;
			this.currSel=null;
		}
	},
	enable: function(){
		this.elHandle.removeAttribute('disabled');
		//this.element.update('<a href="javascript:;">添加图片</a>');
		//this.element.observe('click', this.openFileWin.bindAsEventListener(this));
	},
	disable: function(){
		this.elHandle.setAttribute('disabled', 'disabled');
		//this.element.update('图片上传中...');
		//this.element.stopObserving();
	},
	getGrabById: function(id){
		return this.aGrabs.find(function(oGrab){return oGrab.id == id});
	}
});

Object.extend(Seven.SRTE.Grab, {
	instances: [],
	template: {
		grab: new Template('\
			<div class="pic_inf">\
				<h4>#{name}</h4>\
				<img src="#{src}"/>\
				<a href="javascript:;" class="blue_l">删除</a>\
			</div>\
			<div class="hdl">\
				<label>采集网页名称(30字以内)</label>\
				<textarea>#{desc}</textarea>\
				<div class="tt">截图位置</div>\
				<ul class="position">\
					<li><label><input class="g_rad" name="pos_#{id}" type="radio" checked="checked" value="0" /><span class="left">左</span></label></li>\
					<li><label><input class="g_rad" name="pos_#{id}" type="radio" value="1" /><span class="center">中</span></label></li>\
					<li><label><input class="g_rad" name="pos_#{id}" type="radio" value="2" /><span class="right">右</span></label></li>\
				</ul>\
			</div>\
		')
	}
})




Seven.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};
  }
}
/*页面级通用脚本*/

/*
document.observe('dom:loaded',function(event){
	///////g_search
	var gSearchRoot = $('g_search'),
		gSearchInput = $('g_search_txt'),
		gSearchSelect = $('g_search_select'),
		gSearchToggleHandle =  $('g_search_select_toggle_hdlAll');
		gSearchSelect.hide();
	if(gSearchRoot && gSearchInput && gSearchSelect && gSearchToggleHandle){
		gSearchInput.observe('focus', function(){this.value = ''})
		gSearchSelect.hide();
		gSearchToggleHandle.observe('click', function(){
			gSearchSelect.toggle();
			gSearchRoot.toggleClassName('active');
		})
		function closeSelect(){
			gSearchSelect.hide();
			gSearchRoot.removeClassName('active');
		}
		
		LayerManager.register(gSearchSelect, {close: closeSelect, rootElement: gSearchRoot});
	}
	//////u_setting
	var uSettingRoot = $('u_setting'),
		uSettingMenuTogglehandle = $('u_setting_toggle_hdl');
	if(uSettingRoot)
		uSettingMenu = uSettingRoot.down('ul');
	if(uSettingRoot && uSettingMenuTogglehandle && uSettingMenu){
		var flag=0;
		uSettingMenuTogglehandle.observe('click', function(){
			uSettingRoot.toggleClassName('active');
			if(flag==0){
				uSettingMenu.setStyle({display:'block',zIndex:'3'});
				flag=1;
			}else{
				uSettingMenu.setStyle({display:'none',zIndex:'-1'});
				flag=0
			}
		})
		function closeSettingMenu(){
			uSettingRoot.removeClassName('active');
		}
		LayerManager.register(uSettingMenu, {close: closeSettingMenu, rootElement: uSettingRoot});
	}
})
*/
Seven.lifeshowCategoryInit = function(element){
	var elRoot = $(element);
	var elClasses = elRoot.select('.cls');
	elClasses.each(function(elCls){
		var elHdl = elCls.down('.op'),
			elSub = elCls.down('ul');
		if(elHdl && elSub && !elCls.hasClassName('locked'))
			elHdl.observe('click', function(){
				elSub.toggle();
				elCls.toggleClassName('expanded');
			})
	})
}

Seven.message = {
	requestUrl: 'messageCountAjax.html?method=getMessage',
	interval: 60000,
	timer: null,
	page: null,
	config: {
		'1': {
			update: function(data){
				var elMsgs = $('content').down('.p_message_tab').select('a'),
					newsCount = 0;
				elMsgs.each(function(elMsg, i){
					if(data.message[i] == 0){
						elMsg.className = 'no_record';
						elMsg.update('0条新');
					}else{
						elMsg.className = 'has_record';
						elMsg.update(data.message[i] + '条新');
						newsCount += data.message[i];
					}
				})
				if(newsCount){
					data.sound && Seven.message.playSound();
					data.flash && Seven.message.playAnimation(newsCount);
				}
			}
		}
	},
	initialize: function(){
		Seven.message.page = Seven.message.identify();
		if(Seven.message.page != 'UNKNOW'){
			Seven.message.loadConfig(Seven.message.page);
			Seven.message.timer = window.setInterval(Seven.message.getMsg, Seven.message.interval);
		}
	},
	getMsg: function(){
		new Ajax.Request(Seven.message.requestUrl, {
			method: 'GET',
			onSuccess: function(transport){
				var result = transport.responseText.evalJSON();
				Seven.message.update(result);
			}
		})
	},
	update: Prototype.emptyFunction,
	identify: function(){
		var url = location.toString();
		if(url.indexOf('method=messageHome') > -1)
			return 1;
		return 'UNKNOW';
	},
	loadConfig: function(config){
		Object.extend(Seven.message, Seven.message.config[config]);
	},
	playSound: function(){
		
	},
	playAnimation: function(nNewMsgs){
		//document.title = ''
	}
}


/*
 * @class Seven.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.
 */
Seven.Suggest = Class.create({
	initialize: function(element, url, options){
		this.element = $(element);
		this.elInput = this.element.down('.g_txt');
		this.queryUrl = url;
		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('<ul><li>没有结果。</li></ul>');
				this.elResult.show();
				//if(this.elResult.next()){this.elResult.next().hide()}
			},
			onNormalResult: Prototype.emptyFunction,
			onSelect: Prototype.emptyFunction,
			local: false,
			localQuery: Prototype.emptyFunction			
		}
			
		
		this.options = Object.extend(defaultConfig, options || {});
		
		if(this.options.local){
			this.options.checkInterval = 200;
			this.options.requestTimeout = 100;
		}		
		
		
		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});
		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('click', 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();
		}
		Seven.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){
		var elm = e.element();
		//newYardItem
		if(elm.id!="newYardItem"){
			e.stop();
			this.options.onSelect.bind(this)(elm);
			if(!this.options.multiSelect)
				this.elResult.hide();
		}
	},
	_onTyping: function(){
		if(!this.checkTimer)
			this.checkTimer = setInterval(function(){this._check()}.bind(this), this.options.checkInterval);		
	},
	endType: function(){
		if(this.checkTimer){
			this.checkTimer = clearInterval(this.checkTimer);
		}
		if(this.requestTimer){
			this.requestTimer = clearTimeout(this.requestTimer);
		}
	},
	_check: function(){
		var currentKey = this.elInput.getValue();
		if(this.options.minChars == 0 || (currentKey != this.lastKey)){
			if(this.requestTimer)
				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(Seven.Suggest, {
	instances: [],
	template: {
		resultItem: new Template('<a href="javascript:;">#{name}</a>')
	}
})


Seven.getUserGroups = function(){
	if(Seven.uGroups){
		Seven.uGroups = null;
	}
	new Ajax.Request('friendss.html?method=getFriendsCategoryInfo', {
		method: 'GET',
		onSuccess: function(transport){
			try{
				var result = transport.responseText.evalJSON();
				if(result.groups && result.groups.length){
					Seven.uGroups = result.groups;
					Seven.groupsToSelectOptions();
				}
			}catch(e){}
		}
	})
}

Seven.groupsToSelectOptions = function(){
	if(!Seven.uGroups || !Seven.uGroups.length)
		throw 'invalid Seven.uGroups when call Seven.groupsToSelectOptions';
	Seven.DB.selectOptions.groups = [];
	Seven.uGroups.each(function(gp){
		Seven.DB.selectOptions.groups.push([gp.name, gp.gid]);
	})
}


/***************************************/

Seven.initDateOptions = function(){
	Seven.DB.selectOptions.year = $A($R(1900, (new Date).getFullYear())).collect(function(y){return [y, y]});
	Seven.DB.selectOptions.month = $A($R(1, 12)).collect(function(m){return [m, m]});
	Seven.DB.selectOptions.day = $A($R(1, 31)).collect(function(d){return [d, d]});	
}

Seven.getDays = function(selectYear, selectMonth){
	var year = selectYear && selectYear.getValue() || 1900,
		month = selectMonth && selectMonth.getValue() || 1,
		days = [31,28,31,30,31,30,31,31,30,31,30,31], day;

	if(month == 2){
		if((year%4 == 0 && year%100 != 0) || year%400 == 0 || year < 1900)
			day = 29;
		else
			day = days[month-1];
	}else{
		day = days[month-1];
	}
	return $A($R(1, day));
}

/****************************************/
Seven.initUYards = function(yards){
	Seven.uYards = {};
	yards.each(function(y){
		Seven.uYards[y.yardId] = y;
	})
}

/*****************************************/
Seven.onAjaxCommonResponse = function(result, options){
	var options = Object.extend({
		show: 'seven',//native, seven, id
		message: {
			success: '成功',
			failure: '失败'
		},
		onSuccess: Prototype.emptyFunction
	}, options || {})
		
	switch(result){
		case '1':
			show(options.message.success);
			options.onSuccess();
			break;
		case '0':
			show(options.message.failure);
		case '3':
			options.onSuccess();
	}
	
	function show(message){
		switch(options.show){
			case 'native':
				alert(message);
				break;
			case 'seven':
				new Seven.Window({type: 'alert', content: message});
				break;
			default:
				var container = $(options.show);
				if(container)
					container.update(message);
				break;
		}
	}
	
}
/*****************************************/

Seven.uYards = {
	initialize: function(sUserId, fOnSuccess){
		if(!id)return;
		var url = 'yardAjax.html?method=userJoinYards',
			requestUrl = url + '&userId=' + id
		
		new Ajax.Request(requestUrl, {
			method: 'GET',
			onSuccess: function(transport){
				try{
					var result = transport.responseText.evalJSON();
					Seven.uYards = result;
					if(fOnSuccess)
						fOnSuccess();					
				}catch(e){}
			}
		})
	}
}


/**********************************
deprecated
***********************************/

var Suggest = Class.create({
	initialize: function(element, options){
		this.element = $(element);
		this.options = Object.extend({
			ajax: false,
			ajaxURL: null,
			dbURL: null
		}, options || {})
		this.db = {};
		this.selected = [];
		this.requestTimer = null;
		this.previousKey = '';
		this.elInput = this.element.down('.suggest_input');
		this.elSelected = this.element.down('.suggest_selected');
		this.elSuggest = this.element.down('.suggest_list');
		this.elSelectedInput = this.element.down('.suggest_selected_wrap');
		this.elSuggestLayer = this.element.down('.suggest_list_wrap');
		this.elSuggestOpenPredefinedHandle = this.element.down('.suggest_open_predefined_handle');
		this.elPredefined = this.element.down('.suggest_predefined');
		this.elSuggestLayer.hide();
		this.elPredefined.hide();
		this.sresize = new Seven.SimpleResize(this.elSuggestLayer);
		
		if(!this.options.ajax)
			this.initDB();

		//this.element.observe('click', this.onClick.bindAsEventListener(this));
		//this.elInput.observe('keydown', this.onKeydown.bindAsEventListener(this));
		this.elInput.observe('focus', this.onFocusInput.bindAsEventListener(this));
		this.elInput.observe('blur', this.onBlurInput.bindAsEventListener(this));
		this.elSuggestOpenPredefinedHandle.observe('click', function(){this.elPredefined.toggle()}.bind(this));
		this.elSuggest.observe('click', this.onClickSuggest.bindAsEventListener(this));
		this.elSelectedInput.observe('click', function(){this.elInput.focus()}.bind(this));
		this.elPredefined.observe('click', this.onClickSuggestPredefined.bindAsEventListener(this));
		this.elSelected.observe('click', function(e){
			var elt = e.element();
			if(elt.tagName.toUpperCase() == 'BUTTON'){
				this.reject(this.getSuggestObjectByElement(elt.up('.suggest_item')));
			}
			
		
		}.bindAsEventListener(this))
		
		
		
		LayerManager.register(this.elPredefined, {rootElement: this.element});
		LayerManager.register(this.elSuggestLayer, {close: this.closeSuggest.bind(this), rootElement: this.element});
		
		Suggest.instances.push(this);
	},
	onFocusInput: function(){
		this.doInputTimer = window.setInterval(function(){this.detectKey()}.bind(this), 100);
	},
	onBlurInput: function(){
		window.clearInterval(this.doInputTimer);
	},
	onClick: function(e){
		e.stop();
		var elm = e.element();
		if(elm == this.element){
			this.elInput.focus();
		}else if(elm == this.elShowSuggestHandle){
			
		}else if(elm == this.elInput){
			
		}
	
	},
	onKeydown: function(e){
		if(this.requestTimer)window.clearTimeout(this.requestTimer);
		if(e.keyCode)
 		switch(e.keyCode){
 			case 8:
 				if($F(this.elInput) == '' && this.elSelected.down('.suggest_item')){
 					var childs = this.elSelected.childNodes;
 					this.reject(this.getSuggestObjectByElement($(childs[childs.length - 1])));
 				}
 				break;
 			default:
 				this.requestTimer = window.setTimeout(function(){this.request()}.bind(this), 200);
 				break;
 		}
	},
	onClickSuggest: function(e){
		e.stop();
		var elm = e.element().up('.suggest_item');
		if(elm){
			var oSuggestItem = this.getSuggestObjectByElement(elm);
 		this.select(oSuggestItem);
 		if(!this.elSuggest.down('.suggest_item'))
 			this.closeSuggest();
		}
	},
	onClickSuggestPredefined: function(e){
		e.stop();
		var elm = e.element();
		if(elm.tagName.toUpperCase() == 'A'){
			var predefinedSelected = elm.href.match(/\#suggest_predefined_(.*)/)[1];
			if(predefinedSelected){
				if(this.requestTimer)
					window.clearTimeout(this.requestTimer);
				this.request(predefinedSelected);
			}
			
		}
		this.elPredefined.hide();
	},
	detectKey: function(){	
		var curKey = $F(this.elInput);
		if(!curKey.blank() && this.previousKey != curKey){
			window.clearTimeout(this.requestTimer);
			this.requestTimer = window.setTimeout(function(){this.request()}.bind(this), 200);
			this.previousKey = curKey;
		}
	},
	select: function(oSuggestItem){
		this.selected.push(oSuggestItem);
		this.elSelected.insert(oSuggestItem.element);
		oSuggestItem.selected = true;
	},
	radio: function(oSuggestItem){
		this.selected=[];
		this.selected.push(oSuggestItem);
		this.elSuggest.insert(this.elSelected.down("li"));
		this.elSelected.update(oSuggestItem.element);
		if(this.curResult=="ALL"&&this.elSelected.down("li")){
			this.elSuggest.insert(this.elSelected.down("li"))
			this.elSelected.update(oSuggestItem.element);
			//this.preResult=this.curResult;
		}
		else if(this.preResult!=this.curResult&&this.preResult!="ALL"){
			this.elSelected.update(oSuggestItem.element);
			this.preResult=this.curResult;
		}
		else{
			this.elSuggest.insert(this.elSelected.down("li"))
			this.elSelected.update(oSuggestItem.element);
		}
		oSuggestItem.selected = true;
	},
	reject: function(deletingItem){
		if(!deletingItem){
			if(this.selected.length)
				var deletingItem = this.selected.pop();//pop default
		}else	
			this.selected = this.selected.without(deletingItem);
		deletingItem.element.remove();
	},
	request: function(predefinedName){
		var result;
		this.elSuggest.update('查询中...');
		this.elSuggestLayer.show();
		
		window.setTimeout(function(){
 		if(!this.options.ajax){
   		if(predefinedName){
  			result = this.query({group: predefinedName});
  		}else{
    		var key = $F(this.elInput);
   		if(key.blank())return;
  			result = this.query({key: key});		        		 
  		}
 		}else{
 			//ajax request
 		}
 		
 		if(result.length >= 100){
 			//too much results	
 		}
 		
 		var resultHTML = (result.length ? '<p>共有' + result.length + '条记录</p>' : '<p>没有记录</p>') + result.collect(function(itm){return this.formatQueryResult(itm);}.bind(this)).join('');
			this.elSuggest.update(resultHTML || 'no result');
		}.bind(this), 100)
		
		

		
		/*
		var _rl = result.length;
		if(_rl <= 20){
			this.elSuggest.addClassName('small');
		}else if(_rl > 20 && _rl <= 100){
			this.elSuggest.addClassName('middle');
		}else{
			this.elSuggest.addClassName('large');
		}
		*/
		//this.elSuggestLayer.show();
		//this.elInput.clear(); 	
	},
	query: function(queryObject){
		var group = queryObject.group,
			key = queryObject.key,
			validDB = [],
			result = [];
		if(group){
			validDB = this.db[group];
		}else{
			validDB = this.db.ALL;
		}
		if(key){
			var reg = new RegExp(key), result_py, result_nor;
			
			/*
			
			if(/^[a-zA-Z]*$/.test(key)){//纯字母//拼音匹配
	var reg_cn = new RegExp("\\b"+ key +"[^,]+",'g');
	var result_py = this.db.pinyin._all.match(reg_cn, 'gi');
	if(result_py){
		for(var i = 0, j = result_py.length; i < j; i ++){
			result_py[i] = this.db.pinyin[result_py[i]].ori;
		}
		result_py = result_py.flatten().uniq();
		for(var i = 0, j = result_py.length; i < j; i ++){
			result_py[i] = this.getSuggetsObjectByUID(result_py[i]);
		}							
	}

			}
			
			*/
			
			
			//正常匹配
			result_nor = validDB.findAll(function(itm){
 				return reg.test(itm.name) || reg.test(itm.uid);
 			}) || [];
  			result = result_nor.concat(result_py || [])
		}else{
			result = validDB;
		}
		return result.reject(function(item){return this.selected.indexOf(item) > -1}.bind(this));
	},
	initDB: function(){
		if(!this.options.dbURL)
			throw 'dbURL is null';
		new Ajax.Request(this.options.dbURL, {
			method: 'GET',
			onSuccess: function(transport){
				var data = transport.responseText.evalJSON();
				var groupTemplate = new Template('<a href="#suggest_predefined_#{gid}">#{name}</a>');
//				var data = {};
// 				this.db.pinyin = {
//					_all: []
//				};
				//test data    				
//				data.groups = [{id: "1", name: "现在同事"}, {id: "2", name: "大学同学"}, {id: "3", name: "高中同学"}];
//				data.friends = [];

//				for(var i = 0; i < 1000; i ++){
//					var r = parseInt(Math.random() * 3) + 1 + '';
//					data.friends.push({name: "杜一飞", uid: i, gid: r});
//				}
//				data.friends.push({name: "阿飞", uid: 1001, gid: "1"});
				if(data){
					data.groups.each(parseGroup, this);
					data.friends.each(parseFriend, this);
					//this.db.pinyin._all = this.db.pinyin._all.join(',');
		    		//cache the all list
		  			//if(!this.db.ALL){
	  				temp = []
		   			for(var g in this.db){
		   				if(g == 'pinyin')continue;
		   				temp = temp.concat(this.db[g]);
		   			}
		   			this.db.ALL = temp;
			   		//}
		   			this.elPredefined.down('ul').insert({top: new Element('li').update('<a href="#suggest_predefined_ALL">所有类别</a>')});
				}
				
				
				
				
				function parseGroup(group){
					this.db[group.gid] = [];			
					this.elPredefined.down('ul').insert(new Element('li').update(groupTemplate.evaluate(group)));
				}
				
				function parseFriend(friend){
					var group = data.groups.find(function(group){
						return group.gid == friend.gid;
					})
					if(group){
						if(!this.db[group.gid])
							this.db[group.gid] = [];
						this.db[group.gid].push(friend);
						//var fn = friend.name.split('');
						/*
						for(var m = 0, n = fn.length; m < n; m ++){
						      fn[m] = (fn[m].charCodeAt() < 1000 || fn[m].charCodeAt() > 60000) ? fn[m] : lookUpWord(fn[m]);
						}
						var py = fn.join('');
						if(!this.db.pinyin[py])
							this.db.pinyin[py] = {
								ori: []
							}
						this.db.pinyin[py].ori.push(friend.uid);
						if(this.db.pinyin._all.indexOf(py) == -1)
							this.db.pinyin._all.push(py);
						*/
					}else{
						//alert('unkown group with uid: ' + friend.uid)
						//throw 'unkown group with uid: ' + friend.uid;
							
					}
				}				
			}.bind(this)
		});     		
	},
	formatQueryResult: function(itm){
		if(this.selected.indexOf(itm) > -1){
			return Suggest.template.selectedSuggestItem.evaluate(itm);
		}else{
			return Suggest.template.suggestItem.evaluate(itm);
		}
	},
	getSuggestObjectByElement: function(elm){
		var oSuggest = this.db.ALL.find(function(itm){return itm.uid == elm.id.replace('uid_', '')});
		//if(!oSuggest.element)
		oSuggest.element = elm;
		return oSuggest;
	},
	getSuggetsObjectByUID: function(uid){
		return this.db.ALL.find(function(itm){return itm.uid == uid});
	},
	closeSuggest: function(){
		this.elSuggest.update();
		this.elSuggestLayer.hide();
	},
	openSuggest: function(){
		LayerManager.active(this.elSuggestLayer);
		this.elSuggestLayer.show();
	},
	initBlackItem: function(item, wrap){
		//if(this.selected.find(function(selected){return selected.uid == item.uid})){
		//	alert('此用户已经选择。');
		//	return;
		//}
		
		var o = this.db.ALL.find(function(itm){return itm.uid == item.uid});
		if(o){
			o.element = new Element('ul').update(Suggest.template.suggestItem.evaluate(item)).down();
			o.selected = true;
			this.selected.push(o);
			$(wrap).insert(o.element);
		}	
	}

})

Object.extend(Suggest, {
	instances: [],
	template: {
		suggestItem: new Template('<li class="suggest_item" id="uid_#{uid}"><a href="javascript:;">#{name}<button type="button" hidefocus="true" ><img src="images/icon/delete.gif" alt="移除" title="移除" /></button></a></li>'),
		selectedSuggestItem: new Template('<li class="suggest_item selected" id="uid_#{uid}"><a href="javascript:;>#{name}<button hidefocus="true" ><img src="images/icon/delete.gif" /></button></a></li>')
	}
})

Seven.Folder= Class.create({
	initialize: function(btn,menu,options){
		this.trigger=$(btn);
		this.folder=$(menu);
		this.options={
			triggerClass:"folder_btn",
			triggerCurClass:"folder_btn_on",
			//slideDownTime:150,
			//slideUpTime:100,
			beforeFun:function(){},
			afterFun:function(){}
		}
		Object.extend(this.options,options);
		this.delay=null;
		this.trigger.addClassName(this.options.triggerClass)
		this.trigger.observe('mouseover',function(){
			this.clearDelay();
			this.slideDown();
		}.bindAsEventListener(this))
		
		this.folder.observe('mouseover',function(){
			this.clearDelay();
		}.bindAsEventListener(this))
		
		this.trigger.observe('mouseout',function(){
			var myThis=this;
			this.delay=setTimeout(function(){
				myThis.slideUp();
			},1);
		}.bindAsEventListener(this))
		
		this.folder.observe('mouseout',function(){
			var myThis=this;
			this.delay=setTimeout(function(){
				myThis.slideUp();
			},1);
	
		}.bindAsEventListener(this))
	},
	slideUp:function(){
		this.options.afterFun();
		//this.folder.slideUp(this.options.slideUpTime);
		this.folder.setStyle({display:"none"});
		this.trigger.removeClassName(this.options.triggerCurClass)
	},
	slideDown:function(){
		this.options.beforeFun();
		//this.folder.slideDown(this.options.slideDownTime);
		this.folder.setStyle({display:"block"});
		this.trigger.addClassName(this.options.triggerCurClass)
	},
	clearDelay:function(){
		if(this.delay!=null) {
			clearTimeout(this.delay)
		}	
	}
	
})
Seven.Folder.instances=[];
	


