/*
 * jQuery RTE plugin 0.2 - create a rich text form for Mozilla, Opera, and Internet Explorer
 *
 * Copyright (c) 2007 Batiste Bieler
 * Distributed under the GPL (GPL-LICENSE.txt) licenses.
 */

// define the rte light plugin
jQuery.fn.rte = function(css_url) {

    if (document.designMode || document.contentEditable) {
        $(this).each(function() {
            var textarea = $(this);
            enableDesignMode(textarea);
        });
    }

    function formatText(iframe, command, option) {
        iframe.contentWindow.focus();
        try {
            iframe.contentWindow.document.execCommand(command, false, option);
        } catch (e) { console.log(e) }
        iframe.contentWindow.focus();
    }

    function tryEnableDesignMode(iframe, doc, callback) {
        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(iframe, doc, callback) }, 250);
        return false;
    }

    function enableDesignMode(textarea) {
        // need to be created this way
        var iframe = document.createElement("iframe");
        iframe.frameBorder = 0;
        iframe.frameMargin = 0;
        iframe.framePadding = 0;
        if (textarea.attr('class'))
            iframe.className = textarea.attr('class');
        if (textarea.attr('id'))
            iframe.id = textarea.attr('id');
        if (textarea.attr('name'))
            iframe.title = textarea.attr('name');
        textarea.after(iframe);
        var css = "";
        if (css_url)
            var css = "<link type='text/css' rel='stylesheet' href='" + css_url + "' />\n";
        css += "<style type=\"text/css\">";
        css += "body{font-family:Arial;}p{margin-top:0px;margin-bottom:0px;padding-top:0px;padding-bottom:0px;}\n";
        css += "img{max-width:180px;max-height:270px;border:none;width:180px;}\n";
        css += "</style>";
        var content = textarea.val();
        // Mozilla need this to display caret
        if ($.trim(content) == '')
            content = '<br>';
        var doc = "<html><head>" + css + '</head><body class="frameBody">' + content + "</body></html>";
        tryEnableDesignMode(iframe, doc, function() {
            $(iframe).before(toolbar(iframe));
            textarea.remove();
        });
    }

    function disableDesignMode(iframe, submit) {
        var content = iframe.contentWindow.document.getElementsByTagName("body")[0].innerHTML;
        if (submit == true)
            var textarea = $('<input type="hidden" />');
        else
            var textarea = $('<textarea></textarea>');
        textarea.val(content);
        t = textarea.get(0);
        if (iframe.className)
            t.className = iframe.className;
        if (iframe.id)
            t.id = iframe.id;
        if (iframe.title)
            t.name = iframe.title;
        $(iframe).before(textarea);
        if (submit != true)
            $(iframe).remove();
    }

    function toolbar(iframe) {
        var tb = $("<div class='rte-toolbar'><div>\
                <a href='#' class='bold' title='Bold|Select the text that you wish to bold then click here. Bolding is $0.25 per word with a maximum of $2.00 per ad.'><img src='img/bold.gif'/></a>\
                <a href='#' class='left' title='Left Align|Align your text to the left. Alignment is free.'><img src='img/left.gif' /></a>\
                <a href='#' class='center' title='Center|Center align your text. Alignment is free.'><img src='img/center.gif' /></a>\
                <a id=' href='#' class='image' title='Upload Image|Browse for a photo to upload. There is a flat rate of $5.00 for the image.<iframe id=\"iUpload\" src=\"imageupload.aspx\" frameborder=\"0\" scrolling=\"no\" width=\"255px\" height=\"40px\"></iframe>'><img src='img/image.png' /></a><br />\
            </div></div>");

        $('.bold', tb).click(function() { formatText(iframe, 'bold'); return false; });
        $('.center', tb).click(function() { formatText(iframe, 'justifycenter'); return false; });
        $('.left', tb).click(function() { formatText(iframe, 'justifyleft'); return false; });

        $('.disable', tb).click(function() { disableDesignMode(iframe); tb.remove(); return false; });
        $(iframe).parents('form').submit(function() {
            disableDesignMode(iframe, true);
        });

        var iframeDoc = $(iframe.contentWindow.document);
        iframeDoc.mousedown(function() {
            ifsHTML = iframe.contentWindow.document.getElementsByTagName("body")[0].innerHTML;
            if (ifsHTML.indexOf("Your text here.") > -1 && ifsHTML.indexOf("Your text here.") < 5) {
                iframe.contentWindow.document.getElementsByTagName("body")[0].innerHTML = '';  
            }
            showLivePreview();
        });

        return tb;
    }

    function getSelectionElement(iframe) {
        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;
    }
}