// +----------------------------------------------------------------+
// | SimpleTextEditor 1.0                                           |
// | Author: Cezary Tomczak [www.gosu.pl]                           |
// | Free for any use as long as all copyright messages are intact. |
// +----------------------------------------------------------------+

function SimpleTextEditor(id, objectId) {
    if (!id || !objectId) { alert("SimpleTextEditor.constructor(id, objectId) failed, two arguments are required"); }
    var self = this;
    this.id = id;
    this.objectId = objectId;
    this.frame;
    this.viewSource = false;
    
    this.path = ""; // with slash at the end
    this.cssFile = "";
    this.charset = "iso-8859-1";

    this.editorHtml = "";
    this.frameHtml = "";

    this.textareaValue = "";

    this.browser = {
        "ie": Boolean(document.body.currentStyle),
        "gecko" : (navigator.userAgent.toLowerCase().indexOf("gecko") != -1)
    };

    this.init = function() {
        if (document.getElementById && document.createElement && document.designMode && (this.browser.ie || this.browser.gecko)) {
            // EDITOR
            if (!document.getElementById(this.id)) { alert("SimpleTextEditor "+this.objectId+".init() failed, element '"+this.id+"' does not exist"); return; }
            this.textareaValue = document.getElementById(this.id).value;
            var ste = document.createElement("div");
            document.getElementById(this.id).parentNode.replaceChild(ste, document.getElementById(this.id));
            ste.id = this.id+"-ste";
            ste.innerHTML = this.editorHtml ? this.editorHtml : this.getEditorHtml();
            // BUTTONS
            var buttons = ste.getElementsByTagName("td");
            for (var i = 0; i < buttons.length; ++i) {
                if (buttons[i].className == "button") {
                    buttons[i].id = this.id+'-button-'+i;
                    buttons[i].onmouseover = function() { this.className = "button-hover"; }
                    buttons[i].onmouseout = function() { this.className = this.className.replace(/button-hover(\s)?/, "button"); }
                    buttons[i].onclick = function(id) { return function() { this.className = "button-hover button-click"; setTimeout(function(){ document.getElementById(id).className = document.getElementById(id).className.replace(/(\s)?button-click/, ""); }, 100); } }(buttons[i].id);
                }
            }
            // FRAME
            if (this.browser.ie) {
                this.frame = frames[this.id+"-frame"];
            } else if (this.browser.gecko) {
                this.frame = document.getElementById(this.id+"-frame").contentWindow;
            }
            this.frame.document.designMode = "on";
            this.frame.document.open();
            this.frame.document.write(this.frameHtml ? this.frameHtml : this.getFrameHtml());
            this.frame.document.close();
            insertHtmlFromTextarea();
        }
    };

    function lockUrls(s) {
        if (self.browser.gecko) { return s; }
        return s.replace(/href=["']([^"']*)["']/g, 'href="simpletexteditor://simpletexteditor/$1"');
    }

    function unlockUrls(s) {
        if (self.browser.gecko) { return s; }
        return s.replace(/href=["']simpletexteditor:\/\/simpletexteditor\/([^"']*)["']/g, 'href="$1"');
    }

    function insertHtmlFromTextarea() {
        try { self.frame.document.body.innerHTML = lockUrls(self.textareaValue); } catch (e) { setTimeout(insertHtmlFromTextarea, 10); }
    }

    this.getEditorHtml = function() {
        var html = "";
        html += '<input type="hidden" id="'+this.id+'" name="'+this.id+'" value="">';
        html += '<table class="ste" cellspacing="0" cellpadding="0">';
        html += '<tr><td class="bar"><table id="'+this.id+'-buttons" cellspacing="0" cellpadding="0"><tr>';
        html += '<td><select onchange="'+this.objectId+'.exeCommand(\'\', this.value);this.selectedIndex=0;"><option value=""></option><option value="h1">Heading 1</option><option value="h2">Heading 2</option><option value="h3">Heading 3</option><option value="p">Paragraph</option><option value="pre">Preformatted</option></select></td>';
        html += '<td><div class="separator"></div></td>';
        html += '<td class="button"><img src="'+this.path+'images/bold.gif" width="20" height="20" alt="Bold" title="Bold" onclick="'+this.objectId+'.exeCommand(\'b\')"></td>';
        html += '<td class="button"><img src="'+this.path+'images/italic.gif" width="20" height="20" alt="Italic" title="Italic" onclick="'+this.objectId+'.exeCommand(\'i\')"></td>';
        html += '<td class="button"><img src="'+this.path+'images/underline.gif" width="20" height="20" alt="Underline" title="Underline" onclick="'+this.objectId+'.exeCommand(\'u\')"></td>';
        html += '<td><div class="separator"></div></td>';
        html += '</tr><tr><td class="button"><img src="'+this.path+'images/left.gif" width="20" height="20" alt="Align Left" title="Align Left" onclick="'+this.objectId+'.exeCommand(\'jleft\')"></td>';
        html += '<td class="button"><img src="'+this.path+'images/center.gif" width="20" height="20" alt="Center" title="Center" onclick="'+this.objectId+'.exeCommand(\'jcenter\')"></td>';
        html += '<td class="button"><img src="'+this.path+'images/right.gif" width="20" height="20" alt="Align Right" title="Align Right" onclick="'+this.objectId+'.exeCommand(\'jright\')"></td>';
        html += '<td><div class="separator"></div></td>';
        html += '<td class="button"><img src="'+this.path+'images/indent.gif" width="20" height="20" alt="Indent" title="Indent" onclick="'+this.objectId+'.exeCommand(\'tab\')"></td>';
        html += '<td><div class="separator"></div></td>';
        html += '<td class="button"><img src="'+this.path+'images/link.gif" width="20" height="20" alt="Insert Link" title="Insert Link" onclick="'+this.objectId+'.exeCommand(\'url\')"></td>';
        html += '<td class="button"><img src="'+this.path+'images/link_a.gif" width="20" height="20" alt="Insert Link with anhor" title="Insert Link with anhor" onclick="'+this.objectId+'.exeCommand(\'url_a\')"></td>';
        html += '<td class="button"><img src="'+this.path+'images/image.gif" width="20" height="20" alt="Insert Image" title="Insert Image" onclick="'+this.objectId+'.exeCommand(\'img\')"></td>';
        html += '<td><div class="separator"></div></td>';
        html += '<td class="button"><img src="'+this.path+'images/table.gif" width="20" height="20" alt="Insert Main Table Tag" title="Insert Main Table Tag" onclick="'+this.objectId+'.exeCommand(\'table\')"></td>';
        html += '<td class="button"><img src="'+this.path+'images/tr.gif" width="20" height="20" alt="Insert TR Tag" title="Insert TR Tag" onclick="'+this.objectId+'.exeCommand(\'tr\')"></td>';
        html += '<td class="button"><img src="'+this.path+'images/td.gif" width="20" height="20" alt="Insert TD Tag" title="Insert TD Tag" onclick="'+this.objectId+'.exeCommand(\'td\')"></td>';
        html += '</tr></table></td></tr>';
        html += '<tr><td class="frame"><iframe id="'+this.id+'-frame" frameborder="0"></iframe></td></tr>';
        html += '</table>';
        return html;
    };

    this.getFrameHtml = function() {
        var html = "";
        html += '<style type="text/css">pre { background-color: #eeeeee; padding: 0.75em 1.5em; border: 1px solid #dddddd; }</style>';
        if (this.cssFile) { html += '<link rel="stylesheet" type="text/css" href="'+this.cssFile+'">'; }
        html += '<style type="text/css">html,body { cursor: text; } body { margin: 0.5em; padding: 0; }</style>';
        return html;
    };

    this.openWindow = function(url, width, height) {
        var x = (screen.width/2-width/2);
        var y = (screen.height/2-height/2);
        window.open(url, "", "scrollbars=yes,width="+width+",height="+height+",screenX="+(x)+",screenY="+y+",left="+x+",top="+y);
    };

    

    this.exeCommand = function(cmd, value) {
        	
            this.frame.focus();
            var b=getSel();
            if (typeof value == "undefined") value="";
            if (cmd=="tab") document.selection.createRange().text =  '[' + cmd + value + ']' + b;
            else if (cmd=="url_a") document.selection.createRange().text =  '[url=' + value + ']' + b + '[/url' + value + ']';
            else document.selection.createRange().text =  '[' + cmd + value + ']' + b + '[/' + cmd + value + ']';
             this.frame.focus();
            //this.textareaValue = this.getContent();
            //if (typeof value == "undefined") value=""; 
            //this.textareaValue=this.textareaValue+cmd+value;
            ////this.frame.value=this.textareaValue;
            //insertHtmlFromTextarea();
            ////this.frame.focus();
    };

    this.isOn = function() {
        return Boolean(this.frame);
    };

    this.getContent = function() {
        try { return unlockUrls(this.frame.document.body.innerHTML); } catch(e) { alert("SimpleTextEditor "+this.objectId+".getContent() failed"); }
    };

    this.submit = function() {
        if (this.isOn()) {
            if (this.viewSource) { this.toggleSource(); }
            document.getElementById(this.id).value = this.getContent();
        }
    };
}

function getSel() {
    if (window.getSelection)
       return window.getSelection();
    else if (document.selection)
       return document.selection.createRange().text;
    else if (document.getSelection)
       return document.getSelection();
    else return '';
}

