/*

Textarea JavaScript HTML plugin
Version 0.1
Copyright (C) 2008 Greg Methvin (greg@methvin.net)
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

* Redistributions of source code must retain the above copyright
  notice, this list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright
  notice, this list of conditions and the following disclaimer in the
  documentation and/or other materials provided with the distribution.

* The name of the author may not be used to endorse or promote
  products derived from this software without specific prior written
  permission

THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

var CLASSNAME = "textarea";

// replace all textareas with the classname with the special textarea
window.onload = function() {
    var tas = document.getElementsByTagName("textarea");
    for (var i = 0; ta = tas[i]; i++)
        if (ta.className &&
            ta.className.match(new RegExp("\\b" + CLASSNAME + "\\b")))
            buttonizeTextarea(ta);
}

// add buttons to the textarea
function buttonizeTextarea(el) {
    var b = tagButton; // use a shorter name
    // create an array of buttons to insert
    var buttons = [

        b(el, "<strong>strong</strong>", "<strong>/strong</strong>", "<strong>", "</strong>"),

        b(el, "<em>em</em>", "<em>/em</em>", "<em>", "</em>"),

        b(el, "<code>code</code>", "<code>/code</code>", "<code>", "</code>"),

        b(el, "link", "/link", function () {
            var href = prompt("Enter the URL","http://www.google.com/");
            return "<a" + (href? " href=\"" + esc(href) + "\"" : "") + ">";
        }, "</a>"),

        b(el, "blockquote", "/blockquote", "<blockquote>", "</blockquote>"),

        b(el, "img", null, function () {
            var src = prompt("Enter the image source URL","http://www.google.com/");
            return "<img" + (src? " src=\"" + esc(src) + "\"" : "") + ">";
        }, null),

        function() {
            // I know I'm just creating this function to run once;
            // it's easier this way.
            var but = document.createElement("button");
            but.setAttribute("type","button");
            but.onclick = function () { closeTags(el); };
            but.innerHTML = "Close Tags";
            return but;
        } ()
        
    ];

    // insert the buttons into a container element
    var buttonel = document.createElement("div");
    for (var i = 0; i < buttons.length; i++)
        buttonel.appendChild(buttons[i]);
    
    // finally, insert the div before the text area element
    el.parentNode.insertBefore(buttonel, el);
}

// function for escaping html entities
function esc(s) {                                       
    return s.replace(/&/g,'&amp;')
    .replace(/>/g,'&gt;')
    .replace(/</g,'&lt;')
    .replace(/\"/g,'&quot;')
    .replace(/\'/g,'&apos;');                 
}

// lists of buttons for closing tags
var closebuttons = [];

// This function creates a button to insert tag(s); startCaption and
// endCaption MUST be strings or null; startTag and endTag can be
// either strings or functions that return strings. endCaption and
// endTag can be null if the tag has no end tag.
function tagButton(textarea,
                   startCaption, endCaption,
                   startTag, endTag) {
    var button = document.createElement("button");

    // make functions to print out tags
    var sf = typeof startTag != "function" && startTag != null ?
        function() { return startTag; } : startTag; 
    var ef = typeof endTag != "function" && endTag != null ?
        function() { return endTag; } : endTag;    

    // set initial caption and set an onclick function
    button.innerHTML = startCaption;

    button.onclick = function() {
        insertAtCursor(textarea, sf());
        if (!ef)
            return;
        // keep track of the tag close functions
        closebuttons.unshift(button);
        var start = arguments.callee;
        button.innerHTML = endCaption;
        button.onclick = function() {
            insertAtCursor(textarea, ef());
            button.onclick = start;
            button.innerHTML = startCaption;
            // remove the button from the close functions
            for(var i = 0; i < closebuttons.length; i++)
                if(button == closebuttons[i]) {
                    closebuttons.splice(i, 1);
                    return;
                }
        };
    };
    // use this to tell what textarea the button's click affects; if
    // there is more than one on a page, this allows us to close just
    // the tags for a specific textarea using closeTags
    button.textarea = textarea;

    button.setAttribute("type","button");

    return button;
}

// close all the tags
function closeTags(textarea) {
    for(var i = 0; i < closebuttons.length; i++)
        if(closebuttons[i].textarea == textarea)
            closebuttons[i--].onclick();
}

// insert text at the cursor
function insertAtCursor(el, text) {
    var start = null;
    if(document.selection) {
        el.focus();
        var orig = el.value.replace(/\r\n/g, "\n");
        var range = document.selection.createRange();

        if(range.parentElement() != el)
            return false;
        range.text = text;
			
        var actual = tmp = el.value.replace(/\r\n/g, "\n");

        for(var diff = 0; diff < orig.length; diff++)
            if(orig.charAt(diff) != actual.charAt(diff))
                break;

        for(var i = 0, start = 0; 
            tmp.match(text) 
                && (tmp = tmp.replace(text, "")) 
                && i <= diff; 
            i = start + text.length)
            start = actual.indexOf(text, i);
    } else if(el.selectionStart) {
        start = el.selectionStart;
        end = el.selectionEnd;

        el.value = el.value.substr(0, start)
            + text
            + el.value.substr(end, el.value.length);
    }
		
    if(start != null)
        setCursor(el, start + text.length);
    else
        el.value += text;
}

// set the cursor position
function setCursor(el, pos) {
    if(el.createTextRange) {
        var range = el.createTextRange();
        range.move('character', pos);
        range.select();
    } else if(el.selectionStart) {
        el.focus();
        el.setSelectionRange(pos, pos);
    }
}
