//
// $Id: Textarea.js,v 1.2 2010/07/10 16:47:59 steve Exp $
//
var Textarea = function() {

    this.bold = function(elem) {

        var self = this

        self.insertAtCaret(elem, '', 'bold')
    }

    this.italic = function(elem) {

        var self = this

        self.insertAtCaret(elem, '', 'italic')
    }

    this.underline = function(elem) {

        var self = this

        self.insertAtCaret(elem, '', 'underline')
    }

    this.insertAtCaret = function(elem, myValue, type) {
    
        var self = this
				
        return $(elem).each(
            function(){
           
                //IE support
                //
                if (document.selection) {
                    this.focus()
                    sel = document.selection.createRange()
                    if (! myValue) {
                        myValue = sel.text
                    }
                    myValue = self.getTypedString(myValue, type) 
                    sel.text = myValue
                    this.focus()

                //MOZILLA/NETSCAPE support
                //
                } else if (this.selectionStart || this.selectionStart == '0') {
                    var startPos = this.selectionStart
                    var endPos = this.selectionEnd
                    var scrollTop = this.scrollTop
                    if (! myValue) {
                        myValue = this.value.substring(startPos, endPos)
                    }
                    myValue = self.getTypedString(myValue, type) 
                    this.value = this.value.substring(0, startPos)
                               + myValue
                               + this.value.substring(endPos, this.value.length)
                    this.focus()
                    this.selectionStart = startPos + myValue.length
                    this.selectionEnd = startPos + myValue.length
                    this.scrollTop = scrollTop
                } else {
                    this.value += myValue
                    this.focus()
                }
            })
    }

    this.getTypedString = function(str, type) {

        switch(type) {
            case 'bold':
                return '<b>' + str + '</b>'
                break
            case 'italic':
                return '<i>' + str + '</i>'
                break
            case 'underline':
                return '<u>' + str + '</u>'
                break
            default:
                return str
                break
        }
    }

    this.insertList = function(elem, type) {

        var self = this

        if (type == 'Plain') {
            listString = 'List'
        } else {
            listString = 'OList'
        }
        self.insertAtCaret(elem, "\n[" + listString + "]\n\n[End" + listString + "]")        
    }
}
