/*
 * jQuery RTE plugin 0.5 - create a rich text form for Mozilla, Opera, and Internet Explorer
 *
 * Copyright (c) 2007 Batiste Bieler
 * Distributed under the GPL (GPL-LICENSE.txt) licenses.
 *
 * Modified by Kamran Ayub (1/21/2009)
 * http://intrepidstudios.com/
 *
 * Modified by Anton Simov (10/29/2009)
 * http://www.antonsimov.com/
 */

// define the rte light plugin
(function ($) {
    $.fn.rte = function (options) {
        //
        // plugin defaults
        //
        $.fn.rte.defaults = {
            style: null
        }; // defaults

        //
        // build main options before element iteration
        var opts = $.extend({}, $.fn.rte.defaults, options);

        //
        // iterate and construct the RTEs        
        return this.each(function () {

            var textarea = $(this);
            var myID = textarea.attr("id");
            var iframe = $("iframe#" + myID);            
            textarea.addClass("rte-zone");

            // element specific options
            var settings = $.meta ? $.extend({}, opts, textarea.data()) : opts;

            //
            // enable design mode
            function enableDesignMode() {

                var content = textarea.val();

                // Mozilla needs this to display caret
                if ($.trim(content) == '') {
                    content = '<br />';
                }

                // already created? show/hide
                if (iframe.length > 0) {                    
                    $(iframe).contents().find("body").html(content);                   
                    return true;
                }

                // need to be created this way
                iframe = document.createElement("iframe");
                iframe.frameBorder = 0;
                iframe.frameMargin = 0;
                iframe.framePadding = 0;
                iframe.height = 200;
                if (textarea.attr('class'))
                    iframe.className = textarea.attr('class');
                if (textarea.attr('id'))
                    iframe.id = myID;
                if (textarea.attr('name'))
                    iframe.title = textarea.attr('name');

                textarea.after(iframe);

                var style = "";
                if (settings.style) {
                    style = settings.style;
                }
                else {
                    //IFrame style
                    style = "<style>\
                            .frameBody {\
                            font-family:Verdana, Arial, sans-serif;\
                            font-size:70%;\
                            margin:0;\
                            padding:.5em;\
                            height:100%;\
                            background:#fff; }\
                            .frameBody p {\
                            padding:5px;\
                            margin:0;\
                             }\
                            .pluginDummy {\
                            margin:.5em;\
                            padding:.5em;\
                            height:100px;\
                            width:200px;\
                            background:#666; }\
                            </style>";
                }

                var doc = "<html><head>" + style + "</head><body class='frameBody'>" + content + "</body></html>";

                tryEnableDesignMode(doc, function () {
                    $("#toolbar-" + myID).remove();
                    textarea.before(getToolbar());
                    // hide textarea
                    textarea.hide();
                });

            }

            function tryEnableDesignMode(doc, callback) {
                if (!iframe) { return false; }

                try {
                    iframe.contentWindow.document.open();
                    iframe.contentWindow.document.write(doc);
                    iframe.contentWindow.document.close();
                } catch (error) {
                    console.log(error)
                }
                if (document.contentEditable) {
                    iframe.contentWindow.document.designMode = "On";
                    callback();
                    return true;
                }
                else if (document.designMode != null) {
                    try {
                        iframe.contentWindow.document.designMode = "on";
                        callback();
                        return true;
                    } catch (error) {
                        console.log(error)
                    }
                }
                setTimeout(function () { tryEnableDesignMode(doc, callback) }, 250);
                return false;
            }

            //
            // create toolbar            
            function getToolbar() {

                var toolBar = $("<div class='rte-toolbar' id='toolbar-" + myID + "'>\
		            <ul>\
		                <li><select>\
		                    <option value=''>Select Style</option>\
		                    <option value='p'>Paragraph</option>\
		                    <option value='h2'>Title 2</option>\
		                    <option value='h3'>Title 3</option>\
		                </select></li>\
                        <li><a href='#' class='bold'>Bold</a></li>\
                        <li><a href='#' class='italic'>Italic</a></li>\
                        <li><a href='#' class='unorderedlist'>Unordered List</a></li>\
                        <li><a href='#' class='orderedlist'>Ordered List</a></li>\
                        <li><a href='#' class='link'>Link</a></li>\
                        <li><a href='#' class='image'>Image</a></li>\
                        <li><a href='#' class='switch-code html-code'>HTML</a></li>\
                        </ul>\
                        </div>");
                toolbarFunc(toolBar);
                return toolBar
            }

            function toolbarFunc(tb) {
                $('select', tb).change(function () {
                    var index = this.selectedIndex;
                    if (index != 0) {
                        var selected = this.options[index].value;
                        formatText("formatblock", '<' + selected + '>');
                    }
                });
                $('.bold', tb).click(function () { formatText('bold'); return false; });
                $('.italic', tb).click(function () { formatText('italic'); return false; });
                $('.unorderedlist', tb).click(function () { formatText('insertunorderedlist'); return false; });
                $('.orderedlist', tb).click(function () { formatText('insertorderedlist'); return false; });
                $('.link', tb).click(function () {
                    var p = prompt("URL:");
                    if (p)
                        formatText('CreateLink', p);
                    return false;
                });

                $('.image', tb).click(function () {
                    var p = prompt("image URL:");
                    if (p)
                        formatText('InsertImage', p);
                    return false;
                });

                $('.switch-code', tb).unbind('click').click(function () {

                    if ($(iframe).is(":visible")) {
                        $(this).addClass('html-rte').removeClass('html-code');
                        $('li:not(:last)', tb).addClass('ui-state-disabled');
                        $(':input', tb).attr('disabled', true);
                        $('a:not(.switch-code)', tb).unbind('click').click(function (e) { e.preventDefault(); }); //Unload toolbar functionality
                        textarea.show();
                        $(iframe).hide();

                    }
                    else {
                        $(this).addClass('html-code').removeClass('html-rte');
                        $(':input', tb).attr('disabled', false);
                        $('li:not(:last)', tb).removeClass('ui-state-disabled');
                        toolbarFunc(tb);
                        //Switching from textarea to rte transfers textrea value
                        $(iframe.contentWindow.document.body).html(textarea.val());
                        textarea.hide();
                        $(iframe).show();
                        //AiM CSM Specific!
                        loadPluginRTEFunction(); 
                    }

                    return false;
                });

                var iframeDoc = $(iframe.contentWindow.document);

                var select = $('select', tb)[0];

                iframeDoc.mouseup(function () {
                    updateTextarea();
                    setSelectedType(getSelectionElement(), select);
                    return true;
                });
                iframeDoc.keyup(function () {
                    updateTextarea();
                    setSelectedType(getSelectionElement(), select);
                    var body = $('body', iframeDoc);
                    if (body.scrollTop() > 0)
                        iframe.height = Math.min(350, parseInt(iframe.height) + body.scrollTop());
                    return true;
                });
                iframeDoc.blur(function () {
                    updateTextarea();
                });

                return tb;
            }

            function updateTextarea() { textarea.val($(iframe.contentWindow.document.body).html()); };

            function formatText(command, option) {
                iframe.contentWindow.focus();
                try {
                    iframe.contentWindow.document.execCommand(command, false, option);
                } catch (e) { console.log(e) }
                iframe.contentWindow.focus();
                updateTextarea();
            }

            function setSelectedType(node, select) {
                while (node.parentNode) {
                    var nName = node.nodeName.toLowerCase();
                    for (var i = 0; i < select.options.length; i++) {
                        if (nName == select.options[i].value) {
                            select.selectedIndex = i;
                            return true;
                        }
                    }
                    node = node.parentNode;
                }
                select.selectedIndex = 0;
                return true;
            }

            function getSelectionElement() {
                if (iframe.contentWindow.document.selection) {
                    // IE selections
                    selection = iframe.contentWindow.document.selection;
                    range = selection.createRange();
                    try {
                        node = range.parentElement();
                    }
                    catch (e) {
                        return false;
                    }
                } else {
                    // Mozilla selections
                    try {
                        selection = iframe.contentWindow.getSelection();
                        range = selection.getRangeAt(0);
                    }
                    catch (e) {
                        return false;
                    }
                    node = range.commonAncestorContainer;
                }
                return node;
            }

            //
            // enable design mode now
            enableDesignMode();

        }); //return this.each

    }; // rte

})(jQuery);
