/*
 * 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()
{
	
    $(this).each(function(){
        var textarea = $(this);
        create_rte(textarea);
    });
    
    function create_rte(textarea) {
        // need to be created this way
        var iframe = document.createElement("iframe");
        iframe.frameBorder=0;
        iframe.frameMargin=0;
        iframe.framePadding=0;
        iframe.height="200";
        iframe.width="100%";
        if(textarea.attr('class'))
            iframe.className = textarea.attr('class');
            iframe.id = 'rte-body';
        if(textarea.attr('name'))
            iframe.title = textarea.attr('name');
        textarea.after(iframe);
        var css = "";

        var content = textarea.val();
        
        if($.trim(content)=='') // Mozilla need this to display caret
            content = '<br>';

        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).hide();
        });
    }

    function tryEnableDesignMode(iframe, doc, callback)
	{
        try {
            iframe.contentWindow.document.open();
            iframe.contentWindow.document.write(doc);
            iframe.contentWindow.document.close();
			        $(iframe.contentWindow.document).change(function(){
				alert('a');
			})
        } catch(error) {
            console.log(error)
        }

        iframe.contentWindow.document.designMode = "on";
        callback();

        return false;
    }
    
    function toolbar(iframe)
	{
		// The directory where the toolbar icons can be found
		media_url = BASE_URL + "/js/jquery/rte/images/";

        var tb = $("<div class='rte-toolbar' id='toolbar-"+iframe.title+"'>\
                <a href='#' class='bold' title='bold'><img src='"+media_url+"bold.gif' alt='bold' /></a>\
                <a href='#' class='italic' title='italicize'><img src='"+media_url+"italic.gif' alt='italic' /></a>\
                <a href='#' class='unorderedlist' title='list'><img src='"+media_url+"unordered.gif' alt='unordered list' /></a>\
                <a href='#' class='link' title='insert link'><img src='"+media_url+"hyperlink.gif' alt='link' /></a>\
                <a href='#' class='image' title='insert image'><img src='"+media_url+"image.png' alt='image' /></a>\
            </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; });
        $('.link', tb).click(function(){ 
            var p=prompt("URL:");
            if(p)
			{
				// Make sure it is a valid URL, otherwise, prepend http
				var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
				if(!regexp.test(p))
					p = "http://" + p;
                formatText(iframe, 'CreateLink', p);
			}
            return false; 
		});
        
		$('.image', tb).click(function(){ 
            var p = prompt("image URL:");
            
			if(p) 
				formatText(iframe, 'InsertImage', p);
            
			return false; 
		});
        
        return tb;
    }


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