var IframeWidth="630px";
var IframeHeight="90px";

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();
            //ste.onkeypress = changeVal(this);
            // 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.OpenSmilePopup = function()
    {
        //window.open('popups/smiles.html', 'popup', 'location=0,status=0,scrollbars=0,width=210,height=390,top=300,left=500').focus();
        document.getElementById("smilediv").style.display='block';
    }
    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"><div style="height:20px;"><table id="'+this.id+'-buttons" cellspacing="0" cellpadding="0" style="position:absolute; top:-3px; left:15px;"><tr>';
        html += '<td><a class="bold" alt="Bold" title="Bold" onclick="'+this.objectId+'.execCommand(\'bold\')" > </a> </td>';
        html += '<td><a class="italics" alt="Italic" title="Italic" onclick="'+this.objectId+'.execCommand(\'italic\')"></a></td>';        
        html += '<td><a class="underline" alt="Underline" title="Underline" onclick="'+this.objectId+'.execCommand(\'underline\')"></a></td>';                
        html += '<td><div class="separator"></div></td>';        
        html += '<td><a class="jleft" alt="Justify Left" title="Justify Left" onclick="'+this.objectId+'.execCommand(\'justifyleft\')"></a></td>';                        
        html += '<td><a class="jcenter" alt="Justify Center" title="Justify Center" onclick="'+this.objectId+'.execCommand(\'justifycenter\')"></a></td>';                                
        html += '<td><a class="jright" alt="Justify Right" title="Justify Right" onclick="'+this.objectId+'.execCommand(\'justifyright\')"></a></td>';                                        
        html += '<td><div class="separator"></div></td>';        
        html += '<td><a class="bulletN" alt="Bullet Numbers" title="Bullet Numbers" onclick="'+this.objectId+'.execCommand(\'insertorderedlist\')"></a></td>';                                                
        html += '<td><a class="bulletD" alt="Bullet Dotted" title="Bullet Dotted" onclick="'+this.objectId+'.execCommand(\'insertunorderedlist\')"></a></td>';                                                        
        html += '<td><div class="separator"></div></td>';                        
        html += '<td><a class="link" alt="Hyperlink" title="Hyperlink" onclick="'+this.objectId+'.execCommand(\'createlink\')"></a></td>';                                                                                
        html += '<td><a class="img" alt="Insert Image" title="Insert Image" onclick="'+this.objectId+'.execCommand(\'insertimage\')"></a></td>';                                 
        html += '<td><div class="separator"></div></td>';        
        html += '<td><a href="#Comment" class="paste" alt="Paste Selected Text" title="Paste Selected Text" onclick="'+this.objectId+'.PasteHTML()"></span></td>'; 
        html += '<td><a class="smile" alt="Smiles" title="Smiles" onclick="'+this.objectId+'.OpenSmilePopup()"></a></td>';                                 
        html += '</tr></table></div></td></tr>';
        html += '<tr><td class="frame" id="IframeTD"><iframe style="width:+'+IframeWidth+'; height:'+IframeHeight+';" id="'+this.id+'-frame" frameborder="0"></iframe></td></tr>';
        html += '</table>';
        return html;
    };


    this.getFrameHtml = function() {
        var html = "";
        html += '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">';
        html += '<html><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();
        }
    };
    
    this.InsertHTML = function(Html)
    {
        self.frame.document.body.innerHTML+=Html;
    }                          
            
    this.PasteHTML = function()
    {
        self.frame.document.body.innerHTML+=getSelText();
    }                                             
    
    function getSel()
    {
        var w=window,d=document,gS='getSelection';
        return (''+(w[gS]?w[gS]():d[gS]?d[gS]():d.selection.createRange().text)).replace(/(^\s+|\s+$)/g,'');
    }
    
    function getSelText()
    {
        var txt = '';
        if (window.getSelection)
        {
            txt = window.getSelection();
        }
        else if (document.getSelection)
        {
            txt = document.getSelection();
        }
        else if (document.selection)
        {
            txt = document.selection.createRange().text;
        }
        else return;
        
        return txt;
    }
}


function SetWysiwygValue()
{
    try{document.getElementById("ctl00_ContentPlaceHolder1_TextBox2").innerHTML = ste.frame.document.body.innerHTML;}
    catch(ex){}
    try{document.getElementById("ctl00_ContentPlaceHolder1_TextBox2").innerText = ste.frame.document.body.innerHTML;}
    catch(ex){}
    try{document.getElementById("ctl00_ContentPlaceHolder1_TextBox2").value = ste.frame.document.body.innerHTML;}
    catch(ex){}
}


function SetReply(ID)
{            
        
    var Comment;    
    try
    {
        var CommentDiv = document.getElementById("CommentDiv_"+ID);    
        var Clone = document.createElement("div");
        Clone.innerHTML = CommentDiv.innerHTML;                
                                
        for(var i=0; i<Clone.childNodes.length; i++)
        {
            try
            {                
                if (Clone.childNodes[i].tagName=="DIV")
                {
                    Clone.removeChild(Clone.childNodes[i]);
                }                                
            }
            catch(ex){}
        }
        
        var Text = ltrim(Clone.innerHTML);
        
        while(Text.indexOf("<p>")>-1 || Text.indexOf("<P>")>-1)
        {
            Text = Text.replace("<p>", "").replace("</p>", "<br>").replace("<P>", "").replace("</P>", "<br>");    
        }
        
        while(Text.indexOf("<BR>")==0)
        {
            Text = Text.substring(4,Text.length);
            Text = ltrim(Text);
        }
        
        while(Text.indexOf("<br>")==0)
        {
            Text = Text.substring(4,Text.length);
            Text = ltrim(Text);
        }
                        
        Text = TrimStringRight(Text,"<BR/>");
        Text = TrimStringRight(Text,"<br/>");
        Text = TrimStringRight(Text,"<BR>");  
        Text = TrimStringRight(Text,"<br>");                                                  
        Comment = rtrim(Text);                  
    }
    catch(ex)
    {
        alert(ex);
    }
          
    
    
    
    var Quote = "[Quote]"+Comment+"[/Quote]";    
    ste.InsertHTML(Quote);  
    if (window.location.toString().indexOf("#Comment")==-1)
    {
        window.location = window.location.toString() + "#Comment";
    }
    else
    {
        window.location = window.location.toString();
    }
 
}

function ltrim(stringToTrim) 
{
	return stringToTrim.replace(/^\s+/,"");
}
function rtrim(stringToTrim) 
{
	return stringToTrim.replace(/\s+$/,"");
}

function TrimStringRight(str,trimStr)
{    
    while(str.lastIndexOf(trimStr)==str.length-trimStr.length)
    {
        str = Text.substring(0,str.length-trimStr.length);
        str = ltrim(str);
    }
    
    if (trimStr!="&nbsp;")
    {
        str=TrimStringRight(str,"&nbsp;");
    }
    
    return str;
}