/*
 * jQuery RTE plugin 0.3 - 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, media_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 insertHTML(iframe, html) {
        iframe.contentWindow.focus();
        try {
            if ( document.all ) { // Internet Explorer
                selection = iframe.contentWindow.document.selection;
                range = selection.createRange;
                range.pasteHTML(html);
            } else {
                iframe.contentWindow.document.execCommand('insertHTML', false, html);
            }
        }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;
        iframe.height=200;
        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+"' />"
        var content = textarea.val();
        // Mozilla need this to display caret
        if($.trim(content)=='')
            content = '<p><br></p>';
        var doc = "<html><head>"+css+"</head><body class='frameBody'>"+content+"</body></html>";
        tryEnableDesignMode(iframe, doc, function() {
            $("#toolbar-"+iframe.title).remove();
            $(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();
        return textarea;
    }
    
    function toolbar(iframe) {
        
        var tb = $("<div class='rte-toolbar' id='toolbar-"+iframe.title+"'><div>\
            <p>\
                <a href='#' class='bold'><img src='"+media_url+"bold.gif' alt='bold' /></a>\
                <a href='#' class='italic'><img src='"+media_url+"italic.gif' alt='italic' /></a>\
            </p>\
            <p>\
                <a href='#' class='unorderedlist'><img src='"+media_url+"unordered.gif' alt='unordered list' /></a>\
                <a href='#' class='youtube'><img src='"+media_url+"youtube.gif' alt='youtube' /></a>\
            </p></div></div>");
        $('.bold', tb).click(function(){ formatText(iframe, 'bold');return false; });
        $('.italic', tb).click(function(){ formatText(iframe, 'italic');return false; });
        $('.unorderedlist', tb).click(function(){ formatText(iframe, 'insertunorderedlist');return false; });
        $('.youtube', tb).click(function(){ 
            var p=prompt("Video URL:");
            if(p)
            {
                if ( p.search(/^http:\/\/www\.youtube\.com\/watch\?v=([a-zA-Z0-9_]+)$/ ) >= 0 )
                {
                    insertHTML(iframe, ' '+p+' ');
                } else {
                    alert('Nu ati dat un URL Youtube valid.');
                }
            }
            return false; });
        $(iframe).parents('form').submit(function(){
            disableDesignMode(iframe, true); });
        var iframeDoc = $(iframe.contentWindow.document);
       
        return tb;
    }
}

$(document).ready(function() {
    $('.rte-zone').rte('/static/css/rte.css', '/static/imgs/rte/');
});


