// 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;
	}
	/* 显示盗链图片 */
	$.showImg = function( url ){
		var frameid = 'frameimg' + Math.random().toString().substr(2),
			attr = {};
		if( typeof(url) != 'string' || url.length < 1 ) return;
		if( typeof(arguments[2]) == 'object' ) {
			for(var k in arguments[2]) {
				if( typeof(arguments[2][k]) == 'object' ) {
					for(var k2 in arguments[2][k]) {
						if( typeof(attr[k]) == 'undefined' ) attr[k] = '';
						attr[k] += k2+'="'+arguments[2][k][k2]+'" ';
					}
				}
			}
		}

		var a = typeof(arguments[1]) != 'string' ? '%s' : '<a href="'+arguments[1]+'" target="_blank" style="border:0;" '+attr['a']+'>%s</a>';
		window['img'+frameid] = '<meta http-equiv="Content-Type" content="text/html; charset='+document.charset+'" /><body '+attr['body']+' style="padding:0; margin:0; text-align:center;">'+a.replace('%s', '<img '+attr['img']+' src="'+url+'?114" border="0" onload="parent.$.imgThumb(this); if(this.height > 0 ) parent.document.getElementById(\''+frameid+'\').style.height = this.height + \'px\';" />')+'</body>';
		document.write('<iframe '+attr['iframe']+' id="'+frameid+'" src="javascript:parent.img'+frameid+';" frameBorder="0" scrolling="no" width="100%"></iframe>');
	}
	/* 是否空对象 */
	$.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 = '', vparam = $.getParam('v') == '2' ? '&v=2' : '';
		for(i = 0; i < sun; i++) // 太阳标签
			str += '<a target="_blank" href="?view=gradenote'+vparam+'" 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'+vparam+'" 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'+vparam+'" 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 ) {
		/* 防止内存溢出 */
		obj.onerror = null;
		var path = typeof(arguments[1]) == 'string' ? arguments[1] : 'images/usertou/noavatar.gif';
		obj.src = path;
	}
	// 对话层
	$.dialogbox = {
		id: 'dialogbox', iframeid: '',
		iframe: null, isinit: null,
		callback: null,
		complete: null,
		thisobj: window,
		init: function() {
			if( this.isinit ) return; /* 确保只初始化一次 */
			this.isinit = true;
			if( !document.getElementById(this.id) ) return; /* 子窗口不执行以下代码 */
			/* 点击遮罩层，关闭弹出窗口 */
			id(this.id+'_close').onclick = function(){ $.dialogbox.hide(); };
			/* 禁止冒泡事件 */
			id(this.id+'_container').onclick = $.cancelBubble;
		},
		show: function( title, url, callback ) {
			var thisobj = this;
			this.hide();
			if( typeof(callback) == 'function' )
				this.thisobj.$.dialogbox.callback = this.callback = callback;

			this.showshadow();

			id.call(this.thisobj, this.id).style.display = 'block';
			id.call(this.thisobj, this.id+'_title').innerHTML = title;
			id.call(this.thisobj, this.id+'_title').parentNode.style.display = '';

			this.reset();
			var iframe = id.call(this.thisobj, this.id+'_iframe');
			iframe.style.width = '150px';
			iframe.style.height = '50px';
			this.resize();
			iframe.src = url;
			iframe.onreadystatechange = function(){ // ie
				try{
					if( iframe.contentWindow.document.readyState == 'complete' ) thisobj.resize();
				}catch(e) { }
			}
			iframe.onload = function(){ thisobj.resize(); } // firefox
		},
		showshadow: function() {
			id.call(this.thisobj, 'shadow').style.height = Math.max(
				(this.thisobj.document.documentElement || this.thisobj.document.body).scrollHeight,
				this.thisobj.document.getElementsByTagName('html')[0].clientHeight
			) + 'px';
			id.call(this.thisobj, 'shadow').style.display = 'block';
		},
		reset: function() { // 避免浏览器缓存iframe内容
			try{
				this.ifrmwrite(
					id.call(this.thisobj, this.id+'_iframe').contentWindow.document,
					'<div style="height:30px; width:200px;"><img src="/images/loading.gif" align="absmiddle"/> loading...</div>'
				);
			}catch(e) { id.call(this.thisobj, this.id+'_iframe').src = ''; }
			this.resize(200, 50);
		},
		ifrmwrite: function(iframe, html){
			iframe.open(); iframe.write(html); iframe.close();
		},
		hide: function() {
			this.init();
			var iframe = id.call(this.thisobj, this.id+'_iframe'),
				callback_param = typeof(arguments[0]) != 'undefined' ? arguments[0] : 'close';
			if( !document.getElementById(this.id) ) { // 触发父级页面关闭事件
				return window == this.thisobj ?  alert('Dialogbox层丢失！') : this.thisobj.$.dialogbox.hide();
			}

			if( typeof(this.callback) == 'function' ) this.callback(callback_param);
			if( typeof(this.complete) == 'function' ) this.complete();
			this.thisobj.$.dialogbox.callback = this.callback = null;
			iframe.style.height = iframe.style.width = 'auto';
			id.call(this.thisobj, this.id).style.display =  id.call(this.thisobj, 'shadow').style.display = 'none';
		},
		resize: function() {
			var iframe_obj = id.call(this.thisobj, this.id+'_iframe'),
				width = arguments[0], height = arguments[1];
			try{
				var iframe = iframe_obj.contentWindow.document;

			}catch(e) { width = 150; height = 50; }

			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(this.thisobj, this.id+'_container').style.width = (width+16) + 'px';
			id.call(this.thisobj, this.id).style.margin = -(parseInt(id.call(this.thisobj, this.id).scrollHeight, 10) / 2) + 'px 0 0 0';
		},
		message: function( str ) {
			var iframe_doc = id.call(this.thisobj, this.id+'_iframe').contentWindow.document,
				interval = 2,
				callback = function(){};
			/* 先隐藏，并触发回调函数 */
			this.hide();
			if( typeof(arguments[1]) == 'function' ) callback = arguments[1];
			/* 设置回调函数 */
			this.thisobj.$.dialogbox.callback = this.callback = callback;
			if( !isNaN(arguments[2]) ) interval = arguments[2];
			id.call(this.thisobj, this.id+'_title').parentNode.style.display = 'none';
			/* 显示遮罩层 */
			this.showshadow();
			/* 显示弹出层 */
			id.call(this.thisobj, this.id).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);
			/* 定时关闭 */
			this.thisobj.setTimeout('$.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://" + window.location.host+window.location.pathname;
		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;
	}
	$.iframe_resize = function (iframeid) {
		var win = (this != $ && this != window) ? this : window,
			scrollX = 0,
			scrollY = 0;
		if(win.parent == win) return;
		var iframe = win.parent.document.getElementById(iframeid);
		if(win.parent == win.parent.parent) { // 父级窗口为最顶级时，记录scrollTop
			var scrollObj = win.parent.document;
			scrollX = Math.max(scrollObj.documentElement.scrollLeft, scrollObj.body.scrollLeft);
			scrollY = Math.max(scrollObj.documentElement.scrollTop, scrollObj.body.scrollTop);
		}
		iframe.style.height = '0px';

		var width = win.document.body.scrollWidth,
			height = win.document.body.scrollHeight;
		if( document.documentElement && navigator.userAgent.toLowerCase().indexOf('msie') < 0 ){
			width = Math.max(width, win.document.documentElement.scrollWidth);
			height = Math.max(height, win.document.documentElement.scrollHeight);
		}

		iframe.style.height = height + 'px';

		/* 滚动条定位 */
		if(scrollX || scrollY) {
			/* webkit内核使用body,其他使用documentElement */
			scrollObj = scrollObj[navigator.userAgent.toLowerCase().indexOf('applewebkit') > -1 ? 'body' : 'documentElement']
			scrollObj.scrollLeft = scrollX;
			scrollObj.scrollTop = scrollY;
		}

		/* 递归展开 */
		$.iframe_resize.call(win.parent, iframeid);
	}
	/*
		0=key
		1=值(值为'',则删除cookie)
		2=有效期，单位：秒，如从现在算起，之后的10秒，就填10
		3=path
		4=domain
		5=secure
	*/
	$.cookie = function(){ // cookie
		var key = arguments[0], val = arguments[1], item;
		if( val == null ) {
			item = (new RegExp('(?:\\;\\s?|^)'+$.regexp.quote(key)+'\\=([^\\;]+)','i')).exec(document.cookie);
			return item  && item[1] && typeof(item[1]) == 'string' ? decodeURIComponent(item[1].toString()) : '';
		}else{
			var expire = arguments[2], path = arguments[3], domain = arguments[4], secure = arguments[5];
			item = key + '=' + encodeURIComponent(val);
			if( expire ) item += ';expires=' + new Date( (new Date).getTime() + expire*1000 );
			item += ';path=' + (path ? path : '/');
			if( domain ) item += ';domain=' + domain;
			if( secure ) item += ';secure=' + secure;
			document.cookie = item;
			return true;
		}
	}
	$.imgThumb = function(){ // 图片缩略
		var img = typeof(arguments[0]) == 'object' ? arguments[0] : this,
			maxWidth = img.getAttribute('maxWidth'),
			maxHeight = img.getAttribute('maxHeight'),
			width = parseInt(img.width),
			height = parseInt(img.height);

		if(!isNaN(maxWidth) && maxWidth > 0 && width > maxWidth) { // 宽超出最大
			height = (height/width) * maxWidth;
			width = maxWidth;
		}

		if(!isNaN(maxHeight) && maxHeight > 0 && height > maxHeight) { // 高超出最大
			width = (width/height) * maxHeight;
			height = maxHeight;
		}
		if( !isNaN(width) && width > 0 ) img.style.width = width + 'px';
		if( !isNaN(height) && height > 0 ) img.style.height = height + 'px';
	}
	$.getParam = function(key, params) {
		if(typeof(params) != 'string') params = location.search.substr(1);
		var items = params.split('&');
		for(var i = 0; i < items.length; i++)
			if(items[i].indexOf(key+'=') === 0)
				return decodeURIComponent(items[i].substr(key.length+1));
		return null;
	}

	$.addslashes = function(str) {
		return str.replace(/([\'\"])/ig, '\\$1');
	}
})(jQuery);

function id( domid ) {
	return this.document.getElementById( domid );
}

/* 设置所属域名 */

//var regex = /(?:qtcms\.com):8211$/i, tmp1 = regex.exec(location.host);
//if(tmp1.length > 0) document.domain = tmp1[0];

/*$(function(){
	if( !document.getElementById($.dialogbox.id) && parent && parent.$ && parent.$.dialogbox ) {
		$.dialogbox.callback = parent.$.dialogbox.callback;
		$.dialogbox.thisobj = parent;
	}
});*/