// DEA 20090714 gFilesRefPath is set in filesref.wssi
//alert('gFilesRefPath = ' + gFilesRefPath);

var browser = navigator.userAgent.toLowerCase();
isIE = ((browser .indexOf( "msie" ) != -1) && (browser .indexOf( "opera" ) == -1) && (browser .indexOf( "webtv" ) == -1));
isGecko = (browser .indexOf( "gecko" ) != -1);
isSafari = (browser .indexOf( "safari" ) != -1);
isKonqueror = (browser.indexOf( "konqueror" ) != -1);

var HTMLAreaList= new Array();

function HTMLArea(textarea, config, target) {
    this.isEditabled = false;
    if (HTMLArea.checkSupportedBrowser()) {
        if (typeof config == "undefined") {
            this.config = new HTMLArea.Config();
        } else {
            this.config = config;
        }
        this._htmlArea = null;
        this._htmlAreaObject = null;
        this._textArea = textarea;
        bVar = document; if(target) bVar = target.document;
        this._textAreaObject = bVar.getElementById(textarea);
        this._tool = null;
        this._event = null;
        this._free = true;
        this._mode = "hide";
        this._toolHeader = null;
        this._toolBody = null;
        this._toolFix = false;
        this._externalControll = null;
        this._headerSelect = false;
        this._id = this._textAreaObject.id+"_SHADOW";
        this._headerButtons=new Array();
        this._tagName = (""+this._textAreaObject.tagName).toUpperCase();
        this._styleFile = this.config.styleFile ;
        this._location = this.config.location ;
        this.isEditabled = true;
    }
};

HTMLArea.Config = function () {
    this.version = "1.02.6b";
    /*1.02.5b add header support*/
    /*1.02.6b add create link*/
    this.width = "auto";
    this.height = "auto";
    this.location = "";
    this.actionSet = {
        view: [ "HTMLView","HTMLView", gFilesRefPath+"htmlarea_view.gif","changeView",false],
        header: [ "Header","formatblock", gFilesRefPath+"htmlarea_underline.gif","setFont",true],
        link: [ "Link","createlink", gFilesRefPath+"htmlarea_link.gif","linkEditor",false],
        unlink: [ "UnLink","unlink", gFilesRefPath+"htmlarea_unlink.gif","clearLink",false],
        underline: [ "Underline","underline", gFilesRefPath+"htmlarea_underline.gif","editorCommand",true],
        bold: [ "Bold", "bold",gFilesRefPath+"htmlarea_bold.gif", "editorCommand",true],
        italic: [ "Italic","italic", gFilesRefPath+"htmlarea_italic.gif","editorCommand",true],
        justifyleft: ["Justifyleft","justifyleft",gFilesRefPath+"htmlarea_j_left.gif","editorCommand",true],
        justifycenter: ["Justifycenter","justifycenter",gFilesRefPath+"htmlarea_j_center.gif","editorCommand",true],
        justifyright: ["Justifyright", "justifyright",gFilesRefPath+"htmlarea_j_right.gif","editorCommand",true],
        insertorderedlist: ["Insertorderedlist", "insertorderedlist",gFilesRefPath+"htmlarea_list_num.gif","editorCommand",true],
        insertunorderedlist: ["InsertUnorderedlist", "insertunorderedlist",gFilesRefPath+"htmlarea_list_bullet.gif","editorCommand",true],
        indent: ["Indent","indent",gFilesRefPath+"htmlarea_indent.gif","editorCommand",true],
        outdent: ["Outdent","outdent",gFilesRefPath+"htmlarea_outdent.gif","editorCommand",true],
        undo: ["Undo","undo",gFilesRefPath+"htmlarea_undo.gif","editorCommand",false],
        redo: ["Redo","redo",gFilesRefPath+"htmlarea_redo.gif","editorCommand",false]
    };
    if(isSafari){
        this.actionSet['insertorderedlist'] = null;
        this.actionSet['insertunorderedlist'] = null;
    }
    this.toolbar =["underline","bold", "italic"];
};

HTMLArea.checkSupportedBrowser = function(){
   if (document.getElementById && document.designMode && !isKonqueror) return true;
   else return false;
}

HTMLArea.divContent = function(dvid, direct) {
    document.getElementById(dvid);
    var dv = document.getElementById("" + dvid);
    if (direct == true || direct == false) {
        if (direct == true) {
            dv.className = "HTMLAREA_ACTIVE";
        } else {
            dv.className = "HTMLAREA";
        }
    } else {
        if (dv.className == "HTMLAREA_ACTIVE")
            dv.className = "HTMLAREA";
        else
            dv.className = "HTMLAREA_ACTIVE";
    }
}

HTMLArea.prototype.generate = function (modeGenarate) {
    if (this.isEditabled) {
        if (modeGenarate != false) modeGenarate = true;
        var div = document.createElement("div");
        var localHeight = this.config.height;
        var localWidth = this.config.width;
        if (this.config.width == "auto") localWidth = this._textAreaObject.offsetWidth + "px";
        if (this.config.height == "auto") localHeight = this._textAreaObject.offsetHeight+"px";
        div.style.width = localWidth;
        div.style.height = localHeight;
        div.className = "HTMLAREABOX";
        div.style.display = "none";
        this._textAreaObject.parentNode.insertBefore(div, this._textAreaObject);
        this._tool = div;
        var divTop = document.createElement("div");
        var divBottom = document.createElement("div");
        div.appendChild(divTop);
        div.appendChild(divBottom);
        this._toolHeader = divTop;
        this._toolBody = divBottom;
        var this_ = this;
        var table = document.createElement("table");
        var tBody = document.createElement("tbody");
        var tr = document.createElement("tr");
        tBody.appendChild(tr);
        table.appendChild(tBody);
        var ifr = document.createElement("iframe");
        ifr.src = "javascript:false";
        divBottom.appendChild(ifr);
        ifr.id = this._id;
        ifr.name="";
        ifr.border="0";
        ifr.style.border ="1px solid black";
        ifr.width="100%";
        ifr.height="100%";
        for (i in this.config.toolbar) {
            /*
            var retObject = this.itemDraw(this.config.toolbar[i]);
            tr.appendChild(retObject);
            */
            var retObject;
            var item = this.config.toolbar[i];
            var keys = item;
            var callBack = false;
            if(typeof item == 'object'){
               keys = item[0];
               callBack = item[1];
            }
            var action = this.config.actionSet[keys];
            if(action){

                var td = document.createElement("td");
                var actionMode = action[1];
                var functionMode = action[3];
                var needIlluminate = action[4];
                td.className = "HTMLAREA";
                td.id = "HTMLAREA_SPAN_"+this._id+"_"+action[1];
                if(needIlluminate){
                    if(actionMode!="link" && actionMode!="header")
                    this._headerButtons[actionMode]=td.id;
                }
                if (functionMode == "editorCommand" || functionMode == "changeView"  || functionMode == "linkEditor" || functionMode == "clearLink" ){
                    var img = "<img src='"+this._location+action[2]+"' id='"+action[2]+"' border='0'>";
                    var fn = ""
                    if (functionMode == "editorCommand") {
                        fn="HTMLArea.editorCommand(\""+this._id+"\",\""+actionMode+"\",event); ";
                        if(needIlluminate == true) fn=fn+"HTMLArea.divContent(\""+td.id+"\"); ";
                    }
                    if (functionMode == "changeView") fn="HTMLArea.changeView(\""+this._id+"\",\"hide\","+callBack+")";
                    if (functionMode == "linkEditor") fn="HTMLArea.linkEditor(\""+this._id+"\","+callBack+",event)";
                    if (functionMode == "clearLink") fn="HTMLArea.clearLink(\""+this._id+"\","+callBack+",event)";
                    var href = "<a href='#' onmousedown='"+fn+" ; return false;'>"+img+"</a>";
                        td.innerHTML=href;
                }
                if (functionMode == "setFont") {
                        var select = "";
                        var list = new Array(["h1","h1"],["h2","h2"],["h3","h3"],["h4","h4"],["h5","h5"],["h6","h6"],["p","Normal"],["pre","Formated"],["address","Address"]);
                        select+="<select onChange='HTMLArea.setFont(\""+this._id+"\",this,\""+actionMode+"\",event);' id='SELECTHEADER_"+this._id+"' name='SELECTHEADER_"+this._id+"'>";
                        for(i in list){
                         select+="<option id='"+list[i][0]+"' name='"+list[i][0]+"' value='"+list[i][0]+"'>";
                           select+=list[i][1];
                         select+="</option>";
                        }
                        select+="</select>";
                        td.innerHTML = select;
                        this._headerSelect = "SELECTHEADER_"+this._id;
                        fn="HTMLArea.setFont("+this_.id+")";
                }
                retObject = td;
                tr.appendChild(retObject);
            }
        }
        divTop.appendChild(table);
        HTMLAreaList[ifr.id] = this;
        if (modeGenarate == true) {
            this._textAreaObject.style.display = "none";
            div.style.display = '';
        }
        
        var oDoc = (ifr.contentWindow || ifr.contentDocument); 
        if (oDoc.document) oDoc = oDoc.document;

        var mainContent = "";
        if (this._tagName == "DIV") {
            nowText = this._textAreaObject.innerHTML;
            mainContent = HTMLArea.getAreaBody(nowText, this);
        } else {
            //nowText=this._textAreaObject.value;
            nowText = this._textAreaObject.innerHTML;
            //mainContent = HTMLArea.getAreaBody(nowText.replace(/\n+/g, '<br/>').replace(' ', '&nbsp;'),this);
            //mainContent = mainContent.replace(/</g, '&lt;').replace(/>/g, '&gt;');
            //if (!isIE) mainContent = mainContent.replace(/<script.*<\/script>/g, '');
            mainContent = nowText;
        }

        if (isIE) {
            ifr.designMode = 'On';
        } else {
            if (modeGenarate == true) {
                if(isSafari){
                    iframe = document.getElementById(this._id);
                    doc = iframe.contentDocument;
                    doc.designMode = "on";
                }else
                    oDoc.designMode = "on";
            }
    }
        oDoc.open("text/html");
        oDoc.write(mainContent);
        oDoc.close();
        if (isIE) oDoc.designMode = 'On';
        this._htmlAreaObject = oDoc;

        this._htmlArea = ifr;
        /*
        HTMLArea._addEvents
            (ifr, ["blur"],
             function (event) {
                 try {
                    return this_.setActualValue();
                 }catch(e) {}
             });
        */
        HTMLArea._addEvents
                   
            (ifr, ["keyup", "mouseup", "drag", "blur"/*"blur","keydown","keyup", "keypress", "mousedown", "mouseup", "drag"*/],
             function (event) {
                 try {
                    return this_.updateMenuContext(isIE ? this_._htmlArea.contentWindow.event : event);
                 }catch(e) {}
             });


        if(this._headerSelect!=false) this._headerSelect = document.getElementById(this._headerSelect);

        if(modeGenarate==true) this._mode= "show";

    }

}
HTMLArea._addEvent = function(el, evname, func) {
    if (isIE) {
            el.contentWindow.document.attachEvent("on" + evname, func);
    } else {
        el.contentDocument.addEventListener(evname, func, true);
    }
};

HTMLArea._addEvents = function(el, evs, func) {
    for (var i in evs) {
        HTMLArea._addEvent(el, evs[i], func);
    }
};

HTMLArea.safaryWay = function (obj) {
    obj.setActualValue();
}
HTMLArea.getAreaBody = function (textValue, obj) {
    //var mainContent = '<html><head><style type="text/css">p{margin:0px; padding:0px;}</style></head><body style="background:#ffffff; margin:0px; padding:0px; border:0px solid black; font-size:12px;">'+textValue+'</body></html>' ;
    var mainContent = '<html><body style="background:#ffffff; margin:0px; padding:0px; border:0px solid black; font-size:12px;">'+textValue+'</body></html>' ;
    return mainContent
}
/*
HTMLArea.prototype.updateMenuContext = function (event) {
   this._event = event;
   if(isIE) setTimeout(this.updateMenuContextDark(),100);
   this.updateMenuContextDark();
}
*/

HTMLArea.prototype.updateMenuContext = function (event) {
   this._event = event;
   if(isIE) setTimeout(this.updateMenuContextDark(),10);
   this.updateMenuContextDark();
}

HTMLArea.prototype.updateMenuContextDark = function () {
    if(this._event!=null){
    var mainField = this._htmlAreaObject;
    var listAction = this._headerButtons;
    for(i in listAction){
        if(i=="formatblock"){
           var value = ("" + mainField.queryCommandValue(i)).toLowerCase();
           if (isIE){
                if(value.indexOf("1")>0) value = "h1";
                else if(value.indexOf("2")>0) value = "h2";
                else if(value.indexOf("3")>0) value = "h3";
                else if(value.indexOf("4")>0) value = "h4";
                else if(value.indexOf("5")>0) value = "h5";
                else if(value.indexOf("6")>0) value = "h6";
                else value = "";
           }else{
                objMe._headerSelect.options[value].selected = true;
           }
        }else if(i=="createlink"){


        }else if(i=="unlink"){


        }else{
           HTMLArea.divContent(listAction[i],mainField.queryCommandState(i));
        }

    }
    if(this._free==true) this.setActualValue();
    }
    this._event = null;
}

HTMLArea.prototype.getId = function () {
   var objMe = this;
   return objMe._textAreaObject.id
}
/*
HTMLArea.prototype.setActualValue = function () {
    var objMe =  this;
    objMe._free = false;
    if(objMe._textAreaObject){
        if(objMe._tagName=="DIV") this._textAreaObject.value = this.getValue();
        else this._textAreaObject.value = this.getValue();
    }
    if(isIE) setTimeout(objMe._free = true, 50);
    else setTimeout(function(){objMe._free = true;}, 50);
}
*/

HTMLArea.prototype.setActualValue = function () {
    var objMe =  this;
    objMe._free = false;
    if (objMe._mode == "show") {
        if (objMe._textAreaObject) {
            if (objMe._tagName == "DIV")
                this._textAreaObject.value = this.getValue();
            else
                this._textAreaObject.value = this.getValue();
        }
        try { objMe._free = true; } catch (e) {}
    }
}

HTMLArea.prototype.getValue = function () {
    //return "<html><head><style type='text/css'>p{margin:0px; padding:0px;}</style></head><body>"+this._htmlAreaObject.body.innerHTML+"</body></html>";
    return "<html><body>"+this._htmlAreaObject.body.innerHTML+"</body></html>";
}
HTMLArea.editorCommand = function (editorID,command,event) {
    objMe = HTMLAreaList[editorID];
    var mainField = objMe._htmlArea.contentWindow;
    try {
       var thisCommand = command;
       var thisCommandAction = "";
       if(typeof thisCommand == 'object'){
         var thisCommand = command[0];
         var thisCommandAction = command[1];
        }
        mainField.focus();
        mainField.document.execCommand(thisCommand, false, thisCommandAction);
        mainField.focus();
        if(isSafari)
        if(event){
            event.preventDefault();
            event.returnValue = false;
        }
    } catch (e) {
    }
}
HTMLArea.BR = function (firstNode) {
    var retStr = "\n";
    return retStr;
}
HTMLArea.P = function (firstNode) {
    var retStr = "";
    for (var i=0;i < firstNode.childNodes.length;i++) {
        var cNode = firstNode.childNodes[i];
        retStr = retStr+HTMLArea.parseHelper(cNode);
    }
    return retStr+"\n\r";
}

HTMLArea.OL = function (firstNode) {
    var retStr = "\n";
    var count = 1;
    for (var i=0;i < firstNode.childNodes.length;i++) {
        var cNode = firstNode.childNodes[i];
        if(cNode.tagName=="LI"){
            retStr=retStr+""+count+". "+HTMLArea.htmlToText(cNode)+"\n";
            count++;
        }
    }
    return retStr
}
HTMLArea.UL = function (firstNode) {
    var retStr = "\n";
    for (var i=0;i < firstNode.childNodes.length;i++) {
        var cNode = firstNode.childNodes[i];
        if(cNode.tagName=="LI"){
            retStr=retStr+""+HTMLArea.htmlToText(cNode)+"\n";
        }
    }
    return retStr
}
HTMLArea.parseHelper = function (cNode) {
    var retStr = "";
    var tagName = (""+cNode.tagName).toUpperCase();
    if(tagName=="OL") retStr = retStr+HTMLArea.OL(cNode);
    else if(tagName=="UI") retStr = retStr+HTMLArea.UL(cNode);
    else if(tagName=="BR") retStr = retStr+HTMLArea.BR(cNode);
    else if(tagName=="P") retStr = retStr+HTMLArea.P(cNode);
    else retStr = HTMLArea.htmlToText(cNode);
    if(cNode.nodeValue) retStr = retStr+cNode.nodeValue;
    return retStr;
}
HTMLArea.htmlToText = function (firstNode) {
    var retStr = "";
    for (var i=0;i < firstNode.childNodes.length;i++) {
        var cNode = firstNode.childNodes[i];
        retStr = retStr+HTMLArea.parseHelper(cNode);
    }
    return retStr;
}

HTMLArea.setFont = function (editorID,obj,cmd,evt) {
    try {
        var command = [cmd,"<"+obj.options[obj.selectedIndex].id+">"];
        HTMLArea.editorCommand(editorID,command,evt);
    } catch (e) {        
        alert("setFont"+e);
    }
}
HTMLArea.linkEditor = function (editorID,callback,evt) {
    try {
        uri = prompt("URI","http://www.");
        if(uri){
           var command = ["createlink",uri];
           HTMLArea.editorCommand(editorID,command,evt);
        }
    } catch (e) {        
        alert("linkEditor"+e);
    }
}
HTMLArea.clearLink = function (editorID,callback,evt) {
    try {
        var command = ["unlink",uri];
        HTMLArea.editorCommand(editorID,command,evt);
    } catch (e) {        
        alert("clearLink"+e);
    }
}
var dImportData = "";
HTMLArea.importDocument = function(data) {
    if (dImportData == null) {
        dImportData = document.createElement("DIV");
    }
    if (data) {
        dImportData.innerHTML = data;
        return dImportData.firstChild;
    } else return null;
}

HTMLArea.changeView = function (editorID, mode, callback) {
    try {
        objMe = HTMLAreaList[editorID];
        objMe._mode = mode;
        if (isSafari && mode == "show") {
            objMe._tool.parentNode.removeChild(objMe._tool);
            objMe._textAreaObject.style.display = "none";
            objMe.generate();
        } else {
            var tAView = "";
            var hAView = "none";
            if (mode == "show") {
                tAView = "none";
                hAView = "";
                var nowText = "";
                if (objMe._tagName == "DIV") {
                    nowText = objMe._textAreaObject.innerHTML;
                } else {
                    if (objMe._textAreaObject) {
                        nowText = objMe._textAreaObject.value.replace(/\n+/g, '<br/>').replace(' ', '&nbsp;');
                    }
                }
                var mainContent = HTMLArea.getAreaBody("", objMe);
                //work in both browsers
                objMe._htmlAreaObject.innerHTML = mainContent;
                objMe._htmlAreaObject.body.innerHTML = nowText;
                
            } else {
                var objBody = objMe._htmlAreaObject.body;
                cl = objMe._htmlAreaObject.body.cloneNode(true);
                _area = objMe._textAreaObject;
                setTimeout(function() {
                    pText = HTMLArea.htmlToText(cl);
                    if (_area._tagName == "DIV") 
                        _area.innerHTML = pText;
                    else
                        _area.value = pText;
                }, 10);
            }
            if (!isIE) {
                objMe._textAreaObject.style.display = "none";
                objMe._tool.style.display = "none";
            }
            objMe._textAreaObject.style.display = tAView;
            objMe._tool.style.display = hAView;
            if (mode == "show") {
                if (isIE) {
                    objMe._htmlAreaObject.designMode = "On";
                } else 
                    objMe._htmlAreaObject.designMode = "on";
                if (objMe._toolFix == false) {
                    objMe._tool.style.height = objMe._toolBody.offsetHeight;
                    objMe._toolBody.style.height = objMe._toolBody.offsetHeight - objMe._toolHeader.offsetHeight-4;
                    objMe._toolFix = true;
                }
                try { objMe.setActualValue(); } catch(e) {}
            } else {
            }
        }
        if (mode == "hide" && callback) callback(objMe);
    } catch (e) { alert("changeView.main:"+e); }
}

HTMLArea.updateView = function (editorID) {
    try {
        objMe = HTMLAreaList[editorID];
        objMe._mode = "show";

        var objBody = objMe._htmlAreaObject.body;
        cl = objMe._htmlAreaObject.body.cloneNode(true);
        _area = objMe._textAreaObject;
        /*setTimeout(function() {
            pText = HTMLArea.htmlToText(cl);
            if (_area._tagName == "DIV") 
                _area.innerHTML = pText;
            else
                _area.value = pText;
        }, 10);*/

            var nowText = "";
            if (objMe._tagName == "DIV") {
                nowText = objMe._textAreaObject.innerHTML;
            } else {
                if (objMe._textAreaObject) {
                    nowText = objMe._textAreaObject.value; //.replace(/\n+/g, '<br/>').replace(' ', '&nbsp;');
                }
            }
            //alert('1:' + nowText);
            var mainContent = HTMLArea.getAreaBody("", objMe);
            //alert('2:' + mainContent);
            //work in both browsers
            objMe._htmlAreaObject.innerHTML = mainContent;
            objMe._htmlAreaObject.body.innerHTML = nowText;
      
            //pText = HTMLArea.htmlToText(cl);
            //alert('3:' + pText);
            if (_area._tagName == "DIV") 
                _area.innerHTML = nowText;
            else
                _area.value = nowText;
            //try { objMe.setActualValue(); } catch(e) {}
    } catch (e) { alert("updateView.main:"+e); }
}

HTMLArea.prototype.selectNodeContents = function(node, pos) {
    var range;
    var collapsed = (typeof pos != "undefined");
    if (HTMLArea.is_ie) {
        range = this._doc.body.createTextRange();
        range.moveToElementText(node);
        (collapsed) && range.collapse(pos);
        range.select();
    } else {
        var sel = this._getSelection();
        range = this._doc.createRange();
        range.selectNodeContents(node);
        (collapsed) && range.collapse(pos);
        sel.removeAllRanges();
        sel.addRange(range);
    }
};


/**/
HTMLArea.areaControl = function (obj, id) {
    if (!obj || obj.tagName != "INPUT" || obj.type != "checkbox" || !obj.checked) 
        HTMLArea.changeView(id + "_SHADOW", "hide");
    else 
        HTMLArea.changeView(id + "_SHADOW", "show");
    if (HTMLAreaList[id + "_SHADOW"])
        HTMLAreaList[id + "_SHADOW"]._externalControll = obj;
}
