var userAgent = navigator.userAgent.toLowerCase();
var is_chrome = userAgent.indexOf('chrome') != -1;
var is_firefox = userAgent.indexOf('firefox') != -1;
var is_ie = userAgent.indexOf('msie') != -1;
//var is_opera = userAgent.indexOf('opera') != -1;

var is_opera = userAgent.indexOf('opera') != -1 && opera.version();
var is_moz = (navigator.product == 'Gecko') && userAgent.substr(userAgent.indexOf('firefox') + 8, 3);
var is_msie = (userAgent.indexOf('msie') != -1 && !is_opera) && userAgent.substr(userAgent.indexOf('msie') + 5, 3);

var bTextMode = 1;
var charset = "UTF-8";

var cursor = -1;
var lang = new Array();
var stack = new Array();

function k(id) {
    return document.getElementById(id);
}

function colorcontext(obj, state) {
    obj.style.cursor = 'pointer';
    var mode = state == 'mouseover' ? 'hover' : 'normal';
    obj.className = 'editor_color' + mode;
}

function hideMenu(nm) {
    k(nm).style.display = "none";
}
function showMenu(nm, obj) {
    o=k(nm);
    if (o.style.display != "none")
        return;
//     alert(event.x + "," + obj.offsetLeft + "," + obj.offsetParent.offsetLeft + "," + event.offsetX); 
      //offsetParent
     // offsetTop  offsetHeight clientHeight
    if (is_ie) {
        o.style.left = (event.x - event.offsetX)+"px"; 
        o.style.top = (event.y + obj.clientHeight - event.offsetY + document.body.scrollTop) + "px";        
    }
    else if (is_firefox) {
    //alert(obj.offsetParent.offsetLeft + "," + event.layerX); //offsetLeft
        o.style.left = (fevent.pageX - obj.clientWidth) + "px"; //event.clientX -
        o.style.top = (fevent.pageY + obj.clientHeight) + "px";     //event.clientY   + obj.clientHeight      
    }
    else if (is_chrome) {
        o.style.pixelLeft = event.x - event.offsetX; //
        o.style.pixelTop = event.y + obj.clientHeight - event.offsetY + document.body.scrollTop;

    }
    o.style.display = "block"; 
}


function movePoint() {
    var pn = parseInt(k("ppos").value);
    if (isNaN(pn))
        return;
    var rng = editdoc.createTextRange();
    rng.moveStart("character", pn);
    rng.collapse(true);
    rng.select();
    // returnCase(rng)
}
function tellPoint() {
    checkFocus();
   // editdoc.focus();
    //var rng = editdoc.createRange(); //event.srcElement
    //alert(rng.moveToPoint);
    try {
        //rng.moveToPoint(event.x,event.y); 
    }
    catch (e) {
        //alert(e);
    }
    //rng.moveStart("character", -event.srcElement.value.length)
    //k("ppos").value = rng.text.length;
    //returnCase(rng)
    
}
function selectText(sp, ep) {
    sp = parseInt(sp);
    ep = parseInt(ep);

    if (isNaN(sp) || isNaN(ep))
        return;
    var rng = editdoc.createTextRange();
    rng.moveEnd("character", -editdoc.value.length)
    rng.moveStart("character", -editdoc.value.length)

    rng.collapse(true);
    rng.moveEnd("character", ep);
    rng.moveStart("character", sp);
    rng.select();
    // returnCase(rng);
}
function clearSel() {
    if (is_ie) {
        var ctr = editdoc.document.selection.createRange(); //createTextRange()    
        s = ctr.text;
        if (s == "") {
            pn = getPos();           
            return;
        }
        var rng = editdoc.createTextRange();
        pn = getPos();
        //var pn = parseInt(k("ppos").value);
        //k("Text1").value = pn;
        rng.moveStart("character", pn);
        s1 = rng.text;
        ctr.text = "";
        pn = getPos();

        //s2 = s1.substr(0, s.length);
        v = editdoc.value.split("\r").length - s1.split("\r").length;
        //alert(s+","+s2);
        //    if (s != s2)
        //        k("ppos").value = editdoc.value.length - s1.length-s.length;  //parseInt(k("ppos").value) - s.length - v*2;
        //    else
        k("ppos").value = pn - v; //  editdoc.value.length - s1.length;//
        curSel = s;
    }
    if (is_chrome || is_firefox) {
      // k("ppos").value = editdoc.selectionStart;
       var selStart = editdoc.selectionStart;
       var selEnd = editdoc.selectionEnd;
       k("ppos").value = selStart;
        curSel = editdoc.value.substring(selStart, selEnd);
       // editdoc.value = editdoc.value.substring(0, selStart) + editdoc.value.substring(selEnd);
      // alert();
    }
}
function getPos() {
    if (is_ie) {
        checkFocus();
        var workRange = document.selection.createRange();
        editdoc.select();
        var allRange = document.selection.createRange();
        workRange.setEndPoint("StartToStart", allRange);
        var len = workRange.text.length;
        workRange.collapse(false);
        workRange.select();
        k("ppos").value = len;
        return len;
    }
}
/*=========================================================show showIframe=========================================================================
*/
function showIframe(obj) {
    getPos();
    k("iframe_lbl").innerText = "选择和上传图片：";
    if (is_ie) {
        k("iframe").style.left = (event.x - event.offsetX) + "px";
        k("iframe").style.top = (event.y + obj.offsetHeight - event.offsetY + document.body.scrollTop) + "px"; //+ obj.offsetTop
    }
    if (is_firefox) {
        k("iframe").style.left = (fevent.pageX - obj.clientWidth) + "px";
        k("iframe").style.top = (fevent.pageY + obj.clientHeight) + "px";
    }
    if (is_chrome) {
        k("iframe").style.pixelLeft = event.x - event.offsetX
        k("iframe").style.pixelTop = event.y + obj.offsetHeight - event.offsetY + document.body.scrollTop; //+ obj.offsetTop
    }
    k("iframe").style.display = "block";
//    k("input_in").focus();
}
function showSmiley(obj) {
    getPos();
    k("smiley_lbl").innerText = "选择笑脸图片：";
    if (is_ie) {
        k("smiley").style.left = (event.x - event.offsetX) + "px";
        k("smiley").style.top = (event.y + obj.offsetHeight - event.offsetY + document.body.scrollTop) + "px"; //+ obj.offsetTop
    }
    if (is_firefox) {
        k("smiley").style.left = (fevent.pageX - obj.clientWidth) + "px";
        k("smiley").style.top = (fevent.pageY + obj.clientHeight) + "px";
    }
    if (is_chrome) {
        k("smiley").style.pixelLeft = event.x - event.offsetX
        k("smiley").style.pixelTop = event.y + obj.offsetHeight - event.offsetY + document.body.scrollTop; //+ obj.offsetTop
    }
    k("smiley").style.display = "block";
//    k("input_in").focus();
}

var curInput = "";
    curText = "";
    curSel = "";
function showInput(code, obj) {    
    if (k("input").style.display != "none")
        return;

    if (in_array(code, ['url', 'email'])) {
        clearSel();
    }
    else {
        getPos();
    } 
    //alert(event.y + "," +  obj.clientHeight + "," + obj.offsetHeight);
    curInput = code;
    switch (code) {
        case "url":
            k("input_lbl").innerText = "请输入链接的地址：";
            break;
        case "email":
            k("input_lbl").innerText = "请输入邮箱的地址：";
            break;
        case "img":
            k("input_lbl").innerText = "请输入图片的链接的地址：";
            break;
        case "marquee":
            k("input_lbl").innerText = "请输入要滚动显示的文字：";
            break;       
        case "mp3":
            k("input_lbl").innerText = "请输入Mp3URL：";
            break;
        case "rm":
            k("input_lbl").innerText = "请输入Real 音频或视频URL：";
            break;
        case "qq":
            k("input_lbl").innerText = "请输入要显示的QQ的号码：";
            break;
        case "emule":
            k("input_lbl").innerText = "请输入Emule 的URL：";
            break;  
       case "thunder":
            k("input_lbl").innerText = "请输入迅雷 的URL：";
            break;
        case "bt":
            k("input_lbl").innerText = "请输入BT 的URL：";
            break;
        case "flashget":
            k("input_lbl").innerText = "请输入flashget 的URL：";
            break;     
    }
    if (is_ie) {
        k("input").style.left = (event.x - event.offsetX) + "px";
        k("input").style.top = (event.y + obj.offsetHeight - event.offsetY + document.body.scrollTop) + "px"; //+ obj.offsetTop
    }
    if (is_firefox) {
        k("input").style.left = (fevent.pageX - obj.clientWidth) + "px";
        k("input").style.top = (fevent.pageY + obj.clientHeight) + "px";
    }
    if (is_chrome) {
        k("input").style.pixelLeft = event.x - event.offsetX
        k("input").style.pixelTop = event.y + obj.offsetHeight - event.offsetY + document.body.scrollTop; //+ obj.offsetTop
    }
    k("input_in").value = "";
    k("input").style.display = "block";
    k("input_in").focus();
}

function showInput1(code, obj) {
    if (k("input1").style.display != "none")
        return;
    if (in_array(code, ['url', 'email'])) {
        clearSel();
    }
    else {
        getPos();
    }
    curInput = code;
    switch (code) {
        case "img":
            k("input_lbl1").innerText = "请输入Img URL：";
            k("input_lbl1_2").innerText = "宽(px)";
            k("input_lbl1_3").innerText = "高(px)";
            k("input_in1_2").value = "800";
            k("input_in1_3").value = "600";
            break;
        case "wmv":
            k("input_lbl1").innerText = "请输入Windows MediaPlay 音频或视频URL：";
            k("input_lbl1_2").innerText = "宽(px)";
            k("input_lbl1_3").innerText = "高(px)";
            k("input_in1_2").value = "480";
            k("input_in1_3").value = "400";
            break;
        case "flv":
            k("input_lbl1").innerText = "请输入Flash或者flv 的URL：";
            k("input_lbl1_2").innerText = "宽(px)";
            k("input_lbl1_3").innerText = "高(px)";
            k("input_in1_2").value = "480";
            k("input_in1_3").value = "400";
            break;
        case "qvod":
            k("input_lbl1").innerText = "请输入QVod 的URL：";
            k("input_lbl1_2").innerText = "宽(px)";
            k("input_lbl1_3").innerText = "高(px)";
            k("input_in1_2").value = "640";
            k("input_in1_3").value = "480";
            break;
    }
    if (is_ie) {
        k("input1").style.left = (event.x - event.offsetX) + "px";
        k("input1").style.top = (event.y + obj.offsetHeight - event.offsetY + document.body.scrollTop) + "px"; //+ obj.offsetTop
    }
    if (is_firefox) {
        k("input1").style.left = (fevent.pageX - obj.clientWidth) + "px";
        k("input1").style.top = (fevent.pageY + obj.clientHeight) + "px";
    }
    if (is_chrome) {
        k("input1").style.pixelLeft = event.x - event.offsetX
        k("input1").style.pixelTop = event.y + obj.offsetHeight - event.offsetY + document.body.scrollTop; //+ obj.offsetTop
    }
    k("input_in1").value = "";
    k("input1").style.display = "block";
    k("input_in1").focus();
}
function showInput2(code, obj) {
    if (k("input2").style.display != "none")
        return;
    if (in_array(code, ['url', 'email'])) {
        clearSel();
    } 
    else {
        getPos();
    }
    curInput = code;
    switch (code) {
        case "emule":
            k("input_lbl2").innerText = "请输入Emule 的URL：";
            break;
        case "thunder":
            k("input_lbl2").innerText = "请输入迅雷的标题和URL：";
            break;
        case "bt":
            k("input_lbl2").innerText = "请输入BT 的URL：";
            break;
        case "flashget":
            k("input_lbl2").innerText = "请输入flashget 的URL：";
            break;   
    }
    if (is_ie) {
        k("input2").style.left = (event.x - event.offsetX) + "px";
        k("input2").style.top = (event.y + obj.offsetHeight - event.offsetY + document.body.scrollTop) + "px"; //+ obj.offsetTop
    }
    if (is_firefox) {
        k("input2").style.left = (fevent.pageX - obj.clientWidth) + "px";
        k("input2").style.top = (fevent.pageY + obj.clientHeight) + "px";
    }
    if (is_chrome) {
        k("input2").style.pixelLeft = event.x - event.offsetX
        k("input2").style.pixelTop = event.y + obj.offsetHeight - event.offsetY + document.body.scrollTop; //+ obj.offsetTop
    }
    k("input_in2").value = "";
    k("input2").style.display = "block";
    k("input_in2").focus();
}
function showText(code, obj) {
    if (k("text").style.display != "none")
        return;
    curText = code;
    if (insertCmdToSel(code)) {   
        return;
    }
    switch (code) {
        case "quote":
            k("text_lbl").innerText = "请输入要插入的引用";            
            break;
        case "code":
            k("text_lbl").innerText = "请输入要插入的代码：";
            break;
        case "table":
            k("text_lbl").innerText = "请输入要插入的表格内容：";
            break;
        case "free":
            k("text_lbl").innerText = "请输入要插入的免费信息：";
            break;
    }
    if (is_ie) {
        k("text").style.left = (event.x - obj.offsetLeft) + "px" ;
        k("text").style.top = (event.y + obj.clientHeight - event.offsetY + document.body.scrollTop) + "px";
    }
    if (is_firefox) {
        k("text").style.left = (fevent.pageX - obj.clientWidth) + "px";
        k("text").style.top = (fevent.pageY + obj.clientHeight) + "px";
    }
    if (is_chrome) {
        k("text").style.pixelLeft = event.x - obj.offsetLeft;
        k("text").style.pixelTop = event.y + obj.clientHeight - event.offsetY + document.body.scrollTop;
    }
    k("text_in").value = "";
    k("text").style.display = "block";
    k("text_in").focus();
}
function insertCmdToSel(cmd) {
    if (is_ie) {
        var ctr = editdoc.document.selection.createRange(); //createTextRange()   
        if (ctr.text == "") return false;
        ctr.text = "[" + cmd + "]" + ctr.text + "[/" + cmd + "]";
        return true;
    }
    else if (is_chrome || is_firefox) {
        var selStart = editdoc.selectionStart;
        var selEnd = editdoc.selectionEnd;
        if (selStart == selEnd)
            return false;   
        editdoc.value = editdoc.value.substring(0, selStart)
        + "[" + cmd + "]" + editdoc.value.substr(selStart,selEnd)+ "[/" + cmd + "]"
        + editdoc.value.substring(selEnd);
        return true;
    }
}

function btn_sub(nm) {    
    k(nm).style.display = "none";
    if (nm == "input") {
        switch (curInput) {
            case "url":
                insertlink("url", k("input_in").value);
                break;
            case "email":
                insertlink("email", k("input_in").value);       
                break;
            case "img":
                insertlink("img", k("input_in").value);               
                break;
            case "marquee":
                insertlink("fly", k("input_in").value);  
                break;         
            case "mp3":
                insertlink1("mp3", "480x50",k("input_in").value);  
                break;
            case "rm":
                insertlink("rm", k("input_in").value);
                break;
            case "qq":
                insertlink("qq", k("input_in").value);       
                break;
            case "emule":
                insertlink("emule", k("input_in").value);
                break;
            case "thunder":
                insertlink("thunder", k("input_in").value);
                break;
            case "bt":
                insertlink("bt", k("input_in").value);
                break;
            case "flashget":
                insertlink("flashget", k("input_in").value);
                break;        
        }
    }
    else {
        switch (curText) {
            case "quote":
                insertlink("quote", k("text_in").value); 
                break;
            case "code":
                insertlink("code", k("text_in").value); 
                break;
            case "table":
                insertlink("table", k("text_in").value); 
                break;
            case "free":
                insertlink("free", k("text_in").value); 
                break;
        } 
    }

}

function btn_sub1(nm) {
    k(nm).style.display = "none";
    if (nm == "input1") {
        switch (curInput) {
            case "img":
                insertlink1("img", (k("input_in1_2").value + "x" + k("input_in1_3").value), k("input_in1").value);
                break;
            case "wmv":
                insertlink1("wmv", (k("input_in1_2").value + "x" + k("input_in1_3").value), k("input_in1").value);
                break;
            case "flv":
                insertlink1("flv", (k("input_in1_2").value+"x"+k("input_in1_3").value), k("input_in1").value);
                break;
            case "qvod":
                insertlink1("qvod", (k("input_in1_2").value + "x" + k("input_in1_3").value), k("input_in1").value);
                break;
        }
    }
}
function btn_sub2(nm) {
    k(nm).style.display = "none";
    if (nm == "input2") {
        switch (curInput) {     
            case "emule":               
                insertlink1("emule", k("input_in2_2").value, k("input_in2").value);
                break;
            case "thunder":             
                insertlink1("thunder", k("input_in2_2").value, k("input_in2").value);
                break;
            case "bt":     
                insertlink1("bt", k("input_in2_2").value, k("input_in2").value);
                break;
            case "flashget":       
                insertlink1("flashget", k("input_in2_2").value, k("input_in2").value);
                break;        
        }
    }
}
function btn_cancel(nm) {
    k(nm).style.display = "none";
}

function btn_cancel1(nm) {
    k(nm).style.display = "none";
}     
       
/*=====================================================================================================
*/
function setFont(str, el) {
    if (!validateMode()) return;
    var Index = el.selectedIndex;
    if (Index != 0) {
        el.selectedIndex = 0;
        FormatText(str, el.options[Index].value);
    }
}
function addSnapshot(str) {
    if (stack[cursor] == str) {
        return;
    } else {
        cursor++;
        stack[cursor] = str;

        if (!isUndefined(stack[cursor + 1])) {
            stack[cursor + 1] = null;
        }
    }
}
function checkFocus() {    
    if (!editdoc.hasfocus) {
        editdoc.focus();        
    }
   // editdoc.focus();
}
function in_array(needle, haystack) {
    if (typeof needle == 'string' || typeof needle == 'number') {
        for (var i in haystack) {
            if (haystack[i] == needle) {
                return true;
            }
        }
    }
    return false;
}
function stripSimple(tag, str, iterations) {
    var opentag = '[' + tag + ']';
    var closetag = '[/' + tag + ']';

    if (isUndefined(iterations)) {
        iterations = -1;
    }
    while ((startindex = stripos(str, opentag)) !== false && iterations != 0) {
        iterations--;
        if ((stopindex = stripos(str, closetag)) !== false) {
            var text = str.substr(startindex + opentag.length, stopindex - startindex - opentag.length);
            str = str.substr(0, startindex) + text + str.substr(stopindex + closetag.length);
        } else {
            break;
        }
    }
    return str;
}
function stripComplex(tag, str, iterations) {
    var opentag = '[' + tag + '=';
    var closetag = '[/' + tag + ']';

    if (isUndefined(iterations)) {
        iterations = -1;
    }
    while ((startindex = stripos(str, opentag)) !== false && iterations != 0) {
        iterations--;
        if ((stopindex = stripos(str, closetag)) !== false) {
            var openend = stripos(str, ']', startindex);
            if (openend !== false && openend > startindex && openend < stopindex) {
                var text = str.substr(openend + 1, stopindex - openend - 1);
                str = str.substr(0, startindex) + text + str.substr(stopindex + closetag.length);
            } else {
                break;
            }
        } else {
            break;
        }
    }
    return str;
}

function stripos(haystack, needle, offset) {
    if (isUndefined(offset)) {
        offset = 0;
    }
    var index = haystack.toLowerCase().indexOf(needle.toLowerCase(), offset);

    return (index == -1 ? false : index);
}

function klingCode(cmd, arg) {
    if (cmd != 'redo') {
        addSnapshot(getEditorContents());
    }
    checkFocus();   
    if (cmd.substr(0, 6) == 'custom') {
        var ret = customTags(cmd.substr(8), cmd.substr(6, 1));
    } else if (cmd == 'removeformat') {
        var simplestrip = new Array('b', 'i', 'u');
        var complexstrip = new Array('font', 'color', 'size');

        var str = getSel();
        if (str === false) {
            return;
        }
        for (var tag in simplestrip) {
            str = stripSimple(simplestrip[tag], str);
        }
        for (var tag in complexstrip) {
            str = stripComplex(complexstrip[tag], str);
        }
        insertText(str);
    } else if ( cmd == 'undo') {
        addSnapshot(getEditorContents());
        moveCursor(-1);
        if ((str = getSnapshot()) !== false) {
            editdoc.value = str;
        }
    } else if (cmd == 'redo') {
        moveCursor(1);
        if ((str = getSnapshot()) !== false) {
            editdoc.value = str;
        }
    } else if (in_array(cmd, ['insertorderedlist', 'insertunorderedlist'])) {
        var listtype = cmd == 'insertorderedlist' ? '1' : '';
        var opentag = '[list' + (listtype ? ('=' + listtype) : '') + ']\n';
        var closetag = '[/list]';

        if (txt = getSel()) {
            var regex = new RegExp('([\r\n]+|^[\r\n]*)(?!\\[\\*\\]|\\[\\/?list)(?=[^\r\n])', 'gi');
            txt = opentag + trim(txt).replace(regex, '$1[*]') + '\n' + closetag;
            insertText(txt, strlen(txt), 0);
        } else {
            insertText(opentag + closetag, opentag.length, closetag.length);
            while (listvalue = prompt("输入一个项目列表，留空完成列表", '')) {
                if (is_opera > 8) {
                    listvalue = '\n' + '[*]' + listvalue;
                    insertText(listvalue, strlen(listvalue) + 1, 0);
                } else {
                    listvalue = '[*]' + listvalue + '\n';
                    insertText(listvalue, strlen(listvalue), 0);
                }
            }
        }
    } else if ( cmd == 'outdent') {
        var sel = getSel();
        sel = stripSimple('indent', sel, 1);
        insertText(sel);
    } else if (cmd == 'unlink') {
        var sel = getSel();
        sel = stripSimple('url', sel);
        sel = stripComplex('url', sel);
        insertText(sel);
        //    } else if (cmd == 'createlink') {
        //        insertlink('createlink');
//    } else if (cmd == 'email') {
//        insertlink('email');
//    } else if (cmd == 'insertimage') {
//        insertlink('insertimage');
    } else if (cmd == 'floatleft' || cmd == 'floatright') { 
          applyFormat(cmd, false);
    }
    else {   
        try {  
            applyFormat(cmd,arg);
        } catch (e) {
            var ret = false;
            alert(e);
        }
    }

    if (cmd != 'undo') {
        addSnapshot(getEditorContents());
    }
//    if (wysiwyg) {
//        setContext(cmd);
//        if (cmd == 'forecolor') {
//            k(editorid + '_color_bar').style.backgroundColor = arg;
//        }
//    }    
    return ret;
}

function applyFormat(cmd, argument) {  
    switch (cmd) {
        case 'bold':
        case 'italic':
        case 'underline':
            wrapTags(cmd.substr(0, 1), false);
            break;
        case 'justifyleft':
        case 'justifycenter':
        case 'justifyright':
            wrapTags('align', cmd.substr(7));
            break;
        case 'floatleft':
        case 'floatright':
            wrapTags('float', cmd.substr(5));
            break;
        case 'indent':
            wrapTags(cmd, false);
            break;
        case 'fontname':           
            wrapTags('font', argument);
            break;
        case 'fontsize':
            wrapTags('size', argument);
            break;
        case 'forecolor':
            wrapTags('color', argument);
            break;
        case "url":
        case "email":
            var sel = getSel();
            if (sel) {
                wrapTags(cmd, sel, argument);

            } else {
                wrapTags(cmd, argument, argument);
            }
            break;
        
    }
}

function wrapTags(tagname, useoption, selection) {

    if (isUndefined(selection)) { 
        var selection = getSel();
        if (selection === false) {
            selection = '';
        } else {
            selection += '';
        }
    }
   
    if (useoption !== false) {
        var opentag = '[' + tagname + '=' + useoption + ']';
    } else {
        var opentag = '[' + tagname + ']';
    }

    var closetag = '[/' + tagname + ']';
    var text = opentag + selection + closetag;   
    insertText(text, strlen(opentag), strlen(closetag), in_array(tagname, ['code', 'quote', 'free', 'hide']) ? true : false);
}

function getSel() {
		if(!isUndefined(editdoc.selectionStart)) {
			return editdoc.value.substr(editdoc.selectionStart, editdoc.selectionEnd - editdoc.selectionStart);
		} else if(document.selection && document.selection.createRange) {
			return document.selection.createRange().text;
		} else if(window.getSelection) {
			return window.getSelection() + '';
		} else {
			return false;
        }
}


function insertText(text, movestart, moveend, select, sel) {	  
    checkFocus(); 
        if (!isUndefined(editdoc.selectionStart)) {
            
            var opn = editdoc.selectionStart + 0;
            editdoc.value = editdoc.value.substr(0, editdoc.selectionStart) + text + editdoc.value.substr(editdoc.selectionEnd);
            return;
            if (!isUndefined(movestart)) {
                editdoc.selectionStart = opn + movestart;
                editdoc.selectionEnd = opn + strlen(text) - moveend;
            } else if (movestart !== false) {
                editdoc.selectionStart = opn;
                editdoc.selectionEnd = opn + strlen(text);
            }
        } else if (document.selection && editdoc.document.selection.createRange) {        
            if (isUndefined(sel)) {
                sel = document.selection.createRange();
            }
            sel.text = text.replace(/\r?\n/g, '\r\n');
            if (!isUndefined(movestart)) {
                sel.moveStart('character', -strlen(text) + movestart);
                sel.moveEnd('character', -moveend);
            } else if (movestart !== false) {
                sel.moveStart('character', -strlen(text));
            }
            sel.select();
        } else {
            editdoc.value += text;
        }
    }

function insertlink(cmd, argument) {
   checkFocus(); 
    var tags;
    switch (cmd) {
        case "url":
        case "email":       
            if (curSel) {
                tags = "[" + cmd + "=" + argument + "]" + curSel + "[/" + cmd + "]";                

            } else {
                tags = "[" + cmd + "=" + argument + "]" + argument + "[/" + cmd + "]";                
            }
            break;
        case "img":
        case "fly":
        case "wmv":
        case "mp3":        
        case "rm":
        case "qq":
        case "emule":
        case "thunder":
        case "bt":
        case "flashget":   
        case "quote":
        case "code":
        case "table":
        case "free":
            tags = "[" + cmd + "]" + argument + "[/" + cmd + "]\r\n";
            break;               
    }
    insertToCur(tags);
}
function insertlink1(cmd, argument,url) {
   checkFocus(); 
   var tags;
   switch (cmd) {      
       case "smiley":
           tags = "[" + cmd + "]" + url + "[/" + cmd + "]\r\n";
           break;
       case "emule":
       case "thunder":
       case "bt":
       case "flashget":  
       case "img": 
       case "wmv":
       case "flv":
       case "mp3":
       case "qvod":
           tags = "[" + cmd + "=" + argument + "]" + url + "[/" + cmd + "]\r\n";
           break;
   }
   if (cmd == "img" && argument == "")
       tags = "[" + cmd + "]" + url + "[/" + cmd + "]\r\n";
   insertToEnd(tags);
}

function insertToCur(text) {
    if (is_ie) {
        movePoint();
        obj = editdoc;
        obj.focus();
        var r = document.selection.createRange();
        var ctr = obj.createTextRange();
        var i;

        var s = obj.value;
        var ivalue = " ";
        r.text = ivalue;
        i = obj.value.indexOf(ivalue);
        r.moveStart("character", -ivalue.length);
        r.text = "";

        charvalue = text;
        obj.value = s.substr(0, i) + charvalue + s.substr(i, s.length);
        ctr.collapse(true);
        ctr.moveStart("character", i + charvalue.length);
        ctr.select();
    }
    else if (is_chrome || is_firefox) {
        var selStart = editdoc.selectionStart;
        var selEnd = editdoc.selectionEnd;
        editdoc.value = editdoc.value.substring(0, selStart) + text + editdoc.value.substring(selEnd); //
        //editdoc.selectionStart = editdoc.value.length;
       // editdoc.selectionEnd = editdoc.value.length;
    }
}

function insertToEnd(text) {
    if (is_ie) {
        editdoc.value = editdoc.value + text
        obj.focus();
    }
    else if (is_chrome || is_firefox) {      
        editdoc.value = editdoc.value + text
    } 
}
function getCaret() {
    if (is_ie) {
        var obj = editdoc.body;
        var s = document.selection.createRange();
        //alert(s.text.replace(/\r?\n/g, ' ').length);
        //    s.setEndPoint("StartToStart", obj.createTextRange());
        return s.text.replace(/\r?\n/g, ' ').length;
    }
    else {
        var selStart = editdoc.selectionStart;
        var selEnd = editdoc.selectionEnd;
        return selEnd - selStart;
    }
}
function setCaret(pos) {
    // var obj = editdoc.body ;
    if (is_ie) {
        var r = document.selection.createRange(); ///.createTextRange();obj.
        r.moveStart('character', pos);
        rng.moveEnd("character", pos)
        r.collapse(true);
        r.select();
    }
    else {
        editdoc.selectionStart = pos;
        editdoc.selectionEnd = pos;
    }
}


/*=========================================================common=========================================================================
*/
function isUndefined(variable) {
    return typeof variable == 'undefined' ? true : false;
}
function strlen(str) { //is_ie &&
    return ( str.indexOf('\n') != -1) ? str.replace(/\r?\n/g, '_').length : str.length;
}


function moveCursor(increment) {
    var test = cursor + increment;
    if (test >= 0 && stack[test] != null && !isUndefined(stack[test])) {
        cursor += increment;
    }
}

function addSnapshot(str) {
    if (stack[cursor] == str) {
        return;
    } else {
        cursor++;
        stack[cursor] = str;

        if (!isUndefined(stack[cursor + 1])) {
            stack[cursor + 1] = null;
        }
    }
}

function getSnapshot() {
    if (!isUndefined(stack[cursor]) && stack[cursor] != null) {
        return stack[cursor];
    } else {
        return false;
    }
}

function getEditorContents() {
    return editdoc.value;
}

/**********************************=============================================================firefox */
var fevent;

document.onmousedown = function(e) {
    if(is_firefox)
        fevent = e;
    //alert(e);
}
