// +----------------------------------------------------------------+
// | SimpleTextEditor 1.0                                           |
// | Author: Cezary Tomczak [www.gosu.pl]                           |
// | Free for any use as long as all copyright messages are intact. |
// +----------------------------------------------------------------+

function close_pallet(){
	document.getElementById('pallet').style.display = 'none';
}
function show_pallet(){
	document.getElementById('pallet').style.display = 'block';
}

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-2";

    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 += '<div class="pallet" id="pallet">';
				html += '<table class="pallet_table">';
				html += '<tr><td style="background:#000;" onclick="'+this.objectId+'.execCommand(\'forecolor\',\'#000\');close_pallet();"></td><td style="background:#930;" onclick="'+this.objectId+'.execCommand(\'forecolor\',\'#930\');close_pallet();"></td><td style="background:#330;" onclick="'+this.objectId+'.execCommand(\'forecolor\',\'#330\');close_pallet();close_pallet();"></td><td style="background:#030;" onclick="'+this.objectId+'.execCommand(\'forecolor\',\'#030\');close_pallet();"></td><td style="background:#036;" onclick="'+this.objectId+'.execCommand(\'forecolor\',\'#036\');close_pallet();"></td><td style="background:#008;" onclick="'+this.objectId+'.execCommand(\'forecolor\',\'#008\');close_pallet();"></td><td style="background:#339;" onclick="'+this.objectId+'.execCommand(\'forecolor\',\'#339\');close_pallet();"></td><td style="background:#333;" onclick="'+this.objectId+'.execCommand(\'forecolor\',\'#333\');close_pallet();"></td></tr>';
				html += '<tr><td style="background:#800;" onclick="'+this.objectId+'.execCommand(\'forecolor\',\'#800\');close_pallet();"></td><td style="background:#f60;" onclick="'+this.objectId+'.execCommand(\'forecolor\',\'#f60\');close_pallet();"></td><td style="background:#880;" onclick="'+this.objectId+'.execCommand(\'forecolor\',\'#880\');close_pallet();close_pallet();"></td><td style="background:#080;" onclick="'+this.objectId+'.execCommand(\'forecolor\',\'#080\');close_pallet();"></td><td style="background:#088;" onclick="'+this.objectId+'.execCommand(\'forecolor\',\'#088\');close_pallet();"></td><td style="background:#28f;" onclick="'+this.objectId+'.execCommand(\'forecolor\',\'#28f\');close_pallet();"></td><td style="background:#669;" onclick="'+this.objectId+'.execCommand(\'forecolor\',\'#669\');close_pallet();"></td><td style="background:#888;" onclick="'+this.objectId+'.execCommand(\'forecolor\',\'#888\');close_pallet();"></td></tr>';
				html += '<tr><td style="background:#f00;" onclick="'+this.objectId+'.execCommand(\'forecolor\',\'#f00\');close_pallet();"></td><td style="background:#f90;" onclick="'+this.objectId+'.execCommand(\'forecolor\',\'#f90\');close_pallet();"></td><td style="background:#9c0;" onclick="'+this.objectId+'.execCommand(\'forecolor\',\'#9c0\');close_pallet();close_pallet();"></td><td style="background:#396;" onclick="'+this.objectId+'.execCommand(\'forecolor\',\'#396\');close_pallet();"></td><td style="background:#3cc;" onclick="'+this.objectId+'.execCommand(\'forecolor\',\'#3cc\');close_pallet();"></td><td style="background:#36f;" onclick="'+this.objectId+'.execCommand(\'forecolor\',\'#36f\');close_pallet();"></td><td style="background:#808;" onclick="'+this.objectId+'.execCommand(\'forecolor\',\'#808\');close_pallet();"></td><td style="background:#999;" onclick="'+this.objectId+'.execCommand(\'forecolor\',\'#999\');close_pallet();"></td></tr>';
				html += '<tr><td style="background:#f0f;" onclick="'+this.objectId+'.execCommand(\'forecolor\',\'#f0f\');close_pallet();"></td><td style="background:#fc0;" onclick="'+this.objectId+'.execCommand(\'forecolor\',\'#fc0\');close_pallet();"></td><td style="background:#ff0;" onclick="'+this.objectId+'.execCommand(\'forecolor\',\'#ff0\');close_pallet();close_pallet();"></td><td style="background:#0f0;" onclick="'+this.objectId+'.execCommand(\'forecolor\',\'#0f0\');close_pallet();"></td><td style="background:#0ff;" onclick="'+this.objectId+'.execCommand(\'forecolor\',\'#0ff\');close_pallet();"></td><td style="background:#0cf;" onclick="'+this.objectId+'.execCommand(\'forecolor\',\'#0cf\');close_pallet();"></td><td style="background:#936;" onclick="'+this.objectId+'.execCommand(\'forecolor\',\'#936\');close_pallet();"></td><td style="background:#ccc;" onclick="'+this.objectId+'.execCommand(\'forecolor\',\'#ccc\');close_pallet();"></td></tr>';
				html += '<tr><td style="background:#f9c;" onclick="'+this.objectId+'.execCommand(\'forecolor\',\'#f9c\');close_pallet();"></td><td style="background:#fc9;" onclick="'+this.objectId+'.execCommand(\'forecolor\',\'#fc9\');close_pallet();"></td><td style="background:#ff9;" onclick="'+this.objectId+'.execCommand(\'forecolor\',\'#ff9\');close_pallet();close_pallet();"></td><td style="background:#cfc;" onclick="'+this.objectId+'.execCommand(\'forecolor\',\'#cfc\');close_pallet();"></td><td style="background:#cff;" onclick="'+this.objectId+'.execCommand(\'forecolor\',\'#cff\');close_pallet();"></td><td style="background:#9cf;" onclick="'+this.objectId+'.execCommand(\'forecolor\',\'#9cf\');close_pallet();"></td><td style="background:#c9f;" onclick="'+this.objectId+'.execCommand(\'forecolor\',\'#c9f\');close_pallet();"></td><td style="background:#fff;" onclick="'+this.objectId+'.execCommand(\'forecolor\',\'#fff\');close_pallet();"></td></tr>';
				html += '</table>';
				html += '<p><a href="javascript:close_pallet(\'.$i.\')">zamknij</a></p></div>';
        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+'.execCommand(\'fontName\', this.value);this.selectedIndex=0;"><option value="">font</option><option value="Arial">arial</option><option value="Verdana">verdana</option><option value="Times">times</option><option value="Trebuchet MS">trebuchet</option><option value="Courier">courier</option><option value="Georgia">georgia</option></select></td>';
        html += '<td><div class="separator"></div></td>';
        html += '<td><select onchange="'+this.objectId+'.execCommand(\'fontsize\', this.value);this.selectedIndex=0;"><option value="">size</option><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><!--<option value="<pre>">Preformatted</option>--></select></td>';
        html += '<td><div class="separator"></div></td>';
        html += '<td class="button"><img src="'+this.path+'http://wiecejklientow.com/inc/gfx/ste/bold.gif" width="20" height="20" alt="Bold" title="bold" onclick="'+this.objectId+'.execCommand(\'bold\')"></td>';
        html += '<td class="button"><img src="'+this.path+'http://wiecejklientow.com/inc/gfx/ste/italic.gif" width="20" height="20" alt="Italic" title="italic" onclick="'+this.objectId+'.execCommand(\'italic\')"></td>';
        html += '<td class="button"><img src="'+this.path+'http://wiecejklientow.com/inc/gfx/ste/underline.gif" width="20" height="20" alt="Underline" title="underline" onclick="'+this.objectId+'.execCommand(\'underline\')"></td>';
        html += '<td><div class="separator"></div></td>';
        html += '<td class="button"><img src="'+this.path+'http://wiecejklientow.com/inc/gfx/ste/left.gif" width="20" height="20" alt="Align Left" title="left" onclick="'+this.objectId+'.execCommand(\'justifyleft\')"></td>';
        html += '<td class="button"><img src="'+this.path+'http://wiecejklientow.com/inc/gfx/ste/center.gif" width="20" height="20" alt="Center" title="center" onclick="'+this.objectId+'.execCommand(\'justifycenter\')"></td>';
        html += '<td class="button"><img src="'+this.path+'http://wiecejklientow.com/inc/gfx/ste/right.gif" width="20" height="20" alt="Align Right" title="right" onclick="'+this.objectId+'.execCommand(\'justifyright\')"></td>';
        html += '<td><div class="separator"></div></td>';
        html += '<td class="button"><img src="'+this.path+'http://wiecejklientow.com/inc/gfx/ste/ol.gif" width="20" height="20" alt="Ordered List" title="list" onclick="'+this.objectId+'.execCommand(\'insertorderedlist\')"></td>';
        html += '<td><div class="separator"></div></td>';
        html += '<td class="button"><img src="'+this.path+'http://wiecejklientow.com/inc/gfx/ste/h1.gif" width="20" height="20" alt="H1" title="H1" onclick="'+this.objectId+'.execCommand(\'formatblock\', \'<h1>\')"></td>';
        html += '<td><div class="separator"></div></td>';
        html += '<td class="button"><img src="'+this.path+'http://wiecejklientow.com/inc/gfx/ste/colors.gif" width="20" height="20" alt="Colors" title="list" onclick="javascript:show_pallet();" /></td>';
        html += '<td><div class="separator"></div></td>';
        html += '<td class="button"><img src="'+this.path+'http://wiecejklientow.com/inc/gfx/ste/link.gif" width="20" height="20" alt="Insert Link" title="link" onclick="'+this.objectId+'.execCommand(\'createlink\')"></td>';
        html += '<td class="button"><img src="'+this.path+'http://wiecejklientow.com/inc/gfx/ste/image.gif" width="20" height="20" alt="Insert Image" title="picture" onclick="'+this.objectId+'.execCommand(\'insertimage\')"></td>';
        html += '<td><div class="separator"></div></td>';
        html += '<td class="button"><img src="'+this.path+'http://wiecejklientow.com/inc/gfx/ste/help.gif" width="20" height="20" alt="Help" title="help" onclick="'+this.objectId+'.openWindow(\''+this.path+'http://wiecejklientow.com/inc/steh.html\', \'300\', \'450\')"></td>';
        html += '</tr></table></td></tr>';
        html += '<tr><td class="frame"><iframe id="'+this.id+'-frame" frameborder="0"></iframe></td></tr>';
        html += '<tr><td class="source"><span id="'+this.id+'-viewSource" onclick="'+this.objectId+'.toggleSource()"><a href="#">[Edit in HTML code]</a></span></td></tr>';
        html += '</table>';
        return html;
    };

    this.getFrameHtml = function() {
        var html = "";
        html += '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">';
        html += '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="pl"><head>';
        html += '<meta http-equiv="Content-Type" content="text/html; charset='+this.charset+'">';
        html += '<title>SimpleTextEditor frame</title>';
        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>';
        html += '</head><body></body></html>';
        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.toggleSource = function() {
        var html, text;
        if (this.browser.ie) {
            if (!this.viewSource) {
                html = this.frame.document.body.innerHTML;
                this.frame.document.body.innerText = unlockUrls(html);
                document.getElementById(this.id+"-buttons").style.visibility = "hidden";
                this.viewSource = true;
            } else {
                text = this.frame.document.body.innerText;
                this.frame.document.body.innerHTML = lockUrls(text);
                document.getElementById(this.id+"-buttons").style.visibility = "visible";
                this.viewSource = false;
            }
        } else if (this.browser.gecko) {
            if (!this.viewSource) {
                html = document.createTextNode(this.frame.document.body.innerHTML);
                this.frame.document.body.innerHTML = "";
                this.frame.document.body.appendChild(html);
                document.getElementById(this.id+"-buttons").style.visibility = "hidden";
                this.viewSource = true;
            } else {
                html = this.frame.document.body.ownerDocument.createRange();
                html.selectNodeContents(this.frame.document.body);
                this.frame.document.body.innerHTML = html.toString();
                document.getElementById(this.id+"-buttons").style.visibility = "visible";
                this.viewSource = false;
            }
        }
        document.getElementById(this.id+"-viewSource").checked = this.viewSource ? "checked" : "";
        document.getElementById(this.id+"-viewSource").blur();
    };

    this.execCommand = function(cmd, value) {
        if (cmd == "createlink" && !value) {
            var url = prompt("Enter URL:", "");
            if (url) {
                this.frame.focus();
                this.frame.document.execCommand("unlink", false, null);
                if (this.browser.ie) this.frame.document.execCommand(cmd, false, "simpletexteditor://simpletexteditor/"+url);
                else if (this.browser.gecko) this.frame.document.execCommand(cmd, false, url);
                this.frame.focus();
            }
        } else if (cmd == "insertimage" && !value) {
            var imageUrl = prompt("Enter Image URL:", "");
            if (imageUrl) {
                this.frame.focus();
                this.frame.document.execCommand(cmd, false, imageUrl);
                this.frame.focus();
            }
        } else {
            this.frame.focus();
            this.frame.document.execCommand(cmd, false, value);
            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();
        }
    };
}
