var eConfig = {

    border:"1px solid #DFDFDF",
    bgcolor : "#FFFFFF",
    font : "normal 9pt arial",
    color : "#000",
    margin : "0px",
    width : "447px",
    height : "226px",
    filepath : ".",
    imgpath : "/front/lib/editor/images",
    over_bordercolor : "#FFFFFF",
    over_bgcolor : "#CCFFFF",
    divbtn_bgcolor : "#FFFFFF",


    Btn : null,
    BtnList : {
        font    : ["font","font.gif"],
        size    : ["size","size.gif"],
        color   : ["color","color.gif"],
        hilite  : ["background-color","hilite.gif"],
        bar     : ["line","bar.gif"],
        bold    : ["bold","bold.gif"],
        italic  : ["italic","italic.gif"],
        strike  : ["strike through","strike.gif"],
        underline : ["underline","underline.gif"],
        left    : ["justify left","left.gif"],
        center  : ["justify center","center.gif"],
        right   : ["justify right","right.gif"],
        link    : ["insert link","link.gif"],
        image   : ["Insert Image","image.gif"],
        source  : ["view source(function disabled)","source.gif"]
    },
	//,"bar","image","bar","source"
    BtnTemplate  : {
        basic  : ["preview","font","size","color","hilite","bar","bold","italic","underline","strike","bar","left","center","right","link","bar","image"],
        simple : ["preview","font","size","color","hilite","bar","bold","italic","underline","strike","bar","left","center","right","link","bar","source"]
    },

    name : "ezwigEditor"
}
// eEditor
function eEditor(id) {

    if(typeof(document.execCommand)=="undefined") {
        return;
    }

    eUtil.init();

    this.cfg = eConfig;
    var menu = $(id).readAttribute("MENU");
    if (!menu) {
        menu = 'basic';
    }

    this.cfg.Btn = eConfig.BtnTemplate[menu];
    this.cfg.preid = "ezwigEditor"+"_"+id;
    this.mode = "wyzwyg";
    this.btn = "";
    this.sel      = null;
    this.range    = null;
    this.sel_html = "";
    this._doc       = null;
    this._textarea  = $(id);
    this._div       = document.createElement("div");
    this._divbtn    = document.createElement("div");
    this._iframe    = document.createElement("iframe");
    this._text      = document.createElement("textarea");
    this._div.id    = this.cfg.preid+"_div";
    this._divbtn.id = this.cfg.preid+"_divbtn";
    this._iframe.id = this.cfg.preid+"_iframe";
    this._text.id   = this.cfg.preid+"_text";
}

//eEditor.init
eEditor.prototype.init = function() {

    this._textarea.style.display="none";

	this.cfg.width = this._textarea.style.width;
	this.cfg.height = this._textarea.style.height;

    this._text.style.width = this.cfg.width;
    this._text.style.height= this.cfg.height;
    this._text.style.border= "none";
    this._text.style.display="none";
    this._text.style.font = "9pt arial";
    this._text.style.background = "#efefef url("+this.cfg.imgpath+"/source_bg.gif) 0 -2px";
    this._text.style.lineHeight = "165%";

    this._iframe.style.width = this.cfg.width;
    this._iframe.style.height= this.cfg.height;

    this._iframe.frameBorder = "no";


    this._div.style.border  = this.cfg.border;
    this._div.style.width   = this.cfg.width;

    this._divbtn.style.padding  ="2px";
    this._divbtn.style.backgroundColor = this.cfg.divbtn_bgcolor;
    this._divbtn.style.borderBottom = this.cfg.border;
    if(eUtil.isIE) {this._divbtn.style.width = this.cfg.width;}

    this._textarea.parentNode.insertBefore(this._div, this._textarea);
    this._div.appendChild(this._divbtn);
    this._div.appendChild(this._iframe);
    this._div.appendChild(this._text);

    this.setBtn();

    this._doc = this._iframe.contentWindow.document;
    this._doc.designMode="on";

    var css  = "body{margin:"+this.cfg.margin+";background-color:"+this.cfg.bgcolor+";}";
    css     += " body,table,td{font:"+this.cfg.font+";color:"+this.cfg.color+";}";
    this._iframe.css = css;
    this._doc.open();
    this._doc.write('<html><head><style type="text/css">'+css+'</style></head><body style="ime-mode:disabled">'+this._textarea.value+'</body></html>');
    this._doc.close();

    var self=this;
    eUtil.addEvent(this._doc, "mousedown", eUtil.hideDiv);
    if(eUtil.isIE) {
        eUtil.addEvent(this._doc, "keydown", function(e) {
            var range=self._doc.selection.createRange();
            if(e.keyCode==13 && range.parentElement().tagName!="LI") {
                e.cancelBubble=true; e.returnValue=false;
                range.pasteHTML("<br />"); range.select(); return false;
            }
        });
    }
    this._div.style.margin="0px";
    this._div.style.padding="0px";
    this._div.style.background="url('')";
    this._divbtn.style.margin="0px";
    this._divbtn.style.padding="0px";
    this._divbtn.style.background="url('')";

    //alert($(this._textarea.form).tagName);
    if ($(this._textarea.form)) {
        $(this._textarea.form).observe('submit', function() {
            var f = Event.element(event);
            var g = f.select('textarea.EditCtrl');
            var doc;
            for (var i=0, s=g.size(); i<s; i++) {
                doc = $('ezwigEditor_' + g[i].id + '_iframe').contentWindow.document;
                txt = $('ezwigEditor_' + g[i].id + '_text');

                for(var j in doc.links) {
                    if(!doc.links[j].target) {
                        doc.links[j].target = "_blank";
                    }
                }
                html = doc.body.innerHTML;
                var j =0;
                //html.scan(new RegExp("<img[^>]+src=('|\")(file:\/\/\/[:\\w\\/\\.]+)\\1", "i"), function(match) {
                html.scan(new RegExp("<img[^>]+src=('|\")([:\\w\\\\\\.]+)\\1", "i"), function(match) {
                    //var filepath = match[2].substring(8).replace(/\//g, "\\");
                    var filepath = match[2];
                    var eid = 'editimage' + j;
                    j = j + 1;
                    //alert(filepath);
                    //alert(eid);
                    var ofile = new Element('input', {
                        type: 'file',
                        id: eid,
                        name: eid,
                        value: filepath
                    });
                    f.insert(ofile);

                    //$(eid).value = filepath;

                });

                g[i].value = html.stripScripts();
            }
        });
    }
};

//eEditor.setBtn
eEditor.prototype.setBtn = function() {

    this.cfg.Btn.push("bar");
    var arr=this.cfg.Btn;
    var len=arr.length;
    var str=order=tmp="";
    var btn=tag=null;
    var self=this;
    var bgcolor=this.cfg.divbtn_bgcolor;
    var over_bordercolor=this.cfg.over_bordercolor;
    var over_bgcolor=this.cfg.over_bgcolor;

    for(var i=0;i<len;i++) {
        tmp = "";
        order = eUtil.trim(arr[i]);
        btn = this.cfg.BtnList[order];

        if(order!="br" && !btn) {
            if(order!="") alert("None Command ("+order+")");
            continue;
        }
        if(order=="bar") {
            tag         = document.createElement("img");
            tag.src     = this.cfg.imgpath+"/"+btn[1];
            tag.width   = 2;
            tag.height  = 18;
            tag.hspace  = 4;
            tag.align   ="absmiddle";
            this._divbtn.appendChild(tag);
        }
        else if(order=="br") {
            this._divbtn.appendChild(document.createElement("br"));
        }
        else {
            tag         = document.createElement("img");
            tag.id      = this.cfg.preid+"_btn_"+order;
            tag.src     = this.cfg.imgpath+"/"+btn[1];
            tag.align   ="absmiddle";
            tag.alt     = btn[0];
            tag.cmd     = order;
            tag.style.cursor="pointer";
            tag.style.border="1px solid "+this.cfg.divbtn_bgcolor;

            tag.onclick = function() { self.cmd(this, this.cmd); };
            tag.onmouseover = function()  { this.style.border="1px solid "+over_bordercolor;this.style.backgroundColor=over_bgcolor; };
            tag.onmouseout = function()  { this.style.border="1px solid "+bgcolor;this.style.backgroundColor=""; };
            this._divbtn.appendChild(tag);
        }
    }
};
//eEditor.cmd
eEditor.prototype.cmd = function(btn, order, value)  {

    var self = (this) ? this:eUtil._editor;
    var doc = self._doc;
    if(self.mode=="text" && order!="source") {alert("Use after release 'View Source' Function !");  return;}
    self.focus();
    eUtil.hideDiv();
    self.btn = btn;

    try{var create_func = self.cfg.BtnList[order][2];}catch(e) {}
    if(typeof(create_func)=="function") order = "create_order";

    switch(order) {
        case "create_order":
            self.setSelection();
            eUtil._editor = self;
            eUtil.order = order;
            create_func(self);
        break;
        case "hyperlink":
            var link_text = (self.sel_html) ? self.sel_html : eUtil._linktxt.value;
            var html = "<a href='"+eUtil._linktxt.value+"' target='_blank'>"+link_text+"</a>";
            self.innerHTML(html);
        break;
        case "color":
        case "hilite":
        case "font":
        case "size":
        case "link":
        case "about":
        case "image":
            var div=null;
            if(order=="color")      { order = "forecolor"; eUtil.tblSet_color(); div=eUtil._colortbl;}
            else if(order=="hilite"){ order = "hilitecolor"; eUtil.tblSet_color(); div=eUtil._colortbl;}
            else if(order=="font")  { order = "fontname"; eUtil.tblSet_font(); div=eUtil._fonttbl;}
            else if(order=="size")  { order = "fontsize"; eUtil.tblSet_size(); div=eUtil._sizetbl;}
            else if(order=="about") { eUtil.tblSet_about(); div=eUtil._abouttbl;}
            else if(order=="link")  {
                order = "hyperlink";
                eUtil.tblSet_link();
                div=eUtil._linktbl;
                eUtil._linktxt.value = "http://";
                self.setSelection();
            }
            else if(order=="image") {
                order = "insertImage";
                eUtil.tblSet_image();
                div=eUtil._imagetbl;
            }

            eUtil._editor = self;
            eUtil.order = order;
            eUtil.showDiv(div);
        break;
        case "source":
            if(self.mode=="wyzwyg") {
                self._text.value = self.getHtml();
                self._iframe.style.display = "none";
                self._text.style.display = "";
                btn.onmouseout = null;
                self.mode="text";
            }
            else if(self.mode=="text") {
                doc.body.innerHTML = self.getHtml();
                self._text.style.display = "none";
                self._iframe.style.display = "";
                bgcolor = self.cfg.divbtn_bgcolor;
                btn.onmouseout = function()  { this.style.border="1px solid "+bgcolor;this.style.backgroundColor=""; };
                self.mode="wyzwyg";
            }
        break;
        default:
            if(order=="strike")     order = "strikethrough";
            else if(order=="ul1")   order = "insertorderedlist";
            else if(order=="ul2")   order = "insertunorderedlist";
            else if(order=="hr")    order = "inserthorizontalrule";
            else if(order=="clean") order = "removeformat";
            else if(order=="all")   order = "selectall";
            else if(order=="sup")   order = "superscript";
            else if(order=="sub")   order = "subscript";
            else if(order=="del")   order = "delete";
            else if(order=="justify") order = "justifyfull";
            else if(order=="center"||order=="left"||order=="right") order = "justify"+order;
            else if(order=="hilitecolor" && eUtil.isIE) order = "backcolor";

            doc.execCommand(order, false, value);
        break;
    }
};
//eEditor.focus
eEditor.prototype.focus = function()  {

    if(this.mode=="text") this._text.focus();
    else this._iframe.contentWindow.focus();
    this._iframe.contentWindow.readonly;
}
//eEditor.getHtml
eEditor.prototype.getHtml = function()  {

    var html = "";
    var doc = this._doc;
    if(this.mode=="text") html = this._text.value;
    else {
        for(i in doc.links) { if(!doc.links[i].target) doc.links[i].target = "_blank"; }
        html = doc.body.innerHTML;
    }
    //html = html.stripScripts();
    this._textarea.value = html;
    return html;
}
//eEditor.setSelection
eEditor.prototype.setSelection = function()  {

    var _iframe=this._iframe;
    var sel=null,range=null,html="";

    if(this._doc.selection) {
        sel = this._doc.selection;
        range = sel.createRange();
        html = range.htmlText;
    }
    else if(_iframe.contentWindow.getSelection) {
        sel=_iframe.contentWindow.getSelection();
        if (typeof(sel)!="undefined") range=sel.getRangeAt(0);
        else range=this._doc.createRange();
        if(sel.rangeCount > 0 && window.XMLSerializer) {
            html=new XMLSerializer().serializeToString(range.cloneContents());
        }
    }
    this.sel = sel;
    this.range = range;
    this.sel_html = html;
}
//eEditor.innerHTML
eEditor.prototype.innerHTML = function(html)  {

    if(eUtil.mode=="text") return;
    if(this.range.pasteHTML) this.range.pasteHTML(html);
    else this._doc.execCommand("inserthtml", false, html);
}
//eUtil
var eUtil = {
    _editor : null,
    _colortbl : null,
    _fonttbl : null,
    _sizetbl : null,
    _linktbl : null,
    _linktxt : null,
    arrtbl : new Array("color","font","size","link", "image"),
    order : "",
    is_init : 0,
    isIE : (window.showModalDialog) ? 1:0,

    init : function() {

        if(eUtil.is_init) {
            return;
        }

        var s="<style>";
        s += ".eWebEditorDiv a {text-decoration:none;color:#000}"
        s += "#"+"ezwigEditor"+"_colortbl a {border:1px solid #f5f5f5;padding:0 6px;height:9px;font:8px verdana;text-decoration:none}";
        s += "</style>";

        eUtil.is_init=1;
    },

    showDiv : function(div) {
        if (div) {
            var btn = eUtil._editor.btn;
            div.style.top= eUtil.curTop(btn) + btn.offsetHeight + "px";
            div.style.left = eUtil.curLeft(btn) + "px";
            div.style.display="";
        }
    },

    hideDiv : function() {
        if(typeof(eUtil)!="object") return;
        for(var i=0; i<eUtil.arrtbl.length; i++) {
            try{ eval('eUtil._'+eUtil.arrtbl[i]+'tbl.style.display="none"'); }
            catch(e) { }
/*            var e = $('eUtil._'+eUtil.arrtbl[i]+'tbl');
            if(e) {
                e.hide();
            }*/
        }
    },
    curTop : function(el)  {
        var top = el.offsetTop;
        var parent = el.offsetParent;
        while(parent) { top += parent.offsetTop; parent = parent.offsetParent; }
        return top;
    },
    curLeft : function(el)  {
        var left = el.offsetLeft;
        var parent = el.offsetParent;
        while(parent) { left += parent.offsetLeft; parent = parent.offsetParent; }
        return left;
    },
    tblSet_link : function() {
        if(eUtil._linktbl) return;
        var id = "ezwigEditor"+"_linktxt";
        var s = "<input type='text' value='http://' style='width:230px;font:8pt arial;color:gray' id='"+id+"' /><br>";
        s += "Enter URL<br><br>";
        s += "<a href='javascript:;' onclick=\"eUtil._editor.cmd(null, eUtil.order, '');\">SUBMIT</a>";

        var div = eUtil.getDiv("ezwigEditor"+"_linktbl",s);
        div.style.padding = "15px";
        div.style.font = "8pt arial";
        div.style.background="url('') #FFFFFF";
        document.body.appendChild(div);
        eUtil._linktbl = div;
        eUtil._linktxt = document.getElementById(id);
    },
    tblSet_size : function() {
        if(eUtil._sizetbl) return;
        var size = new Array(8,10,12,14,18,24);
        var s="";

        for(var i=0; i<size.length; i++) {
            s += "<a href='javascript:;' onclick=\"eUtil._editor.cmd(null, eUtil.order,'"+(i+1)+"');\" style='font:"+size[i]+"pt arial;'>ABCD ("+size[i]+")</a><br />";
        }
        var div = eUtil.getDiv("ezwigEditor"+"_sizetbl",s);
        div.style.padding = "5px";
        div.style.background="url('') #FFFFFF";
        document.body.appendChild(div);
        eUtil._sizetbl = div;
    },
    tblSet_font : function() {
        if(eUtil._fonttbl) return;
        var font = new Array("arial","verdana","Comic Sans MS","Courier New","Tahoma","Times New Roman");
        var s=""; var pattern=/^[a-z]+$/;

        for(var i=0; i<font.length; i++) {
            txt = (pattern.test(font[i])) ? "ABCD":"abcd";
            s += "<a href='javascript:;' onclick=\"eUtil._editor.cmd(null, eUtil.order,'"+font[i]+"');\" style='font:9pt "+font[i]+";line-height:170%'>"+txt+" ("+font[i]+")</a><br />";
        }
        var div = eUtil.getDiv("ezwigEditor"+"_fonttbl",s);
        div.style.padding = "3px";
        div.style.background="url('') #FFFFFF";
        document.body.appendChild(div);
        eUtil._fonttbl = div;
    },
    tblSet_color : function() {
        if(eUtil._colortbl) return;
        var col= new Array();
        col[0] = new Array("#ffffff","#e5e4e4","#d9d8d8","#c0bdbd","#a7a4a4","#8e8a8b","#827e7f","#767173","#5c585a","#000000");
        col[1] = new Array("#fefcdf","#fef4c4","#feed9b","#fee573","#ffed43","#f6cc0b","#e0b800","#c9a601","#ad8e00","#8c7301");
        col[2] = new Array("#ffded3","#ffc4b0","#ff9d7d","#ff7a4e","#ff6600","#e95d00","#d15502","#ba4b01","#a44201","#8d3901");
        col[3] = new Array("#ffd2d0","#ffbab7","#fe9a95","#ff7a73","#ff483f","#fe2419","#f10b00","#d40a00","#940000","#6d201b");
        col[4] = new Array("#ffdaed","#ffb7dc","#ffa1d1","#ff84c3","#ff57ac","#fd1289","#ec0078","#d6006d","#bb005f","#9b014f");
        col[5] = new Array("#fcd6fe","#fbbcff","#f9a1fe","#f784fe","#f564fe","#f546ff","#f328ff","#d801e5","#c001cb","#8f0197");
        col[6] = new Array("#e2f0fe","#c7e2fe","#add5fe","#92c7fe","#6eb5ff","#48a2ff","#2690fe","#0162f4","#013add","#0021b0");
        col[7] = new Array("#d3fdff","#acfafd","#7cfaff","#4af7fe","#1de6fe","#01deff","#00cdec","#01b6de","#00a0c2","#0084a0");
        col[8] = new Array("#edffcf","#dffeaa","#d1fd88","#befa5a","#a8f32a","#8fd80a","#79c101","#3fa701","#307f00","#156200");
        col[9] = new Array("#d4c89f","#daad88","#c49578","#c2877e","#ac8295","#c0a5c4","#969ac2","#92b7d7","#80adaf","#9ca53b");
        var s="";
        for(var i=0; i<10; i++) {
            for(var j=0; j<10; j++) {
                color = col[i][j];
                s += "<a href='javascript:;' onclick=\"eUtil._editor.cmd(null, eUtil.order,'"+color+"');\" style='background-color:"+color+";'>&nbsp;</a>";
            }
            s += "<br />";
        }
        var div = eUtil.getDiv("ezwigEditor"+"_colortbl",s);
        document.body.appendChild(div);
        eUtil._colortbl = div;
        div.style.background="url('') #FFFFFF";
    },
    tblSet_image : function() {

        if(eUtil._imagetbl) {
            return;
        }

 var s = "";
 s += "<form name='upload' method='post' action='../lib/Upload.action' enctype='multipart/form-data' target='frmimageupload' style='display: inline;'>";
 s += "<input type='file' name='multi.upfile1' value='' style='width:230px; font:8pt arial;color:gray;'>";
 s += "<input type='button' value='OK' style='width:50px; font:8pt arial;color:gray;' onclick='this.form.submit(); eUtil.hideDiv();'>";
 s += "<iframe id='frmimageupload' name='frmimageupload' style='width:0;height:0;background-color:transparent' frameborder='0' scrolling='no' allowtransparency='true'></iframe>";
 s +="</form>";  

        var div = eUtil.getDivElement("ezwigEditor_imagetbl", s);
        document.body.appendChild(div);

        eUtil._imagetbl = div;
    },
    getDivElement : function(id, html) {
        var div = new Element("div", {
            'id': id,
            'class': "eWebEditorDiv"
        });
        
        div.setStyle({
            position: "absolute",
            backgroundColor: "#f5f5f5",
            display: "none",
            border: "1px solid #ccc",
            padding: "5px",
            background: "url('') #FFFFFF"
        });

        div.update(html);

        return div;
    },
    getDiv : function(id, html) {
        var div = document.createElement("div");
        div.id = id;
        div.className = "eWebEditorDiv";
        div.style.position = "absolute";
        div.style.backgroundColor = "#f5f5f5";
        div.style.display = "none";
        div.style.border = "1px solid #ccc";
        div.style.padding = "5px";
        div.style.background="url('') #FFFFFF";
        div.innerHTML = html;
        return div;
    },
    addEvent : function(object, type, listener) {
        if(object.addEventListener) { object.addEventListener(type, listener, false); }
        else if(object.attachEvent) { object.attachEvent("on"+type, listener); }
    },
    trim : function(s) {return s.replace(/^\s+|\s+$/g,'');}
};

eConfig.BtnList.preview = ["Preview","preview.gif", function (self){
    var w=window.open("","preview","width=600,height=600,status=1,scrollbars=1,resizable=1");
    w.document.open();
    w.document.write("<style>"+self._iframe.css+"</style>"+self.getHtml());
    w.document.close();
}];

Event.observe(window, 'load', function() {
    var g = $$('TEXTAREA.EditCtrl');
    for (var i=0, s=g.length; i<s; i++) {
        var e = new eEditor(g[i].identify());
        e.init();
    }
});

function insertImgSrc(src) {
    eUtil._editor.cmd(null, 'insertImage', src);
}
