var KT = {};
KT.isDebug = false;
KT.debugArea = null;
KT.Chk = {};
KT.Fun = {};
KT.Fun.flashcopyer = null;
KT.Fun.copy = function(str)
{
		var s;
		if(KT.Chk.isString(str)){
			s = str;
		}else if(KT.Chk.isElement(str)){
			s = str.value;
		}else{
			return false;
		}
		if(window.clipboardData && clipboardData.setData){
			clipboardData.setData("text", s);
		}else{
			if(!KT.Fun.flashcopyer){
				var div = new Element("div",{});
				this.flashcopyer = div;
				document.body.appendChild(div);
			}
			this.flashcopyer.innerHTML = '<embed src="/images/clipboard.swf" FlashVars="clipboard=' + encodeURIComponent(s) + '" width="0" height="0" type="application/x-shockwave-flash"></embed>';
		}
		return true;
}
KT.Fun.len = function(str)
{
	var i,rt=0;
	for(i=0;i<str.length;i++)
	{
		rt++;
		if(str.charCodeAt(i)>256)rt++;
	}
	return rt;
}
KT.clipboard = function(objstr){
	var obj					= $(objstr).getElement('.clipboardcopyed');
	obj.innerHTML			= '网址复制成功';
	setTimeout(function(){obj.innerHTML=''},2000);
}
//KT.clipboard.make('baby_link_clipboard','url')

KT.clipboard.make = function(objstr,url)
{
	var obj	=$(objstr);
	var str = '<div style="width:360px;float:left"><iframe frameborder=0 style="width:360px;height:22px" src="/swf/cboard/index.html?'+objstr+'?'+url+'"></iframe></div><div style="margin-left:365px;line-height:22px;font-size:12px;te" class="clipboardcopyed"></div>';
	obj.innerHTML = str;
}

KT.Chk.isUndefined = function (obj) {
	return typeof obj == "undefined";
}
KT.Chk.isString = function (obj) {
    return typeof obj == "string";
}
KT.Chk.isEmpty = function (obj) {
	return obj+"a" == "a";
}
KT.Chk.isElement = function (obj) {
	return obj && obj.nodeType == 1;
}
KT.Chk.isFunction = function (obj) {
	return typeof obj == "function";
}
KT.Chk.isObject = function (obj) {
	return typeof obj == "object";
}
KT.Chk.isArray = function (obj) {
	return obj !== null && typeof obj == "object" &&'splice' in obj && 'join' in obj;
}
KT.Chk.isNumber = function (obj){
	return typeof obj == 'number';
}
KT.Chk.isEqual = function (obja,objb)
{
	return obja+"a" == objb+"a";
}
KT.Chk.isJSON = function (str){
	if (!isString(str) || str === '') {return false;}
	str = replace(/\\./g, '@').replace(/"[^\"\\\n\r]*"/g, '');
	return (/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(str);
}
KT.Chk.isEmail = function (str){
	var par = /^[0-9a-zA-Z_.-]+@[0-9a-zA-Z-]+\.([a-zA-Z]{2,4}|[0-9a-zA-Z-]+\.[a-zA-Z]{2,4})$/;
	return (str.search(par)==0);
}

KT.Chk.isNum = function (str){
	var par = /^[0-9]+$/;
	return (str.search(par)==0);
}
KT.Chk.isPasswd = function (str){
	var par = /^[0-9a-zA-Z_~!@#$%^\-&*()]{6,16}$/;
	return (str.search(par)==0);
}

/**
 *	翻页器
 * param e_id 容器id
 * param link 链接程序的url,此程序接受start和limit作为参数
 * param count 列表总数量
 * param start 起始数量
 * param limit 每页显示数量
**/
KT.Pager = function (e_id, link, count, start, limit)
{
    /* 计算总页数 */
    var page = parseInt(count/limit);
    if (count%limit != 0) {
	page++;
    }
    if (page <= 1) {
	return true;
    }

    /* 计算当前页 */
    var current = parseInt(start/limit);
    current++;

    /* 输出的翻页器html代码 */
    var html = '';
    // html += '<form name="kt_pager" action="'+link+'" method="get">';

    /* 取出link中的参数 */
    var tmp = link.split('?');
    var param_deli = '?';
    if (tmp.length > 1) {
	var tmp2 = tmp[1].split('&');
	for (var i=0; i<tmp2.length; i++) {
	    tmp = tmp2[i].split('=');
	    html += '<input type="hidden" name="'+tmp[0]+'" value="'+tmp[1]+'" />';
	}
	param_deli = '&';
    }

    /* 输出上一页和首页 */
    if (current > 1) {
	html += '<a href="'+link+param_deli+'start=0&limit='+limit+'" class="padding">首页</a>&nbsp;';
	html += '<a href="'+link+param_deli+'start='+(start-limit)+'&limit='+limit+'" class="padding">上一页</a>&nbsp;';
    }

    /* 输出当前页及附近5页 */
    for (var i=current-4; i<=current+4; i++) {
	if (i < 1 || (current - i) > ((page-current>2)?2:(4-page+current))) {
	    continue;
	}
	if (i > page|| (i - current) > ((current-1>2)?2:(5-current))) {
	    break;
	}
	/* 当前页 */
	if (current == i) {
	    html += '<a href="#" onclick="return false;" class="page_green">'+i+'</a>';
	    continue;
	}
	html += '<a href="'+link+param_deli+'start='+(i-1)*limit+'&limit='+parseInt(limit)+'">'+i+'</a>';
    }

    /* 输出下一页和末页 */
    if (current < page) {
        var start_last = (page-1)*limit;
	html += '&nbsp;<a href="'+link+param_deli+'start='+(parseInt(start)+parseInt(limit))+'&limit='+limit+'" class="padding">下一页</a>';
        html += '&nbsp;<a href="'+link+param_deli+'start='+(page-1)*limit+'&limit='+limit+'" class="padding">末页</a>';
    }

    /* 输出跳转框 */
    // html += '&nbsp;&nbsp;&nbsp;第<input type="text" name="pages" value="'+current+'" >页'+
    // 	'<input type="hidden" name="start" value="" />'+
    // 	'<input type="hidden" name="limit" value="'+limit+'" />'+
    // 	'&nbsp;<a href="#" class="btn_page"'+
    // 	' onclick="document.kt_pager.onsubmit();return false"'+
    // 	'>跳转</a></form>';

    $(e_id).set('html', html);
    // document.kt_pager.onsubmit = function() {
    // 	document.kt_pager.start.value=(document.kt_pager.pages.value-1)*limit;
    // 	document.kt_pager.submit();
    // }
    return true;
}

KT.Timy = function(stime)
{

	var today	= new Date();
	var st		= KT.Timy.serverTime || 0;
        st = st*1000;
	return parseInt((st - stime.getTime())/1000);
}

KT.Timing = function(stime){
	var onesec	= 1;
	var onemin	= 60;
	var onehour =3600;
	var oneday	= 86400;
	
	stime		= new Date(stime*1000);
	var time	= KT.Timy(stime);

	if(time<=onesec)
	{
		document.write('1秒前');
	}
	else if(time<=onemin)
	{
		document.write(time+'秒前');
	}
	else if(time<onehour)
	{
		document.write(parseInt(time/onemin)+'分钟前');
	}
	else if(time<oneday)
	{
		//document.write(parseInt(time/onehour)+'小时'+parseInt((time%onehour)/onemin)+'分钟之前' );
		document.write(parseInt(time/onehour)+'小时前');
	}
	else
	{
	    var min = stime.getMinutes();
	    min = (parseInt(min)<10)?(min='0'+min):min;		
	    document.write((stime.getMonth()+1)+'月'+stime.getDate()+'日');
	}	
}

KT.getTiming = function(stime){
	stime = parseInt(stime);
	var sd = new Date(stime*1000);
	var td = new Date();
	var st = KT.Chk.isUndefined(KT.Timy.serverTime)?parseInt(td.getTime()/1000):KT.Timy.serverTime;
	stime = st - stime;

	if(stime<=1)
	{
		return '1秒前';
	}
	else if(stime<=60)
	{
		return stime+'秒前';
	}
	else if(stime<3600)
	{
		return parseInt(stime/60)+'分钟前';
	}
	else if(stime<86400)
	{
		return parseInt(stime/3600)+'小时前';
	}
	else if(stime<864000)
	{
		return parseInt(stime/86400)+'天前';
	}
	else
	{
	    var min = sd.getMinutes();
	    min = (parseInt(min)<10)?(min='0'+min):min;		
	    return (sd.getMonth()+1)+'月'+sd.getDate()+'日';
	}	
}

KT.logout = function(){
	//new jDialog({"title":"退出登录","width":300,"height":150,"disableBG":true,"content":"正在保存用户信息"}).create();
	var jsonRequest = new Request.JSON({url: "/user/logout.php", onSuccess: function(r)
	{
		top.location.replace('/');
	}}).get({time:Math.random()});
}

KT.HtmlEncode = function(str) {
        var   s   =   "";  
        if   (str.length   ==   0)   return   "";  
        for   (var   i=0;   i<str.length;   i++)  
        {  
              switch   (str.substr(i,1))  
              {  
                      case   "<"     :   s   +=   "&lt;";       break;  
                      case   ">"     :   s   +=   "&gt;";       break;  
                      //case   "&"     :   s   +=   "&amp;";     break;  
                      case   "\""   :   s   +=   "&quot;";   break;  
                      case   "\n"   :   s   +=   "<br>";       break;  
                      default       :   s   +=   str.substr(i,1);   break;  
              }  
        }  
        return   s;  
  }  


/* 给带http的网址自动加上链接 */
KT.AutoLink = function(str){
	var url_pattern = /(http\:\/\/[a-zA-Z0-9\.\/\\?!@#$%^&:;_+=-]+)/g;
	var tmp = str.replace(url_pattern, "<a href=\"$1\" class=\"extlink\" target=\"_blank\">$1</a>");
	var url_pattern_tmp = /(<a href=\"http\:\/\/[a-zA-Z]+\.kuantu\.com[a-zA-Z0-9\.\/\\?!@#$%^&:;_+=-]+\") class=\"extlink\"/g;
	var src = tmp.replace(url_pattern_tmp, "$1");
	return src;
}

/* 插入字符让字符串能自动换行，修改中 */
KT.BreakWord = function(str){
	str = KT.HtmlEncode(str);
	str = KT.AutoLink(str);
	//var re = /&lt;|&gt;|&amp;|&quot;|<a.+<\/a>|<br>|[^0-9a-zA-Z&<]+|[(^&lt;)(^&gt;)0-9a-zA-Z]{0,15}/g;
	//var s = str.trim().match(re).join('&#8203;');
	s = str.replace(/([a-zA-Z]{15})/g, '$1&#8203;');
	return s;
}

/* 判断字符串是否小于长度，用处如：若大于，则显示“>>”按钮  */
KT.CheckWordLength = function(str, l){
	l = (l/2).toInt(); //因为暂时只判断中文
	s = str.replace(new RegExp("&#8203;","g"),'');
    s = s.replace(new RegExp('<.+?>','g'),'')
	if($('more_current_word')){
		if (s.length>l)
		{
			$('more_current_word').style.display = "block";
		}else{
			$('more_current_word').style.display = "none";
		}
	}
	//return str.substring(0, l);
}

/* 处理字符串 */
KT.FiltWord = function(str, options){
	options = $extend({
            noTag: true,
			breakWord: true,
			autoLink: true,
            localDomain: 'kuantu\.com',
            wordLimit: -1
	}, options || {});
    if (str.length == 0) return '';
    var s = '';
    
    if (options.noTag){
        for (var i=0, l=str.length; i<l; i++){
            switch (str.substr(i, 1)){
                case "<": s += "&lt;"; break;
                case ">": s += "&gt;"; break;
                default : s += str.substr(i, 1); break;
            }
        }
    } else {
        s = str;
    }
    if (options.autoLink){
        var url_pattern = /http\:\/\/([a-zA-Z0-9\.\/\\?!@#$%^:;_+=-]|(?:&(?!lt;|gt;)))+/g;
        s = s.replace(url_pattern, function(link){
            var extlink = '';
            var reg = new RegExp('^http://(?:\\w+?\\.)?'+options.localDomain);
            if(link.match(reg))
                extlink = ' class="extlink"';
            return '<a href="' + link + '"' + extlink +' target="_blank">' + link + '</a>';
        });
    }
    
    var s_pattern = /<a[^>]*>.*?<\/a[^>]*>|&lt;|&gt;|&|\\|\\n|[a-zA-Z]{15}/gi;
    s = s.replace(s_pattern, function(match){
        if(options.breakWord && match.search(/^[a-zA-Z]/)===0) 
            return match + '&#8203;'
        switch (match){
            case '&': return options.noTag ? '&amp;' : match;
            case '\"': return options.noTag ? '&quot;' : match;
            case '\n': return options.noTag ? '<br>' : match;
            default: return match;
        }
    });
    var s_pattern = /<script[^>]*?>.*?<\/script>/ig;
    s = s.replace(s_pattern,'').trim();


    return s; 
}

/* 某element逐渐消失，最后在页面中移除。*/
KT.RemoveElement = function(obj, options){
		this.options = $extend({
			duration: 500			//消失过程的时间
		}, options || {});

		var efx = obj.get('tween', {property: 'opacity', duration: this.options.duration});
		efx.addEvent('complete',function()
			{
				obj.dispose();
			}.bind(this));
		efx.start(1,0);
}

KT.debug = function(t)
{
	if(KT.isDebug)
	{
		if(KT.debugArea == null)
			KT.debugArea = new Element("textarea",{"value":t,"styles":{"position":"absolute","top":10,"left":10,"width":125,"height":500,"font-size":"12px"}}).inject(document.body);
		else
			KT.debugArea.set("value",KT.debugArea.get("value")+"\n"+t);
	}
}

//秒数转时间
KT.second2day = function(second){
	document.write(KT.getSecond2day(second));
}

KT.getSecond2day = function(second){
	var str = '';
	if(second/(3600*24) >= 1){
		str += Math.floor(second/(3600*24)) + '天';
	}else if(second/3600 >= 1){
		str += Math.floor(second/3600) + '小时';
	}else if(second/60 >= 1){
		str += Math.floor(second/60) + '分钟';
	}else{
		str += second + '秒';
	}
	return str;
}

KT.getFormatTime = function(time){
	return new Date(parseInt(time) * 1000).toLocaleString().replace(/\s.*?$/,''); 
}

//checkbox的全选。使用方法：KT.AddCheckAll('check_all_id', 'im_group');参数1：全选checkbox控件id，checkbox组name
KT.AddCheckAll = function(check_all_id, check_group_name){
	var check_all = $(check_all_id);
	var check_group = $$('input[name='+check_group_name+']');
	check_all.addEvents({
		'click': function(){
				for(var i=0, l=check_group.length; i<l; i++){
					check_group[i].checked = check_all.checked;
				}
		}
	});
	check_group.addEvents({
		'click': function(){
			var tmp = true;
			for(var i=0, l=check_group.length; i<l; i++){
				if(!check_group[i].checked){
					tmp = false;
					break;
				}
			}
			check_all.checked = tmp;
		}
	});
}

// 取出checkbox里被选中的数据
KT.checkboxCheckedArr = function(checkboxName){
	var checkboxs = document.getElements('input[name='+checkboxName+']');
	var arr = new Array();
	for (var i=0, l=checkboxs.length; i<l; i++)
	{
		if (checkboxs[i].checked)
		{
			arr.push(checkboxs[i].value);
		}
	}
	return arr;
}

KT.GoUrl = function(url) {
	if (url != '') {
		window.location=url;
	}
	else {
		window.location.reload();
	}
}

KT.checkEmail = function(email){
	var re = /^\s*\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*\s*$/;
	return re.test(email);
}
KT.formatBirth = function(birth){    
        birthStr = '';
        var year = birth.substr(0,4);
        var month = birth.substr(5,2);
        var day = birth.substr(8,2);
        if(year == '0000') birthStr = '某年' ;
        else  birthStr = year+'年' ;
        if(month == '00') birthStr = birthStr+'某月' ;
        else  birthStr = birthStr+month+'月' ;
        if(day == '00') birthStr = birthStr+day+'日' ;
        else  birthStr = birthStr+day+'日' ;
        return birthStr;
}
KT.getAstro = function(birth){    
        var month = birth.substr(5,2);
        var day = birth.substr(8,2);
        var s="魔羯水瓶双鱼牡羊金牛双子巨蟹狮子处女天秤天蝎射手魔羯";
        var arr=[20,19,21,21,21,22,23,23,23,23,22,22];
        return s.substr(month*2-(day<arr[month-1]?2:0),2) + '座';
}

// 删除字符串中的所有空格
KT.trimAll = function(str){
	return str.replace(/\s/g, '');
}

