// basic extends 基础扩展，全局调用
(function($){
	/* 全局附加参数(string，i.e. &username=xxx&xxx=xxx) */
	$.params = '';
	// 获得字符串字节长度
	$.byteLength = function(str) {
		var byteLen = 0,len = str.length;
		if( !str ) return 0;
		for( var i=0; i<len; i++ ) {
			if( str.charCodeAt(i)>255 ) byteLen += 2;
			else byteLen++;
		}
		return byteLen;
	}
	/* 是否空对象 */
	$.isEmptyObj = function( o ) {
		if( typeof(o) != 'object' ) return false;
		for( var k in o ) return false;
		return true;
	}
	/* 复制到剪切板 */
	$.copy2clipboard = function( txt ) {
		if( typeof(clipboardData) == 'object' ) {
			clipboardData.clearData();
			clipboardData.setData('Text', txt);
		}else if( typeof(netscape) == 'object' ) {
			try{
				netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
			}catch(e){ alert('该操作被浏览器拒绝!\n如果想启用该功能，请在地址栏内输入 about:config\n然后将项 signed.applets.codebase_principal_support 值该为true'); }
			var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
			if( typeof(clip) != 'object' ) return;
			var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
			trans.addDataFlavor('text/unicode');
			var strobj = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
			strobj.data = txt;
			trans.setTransferData( 'text/unicode', strobj, txt.length*2 );
			clip.setData(trans, null, Components.interfaces.nsIClipboard.kGlobalClipboard);
		}else{
			alert('您使用的浏览器不支持javascript复制文本！\n请使用IE/Firefox浏览器！');
			return false;
		}
		return true;
	}
	// 返回等级
	$.level = function( exp ) { return exp < 50 ? 0 : (exp - 50 - (exp-50) % 1000) / 1000 + 1; }
	/* 输出性别 */
	$.sex = function( sex ) {
		if( sex == 1 ) { /* 男 */
			sex = '<span style="font-family:\'宋体\'; font-size:13px; color:#1981d2;" title="性别：男">♂</span>';
		}else if( sex == 2 ) { /* 女 */
			sex = '<span style="font-family:\'宋体\'; font-size:13px; color:#ed058d;" title="性别：女">♀</span>';
		}else{ /* 保密 */
			sex = '<span style="color:#008000; font-family:Arial, Helvetica, sans-serif; font-size:12px;" title="性别：保密">○</span>';
		}
		document.write(sex);
	}
	/* 血型 */
	$.showblood = function( blood ){
		switch(blood) {
			case '1': return document.write('A型');
			case '2': return document.write('B型');
			case '3': return document.write('O型');
			case '4': return document.write('AB型');
			default: return document.write('其他');
		}
	}
	/* 职业 */
	$.showjob_list = ['演员', '歌手', '主持人', '模特', '导演', '运动员', '其他'];
	$.showjob = function( list, write ) {
		if( list.length < 1 ) return;
		list = list.substr(1, list.length-2).split('/');
		for(var i = 0; i < list.length; i++)
			list[i] = $.showjob_list[list[i]-1];
		if( typeof(write) != 'undefined' && write ) {
			document.write(list.join(','));
		}
	}
	/* 星座 */
	$.startgroup = ['白羊', '金牛', '双子', '巨蟹', '狮子', '处女', '天枰', '天蝎', '射手', '魔羯', '水瓶' ,'双鱼'];
	$.startgroup_date = [ [3,21, 4,20], [4,21, 5,21], [5,22, 6,21], [6,22, 7,22], [7,23, 8,23], [8,24, 9,23], [9,24, 10,23], [10,24, 11,22], [11,23, 12,21], [12,22, 1,20], [1,21, 2,19], [2,20, 3,20] ];
	$.showstartgroup = function(format){
		var obj = new Date(typeof(format) == 'string' ? format.replace(/\-/ig, '/') : format),
			month = obj.getMonth()+1,
			day = obj.getDate(),
			obj2 = '';
		if( format == '0000-00-00' || !month || !day ) return;
		for(var i = 0; i < 12; i++) {
			obj2 = $.startgroup_date[i];
			if( obj2[0] > obj2[2] ) {
				if( month >= obj2[0] && day >= obj2[1] || month <= obj2[2] && day <= obj2[3] )
					return document.write($.startgroup[i]+'座');
			}else if( (month > obj2[0] || (month == obj2[0] && day >= obj2[1])) && (month < obj2[2] || (month == obj2[2] && day <= obj2[3])) )
				return document.write($.startgroup[i]+'座');
		}
	}
	// 输出等级图片标签
	$.showlevel = function( exp ) {
		var level = $.level( exp );
		var start = level % 16 % 4; //星星
		var moon = (level % 16 - start) / 4; //月亮
		var sun = (level - level % 16) / 16; //太阳
		var i = 0, str = '';
		for(i = 0; i < sun; i++) // 太阳标签
			str += '<a target="_blank" href="?view=gradenote" style="width:15px; padding:0;"><img src="images/user/sun.gif" title="等级：'+level+'" /></a>';
		for(i = 0; i < moon; i++) // 月亮标签
			str += '<a target="_blank" href="?view=gradenote" style="width:15px; padding:0;"><img src="images/user/moon.gif" title="等级：'+level+'" /></a>';
		for(i = 0; i < start; i++) // 星星标签
			str += '<a target="_blank" href="?view=gradenote" style="width:15px; padding:0;"><img src="images/user/start.gif" title="等级：'+level+'" /></a>';
		document.write(str);
	}
	// 停止冒泡事件
	$.cancelBubble = function( e ) {
		if ( e && e.stopPropagation ) e.stopPropagation();
		else window.event.cancelBubble = true;
	}
	// 日期格式化，显示中文
	$.dateformat = function( timestamp, nowstamp ) {
		if( isNaN(timestamp) ) { document.write( '很久之前' ); return; }
		var curday = nowstamp - nowstamp % 86400;
		var str = '';
		if( nowstamp <= timestamp + 60 ) { // 1分钟内
			str = (nowstamp - timestamp) + '秒前';
		}else if( nowstamp <= timestamp + 3600 ) { // 1小时内
			str = Math.ceil((nowstamp - timestamp)/60) + '分钟前';
		}else if( curday <= timestamp ) { // 当天，显示小时
			str = Math.ceil((nowstamp - timestamp)/3600) + '小时前';
		}else if( curday - 86400 <= timestamp ) { // 1天前，显示昨天
			str = '昨天';
		}else if( curday - 86400 * 2 <= timestamp ) { // 2天前，显示前天
			str = '前天';
		}else { // 显示多少天/年
			var day = Math.ceil((nowstamp - timestamp)/86400);
			if( day >= 365 ) str = Math.floor(day/365) + '年前';
			else str = Math.ceil((nowstamp - timestamp)/86400) + '天前';
		}
		return arguments[2] == 1 ? str : document.write( str );
	}
	/* 默认图片，当图片无法读取时，更改src为默认图片路径 */
	$.defaultImg = function( obj, path ) {
		/* 防止内存溢出 */
		obj.onerror = null;
		obj.src = path;
	}
	// 对话层
	$.dialogbox = {
		iframe: null, isinit: null,
		callback: parent != self ? parent.$.dialogbox.callback : null,
		complete: null,
		init: function() {
			if( this.isinit ) return; /* 确保只初始化一次 */
			this.isinit = true;
			if( parent != self ) return; /* 非父级窗口调用不执行以下代码 */
			/* 点击遮罩层，关闭弹出窗口 */
			id.call(parent, 'dialogbox_close').onclick = function(){ $.dialogbox.hide(); };
			/* 禁止冒泡事件 */
			id.call(parent, 'dialogbox_container').onclick = $.cancelBubble;
		},
		show: function( title, url, callback ) {
			this.hide();
			if( typeof(callback) == 'function' )
				parent.$.dialogbox.callback = this.callback = callback;
			var iframe = id.call(parent, 'dialogbox_iframe'),
				iframe_doc = iframe.contentWindow.document;
			this.showshadow();
			id.call(parent, 'dialogbox').style.display = 'block';
			id.call(parent, 'dialogbox_title').innerHTML = title;
			id.call(parent, 'dialogbox_title').parentNode.style.display = '';
			this.reset();
			iframe.src = url;
			iframe.onreadystatechange = function(){ // ie
				if( iframe.contentWindow.document.readyState == 'complete' ) $.dialogbox.resize();
			}
			iframe.onload = function(){ $.dialogbox.resize(); } // firefox
		},
		showshadow: function() {
			id.call(parent, 'shadow').style.height = Math.max(
				(parent.document.documentElement || parent.document.body).scrollHeight,
				parent.document.getElementsByTagName('html')[0].clientHeight
			) + 'px';
			id.call(parent, 'shadow').style.display = 'block';
		},
		reset: function() { // 避免浏览器缓存iframe内容
			this.ifrmwrite(
				id.call(parent, 'dialogbox_iframe').contentWindow.document,
				'<div style="height:30px; width:200px;"><img src="images/loading.gif" align="absmiddle"/> loading...</div>'
			);
			this.resize(200, 50);
		},
		ifrmwrite: function(iframe, html){
			iframe.open(); iframe.write(html); iframe.close();
		},
		hide: function() {
			this.init();
			var iframe = id.call(parent, 'dialogbox_iframe'),
				callback_param = typeof(arguments[0]) != 'undefined' ? arguments[0] : 'close';
			if( parent != self ) { // 触发父级页面关闭事件
				return parent.$.dialogbox.hide();
			}

			if( typeof(this.callback) == 'function' ) this.callback(callback_param);
			if( typeof(this.complete) == 'function' ) this.complete();
			parent.$.dialogbox.callback = this.callback = null;
			iframe.style.height = iframe.style.width = 'auto';
			id.call(parent, 'dialogbox').style.display =  id.call(parent, 'shadow').style.display = 'none';
		},
		resize: function() {
			var iframe_obj = id.call(parent, 'dialogbox_iframe'),
				iframe = iframe_obj.contentWindow.document,
				width = arguments[0],
				height = arguments[1];
			if( !width || !height ) {
				width = iframe.body.scrollWidth;
				height = iframe.body.scrollHeight;
				if(iframe.documentElement){
					width = Math.max(width, iframe.documentElement.scrollWidth);
					height = Math.max(height, iframe.documentElement.scrollHeight);
				}
			}
			iframe_obj.style.height = height + 'px';
			iframe_obj.style.width = width + 'px';
			id.call(parent, 'dialogbox_container').style.width = (width+16) + 'px';
			id.call(parent, 'dialogbox').style.margin = -(parseInt(id.call(parent, 'dialogbox').scrollHeight, 10) / 2) + 'px 0 0 0';
		},
		message: function( str ) {
			var iframe_doc = id.call(parent, 'dialogbox_iframe').contentWindow.document,
				interval = 2,
				callback = function(){};
			/* 先隐藏，并触发回调函数 */
			this.hide();
			if( typeof(arguments[1]) == 'function' ) callback = arguments[1];
			/* 设置回调函数 */
			parent.$.dialogbox.callback = this.callback = callback;
			if( !isNaN(arguments[2]) ) interval = arguments[2];
			id.call(parent, 'dialogbox_title').parentNode.style.display = 'none';
			/* 显示遮罩层 */
			this.showshadow();
			/* 显示弹出层 */
			id.call(parent, 'dialogbox').style.display = 'block';
			/* 写入数据 */
			iframe_doc.body.innerHTML = '<div style="height:30px; width:100%; font-weight:bold; padding:10px 0 0 0; font-size:14px; text-align:center;">'+str+'</div>';
			iframe_doc.body.style.width = '200px ';
			iframe_doc.body.style.height = '30px';
			/* 设置大小 */
			this.resize(216, 30);
			/* 定时关闭 */
			parent.setTimeout('parent.$.dialogbox.hide("message_close");', interval*1000);
		}
	}
	$.favorite = function(){ // 收藏网址到浏览器
		if (typeof(document.all) == 'object') external.addFavorite(location.href, document.title);
		else if (typeof(sidebar) == 'object') sidebar.addPanel(document.title, location.href, '');
		else alert('您使用的浏览器不支持javascript收藏网址！\n请手动收藏，或使用IE/火狐浏览器！');
	}
	$.homepage = function(url){ // 设置为首页
		if( typeof(url) == "undefined" ) url = "http://" + location.host;
		if( typeof(document.all) == 'object' ) {
			document.body.style.behavior = "url(#default#homepage)";
			document.body.setHomePage(url);
		}else if( typeof(sidebar) == 'object' && typeof(netscape) == 'object' ) {
			try{
				netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
				Components.classes['@mozilla.org/preferences-service;1'].getService(Components. interfaces.nsIPrefBranch).setCharPref('browser.startup.homepage',url);
				alert('成功设置 '+url+' 为Firefox首页');
			} catch (e) { alert( "该操作被浏览器拒绝!\n如果想启用该功能，请在地址栏内输入 about:config\n然后将项 signed.applets.codebase_principal_support 值该为true" ); }
		}else alert('您使用的浏览器不支持javascript设为首页！\n请手动设置，或使用IE/Firefox浏览器！');
	}
	$.regexp = {};
	$.regexp.quote = function( str ) { /* 对字符串进行编码 */
		return str.replace(/([\:\.\+\-\*\?\[\^\]\$\(\)\{\}\=\!\%\<\>\|\\\/)])/g,"\\$1");
	}
	$.regexp.url = function( url ){ // 检测url格式，协议可不存在
		return /^((ht|f)tps?\:\/\/)?(([a-z\d](\-?[a-z\d]+)*\.)+[a-z]{2,4}|(2([0-4]\d|[0-5]{2})|1\d{2}|\d{1,2})(\.(2([0-4]\d|[0-5]{2})|1\d{2}|\d{1,2})){3}|\d+)(\:\d{1,5})?(\/[\s\S]*)?$/i.test(url);
	}
	$.regexp.email = function( email ){ // 检测email格式
		return /^[a-z\d\.\_\-]+\@(?:[a-z\d\.\_\-]+\.)+[a-z]{2,4}$/i.test(email);
	}
	$.execHTML = function( html ){ // 执行html中的js
		var match, reg = /\<script[^\>]*\>(.*?)\<\/script\>/gi;
		while( (match = reg.exec(html)) != null ) {
			html = html.substr(0, match.index) + eval(match[1]) + html.substr(match.index+match[0].length);
		}
		return html;
	}
	$.cookie = function( key, val ){ // cookie

	}
})(jQuery);

function id( domid ) {
	return this.document.getElementById( domid );
}
