/*
 * 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.
 */

var css = "";
var piframe;

	function SelectImage(id){
	//	tb_remove();
		tb_show('Image Options','/PHP/box_image_options_ajax.php?id=' + id + '&height=600&width=800',false);
	}

        function AddImage(imghtml){
		piframe.contentWindow.document.execCommand("inserthtml", false, '<br>wy51wy9h057<br>');
		var temp = piframe.contentWindow.document.body.innerHTML;
		temp = temp.replace("<br>wy51wy9h057<br>", imghtml);
		piframe.contentWindow.document.body.innerHTML = temp;
		BlankPar();
        }

	function BlankPar(){
		var temp = piframe.contentWindow.document.body.innerHTML;

		//if last thing on page is an image (div wrapping image really) then add a blank paragraph
		if (temp.substr(temp.length-6) == '</div>')
		{
			temp = temp + '<p><br></p>';
			piframe.contentWindow.document.body.innerHTML = temp;
		}
	}

// 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 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
        iframe = document.createElement("iframe");
	piframe = iframe;
        iframe.frameBorder=0;
        iframe.frameMargin=0;
        iframe.framePadding=0;
        iframe.height=400;
        iframe.scrolling="no";
	iframe.width='100%';
        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);

        if(css_url)
            css = "<link type='text/css' rel='stylesheet' href='"+css_url+"' />"
        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() {
            $("#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 cols="40" rows="10"></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) {
        
	//<a href='#' class='unorderedlist'><img src='"+media_url+"unordered.gif' alt='unordered list' /></a>\
	//<a href='#' class='disable'><img src='"+media_url+"close.gif' alt='close rte' /></a>\

        var tb = $("<div class='rte-toolbar' id='toolbar-"+iframe.title+"'><div>\
            <div>\
                <select>\
                    <option value=''>no style</option>\
                    <option value='p'>Paragraph</option>\
                    <option value='h2'>Heading</option>\
                </select>\
	    </div>\
	    <div>\
		<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>\
		<a href='#' class='link'><img src='"+media_url+"link.png' alt='link' /></a>\
		<a href='#' class='image'><img src='"+media_url+"image.png' alt='image' /></a>\
	    </div></div></div><b class='Line_Break'></b>");

	$('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 linkurl=prompt("Enter target URL:");
            var linktext=prompt("Enter link text:");
            if((linkurl) && (linktext))
                formatText(iframe, 'inserthtml', '<a href="' + linkurl + '">' + linktext + '</a>');
            return false; });

        $('.image', tb).click(function(){ 
		tb_show('Please Select an Image','/PHP/box_image_list_ajax.php?height=305&width=674',false);
	return false; });

        $('.disable', tb).click(function() {
            var txt = disableDesignMode(iframe);
            var edm = $('<a href="#">Enable design mode</a>');
            tb.empty().append(edm);
            edm.click(function(){
                enableDesignMode(txt);
                return false;
            });
            return false; 
        });

        $(iframe).parents('form').submit(function(){
            disableDesignMode(iframe, true); });

        var iframeDoc = $(iframe.contentWindow.document);
        
        var select = $('select', tb)[0];
        iframeDoc.mouseup(function(){ 
		BlankPar();
            setSelectedType(getSelectionElement(iframe), select);
            return true;
        });

        iframeDoc.keyup(function(){ 
		BlankPar();
            setSelectedType(getSelectionElement(iframe), select, iframe);
            var body = $('body', iframeDoc);
            if(body.scrollTop()>0)
                iframe.height = Math.min(700, parseInt(iframe.height)+body.scrollTop());
		
            return true;
        });

        iframeDoc.keydown(function(event){ 
            return disableCtrlKeyCombination(event);
        });

        iframeDoc.keypress(function(event){ 
            return disableCtrlKeyCombination(event);
        });
        return tb;
    }
        
    function setSelectedType(node, select, iframe) {
        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;
                }
		//If in a div, its probably an img caption, so dont change to a paragraph
                if(nName=='div'){
                    select.selectedIndex=0;
                    return true;
                }
            }
            node = node.parentNode;
        }

	//If no style, set to paragraph
	nName="p";
	formatText(iframe, "formatblock", '<p>');
        for(var i=0;i<select.options.length;i++) {
            if(nName==select.options[i].value){
                select.selectedIndex=i;
            }
        }
	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 disableCtrlKeyCombination(e)
{
        //list all CTRL + key combinations you want to disable
        var forbiddenKeys = new Array('a');
        var key;
        var isCtrl;
        if(window.event)
        {
                key = window.event.keyCode;     //IE
                if(window.event.ctrlKey)
                        isCtrl = true;
                else
                        isCtrl = false;
        }
        else
        {
                key = e.which;     //firefox
                if(e.ctrlKey)
                        isCtrl = true;
                else
                        isCtrl = false;
        }
        //if ctrl is pressed check if other key is in forbidenKeys array
        if(isCtrl)
        {
                for(i=0; i<forbiddenKeys .length; i++)
                {
                        //case-insensitive comparation
                        if(forbiddenKeys[i].toLowerCase() == String.fromCharCode(key).toLowerCase())
                        {
                                //alert('Key combination CTRL + ' +String.fromCharCode(key) +' has been disabled.');
                                return false;
                        }
                }
        }
        return true;
}
