var richtext_obj_name = 'z_richtext';

function zEditGetObject(srl) {
    if(typeof(srl)=='undefined') srl = '';
    var obj_name = richtext_obj_name+srl;
    return xGetElementById(obj_name);
}

function zEditSetHeight(srl, height) {
    var robj = zEditGetObject(srl);
    if(!robj) return;
    robj.style.height = height;
}

function zEditInit(html, srl, height) {
    if(typeof(srl)=='undefined') srl = '';
    var robj = zEditGetObject(srl);
    if(!robj) return;

    if(typeof(html)=='undefined') html = '';
    if(typeof(height)=='undefined') height = '300px';

    if(srl) robj.style.height = '160px';
    else robj.style.height = height;

    robj.style.display = 'block';

    var default_font = xGetElementById('zone_fontname_'+(srl?srl:'') ).options[1].value;

    var contentDocument = robj.contentWindow.document;
    contentDocument.designMode = 'on';
    contentDocument.open("text/html","replace");


    var contentHtml = ''+
        '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'+
        '<html><head><meta http-equiv="content-type" content="text/html; charset=utf-8"/>';
    for(var i in document.styleSheets) {
        var tmp_obj = document.styleSheets[i];
        if(typeof(tmp_obj.href)=='undefined'||tmp_obj.href.lastIndexOf(".css")<0) continue;
        if(tmp_obj.href.indexOf('common/css/common.css')>0 || tmp_obj.href.indexOf('module.css')>0) {
            contentHtml += "<link rel='StyleSheet' HREF='"+tmp_obj.href+"' type='text/css' />";
        }
    }
    contentHtml += ""+
        "</head><body style='background-color:#FFFFFF;font-family:"+default_font+";font-size:9pt;'>"+
        html+
        "</body></html>";
    contentDocument.write(contentHtml);
    contentDocument.close();

    if(xIE4Up) xAddEventListener(robj.contentWindow.document,'keydown',zEditKeyPress);
    else xAddEventListener(robj.contentWindow.document, 'keypress',zEditKeyPress);

    xAddEventListener(document,'keypress',zEditKeyPress);
    xAddEventListener(robj.contentWindow.document,'mousedown',zEditHideObject);

    xAddEventListener(document,'mouseup',zEditEventCheck);
    xAddEventListener(document,'mousedown',zEditHideObject);

    if(xIE4Up) {
        xDisplay('editor_paragraph_'+srl, 'none');
        xDisplay('editor_paragraph_use_'+srl, 'block');
    } else {
        xDisplay('editor_paragraph_'+srl, 'block');
        xDisplay('editor_paragraph_use_'+srl, 'none');
    }

    setTimeout(zEditPrintDefault,1000);
}

function zEditClose(srl) {
    var robj = zEditGetObject(srl);

    robj.contentWindow.document.designMode = 'off';
    if(xIE4Up) xRemoveEventListener(robj.contentWindow.document,'keydown',zEditKeyPress,false);
    else xRemoveEventListener(robj.contentWindow.document, 'keypress',zEditKeyPress,false);
    xRemoveEventListener(robj.contentWindow.document, 'keypress',zEditKeyPress,false);
    xRemoveEventListener(robj.contentWindow.document,'mousedown',zEditHideObject,false);
    xRemoveEventListener(document,'mouseup',zEditEventCheck,false);
    xRemoveEventListener(document,'mousedown',zEditHideObject,false);
}

function zEditInitModule() {
    var robj = zEditGetObject();
    if(!robj) return;

    var fo_obj_name = 'fo_insert';
    var fo_obj = xGetElementById(fo_obj_name);
    if(!fo_obj) return;

    var article_obj = fo_obj.article;
    if(typeof(article_obj)=='undefined') return;

    var article = fo_obj.article.value;
    zEditInit(article);
}

function zEditUseParagraph(obj, srl) {
    if(typeof(srl)=='undefined') srl = '';
    if(obj.checked) {
        xDisplay('editor_paragraph_'+srl, 'block');
    } else {
        xDisplay('editor_paragraph_'+srl, 'none');
    }
}

function zEditGetHTML(srl) {
    var robj = zEditGetObject(srl);
    if(!robj) return;
    var html = '';
    html = xInnerHtml(robj.contentWindow.document.body);

    //return html.trim().replace(/<br>$/ig,'<br />').replace(/<p/ig,'<div').replace(/<\/p>/ig,'</div>');
    return html.trim().replace(/<br>$/ig,'<br />');
}

function zEditGetSelectedHTML(obj) {
    if(xIE4Up) {
        var range = obj.contentWindow.document.selection.createRange();
        var html = range.htmlText;
        range.select();
        return html;
    } else {
        var range = obj.contentWindow.getSelection().getRangeAt(0);
        var dummy = xCreateElement('div');
        dummy.appendChild(range.extractContents());
        var html = xInnerHtml(dummy);
        return html;
    }
}

function zEditReplaceHTML(obj, html) {
    if(xIE4Up) {
        var range = obj.contentWindow.document.selection.createRange();
        range.pasteHTML(html);
    } else {
        var range = obj.contentWindow.getSelection().getRangeAt(0);
        range.deleteContents();
        range.insertNode(range.createContextualFragment(html));
    }
}

function zEditKeyPress(evt)
{
    var e = new xEvent(evt);

    if (e.keyCode == 13) {
        if(xIE4Up && e.shiftKey == false && !xGetElementById("use_paragraph").checked ) {
            var obj = e.target.parentElement.document.selection.createRange();
            obj.pasteHTML('<br />');
            obj.select();
            evt.cancelBubble = true;
            evt.returnValue = false;
            return;
        }
    }

    if (e.ctrlKey) {
        switch(e.keyCode) {
            case 98 : // b
                    zEditDo('Bold',null,e.target);
                    xPreventDefault(evt);
                    xStopPropagation(evt);
                break;
            case 105 : // i
                    zEditDo('Italic',null,e.target);
                    xPreventDefault(evt);
                    xStopPropagation(evt);
                break;
            case 117 : // u
                    zEditDo('Underline',null,e.target);
                    xPreventDefault(evt);
                    xStopPropagation(evt);
                break;
            case 83 : // s
            case 115 : // s
                    zEditDo('StrikeThrough',null,e.target);
                    xPreventDefault(evt);
                    xStopPropagation(evt);
                break;
            /*
            case 37 : // left arrow
                    zEditDo('justifyleft',null,e.target);
                    xPreventDefault(evt);
                    xStopPropagation(evt);
                break;
            case 38 : // up arrow
                    zEditDo('justifycenter',null,e.target);
                    xPreventDefault(evt);
                    xStopPropagation(evt);
                break;
            case 39 : // right arrow
                    zEditDo('justifyright',null,e.target);
                    xPreventDefault(evt);
                    xStopPropagation(evt);
                break;
            */
        }
    }

}

var zEditPrevObj = null;
var zEditPrevSrl = null;
function zEditEventCheck(evt) {
    var e = new xEvent(evt);
    var target_id = e.target.id;
    if(target_id.indexOf('zEdit_')!=-1) {
        var tmp_str = target_id.split('_');
        var method_name = tmp_str[1];
        var srl = tmp_str[2];
        switch(method_name) {
            case 'Bold' :
            case 'Italic' :
            case 'Underline' :
            case 'StrikeThrough' :
            case 'justifyleft' :
            case 'justifycenter' :
            case 'justifyright' :
            case 'indent' :
            case 'outdent' :
            case 'insertorderedlist' :
            case 'insertunorderedlist' :
                    zEditDo(method_name, '', srl);
                break;
            case 'Highlight' :
                    var obj = zEditGetObject(srl);
                    var html = zEditGetSelectedHTML(obj);

                    var response_tags = new Array('error','message','html');
                    var params = new Array();
                    params['html'] = html;
                    request_xml('etc','highlight',params,zEditHighlight,response_tags, obj);
                break;
            default :
                    zEditPrevSrl = srl;

                    switch(method_name) {
                        case "AddEmoticon" :
                                var x = (screen.availWidth - 200)/2;
                                var y = (screen.availHeight - 130)/2;
                                var editor_popup = window.open("./common/tpl/editor_popup/add_emoticon.php","_editorPopup","top="+y+",left="+x+",width=200,height=130,resizable=no,toolbars=no,scrollbars=no");
                                if(editor_popup) editor_popup.focus();
                                return;
                            break;
                        case "Quotation" :
                                var x = (screen.availWidth - 400)/2;
                                var y = (screen.availHeight - 400)/2;
                                var editor_popup = window.open("./common/tpl/editor_popup/add_quotation.php","_editorPopup","top="+y+",left="+x+",width=400,height=400,resizable=no,toolbars=no,scrollbars=no");
                                if(editor_popup) editor_popup.focus();
                                return;
                            break;
                        case "AddUrl" :
                                var x = (screen.availWidth - 400)/2;
                                var y = (screen.availHeight - 220)/2;
                                var editor_popup = window.open("./common/tpl/editor_popup/add_url.php","_editorPopup","top="+y+",left="+x+",width=400,height=220,resizable=no,toolbars=no,scrollbars=no");
                                if(editor_popup) editor_popup.focus();
                                return;
                            break;
                        case "AddImage" :
                                var x = (screen.availWidth - 400)/2;
                                var y = (screen.availHeight - 220)/2;
                                var editor_popup = window.open("./common/tpl/editor_popup/add_image.php","_editorPopup","top="+y+",left="+x+",width=400,height=80,resizable=no,toolbars=no,scrollbars=no");
                                if(editor_popup) editor_popup.focus();
                                return;
                            break;
                        case "AddMultimedia" :
                                var x = (screen.availWidth - 400)/2;
                                var y = (screen.availHeight - 220)/2;
                                var editor_popup = window.open("./common/tpl/editor_popup/add_multi.php","_editorPopup","top="+y+",left="+x+",width=400,height=110,resizable=no,toolbars=no,scrollbars=no");
                                if(editor_popup) editor_popup.focus();
                                return;
                            break;
                        case "HTML" :
                                var x = (screen.availWidth - 400)/2;
                                var y = (screen.availHeight - 500)/2;
                                var editor_popup = window.open("./common/tpl/editor_popup/add_html.php","_editorPopup","top="+y+",left="+x+",width=400,height=500,resizable=no,toolbars=no,scrollbars=no");
                                if(editor_popup) editor_popup.focus();
                                return;
                            break;
                    }

                    var obj = xGetElementById('zone_'+method_name);
                    if(!obj.style.visibility || obj.style.visibility == 'visible') {
                        obj.style.visibility = 'hidden';
                        return;
                    }

                    var w = xWidth(obj);
                    var h = xHeight(obj);
                    var x = e.pageX;
                    var y = e.pageY;
                    if(w+x>getBodyWidth()) x = getBodyWidth()-w;
                    if(h+y>getBodyHeight()) y = getBodyHeight()-h;
                    xLeft(obj,x-5);
                    xTop(obj,y+10);

                    obj.style.visibility = 'visible';
                    zEditPrevObj = obj;
                break;
        }
    }
    return;
}

function zEditDo(name, value, target) {
    if(typeof(target)=='object') _zEditDoObject(name, value, target);
    else _zEditDoSrl(name, value, target);
}

function _zEditDoSrl(name, value, srl) {
    var robj = zEditGetObject(srl);
    zEditFocus(srl);
    if(xIE4Up) robj.contentWindow.document.execCommand(name, false, value);
    else robj.contentWindow.document.execCommand(name, false, value);
    zEditFocus(srl);
}

function _zEditDoObject(name, value, obj) {
    if(xIE4Up) {
        obj.parentElement.document.execCommand(name, false, value);
    } else {
        obj.parentNode.execCommand(name, false, value);
    }
}

function zEditHideObject(evt) {
    if(!zEditPrevObj) return;
    var e = new xEvent(evt);
    var tobj = e.target;
    while(tobj) {
        if(tobj.id == zEditPrevObj.id) { 
            return;
        }
        tobj = xParent(tobj);
    }
    zEditPrevObj.style.visibility = 'hidden';
    zEditPrevObj = null;
    return;
}

function zEditFontName(obj,srl) {
    var value = obj.options[obj.selectedIndex].value;
    if(!value) return;
    zEditDo('FontName',value,srl);
    obj.selectedIndex = 0;
}

function zEditFontSize(obj,srl) {
    var value = obj.options[obj.selectedIndex].value;
    if(!value) return;
    zEditDo('FontSize',value,srl);
    obj.selectedIndex = 0;
}

function zEditSetForeColor(color_code) {
    if(zEditPrevObj.style.visibility == 'hidden') return;
    zEditDo("ForeColor",color_code,zEditPrevSrl);
    zEditPrevObj.style.visibility = 'hidden';
    zEditFocus(zEditPrevSrl);
}

function zEditSetBackColor(color_code) {
    if(zEditPrevObj.style.visibility == 'hidden') return;
    if(xIE4Up) zEditDo("BackColor",color_code,zEditPrevSrl);
    else zEditDo("hilitecolor",color_code,zEditPrevSrl);
    zEditPrevObj.style.visibility = 'hidden';
    zEditFocus(zEditPrevSrl);
}

function zEditInsertEmoticon(obj) {
    zEditFocus(zEditPrevSrl);
    zEditDo("InsertImage",obj.src,zEditPrevSrl);
    zEditFocus(zEditPrevSrl);
}

function zEditDoInsertUrl(link, srl) {
    zEditFocus(srl);
    var robj = zEditGetObject(srl);
    zEditReplaceHTML(robj, link);
}

function zEditInsertUrl(text, url, link_type) {
    if(!text || !url) return;
    if(!/^(http|ftp)/i.test(url)) url = 'http://'+url;

    var link = '';
    if(!link_type) link = "<a href=\""+url+"\" target=\"_blank\">"+text+"</a>";
    else link = "<a href=\""+url+"\" class=\""+link_type+"\" style='text-decoration:none;' target=\"_blank\">"+text+"</a>";

    zEditFocus(zEditPrevSrl);
    var obj = zEditGetObject(zEditPrevSrl)
    zEditReplaceHTML(obj, link);
}

function zEditInsertImage(url, src_align) {
    if(!url) return;
    if(!/^(http|ftp)/i.test(url)) url = 'http://'+url;

    zEditFocus(zEditPrevSrl);

    var html = "<img src=\""+url+"\" border=\"0\" align=\""+src_align+"\" />";
    var obj = zEditGetObject(zEditPrevSrl);
    zEditReplaceHTML(obj, html);
}


function zEditGetMultimediaHtml(url, width, height, source_filename) {
    if(typeof(width)=='undefined'||!width) width = 540;
    if(typeof(height)=='undefined'||!height) height= 420;

    var type = "application/x-mplayer2";
    var pluginspace = "http://www.microsoft.com/Windows/MediaPlayer/";
    var kind = 'movie';

    if(/\.swf$/i.test(url)) kind = 'flash';
    if(typeof(source_filename)!='undefined' && /\.swf$/i.test(source_filename)) kind = 'flash';

    if(kind=='flash') {
        type = "application/x-shockwave-flash";
        pluginspace = "http://www.macromedia.com/go/getflashplayer";
    }
    var html = "<embed src=\""+url+"\" width=\""+width+"\" height=\""+height+"\" autostart=\"0\"  type=\""+type+"\" pluginspage=\""+pluginspace+"\"></embed><BR />";
    return html;
}

function zEditInsertMultimedia(url, width, height) {
    if(url) {
        var html = zEditGetMultimediaHtml(url, width, height);
        zEditFocus(zEditPrevSrl);
        var obj = zEditGetObject(zEditPrevSrl)
        zEditReplaceHTML(obj, html);
        zEditFocus(zEditPrevSrl);
    }
}

function zEditInsertHTML(html) {
    if(!html) return;

    zEditFocus(zEditPrevSrl);
    var obj = zEditGetObject(zEditPrevSrl)
    zEditReplaceHTML(obj, html);
    zEditFocus(zEditPrevSrl);
}

function zEditInsertQuotation(html) {
    if(!html) return;

    if(!xIE4Up) html += "<br />";
    zEditFocus(zEditPrevSrl);
    var obj = zEditGetObject(zEditPrevSrl)
    zEditReplaceHTML(obj, html);
    zEditFocus(zEditPrevSrl);
}

function zEditHighlight(ret_obj, response_tags, obj) {
    var html = ret_obj['html'];
    html = "<div class='php_code'>"+html+"</div>";
    if(!xIE4Up) html += "<br />";
    zEditReplaceHTML(obj, html);
}

function zEditFocus(srl) {
    var robj = zEditGetObject(srl);
    if(xIE4Up) robj.contentWindow.focus();
    else robj.contentWindow.focus()
}

function zEditPrintDefault() {
    zEditPrintColorTable();
}

function zEditPrintColorTable() {
    var color = new Array('000000','993300','333300','003300','003366','000080','333399','333333','800000','FF6600','808000','008000','008080','0000FF','666699','808080','FF0000','FF9900','99CC00','339966','33CCCC','3366FF','800080','969696','FF00FF','FFCC00','FFFF00','00FF00','00FFFF','00CCFF','993366','c0c0c0','FF99CC','FFCC99','FFFF99','CCFFCC','CCFFFF','99CCFF','CC99FF','FFFFFF');
    var type_list = new Array('Fore','Back');

    for(var j=0;j<type_list.length; j++) {
        var type = type_list[j];
        var html = '';
        for(var i=0;i<color.length;i++) {
            html += "<img src=\"./common/images/edit/color_block.gif\" onFocus=\"this.blur()\" style=\"margin:2px;width:10px;height:10px;cursor:pointer;border:1px solid;border-color:#000000;background-color:#"+color[i]+"\" onClick=\"zEditSet"+type+"Color('#"+color[i]+"')\" onMouseOver=\"this.style.borderColor='#ffffff'\" onMouseOut=\"this.style.borderColor=''\" />";
            if((i+1)%8==0) html += "<br />";
        }
        if(type=='Fore') {
            xInnerHtml('zone_ShowColor', html);
            xWidth('zone_ShowColor', xWidth('zone_ShowColor'));
        } else {
            xInnerHtml('zone_ShowBackColor', html);
            xWidth('zone_ShowBackColor', xWidth('zone_ShowBackColor'));
        }
    }
}

