if(parent.InitMainFrame)window.setTimeout(parent.InitMainFrame,800)
//http://mng.qbar.qq.com/cafecgi_mng_showallinfo.cgi
//==================================================================
var Params = new Array();
var _$paramStr = new String(window.location.href.replace(/.*(#|\?)/g,''));
if (_$paramStr.length > 0)
{
    var _$paramArr = _$paramStr.split('&');
    for (var i = 0; i < _$paramArr.length; i++)
    {
        if (_$paramArr[i].indexOf('=') >= 0)
        {
            var _$paramKeyVal = _$paramArr[i].split('=');
            Params[_$paramKeyVal[0]] = decodeURIComponent(_$paramKeyVal[1]);
        }
    }
}
//=================================================================
var gotopage = T.GetCookie('tmpPage')||1;

//=================================================================
//Params: action atclid replyid / title
var action = Params.action || "add"; // modify quote reply modreply
var atclid = Params.atclid || 0;
var replyid = Params.replyid || 0;
var title = Params.title || "";
var qbarid = null;//parent.G.qbarid;
var Boards = parent.G_boards;//需要对FF做修正
var ulevel = null;//parent.STATIC_RESULT.static_selfuser.level;
var minFitEditorHeight;//parent.document.body.clientHeight-500;
var Main_RESULT;
var uin=T.GetUIN(),unick;
var RESULT1;


if (uin) uin = String(uin).replace(/^(\D|0)+/ig,'');
else uin = 0;
//==================================================================
T.OnDOMLoaded.Load(Init);
//==================================================================

if (window==window.top)
{
    //--window.location.hash = T.isIE?"":"#";
}

function IsHaveWritePriv(brdid)
{
	if(brdid==0)return true;
    var priv = action=="add" ? Boards[brdid].postpriv : Boards[brdid].simrplpriv;

    return parent.IsHaveReadPriv(brdid,priv);
}

function BasicDataAllLoaded()
{
    T.RenderDOM('DOM_MainTop',Main_RESULT);
	ulevel = Main_RESULT.sys_param.ulevel;
	var topBackStyle = T.$("DOM_topBanner").style;
	//topBackStyle.backgroundRepeat = "no-repeat";
    var backimg = Main_RESULT.cafe_info.head_img;
    document.title = Main_RESULT.cafe_info.name+":Q吧";
    if (!backimg) backimg = 1;
    var backimgurl = "";
    if (parseInt(backimg)==Number(backimg))
    {
        backimgurl="url(http://imgcache.qbar.qq.com/qbar/qbar2/images_banner/"+parseInt(backimg)+".gif)";
    }
    else backimgurl="url("+backimg+")";
    /***********************************************/
    var _$headHeight = Main_RESULT.cafe_info.headimgheight;
    
    if (!_$headHeight) _$headHeight = 100;
    _$headHeight = parseInt(_$headHeight);
    if (_$headHeight>120)_$headHeight = 120;
    
    if (_$headHeight<=120) topBackStyle.height = _$headHeight;
    if (_$headHeight<1) T.$("DOM_topBanner").outerHTML = "";
    
    if (_$headHeight>0 && _$headHeight<50) T.$("DOM_topBanner").innerHTML = "";
    //if (_$headHeight>=50) T.$('DOM_topBanner').getElementsByTagName("div")[0].style.top = (_$headHeight-40)/2+25;
    //
	if (_$headHeight>0)topBackStyle.backgroundImage  = backimgurl;
	topBackStyle.backgroundImage  = backimgurl;
    /***********************************************/
    T.RenderDOM('DOM_MainFooter',Main_RESULT);
    if (Main_RESULT.sys_param.uin) QBAR1.LoadFavorite();
}

var QBAR1 = {
    LoadFavorite:function(){
        T.LoadJS("http://imgcache.qbar.qq.com/qbar/qbar2/QBAR1.js",QBAR1.LoadFavorite);
    }
}

function ShowData(time)
{
    var date = new Date(time*1000);
    var y = date.getFullYear();
    var m = date.getMonth()+1;
    var d= date.getDate();
	return (y+"."+m+"."+d);
}

function Init()
{
	if (ulevel==0 && uin)
    {
        alert("对不起，只有成员才能发帖，您不是本Q吧成员");
		if (window!=window.top) window.history.back();
        return;
    }
	else if (ulevel==0 && T.GetUIN()=='')
	{
		alert("对不起，成员登录后才能发帖，您登录已超时");
		if (window!=window.top) window.history.back();
        return;
	}
    else if (!uin)
    {
        top.T.CreateLoginFrameWin();
        if (window!=window.top) window.history.back();
        return;
    }
	parent.scrollTo(0,120);
    T.LoadData("http://mng.qbar.qq.com/cgi-bin/cafecgi_mng_showallinfo.cgi",function(RESULT)
    {
        RESULT1=Main_RESULT = RESULT;
        qbarid = RESULT.cafe_info.id;
        ulevel = RESULT.sys_param.ulevel;
        uin = RESULT.sys_param.uin;
        unick = RESULT.sys_param.unick;

        minFitEditorHeight = document.body.clientHeight-(window==window.top?390:400);
        
        if (minFitEditorHeight<=320) minFitEditorHeight = 320;
		if (minFitEditorHeight>500) minFitEditorHeight = 500;
		

        if (window==window.top)
        {
            document.body.style.margin="2px 5px";
            
            T.LoadData("http://mng.qbar.qq.com/cgi-bin/cafecgi_mng_showboard.cgi",function(RESULT){
                var boards = RESULT.boards;
                for (var i=0; i<boards.length; i++)
                {
                    Boards[boards[i].brdid] = boards[i];
                    /*
                    Boards[boards[i].brdid].readpriv = a[boards[i].readpriv];
                    Boards[boards[i].brdid].postpriv = a[boards[i].postpriv];
                    Boards[boards[i].brdid].simrplpriv = a[boards[i].simrplpriv];*/
                    //if (boards[i].type=="6") Boards['atd']=boards[i]; //每日报到型专门赋值 
                }
                BasicDataAllLoaded();
                Init2();
				try{
					T.$('DOM_BODYDIV').style.width='990px';
					T.$('title').style.width='700px';
				}catch(e){}
            });
        }
        else
        {
            Boards = parent.G_boards;
            Init2();
			/*
			document.body.ondblclick=function(){parent.AutoSetFullViewMode()}
			if (window.name=='Dname_mainFrame2')
			{
				parent.document.body.style.overFlow='hidden';
				document.getElementsByTagName('html')[0].style.overflowY='scroll';	minFitEditorHeight=parent.document.documentElement.clientHeight-295;//242
				parent.AutoSetFullViewMode(2);
			}
			*/
        }
    });
}

function Init2()
{
    T.RenderDOM('DOM_TPL',RESULT1);
	T.$('D_1').href=BASE
	T.$('D_1').onclick=function(){
		window.setTimeout(function(){location.href='../home_.htm'},10);
	return false}

    if (action=='add' && T.$("DOM_setTopTD"))
    {
        T.$("DOM_setTopTD").style.display="";
    }
    if (action=='add')
    {
        T.$("DOM_brdTR").style.display = "";
        T.$("DOM_titleTR").style.display = "";
        
        if (Params.brdid)
        {
            T.$("brdid").value = Params.brdid;
        }
        InitEditor();
		if(RESULT1.cafe_info.req_verify==1)VerifyCode_Change();
    }
    else if (action=='modify' && atclid && replyid)
    {
        var u = "http://bbs.qbar.qq.com/cgi-bin/cafe_cgi_bbs_general_richreply_read.cgi?atclid="+atclid+"&replyid="+replyid;
        T.LoadData(u,InitEditor);
    }
    else if (action=='modify' && atclid)
    {
        if (T.$("DOM_setTopTD"))
        {
            T.$("DOM_setTopTD").className="listbg";
        }
        T.$("DOM_titleTR").style.display = "";

        var u = "http://bbs.qbar.qq.com/cgi-bin/cafe_cgi_bbs_general_article_read.cgi?atclid="+atclid;
        T.LoadData(u,InitEditor);
    }
    else if (action=='quote' && atclid)
    {
        //这里需要修改为查看单个回帖的CGI
        var u = "http://bbs.qbar.qq.com/cgi-bin/cafe_cgi_bbs_general_richreply_read.cgi?atclid="+atclid+"&replyid="+replyid;
        if (!replyid)
        {
            u = "http://bbs.qbar.qq.com/cgi-bin/cafe_cgi_bbs_general_article_read.cgi?atclid="+atclid;
        }
        T.LoadData(u,SetContent_Quote);
		if(RESULT1.cafe_info.req_verify==1)VerifyCode_Change();
    }
    else if (action=="reply" && atclid)
    {
        InitEditor();
		if(RESULT1.cafe_info.req_verify==1)VerifyCode_Change();
    }
    
    if (atclid) T.$("atclid").value = atclid;
    if (action=="quote" || action=="reply")
    {
        T.$("title").removeNode(true);
        T.$("brdid").removeNode(true);
        
        T.$("DOM_replyTitleTR").style.display = "";
        T.$("DOM_replyTitle").value = title;
    }
    else if (action=="modify")
    {
        T.$("brdid").removeNode(true);
        if (replyid){
            T.$("title").removeNode(true);
        }
    }
	
    ChangeSetBrdid();
	if(!T.$('brdid'))return;
	T.$('brdid').onchange=ChangeSetBrdid;
}

function ChangeSetBrdid()
{
	if(!T.$('brdid'))return;
	if(T.$('brdid').value==''||IsHaveWritePriv(T.$('brdid').value)) T.$('D_showPrivMsg').style.display='none';
	else if(T.$('D_showPrivMsg'))T.$('D_showPrivMsg').style.display='';
}

function RenewQQVideo(str)
{
	var div=document.createElement("DIV");
	div.innerHTML=str;
	allimgs=div.getElementsByTagName("img");
	for (var i=allimgs.length-1;i>=0;i--)
	{
		var item=allimgs[i];
		if (item.mtype && item.vid && item.mtype=="qqvideo")
		{
			var vid=item.vid;
			item.outerHTML='<img mtype="qqvideo" vid="'+vid+'" style="display:block" src="http://imgcache.qbar.qq.com/b03style/img_default/icon_qqvideo2.gif" title="http://video.qq.com/res/qqplayerout.swf?vid='+vid.toTitle()+'">';
		}
	}
	return div.innerHTML;
}

function SetContent_Quote(RESULT)
{
    var $ = function(a){return T.$(a)};
    var a = RESULT.atcl_main;
    if (!a) a = RESULT.reply;

    var quoteHTML = "<div align=center><div class='BBS_QUOTE'><img src='http://imgcache.qq.com/qbar_v1/client/images/qbar_iconb24.gif'> <B>引用 "+a.unick.toHTML()+" ("+a.uin+")在 "+new Date(a.time*1000).toLocaleString();
	if(!Params.retofloor)quoteHTML+="(顶楼)"
    
    quoteHTML += "的发表:</B><br>"+RenewQQVideo(a.cont)+"</div></div><br>";

    $('DOM_editor').value = quoteHTML;
    $("atclid").value = atclid;
    //if ($("title")) $("title").value = title;
    Editor = new FCKeditor('DOM_editor','100%');
	Editor.BasePath	= "../Editor/";
    Editor.ReplaceTextarea();
    //----T.AutoWinHeight(450);
}

var Editor;
function InitEditor(RESULT)
{
    if (RESULT) {
        SetArticle(RESULT);
        var a = RESULT.atcl_main;
        if (!a) a = RESULT.reply;
        T.$('DOM_editor').value = RenewQQVideo(a.cont);
    }

    Editor = new FCKeditor('DOM_editor','100%');
	Editor.BasePath	= "../Editor/";
	
    Editor.ReplaceTextarea();
    
    //----T.AutoWinHeight(450);
	//T.$('DOM_editorTD').innerHTML = editor.CreateHtml();
}


function SetArticle(RESULT)
{
    var $ = function(a){return T.$(a)};
    var a = RESULT.atcl_main;
    if (!a) a = RESULT.reply;
    $("atclid").value = atclid;
    if ($("title")) $("title").value = a.title;

	var _$photos = a.photos;
    for (var i=0; i<_$photos.length; i++)
    {
        var _$codeArr = _$photos[i].code.split("|");
        var _$code = _$codeArr[0]+"|"+_$codeArr[1];
		allPhotos.push({code:_$code,surl:_$photos[i].surl,lurl:_$photos[i].lurl,size:_$photos[i].size});
    }

    SetImgSizeSum();

    if ($("isatp") && a.top==2)   { $("isatp").checked = $("istp").disabled = true; }
    else if ($("isatp") && a.top==1) { $("istp").checked = $("isatp").disabled = true; }
    else {  }

    if ($("brdid")) $("brdid").disabled = true;
    if ($("lock0"))
    {
        $("lock0").checked = (a.lock==1);
        $("lock1").checked = (a.lock==0);
    }

    if ($("brdid")) $("brdid").value = a.brdid;
}

/** 新增、修改、回复帖子的提交操作 */
var $ = function(id){return T.$(id)};
var G_editcontent;
function ArticleSubmit()
{
    try{top.onLoginSuccesReLoad=false}catch(e){}

    if($("brdid") && !$("brdid").disabled)
    {
        if($("brdid").value==0)
        {
			alert('请选择版面');
            $("brdid").focus();
            return;
        }
		else if($("D_showPrivMsg").style.display!='none')
        {
			alert('你无本版发帖权限，请选择其他版面');
            $("brdid").focus();
            return;
        }
    }

    if ($("title") && $("title").value.length2() > 75)
    {
		alert("标题过长,当前标题有 "+$("title").value.length2()+" 字节\n\n(最大允许75字节)")
        //T.ERROR.MSG(7,"当前标题有 "+$("title").value.length2()+" 字节");
        $("title").focus();
        return;
    }
    else if ($("title") && $("title").value.trim2()=="")
    {
		alert('标题不能为空')
        //T.ERROR.MSG(11);
        $("title").focus();
        return;
    }


    var _$editbody = FCKeditorAPI.GetInstance('DOM_editor').EditorDocument.body; 
    G_editcontent = _$editbody.innerHTML;

	if (G_editcontent.length<10 && (action=="reply" || action=="quote" || replyid))
	{
		alert('麻烦多写点内容啦~~\n\n回复字数至少为10个');
		return;
	}

	if(IsEmptyValue())
	{
		alert("内容不能为空");
		return;
	}

    if (G_editcontent.length2() > 30000 && T.$("title") && T.$("title").value)
    {
		alert("内容过多,当前内容有 "+G_editcontent.length2()+" 字节\n\n(最大允许30000字节)")
        //T.ERROR.MSG(8,"当前内容有 "+_$content.length2()+" 字节");
        return;
    }
    else if (!T.$("title") && G_editcontent.length2() > 20000)
    {
		alert("内容过多,当前内容有 "+G_editcontent.length2()+" 字节\n\n(最大允许20000字节)")
        //T.ERROR.MSG(10,"当前内容有 "+_$content.length2()+" 字节");
        return;
    }
    else if (G_editcontent.toText().trim2().length==0 && _$editbody.getElementsByTagName('IMG').length==0)
    {
		alert("内容不能为空")
        //T.ERROR.MSG(12);
        return;  
    }  
    else 
    {
        var _$img = allPhotos;
        var _$imgcount = 0;
        var _$lastIndex;
        var _$imgHtml = "";
        for (var i=0;i<_$img.length;i++)
        {
            var _$lurl = _$img[i].lurl;
            var _$match = _$lurl.match(/^http:\/\/.*\//);
            if (_$match)
            {
                var _$domain = _$match[0].toLowerCase();
                var _$lurl2 = _$domain + _$lurl.replace(_$match[0],'');
                if (G_editcontent.indexOf(_$lurl)==-1 && G_editcontent.indexOf(_$lurl2)==-1)
                {
                    _$imgcount ++;
                    _$lastIndex = i;
                    _$imgHtml += GetHTMLOnInsertImg()+'<IMG src="'+_$lurl2+'"><br>'+GetHTMLOnInsertImg();
                }
            }
        }
        if (_$imgcount>0)
        {            
            if (!window.confirm('有 '+_$imgcount+' 图片附件未被使用，点击“确定”不使用这些图片（以后会被自动删除）\n\n点击“取消”，图片将被自动插入在文章内'))
            {
                FCKeditorAPI.GetInstance('DOM_editor').InsertHtml(_$imgHtml);
                return;
            }
        }
    }

	var v=null;
	if(RESULT1.cafe_info.req_verify==1&&(action=='add'||action=='quote'||action=='reply'))
	{
		v=T.$('D_verifyCode').value;
		if (v.length!=4)
		{
			alert('请正确填写验证码');
			VerifyCode_Focus(true);
			return;
		}		
	}
	
	var _$param  = _$GetArticleParams();
	if (!_$param) return;
	if (v) _$param.push('verifycode='+v);

    var u, cb;
    //以下的分支和最开始的分支逻辑应一致
    if (action=='add')
    {
        u = "http://bbs.qbar.qq.com/cgi-bin/cafe_cgi_bbs_general_article_post.cgi";
        cb = OnAddSuccess;
    }
    else if (action=='modify' && atclid)
    {
        u = "http://bbs.qbar.qq.com/cgi-bin/cafe_cgi_bbs_general_article_mod.cgi";
        if (replyid) {
            u = "http://bbs.qbar.qq.com/cgi-bin/cafe_cgi_bbs_general_richreply_mod.cgi";            
        }
        cb = OnModSuccess;
    }
    else if ((action=="reply" || action=="quote") && atclid)
    {
        u = "http://bbs.qbar.qq.com/cgi-bin/cafe_cgi_bbs_general_richreply_post.cgi";
        cb = function(data){
			var url = atclid;
			if (gotopage>1) url += '-'+gotopage;
			if(GetContentDouche()>5)
			{
				alert("内容分析系统怀疑您正在恶意灌水，您可能会受到扣分、禁言等处罚，请不要发表类似内容！");
			}
			location.href='../'+url+'.htm';
		};
    }

    T.PostData2([1,u], _$param, cb,OnPostContentFail);

    function OnModSuccess()
    {
		var url = atclid;
		if (gotopage>1) url += '-'+gotopage;
		location.href='../'+url+'.htm';
    }

    function OnAddSuccess(data)
    {
		var url = data.atcl.id;		
		location.href='../'+url+'.htm';
    }
}

function GetContentDouche() {
	var words=G_editcontent;
	var W = new Object();
	var Result = new Array();
	var iNumwords = 0;
	var iEnglish = 0;
	var iNumber = 0;
	var iTotal = 0;
	var iOther = 0;
	var fir=0,sec=0;
	var score=0;
	for (i=0; i<words.length; i++) {
		var c = words.charAt(i);
		if (c.match(/[\u4e00-\u9fa5]/)) {
			if (isNaN(W[c]))W[c] = 1;
			else W[c]++;
			iNumwords++;
			iTotal++;
		}
		else if (c.match(/[a-zA-Z]/)) {
			if (isNaN(W[c]))W[c] = 1;
			else W[c]++;
			iEnglish++;
			iTotal++;
		}
		else if (c.match(/[0-9]/)) {
			if (isNaN(W[c]))W[c] = 1;
			else W[c]++;
			iNumber++;
			iTotal++;
		}
		else if (c.match(/[\u0000-\u0020]/)) {			
		}
		else {
			if (isNaN(W[c]))W[c] = 1;
			else W[c]++;
			iOther++;
			iTotal++;			
		}
	}
	for (var high in W )
	{
		if (fir<W[high])
		{
			sec = fir;
			fir = W[high];
		}
		else if (sec<W[high])
		{
			sec = W[high];
		}
	}
	
	if (iTotal > 7)
	{
		score = fir/iTotal * 10 + sec/iTotal * 5;
		if (iOther/iTotal > 0.8){
			score += 4;
		}
	}
	return score;	
}

function OnPostContentFail(RESULT)
{
    var retcode = RESULT.sys_param.ret_code;
	var reg=/4320(\d+)/i;
    if (retcode==4015)
    {
        alert('验证码错误，请重新填写');
        VerifyCode_Change(true);
		return;
        //T.ERROR.MSG(4015);
    }
	else if (retcode==4321)
	{
		alert("对不起，您今天发帖过多！\n每天最多能发表30条主帖、100条回复");
		VerifyCode_Change(true);
		return;
	}
	else if (reg.test(retcode))
	{
		var tmpt=parseInt(RegExp.$1,10);
		var m=Math.floor(tmpt/60);
		var s=Math.floor(tmpt%60);
		var str="";
		if (m)
		{
			str+=m+"分";
		}
		if (s)
		{
			str+=s+"秒";
		}
		alert("对不起，您的操作频率太快，请间隔“"+str+"”后再操作！\n\n时间间隔:发帖1分钟、回帖45秒、留言5分钟");
		VerifyCode_Change(true);
		return;
	}
    else T.PrepResult(RESULT);//此处可以调用T的默认方法，或自行采用其他方法，或者同时调用
	VerifyCode_Change();
}

function VerifyCode_Focus(flag)
{
	if(RESULT1.cafe_info.req_verify==0||action=='modify')return;
	var d=T.$('D_verifyCode');
	d.style.color='black';
	if(d.value==d.defaultValue||flag)
	{
		d.maxLength=4;
		d.value = '';
	}
	d.focus();
}

function VerifyCode_Change(flag)
{
	if(RESULT1.cafe_info.req_verify==0||action=='modify')return;
	T.$('D_vcodeimg').src = 'http://ptlogin2.qq.com/getimage/verifycookie?aid=3000701&'+Math.random();
    window.setTimeout(VerifyCode_Change,1000*60*20);
	if (flag)
	{
		var d=T.$('D_verifyCode');
		d.style.color='black';
		d.value = '';
		VerifyCode_Focus();
	}
}

T.OnDOMLoaded.Load(function(){
	try{
		if (T.isIE)document.body.attachEvent('onkeydown',OnBodyKeyUp);
		else window.addEventListener('keydown',OnBodyKeyUp,false);
	}catch(e){}
});

function OnBodyKeyUp(event)
{
	if(T.isIE)
	{
		if(event.keyCode==13&&(event.ctrlKey||event.srcElement==T.$('D_verifyCode'))) ArticleSubmit();
		return true;
	}
	if (!T.isIE&&!event)return true;

	var e = T.Event(event);
	//Ctrl + Enter 提交数据
	if(e.keyCode==13&&(e.ctrlKey||e.target==T.$('D_verifyCode')))ArticleSubmit();
}

function _$GetArticleParams()
{
    var pa = [];

    //pa.push("brdtype="+G.brdtype);    
    if ($("brdid") && !$("brdid").disabled) pa.push("brdid=" + $("brdid").value);
    if ($("atclid") && $("atclid").value) pa.push("atclid=" + $("atclid").value);
    if ($("title") && $("title").value && $("title").value!=undefined) pa.push("title=" + $("title").value);
    if ($("lock") && $("lock").checked) pa.push("lock=1");
    if ($("isatp") && $("isatp").checked) pa.push("top=2");
        else if ($("istp") && $("istp").checked) pa.push("top=1");
    //if ($("alwct")) pa.push("alwct=" + ($("alwct").checked?1:0));
    //if ($("alwcp")) pa.push("alwcp=" + ($("alwcp").checked?1:0));    
    if ($("lock")) pa.push("lock=" + ($("lock").checked?1:0));

	for (var i=0; i<allPhotos.length; i++)
	{
		pa.push("photo="+allPhotos[i].code);
	}

	var allimgs=FCKeditorAPI.GetInstance('DOM_editor').EditorDocument.getElementsByTagName("img");
	var chksum=0;
	for (var i=0; i<allimgs.length; i++)
	{
		if (allimgs[i].mtype=="qqvideo") chksum++;
	}
	if (chksum>5)
	{
		alert("最多只能插入5个视频！");
		return null;
	}
   //var _$content = FCKeditorAPI.GetInstance('DOM_editor').GetXHTML();
    var _$content = FCKeditorAPI.GetInstance('DOM_editor').EditorDocument.body.innerHTML;
    /*
    if ( action=="quote")
    {
            var _$quoteHTML = "<div align=center>"+T.$('DOM_quoteContent').innerHTML+"</div>";
            _$content = _$quoteHTML + _$content;
    }*/
    if (replyid) pa.push("replyid="+replyid);
	
	var videolist=[];

	var rdiv=document.createElement("DIV");
	rdiv.innerHTML=_$content;
	allimgs=rdiv.getElementsByTagName("img");
	for (var i=allimgs.length-1; i>=0; i--)
	{
		if (allimgs[i].mtype=="qqvideo")
		{
			var vid=allimgs[i].vid;
			allimgs[i].outerHTML='<img mtype="qqvideo" vid="'+vid+'">';
			videolist.push(vid);
		}
	}

	pa.push("video=" + videolist.join("|"));
	pa.push("content=" + rdiv.innerHTML);
    //pa.push("content=" + T.GetRand());
    return pa;
}

function SetContentLenPer()
{
	var maxlen = 20000;
	if(T.$("title") && T.$("title").value)maxlen=30000;
	var l=FCKeditorAPI.GetInstance('DOM_editor').EditorDocument.body.innerHTML.length2()/maxlen;
	l=100*l;
	var t='';
	if (l>100)t='<span style="color:red">'+String(l).substr(0,6)+"</span>";
	else t=String(l).substr(0,4);
	T.$('D_contLenPer').innerHTML=t;
}

function IsEmptyValue()
{
	var fckBody = FCKeditorAPI.GetInstance('DOM_editor').EditorDocument.body;
	var bh=fckBody.innerHTML;
	if(bh.length==0)return true;
	if (bh.replace(/\"|\'|\s|\n/gi,'').toLowerCase()==
		defHTML.replace(/\"|\'|\s|\n/gi,'').toLowerCase())
	{
		return true;
	}
	return false;
}

var bodyInnerDrag=false;
var defHTML='<SPAN style="COLOR: #808080">禁止发布色情、违法信息，商业广告，或群、Q吧、家族、空间的推广广告。<br><br>视情节，将给予禁止在Q吧平台发贴、回收QQ号码、回收群号码、回收Q吧、通报公安机关等处罚。</SPAN>';
function FCKeditor_OnComplete( editorInstance )
{
	SetContentLenPer();
    //EditorClearContent();//清除代码
    var fckDoc = FCKeditorAPI.GetInstance(editorInstance.Name).EditorDocument;
    var fckBody = fckDoc.body;
	fckDoc.selection.empty();
    if(fckBody.innerHTML=='')fckBody.innerHTML=defHTML;
	fckBody.onkeyup =SetContentLenPer;

	fckBody.onpropertychange =SetContentLenPer;

	fckBody.onpaste = EditorOnBodyPaste;
	fckBody.onclick = function(){
		if(IsEmptyValue())fckBody.innerHTML='';
	};

	fckBody.ondragstart = fckBody.ondragend = function(){ bodyInnerDrag = true; }
	fckBody.ondragenter = function(){ if(!bodyInnerDrag)return false; }
	//fckBody.ondragleave = fckBody.ondragend = function(){ bodyInnerDrag = false; }

	fckBody.attachEvent("onkeydown", OnBodyKeyUp);


    //fckBody.onkeyup = OnBodyKeyUp;
    //fckBody.onkeydown = fckBody.onkeypress = fckBody.onkeyup = EditorKeyEnterOnImage;
    
    T.$("DOM_editor___Frame").style.height=minFitEditorHeight+'px';
	//----T.AutoWinHeight(100);
    T.onLoginNeedReload=false;
	

}

function EditorKeyEnterOnImage()
{
    return false;
}

function EditorOnBodyPaste()
{
	SetContentLenPer();
    //try{
    //    window.clipboardData.setData('Text',window.clipboardData.getData('Text'));
    //}catch(e){}
    //FCKeditorAPI.GetInstance('DOM_editor').InsertHtml("&nbsp;");
    //TryEditorClearContent();
    //TryEditorAutoHeight();
}

function TryEditorClearContent()
{
    if (T.$('DOM_autoClearFlag').checked) EditorClearContent();
}

function TryEditorAutoHeight()
{
    window.clearTimeout(_$editorAutoHeightTimer);
    _$editorAutoHeightTimer = window.setTimeout(EditorAutoHeight,200);
}

var _$editorAutoHeightTimer;
function EditorAutoHeight()
{
    var h = FCKeditorAPI.GetInstance('DOM_editor').EditorDocument.body.scrollHeight;
    var h0=170, maxh = 360;
    
    if (h>h0) h0 = h;
    if (h0>maxh) h0 = maxh;
    var ch = parseInt(T.$("DOM_editor___Frame").style.height);
    if (!ch || ch<h0) T.$("DOM_editor___Frame").style.height = h0+30+"px";
    //----T.AutoWinHeight(150);
}

function TryAutoJoin()
{
	if (ulevel==0)
	{
		if (window.confirm('非本吧成员不能上传图片，您是否需要自动加入本Q吧？'))
		{
			T.LoadData('http://mng.qbar.qq.com/cgi-bin/cafecgi_mng_joinapply.cgi?typeid=1&answer1=00&answer2=00&answer3=&answer4=&answer5=', loadback);
			function loadback()
			{
				T.UpdateLastTime();
				alert("已成功加入，请选择您想进行的上传操作");
				ulevel = 1;
			}
		}
		return false;
	}
	return true;
}

/** 上传、连接图片相关功能 */
var pa;
function ToInsertImage()
{
    //if (this.doc.selection.type == "None") this.win.focus();
    //var sel = this.doc.selection.createRange();
    //this.doc.execCommand('InsertImage','','http://imgcache.qbar.qq.com/qbar/qbar/images/btn_write_cafe.gif');
    //sel.pasteHTML("<img border=2 src='http://imgcache.qbar.qq.com/qbar/qbar/images/btn_write_cafe.gif'>");
     //取消当前选中。以后可判断是 control 的或者 text 的就取消
    //var winparam = {qbarid:G.qbarid,Editor:Editor,DOM_imgList:$('DOM_imgList'),DOM_imgSizeSum:$('DOM_imgSizeSum')}

    //var imginfo="http://imgcache.qq.com/qbar_v1/client/images/qbar_post.gif";

	if (!TryAutoJoin()) return;

	if (allPhotos.length>14)
	{
		alert("最多只能插入15张图片！");
		return;
	}


    pa = {qbarid:qbarid};
    try{
        if (window.showModalDialog != null)  // IE
        {
            FCKeditorAPI.GetInstance('DOM_editor').EditorDocument.selection.empty();
            var imginfo=window.showModalDialog("../e/editor_insertImage.Dialog.htm",pa, "dialogHeight:250px;dialogWidth:380px;center:yes;status:0;help:no;scroll:no;resizable:no");  
        }
        else // firefox 
        {
            var ffwin = window.open("../e/editor_insertImage.Dialog.htm", "", 'modal=yes,height=170,width=349,scroll=0');
        }
    }catch(e){}
    
    if (!imginfo) return;
	DoInsertImg(imginfo);
	/*
    var imgpath;
    if (typeof(imginfo)=="object")
    {
        imgpath = imginfo[0].lurl;
    }
    else
    {
        imgpath = imginfo;
        imginfo = null;
    }
   	//FCKeditorAPI.GetInstance('DOM_editor').focus();
	FCKeditorAPI.GetInstance('DOM_editor').InsertHtml(GetHTMLOnInsertImg()+"<img src='"+imgpath+"'>"+GetHTMLOnInsertImg());
	//FCKeditorAPI.GetInstance('DOM_editor').EditorDocument.execCommand('InsertImage','',imgpath);
    SetContentLenPer();
	if (!imginfo) return;

	allPhotos.push(imginfo[0]);*/
/*
    var _$opt   = document.createElement("OPTION");
	//_$opt.text  = "PIC_"+($('DOM_imgList').options.length+1)+"　"+imginfo.size + "K";
    _$opt.text  = imginfo[0].size + "K";
	_$opt.value = imginfo[0].code;
    _$opt._lurl = imginfo[0].lurl;
    //_$opt._surl = imginfo[0].surl;
    _$opt._size = imginfo[0].size;
    _$opt.selected = true;
    /*
    var _$sel = T.$('DOM_imgList');
    _$sel.options.add(_$opt);
    
	ToViewImg(_$sel);

    SetImgSizeSum();*/
    //T.OpenTipWin("http://imgcache.qbar.qq.com/qbar/qbar/tpl/editor_insertImage.tpl.htm", {left: -58,top:-13});
}


var allPhotos=[]; //二维数组 code,lurl,surl,size
function FFcallback(retVal)
{
    if (typeof(retVal)=="string")
    {
        var imgsrc = retVal;
    }
    FCKeditorAPI.GetInstance('DOM_editor').InsertHtml(GetHTMLOnInsertImg()+"<img src='"+imgsrc+"'>"+GetHTMLOnInsertImg());
}

function ToViewImg(obj)
{
    var index = Number(obj.selectedIndex);
    var imgview = T.$('DOM_imgView');
    if (index>0)
    {
        imgview.src = obj.options[index]._lurl;
        imgview.style.visibility='visible';
    }
    else
    {
        imgview.style.visibility='hidden';
    }
}

function SetImgSizeSum()
{
	return;
    var _$sum = 0;
    for (var i=0; i<T.$('DOM_imgList').options.length; i++)
    {
        //_$sum += Number($('DOM_imgList').options[i].text.replace(/K/ig,''));
        var _size = T.$('DOM_imgList').options[i]._size;
        if (_size) _$sum += Number(_size);
    }
    T.$('DOM_imgSizeSum').value = _$sum;
}

function RemoveImage()
{
    var _$sel = T.$('DOM_imgList');
    var _$idx = _$sel.selectedIndex;
    if (_$idx<1 || !_$idx) return;
    var _$optsel = _$sel.options[_$idx];

    var _$images = FCKeditorAPI.GetInstance('DOM_editor').EditorDocument.getElementsByTagName("IMG");
    for (var i=_$images.length-1; i>=0; i--)
    {
        if (_$images[i].src.toLowerCase()==_$optsel._lurl.toLowerCase())
        {
             _$images[i].removeNode(true);
        }
    }
    
    _$optsel.removeNode(true);
    if (_$sel.options.length==_$idx) _$idx --;
    _$sel.options[_$idx].selected = true;
    ToViewImg(_$sel);

    SetImgSizeSum();
}


//===============================================================

function DoInsertImg(obj)
{
	var str="";
	if (typeof(obj)=="object")
	{
		var temp=[];
		for (var i=0; i<obj.length; i++)
		{
			if (i>0) temp.push(GetHTMLOnInsertImg());
			temp.push("<img src='"+obj[i].lurl+"'>"+GetHTMLOnInsertImg());
			allPhotos.push(obj[i]);
		}
		str=temp.join("");
	}
	else if (typeof(obj)=="string")
	{
		if (arguments[1])
		{		
			switch (arguments[1])
			{
				case "qqvideo":
					str=GetHTMLOnInsertImg()+"<img mtype='qqvideo' vid='"+obj+"' style='width:168px;height:126px;display:block' src='http://imgcache.qbar.qq.com/b03style/img_default/icon_qqvideo2.gif' title='http://video.qq.com/res/qqplayerout.swf?vid="+obj+"'>"+GetHTMLOnInsertImg();
					break;
			}
		}
		else
		{
			str=GetHTMLOnInsertImg()+"<img src='"+obj+"'>"+GetHTMLOnInsertImg();
		}
	}
	else
	{
		alert(ct);
	}
	
	if (IsEmptyValue())
	{
		FCKeditorAPI.GetInstance('DOM_editor').SetHTML('');
	}

	FCKeditorAPI.GetInstance('DOM_editor').InsertHtml(str);
	SetContentLenPer();
}

//===============================================================

function ToInsertQQVideo()
{
	if (!TryAutoJoin()) return;

	var allimgs=FCKeditorAPI.GetInstance('DOM_editor').EditorDocument.getElementsByTagName("img");
	var chksum=0;
	for (var i=0; i<allimgs.length; i++)
	{
		if (allimgs[i].mtype=="qqvideo") chksum++;
	}

	if (chksum>4)
	{
		alert("最多只能插入5个视频！");
		return;
	}

	var videos=null;
    try{
        if (window.showModalDialog != null)  // IE
        {
            FCKeditorAPI.GetInstance('DOM_editor').EditorDocument.selection.empty();
            videos=window.showModalDialog("../e/editor_insertVideo.Dialog.htm","", "dialogHeight:360px;dialogWidth:500px;center:yes;status:0;help:no;scroll:no;resizable:no");  
        }
        else // firefox 
        {
            var ffwin = window.open("../e/editor_insertVideo.Dialog.htm", "", 'modal=yes,height=360,width=500,scroll=0');
        }
    }catch(e){}
    
    if (!videos) return;
	DoInsertImg(videos,"qqvideo");/*
    FCKeditorAPI.GetInstance('DOM_editor').InsertHtml(GetHTMLOnInsertImg()+"<img mtype='qqvideo' vid='"+videos+"' style='width:168px;height:126px;display:block' src='http://imgcache.qbar.qq.com/b03style/img_default/icon_qqvideo2.gif' title='http://video.qq.com/res/qqplayerout.swf?vid="+videos+"'>"+GetHTMLOnInsertImg());
	SetContentLenPer();*/
}

//================================图形编辑器===========================================

function PicEditor()
{
	if (!TryAutoJoin()) return;
	if(window.ActiveXObject)
	{
		try
		{
			T.$("uploader").innerHTML = '<OBJECT id=PhotoDraw  style="display:none;border-style:none"  codeBase="http://pic.qbar.qq.com/controls/QQPhotoDraw.cab#version=1,2,104,90" height=0 width=0 classid=CLSID:2375BEE5-F175-4F1C-81EC-8E4E2E72E2DD><PARAM NAME="FrameType" VALUE="0"><PARAM NAME="ReportServerIP" VALUE="127.0.0.1"><PARAM NAME="ReportServerPort" VALUE="8210"></OBJECT>';
			ShowPicEditor();
		}
		catch(e)
		{
			var cf = confirm("上传工具没有安装。因为浏览器拦截了ActiveX插件或您取消了插件安装。\n您可以下载客户端安装版直接安装，或允许拦截器安装插件。\n自动下载客户端安装版，请点击“确定”；否则请点击“取消”。");
			if(cf)
			{
				window.location="http://pic.qbar.qq.com/controls/QQPhotoDrawSetup.exe";
			}
		}
	}
	else
	{
		alert("您的浏览器似乎不支持ActiveX插件，因此无法安装相片上传工具。\n如您希望安装相片上传工具，请使用IE浏览器并打开支持ActiveX插件选项。");
	}
}

function ShowPicEditor()
{
	var len=allPhotos.length;
	if (len>14)
	{
		alert("最多只能插入15张图片！");
		return;
	}

	var d = BASE;

	var key=T.GetCookie("qbarkey"), k;
	if (key)
	{
		k=key;
	}
	else
	{
		k=T.GetCookie("skey");
	}

	var q = uin;
	var n = unick;
	var cs=15-len;
	var param = {ID:qbarid,SUM:Main_RESULT.cafe_info.album_size,USED:Main_RESULT.cafe_info.album_used,DOMAIN:d,QQ:q,KEY:k,nick:n,imgsum:cs};
	var imginfo = window.showModalDialog("../e/piceditor.htm",param, "dialogHeight:560px;dialogWidth:618px;center:yes;status:0;help:no;scroll:no;resizable:yes");
	
	if (!imginfo) return;
	DoInsertImg(imginfo);
	/*
	//parent.STATIC_RESULT.cafe_info.album_used = imginfo.USED;
	var temp="";
	for (var i=0; i<imginfo.length; i++)
	{
        if (i>0) temp += GetHTMLOnInsertImg();
        temp += "<img src='"+imginfo[i].lurl+"'>"+GetHTMLOnInsertImg();
		allPhotos.push(imginfo[i]);
	}

	FCKeditorAPI.GetInstance('DOM_editor').InsertHtml(temp);
	SetContentLenPer();
	//SetImgSizeSum();*/
}

function GetHTMLOnInsertImg()
{
    return T.$('DOM_insertBreakOnImg').checked?"<br>":"";    
}

//********************************************************************
var _$contentHeightTimer;
function EditorContentContract(type)
{
    window.clearTimeout(_$contentHeightTimer);
    _$contentHeightTimer = window.setTimeout(function()
    {
        var _$height = parseInt(T.$("DOM_editor___Frame").style.height);
        if (!_$height||_$height<=minFitEditorHeight) return;
        _$height = _$height/(type==2?3:2);
        if (_$height<=minFitEditorHeight) _$height=minFitEditorHeight;
        T.$("DOM_editor___Frame").style.height = _$height+'px';
        T.AutoWinHeight(100);
    },type==2?0:260);
}

function EditorContentExpand(type)
{
    window.clearTimeout(_$contentHeightTimer);
    _$contentHeightTimer = window.setTimeout(function()
    {
        var _$height = parseInt(T.$("DOM_editor___Frame").style.height);
        if (!_$height) _$height = minFitEditorHeight;
        T.$("DOM_editor___Frame").style.height = _$height*(type==2?3:2)+'px';    
        T.AutoWinHeight(100);
    },type==2?0:260);
}
//********************************************************************
//********************************************************************
//********************************************************************

function EditorClearContent()
{
    T.$('DOM_clearContent').innerText = "正在清理中";
    window.setTimeout(_$EditorClearContentImmediate,5);
}

function _$EditorClearContentImmediate()
{
    var _$editbody = FCKeditorAPI.GetInstance('DOM_editor').EditorDocument.body;
    var alltag = _$editbody.getElementsByTagName('*');
    //var len = alltag.length;
    for (var i=alltag.length-1;i>=0;i--)
    {
        //清除危险标签
        if (TagIsDanger(alltag[i]) || alltag[i].tagName=='!')
        {
            alltag[i].removeNode(true);
            continue;
        }
        //if (alltag[i].tagName.toLowerCase()=='font' && alltag[i].face=="Arial") {
        //    alltag[i].removeNode(false);           continue;     }
        if (alltag[i].tagName.toLowerCase()!='br')
        ClearDangerAttributes(alltag[i]);
        //多余样式class
        //多余事件
        //去处隐藏的

    }

    //FCKeditorAPI.GetInstance('DOM_editor').SetHTML(_$html.replace(/\sclass=\"\"/gi,''));
    T.$('DOM_clearContent').innerText = "自动清理代码";
}

function ClearDangerAttributes(tag)
{
    if (tag.tagName.toLowerCase()=="img")
    {
        tag.removeAttribute("style");
    }
    var atts = tag.attributes;
    if (!atts) return;
    var len = atts.length;
    for (var j=len-1;j>=0;j--)
    {
        var n = atts[j].nodeName.toLowerCase();
        var v = String(atts[j].nodeValue).toLowerCase();//此时可能为空
        //需要对qbar内支持和允许的样式做特殊处理
        if (n=="class" && v!="" && v!='bbs_quote')
        {
            tag.className="";
            continue;
        }
        else if (n.substr(0,2)=="on" || n=="_fcksavedurl")
        {
            tag.removeAttribute(atts[j].nodeName);
            continue;
        }

        if (v && (n=="src"||n=="href"))
        {
            var p = String(v).replace(/\n|\r|\s/g,'');
            if (/^(javascript|vbscript|jscript):/g.test(p))
            {
                tag.removeAttribute(atts[j].nodeName);
                continue;
            }            
        }
    }
}

function TagIsDanger(tag)
{
    var tagname = tag.tagName.toLowerCase();
    //if (/<(applet|area|base|basefont|dbo|bgSound|body|button|dir|embed|form|frame|frameset|html|iframe|import|input|isIndex|link|map|marquee|meta|object|param|pre|script|select|textarea|title|xml|xmp)/.test("<"+tagname))
    if (/<(applet|area|base|basefont|dbo|bgSound|body|button|dir|embed|form|frame|frameset|html|iframe|import|input|isIndex|link|map|marquee|meta|object|param|script|select|textarea|title|xml|xmp)/.test("<"+tagname))
    {
        return true;
    }
    return false;
}

function EditorEmptyContent()
{
    if (!window.confirm('您要清除正在编写的内容吗？')) return;
	allPhotos=[];
    FCKeditorAPI.GetInstance('DOM_editor').SetHTML('');
	window.setTimeout(SetContentLenPer,800);
}
//********************************************************************
function LoadShowBrdrule()
{
    T.RunJS('/qbar/qbar2/bbs_showBrdrule.js');
}
//********************************************************************
function OnChooseImg(img)
{
    var src = img.src;
    var _$editbody = FCKeditorAPI.GetInstance('DOM_editor').EditorDocument.body;
    var imgs = _$editbody.getElementsByTagName('img');
    for (var i=0;i<imgs.length;i++)
    {
        imgs[i].style.border="";
        if (imgs[i].src==src)
        {
            imgs[i].style.border="2px solid red";
        }
    }
}

function AutoLimitTitle(obj)
{
    if (obj.value.length2()>75)
    obj.value=obj.value.left2(75);
}

function EditorContentCount___DEL(obj)
{
    var h = FCKeditorAPI.GetInstance('DOM_editor').EditorDocument.body.innerHTML.length2();
    obj.innerHTML = "共<b class='red'>&nbsp;"+h+"&nbsp;</b>字节(最大值:"+ (T.$("title")?30000:20000) +")";
    window.setTimeout(function(){obj.innerHTML="字数检查"},2000);
}

//===========================================
function PasteContent()
{
	alert('浮动一个大点的层');
}

/*
window.onbeforeunload=function(){
	event.returnValue = "您有未保存的内容，离开后无法保存这些正在编辑的内容";
}
*/
window.onbeforeunload=function(){
	
}


/******** QQMail截屏功能 ************/

function PreSetupControl(type,callback)
{
	switch (type)
	{
		case 0:
			!DetectScreenCapture(0,2)?helper():callback();
			break;
		case 1:
			!DetectPhotoDraw(1,2)?helper():callback();
			break;
	}

	function helper()
	{
		var controls=T.$("D_preSetupControl");
		controls.style.left="250px";
		controls.style.top="150px";
		controls.style.display="block";
		CreateMask();
	}
}

function CreateMask()
{
	var t=T.$("D_setupmask");
	if (t)
	{
		t.style.display="";
	}
	else
	{
		var div=document.createElement("DIV");
		div.setAttribute("id","D_setupmask");
		var ds=div.style;
		ds.position="absolute";
		ds.top="0px";
		ds.left="0px";
		ds.zIndex=10;
		ds.width="100%";
		ds.height="100%";
		ds.backgroundColor="#FFF";
		ds.filter="Alpha(opacity=0)";
		ds.MozOpacity="0";
		ds.display="";
		div.attachEvent("onclick",HighLightDialog);
		document.body.appendChild(div);
	}

	var selects=document.getElementsByTagName("SELECT");
	for (var i=0; i<selects.length; i++)
	{
		var item=selects[i];
		if (item.style.display!="none" && item.style.visibility!="hidden")
        {
            item.style.visibility="hidden";
            item._visibility = 1;
        }
	}
}

var CurrentDialogInterval=null;
function HighLightDialog()
{
	try{
		if (CurrentDialogInterval) clearInterval(CurrentDialogInterval);
	
		var obj=T.$("D_preSetupControl");
		if (obj && obj.style.display!="none")
		{
			var times = 1;
			var t = T.$("D_preSetupControl_title");
			if (t)
			{
				CurrentDialogInterval=setInterval(
					function()
					{
						t.style.backgroundColor=(times%2)?"#A0D5FA":"#F7FCFF";
						if (times==4) return clearInterval(CurrentDialogInterval);
						times ++;
					},
				50);
			}	
		}
	}catch(e){}
}

function CloseSetupControl()
{
	T.$("D_setupmask").style.display="none";
	T.$('D_preSetupControl').style.display='none';

	var selects=document.getElementsByTagName("SELECT");
	for (var i=0; i<selects.length; i++)
	{
		var item=selects[i];
		if (item._visibility == 1)
		{
			item.style.visibility="inherit";
			item._visibility = 0;
		}
	}
}

function StartSetup()
{
	T.SetCookie("Base", BASE);
	top.location.href=BASE+"e/presetup.htm";
}

function GetOffset(e)
{
	var l=e.offsetLeft;
	var t=e.offsetTop;
	
	while(e=e.offsetParent)
	{
		l +=e.offsetLeft;
		t +=e.offsetTop;
	}
	return [l,t];
}


var gActiveXObj = ["FMO.ScreenCapture","QQPhotoDraw.PhotoDraw.1"];
var gActivexLastVerNo = ["1.0.0.5","1.2.104.90"];
var gEditorAxMinVer = ["1.0.0.4"];

function DetectScreenCapture(activexId, detectType)
{
	var result = false;
	try {
		var o = new ActiveXObject(gActiveXObj[activexId]);
		if ((detectType != 1 && detectType != 2) || parseInt(o.version.split(".").join("")) >= parseInt((detectType == 1 ? gEditorAxMinVer : gActivexLastVerNo)[activexId].split(".").join(""))) result = true;
		o = null;
	}catch(e){}
	return result;
}

function DetectPhotoDraw(activexId, detectType)
{
	var result = false;
	try
	{
		var o = new ActiveXObject(gActiveXObj[activexId]);

		if (!detectType || detectType==1)
		{
			return true;
		}
		else
		{
			var t = gActivexLastVerNo[1].split(".");
			var lastver = parseInt(t[0])*100+parseInt(t[1]);
			if (o.GetVersion()>=lastver) result = true;
		}
		
		o = null;
	}catch(e){}
	return result;
}

function GetActiveXVer(activexId) {
	var ver = "";
	try {
		var o = new ActiveXObject(gActiveXObj[activexId]);
		ver = activexId == 0 ? "1.0.0.3" : "";
		if (o.version) ver = o.version;
		o = null;
	}catch(e){}
	return ver;
}

function ScreenSnap()
{
	//if (gScreenSnapObj) gScreenSnapObj = null;
	//if (gImgUploaderObj) {
	//	gImgUploaderObj.StopUpload();
	//	gImgUploaderObj = null;
	//}

	gScreenSnapObj = new ActiveXObject("FMO.ScreenCapture");
	gImgUploaderObj = new ActiveXObject("FMO.Uploader");
	
	//if (mode == "paste") {
	//	fUploadCustomImg();
	//	return;
	//}

	//fHideTBPMenu();

	gScreenSnapObj.OnCaptureFinished = function() {
		window.focus();
		FUploadCustomImg(1);
	};
	gScreenSnapObj.OnCaptureCanceled = function() {
		window.focus();
	};
	gScreenSnapObj.DoCapture();
}

function FUploadCustomImg(bIsWarn) {
	if (!gScreenSnapObj.IsClipBoardImage) {
		if (bIsWarn) alert("截屏不成功!");
		return;
	}
	gTBPScreenImg = gScreenSnapObj.SaveClipBoardBmpToFile(1);
	if (!gTBPScreenImg) {
		if (bIsWarn) alert("保存截屏图片不成功!");
		return;
	}
	StartUploadCustomImg();
}

function StartUploadCustomImg()
{
	if (gTBPScreenImg == "") return;

	gImgUploaderObj.StopUpload();
	gImgUploaderObj.ClearHeaders();
	gImgUploaderObj.ClearFormItems();

	gImgUploaderObj.OnEvent = FOnEvent;
	gImgUploaderObj.URL = "http://pic.qbar.qq.com/cgi-bin/cafe_cgi_upload_photo_app.cgi";

	var key=T.GetCookie("qbarkey"), ckie;
	if (key)
	{
		ckie='qbarkey='+key;
	}
	else
	{
		ckie='uin='+T.GetCookie('uin')+'; skey='+T.GetCookie("skey");
	}

	gImgUploaderObj.AddHeader("Cookie", ckie);
	gImgUploaderObj.AddFormItem("cafeid", 0, 0, RESULT1.sys_param.cafeid);// top.STATIC_RESULT.cafe_info.id);
	gImgUploaderObj.AddFormItem("Gjstag", 0, 0, "0");
	gImgUploaderObj.AddFormItem("imagefile", 1, 4, gTBPScreenImg);

	gImgUploaderObj.StartUpload();
}

//绑定上传控件事件
function FOnEvent(obj, eventID, p1, p2, p3) {
	switch(eventID) {
		case 1:		//error
			alert("图片上传失败"); // + ActiveXErrDescription(p1);
			break;
		case 2:		//process
			//pc.innerHTML= parseInt(p1 * 90 / p2) + "%";
			break;
		case 3:		//finish
			if (gImgUploaderObj.ResponseCode != "200") {
				if (!gImgUploaderObj.Response){
					alert('上传失败'); //S("dtprecent").innerHTML = "上传失败";
				} else {
					alert('图片上传失败!'); //S("dialog_tmp").innerHTML = "图片上传失败!";
				}
				return;
			}
			var s = gImgUploaderObj.Response;
			s=s.replace(/^.*\nRESULT\=/g,'');
			s=s.replace(/\\};var\swinname\=.*/g,'}');
			s=s.replace(/\nfinally\{\}.*/g,'');

			eval('RESULT='+s);
			
			if(RESULT.sys_param.ret_code!=0)T.PrepResult(RESULT);
			else
			{/*
				var temp="",imginfo=RESULT.pics;
				for (var i=0; i<imginfo.length; i++)
				{
					if (i>0) temp += GetHTMLOnInsertImg();
					temp += "<img src='"+imginfo[i].lurl+"'>"+GetHTMLOnInsertImg();
					allPhotos.push(imginfo[i]);
				}
				FCKeditorAPI.GetInstance('DOM_editor').InsertHtml(temp);*/
				DoInsertImg(RESULT.pics);
			}
			break;
	} 
}

function Tit2edit()
{
	if (IsEmptyValue()) FCKeditorAPI.GetInstance('DOM_editor').SetHTML('');
	FCKeditorAPI.GetInstance('DOM_editor').Focus();
}