var UBBEditor = function (field_id)
{
    // UBB Editor
    this.__init(field_id);
};

UBBEditor.prototype = 
{
    /*
        Properties
    */
    'id' : '',
    'resource' : null,

    /*
        Init function to detect resource
    */
    '__init' : function(f_id)
    {
        if(document.getElementById)
        {
            try
            {
                this.id = f_id;
                this.resource = document.getElementById(f_id);
            }
            catch(e0)
            {
                this.resource = null;
            }
        }

        if(this.resource == null)
        {
            alert('The UBBEditor is not supported by your browser.');
        }
    },

    /*
        Utils
    */
    // Replace string within a string
    '__replace' : function(needle, replace_with, haystack)
    {
        if(haystack.length >= needle.length)
        {
            for(var i = 0; i <= (haystack.length - needle.length); i++)
            {
                if(haystack.substr(i, needle.length) == needle)
                {
                    haystack = haystack.substr(0, i) + replace_with + haystack.substr(i + needle.length);
                    i = i + replace_with.length;
                }
            }
        }

        return haystack;
    },

    // Replace string within a string
    '__addslashes' : function(haystack)
    {
        haystack = this.__replace('\\', '\\\\', haystack);
        haystack = this.__replace('"', '\\"', haystack);
        haystack = this.__replace('\'', '\\\'', haystack);
        return haystack;
    },

    // Get range of the selection. Will return an array with start index and length.
    '__getRange' : function()
    {
        var start = 0;
        var length = 0;

        if(this.resource != null)
        {
            // Set default range (cursor after last character in textarea)
            start = this.resource.value.length;
            length = 0;

            if(document.selection)
            {
                // Set focus on textarea (to ignore selection outside the textarea)
                this.resource.focus();

                // The current selection 
                var range = document.selection.createRange();

                // Store original text
                var original_text = range.text;

                // Insert ubb marker to find range
                // var marker = '[ubb_marker_' + (Math.round(Math.rand() * 90000) + 10000) + ']';
                var marker = '[ubb_marker_345381223746467363670497069367]';
                range.text = marker;

                // See if marker is found within the textarea
                var index = this.resource.value.indexOf(marker);

                if(index >= 0) // Text selected within textarea
                {
                    start = index;
                    length = original_text.length;

                    // Restore original text in textarea
                    this.resource.value = this.__replace(marker, original_text, this.resource.value);
                }
                else // No text selected within textarea
                {
                    // No selection found. Use default range.
                }
            }
            else if((this.resource.selectionStart >= 0) && (this.resource.selectionEnd >= 0))
            {
                start = this.resource.selectionStart;
                length = this.resource.selectionEnd - start;
            }
        }

        return new Array(start, length);
    },

    '__getText' : function(f_start, f_length)
    {
        var text = '';

        if(this.resource != null)
        {
            if(this.__getText.arguments.length < 1)
            {
                text = this.resource.value;
            }
            else if(this.__getText.arguments.length < 2)
            {
                text = this.resource.value.substr(f_start);
            }
            else
            {
                text = this.resource.value.substr(f_start, f_length);
            }
        }

        return text;
    },

    '__setText' : function(f_string, f_start, f_length)
    {
        if(this.resource != null)
        {
            if(this.__setText.arguments.length < 1)
            {
                this.resource.value = '';
            }
            else if(this.__setText.arguments.length < 2)
            {
                this.resource.value = f_string;
            }
            else if(this.__setText.arguments.length < 3)
            {
                this.resource.value = this.resource.value.substr(0, f_start) + f_string;
            }
            else
            {
                this.resource.value = this.resource.value.substr(0, f_start) + f_string + this.resource.value.substr(f_start + f_length);
            }
        }
    },

    /*
        UBB functions
        Note: Some functions require arguments. If not provided, PROMPT() is used to gather missing info.
    */

    // Clear textarea
    'clear' : function()
    {
        if(this.resource != null)
        {
            this.resource.value = '';
        }
        else
        {
            alert('Invald resource for UBB Editor.');
        }
    },

    // Add: [align]..[/align]
    'setAlign' : function(f_align)
    {
        var range = this.__getRange();

        if(this.setAlign.arguments.length < 1)
        {
            f_align = prompt('How should we align this text?\nEg: left, center, right, justify', 'left');
        }

        if(f_align == null)
        {
            // Ignore
        }
        else if(f_align == '')
        {
            // Ignore
        }
        else
        {
            this.__setText('[align="' + this.__addslashes(f_align) + '"]' + this.__getText(range[0], range[1]) + '[/align]', range[0], range[1]);
        }
    },

    // Add: [b]..[/b]
    'setBold' : function()
    {
        var range = this.__getRange();
        this.__setText('[b]' + this.__getText(range[0], range[1]) + '[/b]', range[0], range[1]);
    },

    // Add: [code="f_type"]..
    'setCode' : function(f_type)
    {
        var range = this.__getRange();

        if(this.setCode.arguments.length < 1)
        {
            f_type = prompt('How should we treat this code?\nEg: PHP, SQL, HTML, JS', '');
        }

        if(f_type == null)
        {
            // Ignore
        }
        else if (f_type == '')
        {
            this.__setText('' + this.__getText(range[0], range[1]) + '', range[0], range[1]);
        }
        else
        {
            this.__setText('[code="' + this.__addslashes(f_type) + '"]' + this.__getText(range[0], range[1]) + '', range[0], range[1]);
        }
    },

    // Add: [color="f_color"]..[/color]
    'setColor' : function(f_color)
    {
        var range = this.__getRange();

        if(this.setColor.arguments.length == 0)
        {
            f_color = prompt('What color should we use?\nEg: #000000, rgb(0, 0, 0), black', '#000000');
        }

        if(f_color == null)
        {
            // Ignore
        }
        else if(f_color == '')
        {
            // Ignore
        }
        else
        {
            this.__setText('[color="' + this.__addslashes(f_color) + '"]' + this.__getText(range[0], range[1]) + '[/color]', range[0], range[1]);
        }
    },

    // Add: [image="f_url"]..[/image]
    'setImage' : function(f_url)
    {
        var range = this.__getRange();

        if(this.setImage.arguments.length < 1)
        {
            f_url = prompt('What image should we add?\nEg: http://www.domain.tld/folder/image.jpg', 'http://');
        }

        if(f_url == null)
        {
            // Ignore
        }
        else if(f_url == '')
        {
            // Ignore
        }
        else
        {
            this.__setText('[img]' + this.__addslashes(f_url) + '' + this.__getText(range[0], range[1]) + '[/img]', range[0], range[1]);
        }
    },
    
    // Add: [i]..[/i]
    'setItalic' : function()
    {
        var range = this.__getRange();
        this.__setText('[i]' + this.__getText(range[0], range[1]) + '[/i]', range[0], range[1]);
    },

    // Add: [quote="f_name"]..[/quote]
    'setQuote' : function(f_name)
    {
        var range = this.__getRange();

        if(this.setQuote.arguments.length == 0)
        {
            f_name = prompt('Who\'s quote are you using?', '');
        }

        if(f_name == null)
        {
            // Ignore
        }
        else if(f_name == '')
        {
            this.__setText('[quote]' + this.__getText(range[0], range[1]) + '[/quote]', range[0], range[1]);
        }
        else
        {
            this.__setText('[quote="' + this.__addslashes(f_name) + '"]' + this.__getText(range[0], range[1]) + '[/quote]', range[0], range[1]);
        }
    },

    // Add: [s]..[/s]
    'setStrike' : function()
    {
        var range = this.__getRange();
        this.__setText('[s]' + this.__getText(range[0], range[1]) + '[/s]', range[0], range[1]);
    },

    // Add: [sub]..[/sub]
    'setSubscript' : function()
    {
        var range = this.__getRange();
        this.__setText('[sub]' + this.__getText(range[0], range[1]) + '[/sub]', range[0], range[1]);
    },

    // Add: [sup]..[/sup]
    'setSuperscript' : function()
    {
        var range = this.__getRange();
        this.__setText('[sup]' + this.__getText(range[0], range[1]) + '[/sup]', range[0], range[1]);
    },

    // Add replace selected text with given text
    'setText' : function(f_string)
    {
        var range = this.__getRange();

        if(this.setText.arguments.length < 1)
        {
            f_string = prompt('What text should use to overwrite the selection?\nEg: hello world', '');
        }

        if(f_string == null)
        {
            // Ignore
        }
        else if(f_string == '')
        {
            // Ignore
        }
        else
        {
            this.__setText(f_string, range[0], range[1]);
        }
    },

    // Add: [u]..[/u]
    'setUnderline' : function()
    {
        var range = this.__getRange();
        this.__setText('[u]' + this.__getText(range[0], range[1]) + '[/u]', range[0], range[1]);
    },

    // Add: [url="f_url"]..[/url]
    'setUrl' : function(f_url)
    {
        var range = this.__getRange();

        if(this.setUrl.arguments.length == 0)
        {
            f_url = prompt('What url should we use?\nEg: http://www.domain.tld', 'http://');
        }

        if(f_url == null)
        {
            // Ignore
        }
        else if(f_url == '')
        {
            // Ignore
        }
        else
        {
            if(range[1] > 0)
            {
                this.__setText('[url="' + this.__addslashes(f_url) + '"]' + this.__getText(range[0], range[1]) + '[/url]', range[0], range[1]);
            }
            else
            {
                this.__setText('[url="' + this.__addslashes(f_url) + '"]' + f_url + '[/url]', range[0], range[1]);
            }
        }
    }
}; 
