/*
 * 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, path, limit_word_count, image_upload, text_class) {

    if(document.designMode || document.contentEditable)
    {
        $(this).each( function(){
            var textarea = $(this);
            enableDesignMode(textarea);
        });
    }

    function set_link_targets_to_parent(iframe) {
    	var iframeDoc = $(iframe.contentWindow.document);
    	var msg = iframeDoc.children().children('body');
    	var msg_val = msg.html();
    	while(msg_val.indexOf('<a href=')>-1){
    		index = msg_val.indexOf('<a href=');
			str1 = msg_val.substr(0,index);
			str2 = msg_val.substr(msg_val.indexOf('<a href=')+8,msg_val.length);
			msg_val = str1 + '<a target="_parent" href=' + str2;
    	}
    	msg.html(msg_val);
    }

    function formatText(iframe, command, option) {
        iframe.contentWindow.focus();
        try{
            iframe.contentWindow.document.execCommand(command, false, option);
        }catch(e){console.log(e)}

        if (command=='CreateLink'){
        	set_link_targets_to_parent(iframe);
        }
        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='"+path+css_url+"' />"
        var content = textarea.val();
        // Mozilla need this to display caret
        if($.trim(content)=='')
            content = '<br/>';
        var doc = "<html><head>"+css+"</head><body id='"+textarea.attr('id')+"_body' class='frameBody "+text_class+"'>"+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();
    }

	/*
	<p>\
        <select>\
            <option value=''>Bloc style</option>\
            <option value='p'>Paragraph</option>\
            <option value='h3'>Title</option>\
        </select>\
    </p>\
	<a href='#' class='unorderedlist'><img src='"+path+"unordered.gif' alt='unordered list' /></a>\
    <a href='#' class='disable'><img src='"+path+"close.gif' alt='close rte' /></a>\

    */
    function toolbar(iframe) {
    	var tb;
    	if (image_upload){
    		var tb = $("<div class='rte-toolbar'>\
	            <p>\
	                <a href='#' class='bold'><img src='"+path+"bold.png' alt='bold' /></a>\
	                <a href='#' class='italic'><img src='"+path+"italic.png' alt='italic' /></a>\
	                <a href='#' class='link'><img src='"+path+"link.png' alt='link' /></a>\
	                <a href='#' class='image'><img src='"+path+"image.png' alt='image' /></a>\
	            </p></div>");
    	}
    	else {
    		var tb = $("<div class='rte-toolbar'>\
            <p>\
                <a href='#' class='bold'><img src='"+path+"bold.png' alt='bold' /></a>\
                <a href='#' class='italic'><img src='"+path+"italic.png' alt='italic' /></a>\
                <a href='#' class='link'><img src='"+path+"link.png' alt='link' /></a>\
            </p></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(){
            var p=prompt("URL: (use http://)");
            if(p)
                formatText(iframe, 'CreateLink', p);
            return false; });
        if (image_upload){
	        $('.image', tb).click(function(){
	            var p=prompt("image URL: (use http://)");
	            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;});
        if (limit_word_count) {
	        iframeDoc.keyup(function(){
	        	var maxChar = 240;
	        	var trailerLength = 0;
	        	var msg = iframeDoc.children().children('body');
	        	var left = $("#body_char_left");
	        	var msg_val = msg.html();
	        	var smsLenLeft = maxChar - (countSpecialChars(msg_val) + trailerLength);
	        	while (smsLenLeft < 0) {
	        		msg_val = msg.html();
	        		if (msg_val.substring(msg_val.length-4,msg_val.length)=='<br>'){
	        			msg.html(msg_val.substring(0,msg_val.length-5) + '<br>');
	        		}
	        		else {
	        			msg.html(msg_val.substring(0,msg_val.length-1));
	        		}
	        		smsLenLeft = maxChar - (countSpecialChars(msg.html()) + trailerLength);
	        	}
	        	left.val(smsLenLeft);
	        });

		}
        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 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;
    }

}


function removeHTMLTags(html_str){
    //if(document.getElementById && document.getElementById("input-code")){
        var strInputCode = html_str; //document.getElementById("input-code").innerHTML;
        /*
              This line is optional, it replaces escaped brackets with real ones,
              i.e. &lt; is replaced with < and &gt; is replaced with >
        */
        strInputCode = strInputCode.replace(/&(lt|gt);/g, function (strMatch, p1){
            return (p1 == "lt")? "<" : ">";
        });
        var strTagStrippedText = strInputCode.replace(/<\/?[^>]+(>|$)/g, "");
        return strTagStrippedText;

  		// Use the alert below if you want to show the input and the output text
  		//        alert("Input code:\n" + strInputCode + "\n\nOutput text:\n" + strTagStrippedText);
    //}
}
