/**
 * 显示Ajax正在处理数据的提示
 */
function loading(text) {
	var dl = new Element('div', {
		id: 'loading',
		html: (text?(text):'正在处理数据，请稍侯……')+'<br /><img src="'+'my/media/ajax_loader.gif" border=0 />',
		styles: {
			'width': '168px',
			'height': '60px',
			'padding': '6px',
			'position': 'absolute',
			'top': 0,
			'left': 0,
			'background-color':'#FFF',
			'color': '#666',
			'border':'#F90 solid 2px',
			'z-index':'1001'
		}
	});
	dl.inject($('pageback'), 'before');
}

/**
 * 隐藏正在处理
 */
function dLoading() {
	if ($('loading')) {
		$('loading').destroy();
	}
}

/**
 * 生成随机数字串，防止Ajax返回重复内容
 */
function r() {
	var r = Math.random(100)*10000;
	return r.toString().substr(0, 4);
}

// 无提示关闭窗口
function closeWindow() { 
	var ua=navigator.userAgent 
	var ie=navigator.appName=="Microsoft Internet Explorer"?true:false 
	if(ie){ 
    var IEversion=parseFloat(ua.substring(ua.indexOf("MSIE ")+5,ua.indexOf(";",ua.indexOf("MSIE ")))) 
	 if(IEversion< 5.5){ 
			var str  = '<object id=noTipClose classid="clsid:ADB880A6-D8FF-11CF-9377-00AA003B7A11">' 
			str += '<param name="Command" value="Close"></object>'; 
			document.body.insertAdjacentHTML("beforeEnd", str); 
			document.all.noTipClose.Click(); 
		} 
		else{ 
			window.opener =null; 
			window.close(); 
		} 
	} 
	else{ 
		window.close() 
	} 
} 

// 在可视化编辑器中插入内部链接
var currenteditor; // 保存当前的编辑器
function createInnerLink(editor) {
	currenteditor = editor;
	if(document.all) { 
		var text = editor.EditorDocument.selection.createRange().text; 
	} 
	else {
		var text = editor.EditorWindow.getSelection(); 
	} 
	if(text=="") {
		alert("请选择选要链接的文章标题");
		return false;
	}
	var topictitle = encodeURI(text);
	var request_url = "/modules/Wiki/index.php"; 
	// 到后台检查要加入的内部链接是否定存在，如果存在的话则直接生成相应的链接，如果不存在则生成新建条目的链接
	var request_pars = 'action=createInnerLink&topictitle='+topictitle+'&randcache='+Math.random(0,2000);
	var myAjax = new Ajax.Updater(
	"confirmbox_content",
	request_url,
	{ 
		method     : 'get', 
		parameters : request_pars,
		onFailure  : reportError, 
		onComplete : function(){},
		evalScripts: true
	});
	// 用于调试输出
	showConfirmbox();
}

// 用户登录
function loginUser(post) {
	// 载入客户端加密组件
	var js_md5 = new Asset.javascript('vendor/md5/md5.js');
	var url = "index.php?mod=system&act=loginuser&r="+Math.random();
	if(!post) {
		// 请求登录页面
		var lrh = new Request.HTML({
			url: url,
			onRequest: loading,
			onComplete: function(tree, els, html, js) {
					dLoading();
					win_login = new HiWindow({
						"name": "win_login",
						"width": 370,
						"height": 400,
						"title": "请填写登录信息",
						"content": html,
						"showmask": true
					});
					// 处理回车事件
					$('name').addEvent('keydown', function(event) {
						if(event.code==13) {
							$('password').focus();
							return false;
						}
					});
					$('password').addEvent('keydown', function(event) {
						if(event.code==13) {
							loginUser(true);
							return false;
						}
					});
					$('name').focus();
			}
		}).get();
	}
	else {
		var rj = new Request.JSON({
			url: url,
			onComplete: function(j) {
					if(j.result) {
						win_login.setContent('<div style="padding:10px;">恭喜，您已成功登录，稍候页面刷新...</div>');
						LOGGED = true;
						(function() {
							window.location.href = 'index.php?mod='+MODULE+'&act='+ACTION+(ID?('&id='+ID):'')+(PAGE?('&page='+PAGE):'');
						}
						).delay(1000);
					}
					else {
						$('login_error').innerHTML = j.error?j.error:'未知登录错误，请重试';
						var myFx = new Fx.Tween('login_error');
						myFx.start('opacity', 1, 0).chain(function(){
							myFx.start('opacity', 0, 1);
						}).chain(function(){
							myFx.start('opacity', 1, 0);
						}).chain(function(){
							myFx.start('opacity', 0, 1);
						});
					}
			}
		});
		rj.post({'password':hex_md5($('password').value), 'name':$('name').value, 'autologin':($('autologin').checked?1:0)});
	}
}

/**
 * 网站时钟
 */ 
function showSiteClock(el){ 
	var day=""; 
	var month=""; 
	var ampm=""; 
	var ampmhour=""; 
	var myweekday=""; 
	var year=""; 
	var myHours=""; 
	var myMinutes=""; 
	var mySeconds=""; 
	mydate=new Date(); 
	myweekday=mydate.getDay(); 
	mymonth=parseInt(mydate.getMonth()+1)<10?"0"+(mydate.getMonth()+1):mydate.getMonth()+1; 
	myday= mydate.getDate(); 
	myyear= mydate.getYear(); 
	myHours = mydate.getHours(); 
	myMinutes = mydate.getMinutes(); 
	mySeconds = parseInt(mydate.getSeconds())<10?"0"+mydate.getSeconds():mydate.getSeconds(); 
	year=(myyear > 200) ? myyear : 1900 + myyear; 
	if(myweekday == 0) 
	weekday=" 星期日 "; 
	else if(myweekday == 1) 
	weekday=" 星期一 "; 
	else if(myweekday == 2) 
	weekday=" 星期二 "; 
	else if(myweekday == 3) 
	weekday=" 星期三 "; 
	else if(myweekday == 4) 
	weekday=" 星期四 "; 
	else if(myweekday == 5) 
	weekday=" 星期五 "; 
	else if(myweekday == 6) 
	weekday=" 星期六 "; 
	$(el).innerHTML=year+"年"+mymonth+"月"+myday+"日 "+myHours+":"+myMinutes+":"+mySeconds+" "+weekday; 
	setTimeout("showSiteClock()", 1000); 
} 


/**
 * 判断字符串中英混合字符串的真实长度
 * 
 * @param {Object} str
 */
function strLength(str) {
	var intLength=0;
	for (var i=0;i<str.length; i++) {
		if ((str.charCodeAt(i) < 0) || (str.charCodeAt(i) > 255))
			intLength=intLength+2
		else
			intLength=intLength+1
	}
	return intLength;
}

/**
 * 页首的收放
 */
function headerToggle() {
	var up = 'my/media/toggleup.gif';
	var down = 'my/media/toggledown.gif';
	if($('headertoggleimg').src.search('down')>0) {
		$('header').setStyle('display', 'block');
		$('headertoggleimg').src = up;
	}
	else {
		$('header').setStyle('display', 'none');
		$('headertoggleimg').src = down;
	}
}

/**
 * 右下角提示框
 */
var cornerTip = new Class({
	
	initialize: function(text){
		this.height = 140;
		this.width = 300;
	    this.domtip = new Element('div', {
			id: 'cornertip',
			styles: {
				'position': 'absolute',
				'width': this.width,
				'height': this.height,
				'right': 0,
				'top': 0,
				'background-color': '#F00',
				'color': '#FFF',	
				'border': '#F90 solid 4px',
				'padding': 6
			}
		});
		
		// 关闭按钮
		var close = new Element('div', {
			id: 'cornertip_close',
			html: '关闭',
			styles: {
				'cursor': 'pointer',
				'text-align': 'right'
			}
		});
		close.addEvent('click', this.close.bind(this));
		close.inject(this.domtip, 'top');
		
		// 内容容器
		this.content = new Element('div', {
			id: 'cornertip_content',
			html: text
		});
		this.content.inject(this.domtip, 'bottom');

	    this.domtip.inject('pageback', 'after');
		this._rePosition();
		
		// 窗口改变大小或滚动时保持位置
		window.addEvents({
			'resize': this._rePosition.bind(this),
			'scroll': this._rePosition.bind(this)
		});

		// 窗口标题闪烁
		title = window.document.title;
		var a = '★您有新消息★';
		var b = '☆您有新消息☆';
		window.document.title = a+title;
		function titleFlicker() {
			if (window.document.title == (a+title)) {
				window.document.title = b+title;
			}
			else if(window.document.title == b+title) {
				window.document.title = a+title;
			}
		}
		titleFlicker.periodical(1000);
		
	},
	
	// 重定义位置
	_rePosition: function() {
		var vh = document.documentElement.clientHeight;
		var sh = document.body.scrollTop;
		var top = vh+sh-this.height+this._top()-23;
		if (top > 0) {
			this.domtip.setStyle('top', top);
		}		
	},
	
	// 获取页面上部卷去的高度
    _top: function(){
        var w3c=(document.getElementById)? true: false;
        var agt=navigator.userAgent.toLowerCase();
        var ie = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1) && (agt.indexOf("omniweb") == -1));

        function IeTrueBody(){
        return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body;
        }

        function GetScrollTop(){
        return ie ? IeTrueBody().scrollTop : window.pageYOffset;
        }

        return GetScrollTop();
    },
	
	// 显示提示
	show: function(){      
	   //this.myFx.slideIn();
	},
	
	// 隐藏提示
	close: function() {
		window.removeEvent('resize', this._rePosition);
		window.removeEvent('scroll', this._rePosition);
		
		// 恢复原标题
		window.document.title = title;
		
		this.domtip.destroy();
	},
	
	setText: function(text) {
		this.content.innerHTML = text;
	}
});

var Roar = new Class({

	Implements: [Options, Events, Chain],

	options: {
		duration: 5000,
		position: 'upperRight',
		container: null,
		bodyFx: null,
		itemFx: null,
		margin: {x: 10, y: 10},
		offset: 10,
		className: 'roar',
		onShow: $empty,
		onHide: $empty,
		onRender: $empty
	},

	initialize: function(options) {
		this.setOptions(options);
		this.items = [];
		this.container = $(this.options.container) || document;
	},

	alert: function(title, message, options) {
		var params = Array.link(arguments, {title: String.type, message: String.type, options: Object.type});
		var items = [new Element('h3', {'html': $pick(params.title, '')})];
		if (params.message) items.push(new Element('p', {'html': params.message}));
		return this.inject(items, params.options);
	},

	inject: function(elements, options) {
		if (!this.body) this.render();
		options = options || {};

		var offset = [-this.options.offset, 0];
		var last = this.items.getLast();
		if (last) {
			offset[0] = last.retrieve('roar:offset');
			offset[1] = offset[0] + last.offsetHeight + this.options.offset;
		}
		var to = {'opacity': 1};
		to[this.align.y] = offset;

		var item = new Element('div', {
			'class': this.options.className,
			'opacity': 0
		}).adopt(
			new Element('div', {
				'class': 'roar-bg',
				'opacity': 0.7
			}),
			elements
		);

		item.setStyle(this.align.x, 0).store('roar:offset', offset[1]).set('morph', $merge({
			unit: 'px',
			link: 'cancel',
			onStart: Chain.prototype.clearChain,
			transition: Fx.Transitions.Back.easeOut
		}, this.options.itemFx));

		var remove = this.remove.create({
			bind: this,
			arguments: [item],
			delay: 10
		});
		this.items.push(item.addEvent('click', remove));

		if (this.options.duration) {
			var over = false;
			var trigger = (function() {
				trigger = null;
				if (!over) remove();
			}).delay(this.options.duration);
			item.addEvents({
				mouseover: function() {
					over = true;
				},
				mouseout: function() {
					over = false;
					if (!trigger) remove();
				}
			});
		}
		item.inject(this.body).morph(to);
		return this.fireEvent('onShow', [item, this.items.length]);
	},

	remove: function(item) {
		var index = this.items.indexOf(item);
		if (index == -1) return this;
		this.items.splice(index, 1);
		item.removeEvents();
		var to = {opacity: 0};
		to[this.align.y] = item.getStyle(this.align.y).toInt() - item.offsetHeight - this.options.offset;
		item.morph(to).get('morph').chain(item.destroy.bind(item));
		return this.fireEvent('onHide', [item, this.items.length]).callChain(item);
	},

	empty: function() {
		while (this.items.length) this.remove(this.items[0]);
		return this;
	},

	render: function() {
		this.position = this.options.position;
		if ($type(this.position) == 'string') {
			var position = {x: 'center', y: 'center'};
			this.align = {x: 'left', y: 'top'};
			if ((/left|west/i).test(this.position)) position.x = 'left';
			else if ((/right|east/i).test(this.position)) this.align.x = position.x = 'right';
			if ((/upper|top|north/i).test(this.position)) position.y = 'top';
			else if ((/bottom|lower|south/i).test(this.position)) this.align.y = position.y = 'bottom';
			this.position = position;
		}
		this.body = new Element('div', {'class': 'roar-body'}).inject(document.body);
		if (Browser.Engine.trident4) this.body.addClass('roar-body-ugly');
		this.moveTo = this.body.setStyles.bind(this.body);
		this.reposition();
		if (this.options.bodyFx) {
			var morph = new Fx.Morph(this.body, $merge({
				unit: 'px',
				chain: 'cancel',
				transition: Fx.Transitions.Circ.easeOut
			}, this.options.bodyFx));
			this.moveTo = morph.start.bind(morph);
		}
		var repos = this.reposition.bind(this);
		window.addEvents({
			scroll: repos,
			resize: repos
		});
		this.fireEvent('onRender', this.body);
	},

	reposition: function() {
		var max = document.getCoordinates(), scroll = document.getScroll(), margin = this.options.margin;
		max.left += scroll.x;
		max.right += scroll.x;
		max.top += scroll.y;
		max.bottom += scroll.y;
		var rel = ($type(this.container) == 'element') ? this.container.getCoordinates() : max;
		this.moveTo({
			left: (this.position.x == 'right')
				? (Math.min(rel.right, max.right) - margin.x)
				: (Math.max(rel.left, max.left) + margin.x),
			top: (this.position.y == 'bottom')
				? (Math.min(rel.bottom, max.bottom) - margin.y)
				: (Math.max(rel.top, max.top) + margin.y)
		});
	}

});


/**
 * 监听用户的最新消息
 */
function monitor() {
	// 当前已经在收件箱页面、提示已经显示、未登录的情况下不做操作
	if(!LOGGED) return false;
	var rh = new Request.JSON({
		url: 'index.php?mod=user',
		onRequest: loading,
		onComplete: function(j) {
			dLoading();
			if(j.result) {
				var c = '<a style="color:#FFF;" href="index.php?mod=sms&amp;act=myinbox">您有'+j.data.unreadsms+'封未读的消息</a>';
				if (typeof(cornertip)!='undefined') {
					cornertip.setText(c);
				}
				else {
					if (ACTION != 'myinbox') {
						cornertip = new cornerTip(c);
					}
				}
			}
			else {
				if(j.message) {
					if(j.type==4) {
						window.location.reload();
					}
					hiisee.tip(j.message);
					dbug.log(j.error);
				}
				else {
					return false;
				}
			}
		}
	}).get({'act': 'monitor', 'r': r()});
}

/**
 * 焦点区域
 * 
 * 可通过键盘移动焦点
 */
var HiFocusArea = new Class({
	options: {
		el:'hifocusarea',
		actions: {},
		itemtype: 'button' // 控件的类型，可选button或a
	},
	
	initialize: function(options) {
		this.setOptions(options);
		el = $(this.options.el);
		this.el = el;
		
		if(!options.actions) options.actions = {};
		
		el.getChildren().each(function(e) {
			e.addEvent('keyup', function(e) {
				switch (e.key) {
					// 右键头
					case 'right':
						this.goNext(e.target);
					break;
					// 左键头
					case 'left':
						this.goPrev(e.target);
					break;
					// 回车执行按钮绑定的动作
					case 'enter':
						if(options.actions[e.target.id]) {
							options.actions[e.target.id]();
						}
					break;
				}
				
			}.bind(this));
		}.bind(this));
		el.getFirst().focus();
	},
	
	goNext: function(btn) {
		var next = btn.getNext();
		if (next) {
			btn.getNext().focus();
		}
		else {
			this.el.getFirst().focus();
		}
	},
	
	goPrev: function(btn) {
		var prev = btn.getPrevious();
		if(prev) {
			prev.focus();
		}
		else {
			this.el.getLast().focus();
		}
	},
	
	goFirst: function() {
		
	},
	
	goLast: function() {
		
	}
});
HiFocusArea.implement(new Events);
HiFocusArea.implement(new Options);

/**
 * 还思浮动窗口
 * @param {Object} title
 * @param {Object} text
 */
var ALL_HIWINDOWS = [];

var HiWindow = new Class({
	options: {
		width: 360,
		height: 200,
		left:null,
		top:null,
		zIndex:800,
		onShow: Class.empty,
		onClose: Class.empty,
		onHide: Class.empty
	},
	
	// 初始化函数
	initialize: function(options){
		this.setOptions(options);
		this.top = options.top;
		this.left = options.left;
		this.width = options.width?(options.width+20):400;
		this.height = options.height?(options.height+26):390;
		
		// 可拖动，如不明确禁止即为可拖动
		this.dragable = options.dragable===false?false:true;
		
		// 如果用户没有指定窗口名称则以时间戳命名
		this.name = "hw_"+(options.name?options.name:($time().toString().substr(8)));
		// 如果已经存在则不做任何操作
		if($(this.name)) {
			return false;
		}
		/* 创建窗口的各个部件 */
		this.zIndex = options.zIndex?options.zIndex:800;
		// 窗体
		var dom_outpanel = new Element("div", {
			"id": this.name,
			"styles": {
				"position": "absolute",
				"width": this.width,
				"top": this.top,
				"left": this.left,
				"z-index":  this.zIndex// 新生成的窗口在最上部
			}
		});
		this.outpanel = dom_outpanel;
		// 点击窗体时的焦点转换
		dom_outpanel.addEvent("click", function() {
			if (!this.focused) {
				this.focus();
			}
		}.bind(this));
		
		// 监听键盘事件
		document.addEvent('keydown', this.onCommand.bindWithEvent(this));
		
		// 只有指定了窗口标题才生成标题条
		if (options.title) {
			// 标题条
			var dom_title = new Element("div", {
				"id": this.name + "_title"
			});
			
			// 生成窗口按钮条
			var dom_btnset = new Element("div", {
				"id": this.name + "_btnset",
				"styles": {
					'text-align': 'right',
					'margin-top': -20,
					'height': 20,
					'float': 'right',
					'width': 66
				}
			});
			
			// 关闭按钮
			var dom_btnClose = new Element("a", {
				"id": this.name + "_close",
				"href": '#',
				"title": "关闭",
				"class": "btn",
				"innerHTML": "&nbsp;"
			});
			dom_btnClose.addClass('btn_close');
			dom_btnClose.addEvent("click", function(){
				this.close();
				return false;
			}.bind(this));
			
			// 最大化按钮
			var dom_btnMax = new Element("a", {
				"id": this.name + "_max",
				"href": '#',
				"title": "最大化",
				"class": "btn",
				"innerHTML": "&nbsp;"
			});
			dom_btnMax.addClass("btn_max");
			dom_btnMax.addEvent("click", function(){
				if (this.status == "maxed") {
					// 设置窗体大小
					dom_outpanel.setStyles({
						"left": this.left,
						"top": this.top,
						"width": this.width,
						"height": undefined
					});
					// 设置窗体大小
					dom_content.setStyles({
						"width": this.width-12,
						"height": undefined
					});
					dom_btnMax.setStyle("background-position", -18);
					this.status = "normal";
				}
				else {
					var ws = window.getSize();
					// 设置窗体大小
					dom_outpanel.setStyles({
						"left": 0,
						"top": 0,
						"width": ws.x - 4,
						"height": ws.y - 4
					});
					// 设定内容大小
					dom_content.setStyles({
						"width": ws.x - 4,
						"height": ws.y - 4
					});
					// 如果是在最小化状态到最大化，则恢复内容的显示
					if (dom_content.getStyle('display') == "none") {
						dom_content.setStyle("display", "block");
					}
					// 切换图标
					dom_btnMax.setStyle("background-position", -58);
					this.status = "maxed";
				}
				return false;
			}.bind(this));
			
			// 最小化按钮
			var dom_btnMini = new Element("a", {
				"id": this.name + "_mini",
				"href": '#',
				"title": "最小化",
				"class": "btn",
				"innerHTML": "&nbsp;"
			});
			dom_btnMini.addClass('btn_mini');
			dom_btnMini.addEvent("click", this.minimize.bind(this));
			
			// 组装标题条
			dom_btnset.adopt(dom_btnMini, dom_btnMax, dom_btnClose)
		}
		
		// 窗口内容
		var dom_content = new Element("div", {
			"id": this.name + "_content",
			"class": 'content',
			"styles": {
				'margin':0,
				'float': 'left',
				'padding':4,
				'overflow': 'auto',
				'width': (this.width-12)
			}
		});
		
		// 组装窗口
		if(dom_title) {
			dom_outpanel.adopt(dom_title, dom_btnset);
			// 设置窗口标题内容
			dom_title.appendText(options.title);

			// 设置标题条样式
			dom_title.addClass('title');
			dom_btnClose.addClass('btn')
		}
		dom_outpanel.adopt(dom_content);
		dom_outpanel.inject(document.body, 'bottom');
		
		
		// 设置窗口里的内容
		if (typeof(options.content) == 'object') {
			dom_content.grab(options.content);
		}
		else {
			dom_content.set("html", options.content);
		}
		
		// 窗口样式
		dom_outpanel.addClass('hiiseeWindow');
		
		// 确定窗口显示的位置
		var ps = dom_outpanel.getSize(); // 面板尺寸
		var ws = window.getSize(); // 窗口尺寸
		if(options.left==null) {
			this.left = ws.x/2-ps.x/2;
		}
		if(options.top==null) {
			// 滚动位置
			var ss = window.getScrollSize();
			var top = (ws.y/2-ps.y/2)+this._getTop();
			this.top = top>80?top:80;
		}
		dom_outpanel.setStyles({
			"left":this.left,
			"top":this.top
		});
		
		// 使用窗口可拖动
		if (this.dragable) {
			var dragoptions = {
				handle: dom_title ? dom_title : dom_content,
				onStart: function(){
				}.bind(this)				,
				onComplete: function(){
				}.bind(this)
			}
			dom_outpanel.makeDraggable(dragoptions);
		}
		
		// 设置对象属性以便返回后的操作
		this.options = options;
		this.content = dom_content;
		this.status = "normal";

		// 显示遮罩
		if(options.showmask) {
			this.showMask();
		}
		
		// 载入远程内容
		if(options.url) {
			this.load();
		}
		
		// 维护保存所有窗口的全局变量
		ALL_HIWINDOWS.push(this);
		
		// 窗口获取焦点
		this.focus();

		// 触发onShow事件
		this.fireEvent("onShow", this, 20);
	},
	
	// 获取页面上部卷去的高度
    _getTop: function(){
        var w3c=(document.getElementById)? true: false;
        var agt=navigator.userAgent.toLowerCase();
        var ie = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1) && (agt.indexOf("omniweb") == -1));

        function IeTrueBody(){
        return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body;
        }

        function GetScrollTop(){
        return ie ? IeTrueBody().scrollTop : window.pageYOffset;
        }

        return GetScrollTop();
    },
	
	// 响应键盘及鼠标动作
	onCommand: function(e, mouse) {
		if (e.key && !e.shift) 
			switch (e.key) {
				case "esc":
					this.close();
				return;
			}
	},
	
	// 关闭窗口
	close: function() {
		// 关闭遮罩
		if(this.options.showmask) {
			this.dropMask();
		}
		if (this.outpanel) {
			this.outpanel.destroy();
		}
		this.fireEvent("onClose", [this], 20);
	},
	
	// 收起
	minimize: function () {
		// 如果已经在最小化状态则恢复
		if(this.status=="minied") {
			// 恢复窗体大小
			this.outpanel.setStyles({
				"width": this.width,
				"height": undefined
			});
			// 恢复内容大小
			this.content.setStyles({
				"display": "block",
				"width": this.width-12,
				"height": undefined
			});
			this.status = "normal";
		}
		else {
			// 如果是在最大化情况下最小化，恢复原始位置
			if(this.status=="maxed") {
				this.outpanel.setStyles({"top": this.top, "left":this.left});
			}
			this.outpanel.setStyles({"width":this.width, "height":24});
			this.content.setStyle("display", "none");
			this.status = "minied";
		}
		return false;
	},
	
	// 设置窗口内容
	setContent: function(html) {
		this.content.innerHTML = html;
		this.rePosition();
	},
	
	// 设置窗口位置坐标
	setPosition: function(x, y) {
		
	},
	
	/**
	 * 获取焦点
	 */
	focus: function() {
		var wins = $$("div.hiiseeWindow");
		wins.each(function(win) {
			if(win.style.zIndex>200) {
				// 每个窗口层之间的z-index相差5留出遮罩的位置
				win.setStyle("z-index", win.style.zIndex-5);
				if ($(win.id + '_mask')) {
					$(win.id + '_mask').setStyle("z-index", win.style.zIndex - 1);
				}
			}
		});
		this.outpanel.setStyle("z-index", 800);
		this.focused = true;
	},
	
	// 显示遮罩
	showMask: function() {
		// 如果已经存在遮罩，则将其移至新生成窗口的下一层，遮住其它窗口
			var ws = window.getScrollSize();
			// 所在的层比窗口低一层
			var zIndex = this.zIndex-1;
			var screenmask = new Element("div", {
				"id": this.name+'_mask',
				"styles": {
					"left": 0,
					"top": 0,
					"position": "absolute",
					"width": ws.x,
					"height": ws.y,
					"background-color": "#000",
					"opacity": 0.3,
					"z-index": zIndex
				}
			});
			// 隐藏窗口之外的select
			var sels = $$("#pagerback select");
			sels.each(function(sel) {
				sel.setStyle("display", "none");
			});
			
			// 隐藏窗口之外的flash
			var flashes = $$('#pageback object');
			flashes.each(function(flash) {
				flash.setStyle("display", "none");
			});
			
			
			this.mask = screenmask;
			screenmask.addEvent('click', function() {
				this.focus();
			}.bind(this));
			screenmask.inject(document.body, 'bottom');
	},
	
	// 关闭遮罩
	dropMask: function() {
		// 显示所有select
		var sels = $$("select");
		sels.each(function(sel){
			sel.setStyle("display", "");
		});
		
		// 显示所有flash
		var flashes = $$("object");
		flashes.each(function(flash){
			flash.setStyle("display", "");
		});
		
		// 删除遮罩层
		if(this.mask) {
			this.mask.destroy();
		}
	},
	
	// 重新调整窗口位置到居中
	rePosition: function() {
		var ps = this.outpanel.getSize(); // 面板尺寸
		if(!ps) {
			ps.x = 200;
		}
		var ws = window.getSize(); // 窗口尺寸
		if(!this.options.left) {
			this.left = ws.x/2-ps.x/2;
		}
		// 滚动位置
		var ss = window.getScroll();
		var top = ((ss.y+ws.y/2)-ps.y/2);
		this.top = top>80?top:80;

		this.outpanel.setStyles({
			"left":this.left,
			"top":this.top,
			"width":ps.x+"px"
		});
	},
	
	/**
	 * 载入远程数据
	 */
	load: function() {
		new Request.HTML({
			url:this.options.url+'&r='+r(),
			onRequest:loading,
			onComplete: function(tree, elements, html, js) {
				dLoading();
				this.content.innerHTML = html;
				
				// 自动为关闭窗口的按钮增加关闭动作
				if($('btn_close')) {
					$('btn_close').addEvent('click', function(){
						this.close();
					}.bind(this));
				}

				// 如果有控件的话，第一个控件获取焦点
				var input = this.content.getElement('input[type!=hidden]');
				if(input) {
					input.focus();
				}

				// 自动为按钮区域增加箭头焦点控制
				if($('hifocusarea')) {
					new HiFocusArea({
						el: 'hifocusarea'
					});
				}
				// 重新调整窗口位置
				this.rePosition();
				this.focus();
				
				this.fireEvent('afterLoad', [html, elements, tree]);
			}.bind(this)
		}).get(this.options.params);
	}
});

HiWindow.implement(new Events);
HiWindow.implement(new Options);

/**
 * Ajax翻页
 */
HiPager = new Class({
    /*Events
        beforeLoad 读取数据前执行
        afterLoad 读取数据后执行
    */
    Implements: [Events, Options],    
 
    options:{
		//后台URL
        url:'',         
	    className:'paging',
	
		// 每页记录数
	    pagesize:10, 

	    //el:控件容器,showNumber:是否显示数字按钮,showText:是否显示页码
	    head:{el:document.body, showNumber:false, showText:true},
	    foot:{el:null,showNumber: true, showText:false}
    },
    
    initialize: function(options){        
       this.setOptions(options);
	
		// 当前页
        this.index = 0; 
        this.pagesize = this.options.pagesize;
		
		$(this.options.head.el).empty();    
        
        this.head = new Element('span', {'class':this.options.className});       
        this.head.injectInside($(this.options.head.el));

        this.loader = new Request.JSON({
			url:this.options.url,
			onRequest:loading,
			onComplete:this.onComplete.bind(this)
		});
     	
		//load参数
        this.param = options.param; 

        if(this.options.foot.el){
            this.foot = this.head.clone();
            this.foot.injectInside($(this.options.foot.el));
        }
    },
    
    onComplete: function(data, text){    
		dLoading();
		if (data.result) {
			data = data ||
			{};
			if (this.index == 0) {
				this.total = data.pagedata.record_count || 0; //总记录数
			}
			// 总页数
			this.totalpage = Math.ceil(this.total / this.pagesize);
			
			this.create(this.head, this.options.head);
			
			if (this.foot) {
				this.create(this.foot, this.options.foot);
			}
			
			this.fireEvent('afterLoad', [data, text]);
		}
		else {
			alert('程序出现错误，请联系管理员');
			dbug.log(data.error);
		}
    },
  
    create: function(panel, options){
        panel.empty();
                
        if(this.index>0){
            var prev = new Element('a', {
				'html':'&nbsp',
				'class':'prev',
				'href':'javascript:void(null)',
				'events': {
					'click':this.click.bind(this,this.index-1)
				}
			});
            panel.grab(prev);
        }  
        
        if(options.showNumber){  
            var beginInx = this.index-2<0?0:this.index-2;
            var endIdx = this.index+2>this.totalpage?this.totalpage:this.index+2;
            
            if(beginInx>0) panel.grab(this.createNumber(0));
            if(beginInx>1) panel.grab(this.createNumber(1));
            if(beginInx>2) panel.grab(this.createSplit());        
            
            for(var i=beginInx; i<endIdx; i++){
                panel.grab(this.createNumber(i));
            }
            
            if(endIdx<this.totalpage-2) panel.grab(this.createSplit());
            if(endIdx<this.totalpage-1) panel.grab(this.createNumber(this.totalpage-2));
            if(endIdx<this.totalpage) panel.grab(this.createNumber(this.totalpage-1));
        }   

        if(this.index<this.totalpage-1){
            var next = new Element('a',{'html':'下一页','class':'next','href':'javascript:void(null)','events':{'click':this.click.bind(this,this.index+1)}});
            panel.grab(next);
        }
        
        if(options.showText) panel.grab(this.createText());        
    },
    
    createNumber: function(i){
        var a = new Element('a', {
			'html':i+1,
			'href':'javascript:void(null)',
			'events':{
				'click':this.click.bind(this,i)
			}
		});
        if(i==this.index){
            a.addClass('clicked');
        }        
        return a;
    },
    
    createSplit: function(){
        var split = new Element('span',{'html':'...'});
        return split;
    },
    
    createText: function(){
        var text = new Element('span',{'html':'第'+(this.index+1)+'/'+(this.totalpage)+'页'});
        return text;
    },
    
    click: function(index){
        this.index = index;
        this.load();
    },
    
    load: function(param){
        this.fireEvent('beforeLoad');
        this.param.page = this.index+1;
        this.param.pagesize = this.pagesize;
        
        if(param) this.param = $merge(this.param,param);
        this.loader.get(this.param);
    },
    
    reload: function(param){
        this.index = 0;
        this.load(param);
    },
    
    setPagesize: function(pagesize){
        this.pagesize = pagesize;
        this.reload();
    }
});

shortcut = {
	'all_shortcuts':{},//All the shortcuts are stored in this array
	'add': function(shortcut_combination,callback,opt) {
		//Provide a set of default options
		var default_options = {
			'type':'keydown',
			'propagate':false,
			'disable_in_input':false,
			'target':document,
			'keycode':false
		}
		if(!opt) opt = default_options;
		else {
			for(var dfo in default_options) {
				if(typeof opt[dfo] == 'undefined') opt[dfo] = default_options[dfo];
			}
		}

		var ele = opt.target;
		if(typeof opt.target == 'string') ele = document.getElementById(opt.target);
		var ths = this;
		shortcut_combination = shortcut_combination.toLowerCase();

		//The function to be called at keypress
		var func = function(e) {
			e = e || window.event;
			
			if(opt['disable_in_input']) { //Don't enable shortcut keys in Input, Textarea fields
				var element;
				if(e.target) element=e.target;
				else if(e.srcElement) element=e.srcElement;
				if(element.nodeType==3) element=element.parentNode;

				if(element.tagName == 'INPUT' || element.tagName == 'TEXTAREA') return;
			}
	
			//Find Which key is pressed
			if (e.keyCode) code = e.keyCode;
			else if (e.which) code = e.which;
			var character = String.fromCharCode(code);
			
			if(code == 188) character=","; //If the user presses , when the type is onkeydown
			if(code == 190) character="."; //If the user presses , when the type is onkeydown

			var keys = shortcut_combination.split("+");
			//Key Pressed - counts the number of valid keypresses - if it is same as the number of keys, the shortcut function is invoked
			var kp = 0;
			
			//Work around for stupid Shift key bug created by using lowercase - as a result the shift+num combination was broken
			var shift_nums = {
				"`":"~",
				"1":"!",
				"2":"@",
				"3":"#",
				"4":"$",
				"5":"%",
				"6":"^",
				"7":"&",
				"8":"*",
				"9":"(",
				"0":")",
				"-":"_",
				"=":"+",
				";":":",
				"'":"\"",
				",":"<",
				".":">",
				"/":"?",
				"\\":"|"
			}
			//Special Keys - and their codes
			var special_keys = {
				'esc':27,
				'escape':27,
				'tab':9,
				'space':32,
				'return':13,
				'enter':13,
				'backspace':8,
	
				'scrolllock':145,
				'scroll_lock':145,
				'scroll':145,
				'capslock':20,
				'caps_lock':20,
				'caps':20,
				'numlock':144,
				'num_lock':144,
				'num':144,
				
				'pause':19,
				'break':19,
				
				'insert':45,
				'home':36,
				'delete':46,
				'end':35,
				
				'pageup':33,
				'page_up':33,
				'pu':33,
	
				'pagedown':34,
				'page_down':34,
				'pd':34,
	
				'left':37,
				'up':38,
				'right':39,
				'down':40,
	
				'f1':112,
				'f2':113,
				'f3':114,
				'f4':115,
				'f5':116,
				'f6':117,
				'f7':118,
				'f8':119,
				'f9':120,
				'f10':121,
				'f11':122,
				'f12':123
			}
	
			var modifiers = { 
				shift: { wanted:false, pressed:false},
				ctrl : { wanted:false, pressed:false},
				alt  : { wanted:false, pressed:false},
				meta : { wanted:false, pressed:false}	//Meta is Mac specific
			};
                        
			if(e.ctrlKey)	modifiers.ctrl.pressed = true;
			if(e.shiftKey)	modifiers.shift.pressed = true;
			if(e.altKey)	modifiers.alt.pressed = true;
			if(e.metaKey)   modifiers.meta.pressed = true;
                        
			for(var i=0; k=keys[i],i<keys.length; i++) {
				//Modifiers
				if(k == 'ctrl' || k == 'control') {
					kp++;
					modifiers.ctrl.wanted = true;

				} else if(k == 'shift') {
					kp++;
					modifiers.shift.wanted = true;

				} else if(k == 'alt') {
					kp++;
					modifiers.alt.wanted = true;
				} else if(k == 'meta') {
					kp++;
					modifiers.meta.wanted = true;
				} else if(k.length > 1) { //If it is a special key
					if(special_keys[k] == code) kp++;
					
				} else if(opt['keycode']) {
					if(opt['keycode'] == code) kp++;

				} else { //The special keys did not match
					if(character == k) kp++;
					else {
						if(shift_nums[character] && e.shiftKey) { //Stupid Shift key bug created by using lowercase
							character = shift_nums[character]; 
							if(character == k) kp++;
						}
					}
				}
			}
			
			if(kp == keys.length && 
						modifiers.ctrl.pressed == modifiers.ctrl.wanted &&
						modifiers.shift.pressed == modifiers.shift.wanted &&
						modifiers.alt.pressed == modifiers.alt.wanted &&
						modifiers.meta.pressed == modifiers.meta.wanted) {
				callback(e);
	
				if(!opt['propagate']) { //Stop the event
					//e.cancelBubble is supported by IE - this will kill the bubbling process.
					e.cancelBubble = true;
					e.returnValue = false;
	
					//e.stopPropagation works in Firefox.
					if (e.stopPropagation) {
						e.stopPropagation();
						e.preventDefault();
					}
					return false;
				}
			}
		}
		this.all_shortcuts[shortcut_combination] = {
			'callback':func, 
			'target':ele, 
			'event': opt['type']
		};
		//Attach the function with the event
		if(ele.addEventListener) ele.addEventListener(opt['type'], func, false);
		else if(ele.attachEvent) ele.attachEvent('on'+opt['type'], func);
		else ele['on'+opt['type']] = func;
	},

	//Remove the shortcut - just specify the shortcut and I will remove the binding
	'remove':function(shortcut_combination) {
		shortcut_combination = shortcut_combination.toLowerCase();
		var binding = this.all_shortcuts[shortcut_combination];
		delete(this.all_shortcuts[shortcut_combination])
		if(!binding) return;
		var type = binding['event'];
		var ele = binding['target'];
		var callback = binding['callback'];

		if(ele.detachEvent) ele.detachEvent('on'+type, callback);
		else if(ele.removeEventListener) ele.removeEventListener(type, callback, false);
		else ele['on'+type] = false;
	}
}


/**
 * 还思通用包
 */
var hiisee_common = new Class({
	tip: function(title, text) {
		var roar = new Roar({
		});
		title = (!title || title.length<1)?'系统提示':title;
		if(!text || text.length<1) {
			text = '------------';
		}
		roar.alert(title, text);
	}
});
hiisee = new hiisee_common();

// 主菜单
var tabdropdown={
	disappeardelay: 200, //set delay in miliseconds before menu disappears onmouseout
	disablemenuclick: false, //when user clicks on a menu item with a drop down menu, disable menu item's link?
	enableiframeshim: 1, //1 or 0, for true or false

	//No need to edit beyond here////////////////////////
	dropmenuobj: null, ie: document.all, firefox: document.getElementById&&!document.all, previousmenuitem:null,
	currentpageurl: window.location.href.replace("http://"+window.location.hostname, "").replace(/^\//, ""), //get current page url (minus hostname, ie: http://www.dynamicdrive.com/)

	getposOffset:function(what, offsettype){
		var totaloffset=(offsettype=="left")? what.offsetLeft : what.offsetTop;
		var parentEl=what.offsetParent;
			while (parentEl!=null){
				totaloffset=(offsettype=="left")? totaloffset+parentEl.offsetLeft : totaloffset+parentEl.offsetTop;
				parentEl=parentEl.offsetParent;
			}
		return totaloffset;
	},

	showhide:function(obj, e, obj2){ //obj refers to drop down menu, obj2 refers to tab menu item mouse is currently over
		if (this.ie || this.firefox)
			this.dropmenuobj.style.left=this.dropmenuobj.style.top="-500px"
		if (e.type=="click" && obj.visibility==hidden || e.type=="mouseover"){
			if (obj2.parentNode.className.indexOf("default")==-1) //if tab isn't a default selected one
				obj2.parentNode.className="selected"
			obj.visibility="visible"
			}
		else if (e.type=="click")
			obj.visibility="hidden"
	},

	iecompattest:function(){
		return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
	},

	clearbrowseredge:function(obj, whichedge){
		var edgeoffset=0
		if (whichedge=="rightedge"){
			var windowedge=this.ie && !window.opera? this.standardbody.scrollLeft+this.standardbody.clientWidth-15 : window.pageXOffset+window.innerWidth-15
			this.dropmenuobj.contentmeasure=this.dropmenuobj.offsetWidth
		if (windowedge-this.dropmenuobj.x < this.dropmenuobj.contentmeasure)  //move menu to the left?
			edgeoffset=this.dropmenuobj.contentmeasure-obj.offsetWidth
		}
		else{
			var topedge=this.ie && !window.opera? this.standardbody.scrollTop : window.pageYOffset
			var windowedge=this.ie && !window.opera? this.standardbody.scrollTop+this.standardbody.clientHeight-15 : window.pageYOffset+window.innerHeight-18
			this.dropmenuobj.contentmeasure=this.dropmenuobj.offsetHeight
			if (windowedge-this.dropmenuobj.y < this.dropmenuobj.contentmeasure){ //move up?
				edgeoffset=this.dropmenuobj.contentmeasure+obj.offsetHeight
				if ((this.dropmenuobj.y-topedge)<this.dropmenuobj.contentmeasure) //up no good either?
					edgeoffset=this.dropmenuobj.y+obj.offsetHeight-topedge
			}
			this.dropmenuobj.firstlink.style.borderTopWidth=(edgeoffset==0)? 0 : "1px" //Add 1px top border to menu if dropping up
		}
		return edgeoffset
	},

	dropit:function(obj, e, dropmenuID){
		if (this.dropmenuobj!=null){ //hide previous menu
			this.dropmenuobj.style.visibility="hidden" //hide menu
			if (this.previousmenuitem!=null && this.previousmenuitem!=obj){
				if (this.previousmenuitem.parentNode.className.indexOf("default")==-1) //If the tab isn't a default selected one
					this.previousmenuitem.parentNode.className=""
			}
		}
		this.clearhidemenu()
		if (this.ie||this.firefox){
			obj.onmouseout=function(){tabdropdown.delayhidemenu(obj)}
			obj.onclick=function(){return !tabdropdown.disablemenuclick} //disable main menu item link onclick?
			this.dropmenuobj=document.getElementById(dropmenuID)
			this.dropmenuobj.onmouseover=function(){tabdropdown.clearhidemenu()}
			this.dropmenuobj.onmouseout=function(e){tabdropdown.dynamichide(e, obj)}
			this.dropmenuobj.onclick=function(){tabdropdown.delayhidemenu(obj)}
			this.showhide(this.dropmenuobj.style, e, obj)
			this.dropmenuobj.x=this.getposOffset(obj, "left")
			this.dropmenuobj.y=this.getposOffset(obj, "top")
			this.dropmenuobj.style.left=this.dropmenuobj.x-this.clearbrowseredge(obj, "rightedge")+"px"
			this.dropmenuobj.style.top=this.dropmenuobj.y-this.clearbrowseredge(obj, "bottomedge")+obj.offsetHeight+1+"px"
			this.previousmenuitem=obj //remember main menu item mouse moved out from (and into current menu item)
			this.positionshim() //call iframe shim function
		}
	},

	contains_firefox:function(a, b) {
		while (b.parentNode)
		if ((b = b.parentNode) == a)
			return true;
		return false;
	},

	dynamichide:function(e, obj2){ //obj2 refers to tab menu item mouse is currently over
		var evtobj=window.event? window.event : e
		if (this.ie&&!this.dropmenuobj.contains(evtobj.toElement))
			this.delayhidemenu(obj2)
		else if (this.firefox&&e.currentTarget!= evtobj.relatedTarget&& !this.contains_firefox(evtobj.currentTarget, evtobj.relatedTarget))
			this.delayhidemenu(obj2)
	},

	delayhidemenu:function(obj2){
		this.delayhide=setTimeout(function(){tabdropdown.dropmenuobj.style.visibility='hidden'; if (obj2.parentNode.className.indexOf('default')==-1) obj2.parentNode.className=''},this.disappeardelay) //hide menu
	},

	clearhidemenu:function(){
		if (this.delayhide!="undefined")
			clearTimeout(this.delayhide)
	},

	positionshim:function(){ //display iframe shim function
		if (this.enableiframeshim && typeof this.shimobject!="undefined"){
			if (this.dropmenuobj.style.visibility=="visible"){
				this.shimobject.style.width=this.dropmenuobj.offsetWidth+"px"
				this.shimobject.style.height=this.dropmenuobj.offsetHeight+"px"
				this.shimobject.style.left=this.dropmenuobj.style.left
				this.shimobject.style.top=this.dropmenuobj.style.top
			}
		this.shimobject.style.display=(this.dropmenuobj.style.visibility=="visible")? "block" : "none"
		}
	},

	hideshim:function(){
		if (this.enableiframeshim && typeof this.shimobject!="undefined")
			this.shimobject.style.display='none'
	},

	isSelected:function(menuurl){
		var menuurl=menuurl.replace("http://"+menuurl.hostname, "").replace(/^\//, "")
		return (tabdropdown.currentpageurl==menuurl)
	},

	init:function(menuid, dselected){
		this.standardbody=(document.compatMode=="CSS1Compat")? document.documentElement : document.body //create reference to common "body" across doctypes
		var menuitems=document.getElementById(menuid).getElementsByTagName("a")
		for (var i=0; i<menuitems.length; i++){
			if (menuitems[i].getAttribute("rel")){
				var relvalue=menuitems[i].getAttribute("rel")
				document.getElementById(relvalue).firstlink=document.getElementById(relvalue).getElementsByTagName("a")[0]
				menuitems[i].onmouseover=function(e){
					var event=typeof e!="undefined"? e : window.event
					tabdropdown.dropit(this, event, this.getAttribute("rel"))
				}
			}
			if (dselected=="auto" && typeof setalready=="undefined" && this.isSelected(menuitems[i].href)){
				menuitems[i].parentNode.className+=" selected default"
				var setalready=true
			}
			else if (parseInt(dselected)==i)
				menuitems[i].parentNode.className+=" selected default"
		}
	}

}

// 初始化页面
window.addEvent("domready", function() {
	// 生成导航菜单
	tabdropdown.init("systemmenu");
	
	// 开始监听用户新消息
	monitor.periodical(180000);
	
	// 提前载入ajax运行图标
	var myImage = new Asset.image('my/media/ajax_loader.gif');
	
	// 开启调拭模式
	// dbug.enable();

	// 显示时钟
	//showSiteClock();
});

