/*
 * 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.
 */


//Mozilla DOm reference: http://developer.mozilla.org/en/docs/Gecko_DOM_Reference

//  validation function used by .NET custom validator control */
function ValidateEmptyRte(source,args) {
    //note: isEmpty() is a jquery rte method;
    args.IsValid=(!document.getElementById(source.controltovalidate).isEmpty());
}
function ValidateMaxLengthRte(source,args) {
    //note: isEmpty() is a jquery rte method;
     var textbox = document.getElementById(source.controltovalidate);
    if (textbox != null)
    {
        args.IsValid=(textbox.MaxLength > 0 && textbox.getLength()>textbox.MaxLength);
    }
    else
    {
        args.IsValid=false;
    }
}
// define the rte light plugin
jQuery.fn.rte = function(img_url_base, css_url) {

    if(document.designMode || document.contentEditable)
    {
        $(this).each( function(){
            var textarea = $(this);
            enableDesignMode(textarea);
            
            //Add IsEmpty() to textarea, use it to check if the content in the rte iframe for a textarea is empty
            document.getElementById(textarea.attr('id')).isEmpty = function(){
                var content = document.getElementById(this.id + 'rteiframe').contentWindow.document.getElementsByTagName("body")[0].innerHTML;
                content = content.replace('<P></P>','');
                content = content.replace('<P>&nbsp;</P>','');
                if (content == '<br>') {content = ''}; //FF default value
                
                return (content.length==0);
            };
            
            //Add getLength() to textarea, use it to check if the length of the content 
            document.getElementById(textarea.attr('id')).getLength = function(){
                var content = document.getElementById(this.id + 'rteiframe').contentWindow.document.getElementsByTagName("body")[0].innerHTML;
                content = content.replace('<P></P>','');
                content = content.replace('<P>&nbsp;</P>','');
                if (content == '<br>') {content = ''}; //FF default value
                
                return (content.length);
            };
            
            
        });
    }
    
    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') + 'rteiframe'; //add 'rteiframe' to 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)=='')&& (!document.all)) {
            content = '<br>';
        }
        
        var doc = "<html><head>"+css+"</head><body class='frameBody'>"+content+"</body></html>";
        tryEnableDesignMode(iframe, doc, function() {
            $(iframe).before(toolbar(iframe));
            //hide textarea: 
            textarea.css({display:'none'});
        });
    }
    
    //Update the textarea value with iframe content
    function disableDesignMode(iframe, submit) {
        var content = iframe.contentWindow.document.getElementsByTagName("body")[0].innerHTML;
        var textarea = $('#' + iframe.id.replace('rteiframe',''));
        textarea.val(content);
    }
    
    function toolbar(iframe) {
        var tb = $("<div class='rte-toolbar'><div style='vertical-align: bottom;'>\
                <a href='#' class='bold'><img src='" + img_url_base + "bold.gif' alt='vet' /></a>\
                <a href='#' class='italic'><img src='" + img_url_base + "italic.gif' alt='cursief' /></a>\
                \
                <a href='#' class='unorderedlist'><img src='" + img_url_base + "unordered.gif' alt='lijst' /></a>\
                <a href='#' class='link'><img src='" + img_url_base + "link.gif' alt='link' /></a>\
                <select style='display:none;'>\
                    <option value=''>Bloc style</option>\
                    <option value='p'>Paragraph</option>\
                    <option value='h3'>Title</option>\
                </select>\
            </div></div>");
        $('select', tb).change(function(){
            var index = this.selectedIndex;
            if( index!=0 ) {
                var selected = this.options[index].value;
                formatText(iframe, "formatblock", '<'+selected+'>');
            }
        });
        $('.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; });
        $('.link', tb).click(function(){ 
            //Note: links always have target = "_blank"
            var selectedText = getSelectedText(iframe);
            
            if (selectedText==""){
                alert ('Selecteer eerst een stuk tekst waar je een link aan wilt koppelen.');
                return false;
            }
            
            var p=prompt("Geef de Url op:","http://");
            if(p) {
                if(p.toLowerCase().indexOf('http://')!=0) {
                    p = 'http://' + p ;
                }
                
                formatText(iframe, 'CreateLink', p);
                
                //set target for link to _blank
                var Links = (iframe.contentWindow.document.getElementsByTagName('a'));
                for (var i = 0; i < Links.length; i++) {
                    Links[i].target = "_blank";
                }
                
                
            }
            
            return false; });
        $('.image', tb).click(function(){ 
            var p=prompt("image URL:");
            if(p)
                formatText(iframe, 'InsertImage', p);
            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);
        
        var select = $('select', tb)[0];
        iframeDoc.mouseup(function(){ setSelectedType(getSelectionElement(iframe), select);return true;});
        iframeDoc.keyup(function(){ setSelectedType(getSelectionElement(iframe), select);return true;});
        
        return tb;
    }
        
    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 getSelectedText(iframe) {
        if (iframe.contentWindow.document.selection) {
            // IE selections
            try {
                selection = iframe.contentWindow.document.selection;
                range = selection.createRange();
                return range.text;
            }
            catch(e){
                return "";
            }
            
        } else {
            // Mozilla selections
            try {
                selection = iframe.contentWindow.getSelection();
                range = selection.getRangeAt(0);
                return range;
            }
            catch(e){
                return "";
            }
            
        }
        return "";
    }
    
    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;
    }
}
