/*

	jQuery jxEditor plugin
	Copyright (c) 2010 Gael Jaunin

	For support and tutorials visit
	http://www.xuserver.net/

	License: GNU Lesser General Public License (LGPL) 
	at http://opensource.org/licenses/lgpl-2.1.php

	This plugin is free software;  you can redistribute it  and/or  modify  it 
	under the terms of the GNU Lesser General Public License as  published  by 
	the Free Software Foundation;  either version 2.1 of the License,  or  (at 
	your option) any later version.
	This software is distributed in the hope  that  it  will  be  useful,  but 
	WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
	or FITNESS FOR A PARTICULAR PURPOSE.  See the  GNU Lesser  General  Public 
	License for more details.
	You should have received a copy of  the  GNU Lesser General Public License 
	along with this library;  if not,  write to the  Free Software Foundation, 
	Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

	THIS COMMENT AND COPYRIGHT NOTICE MUST BE RETAINED IN THE CODE AS IS FOR LEGAL USE

*/

(function($) {
		  
	$.fn.jxAutocomplete = function(options) {
		// make sure we have an options object
		options = options || {};
		// setup our defaults
		var defaults = { 
			  minChars: 0
			, width: 310
			, matchContains: true
			, autoFill: false
			, formatItem: function(row, i, max) {
				return row.name;
			}
			, formatMatch: function(row, i, max) {
				return row.name;
			}
			, formatResult: function(row) {
				return row.name;
			}
		};
		
		options = $.extend(defaults, options);
		return this.each(function() {
			var $this = $(this),
				data = [],
				$input = $('<input type="text" />');
			if (this.tagName.toLowerCase() != 'select') { return; }
			
			$this.children('option').each(function() {
				var $option = $(this);
				data.push({
					"label": $option.html()
					, "id":$option.val()
				});
				
			});
			$this.after($input);
			$input.attr("style", $this.attr("style") );
			$input.autocomplete({
				source: data,
				minLength: 2,
				select: function( event, ui ) {
					$($this.find('option[value=' + ui.item.id + ']')[0]).attr('selected', true);
					$this.change();
				}
			});
			
			$input.blur(function(){
				if(this.value == ""){
					$($this.find('option[value=]')[0]).attr('selected', true);
				}
				if(this.value != $this[0].options[$this[0].selectedIndex].text){
					$input.val($this[0].options[$this[0].selectedIndex].text);
				}  
			});
			$input.val($this[0].options[$this[0].selectedIndex].text);
			$this.hide();
		});
	};		  
  
})(jQuery);




jQuery.fn.jxEditor = function(tabUnique) {

    if(document.designMode || document.contentEditable){
        $(this).each( function(){
            var textarea = $(this);
            enableDesignMode(textarea);
        });
    }
    
    function applyCommand(iframe, command, option) {
        iframe.contentWindow.focus();
        try{
            iframe.contentWindow.document.execCommand(command, false, option);
        }catch(e){console.log(e)}
        iframe.contentWindow.focus();
    }
    
    function setDesignMode(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(){setDesignMode(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');
        iframe.tabUnique = tabUnique;
        textarea.after(iframe);
        var css = "";
        
        
        var content = textarea.val();
        // Mozilla need this to display caret
        if($.trim(content)=='')content = '<br />';
        
        var doc = "<html><head><style>"+jxcssstring.text()+"</style></head><body class='ui-widget ui-corner-all frameBody'>"+content+"</body></html>";
        setDesignMode(iframe, doc, function() {
            $("#menubar-"+iframe.title).remove();
            $(iframe).before(menubar(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 menubar(iframe) {

        var tb = $("<div class='jxEditormenubar' id='menubar-"+iframe.title+"'>\
            <div class='ui-widget-content ui-state-hover ui-corner-top' style='padding:3px;border-bottom:0px;'>\
              <a href='javascript:void(0)' class='jxEditor-disable jxEditorOnTab-"+iframe.tabUnique +"' title='toggle mode' >toggle mode</a>\
              <select style='width:100px' >\
                <option value=''>bloc</option>\
                <option value='p'>paragraph</option>\
                <option value='h1'>title 1</option>\
                <option value='h2'>title 2</option>\
                <option value='h3'>title 3</option>\
              </select>\
              <span class='jx-buttonset'>\
                <a href='javascript:void(0)' class='jxEditor-bold'><b>b</b></a>\
                <a href='javascript:void(0)' class='jxEditor-italic'><i>i</i></a>\
                <a href='javascript:void(0)' class='jxEditor-underline'><u>u</u></a>\
              </span>\
              <span class='jx-buttonset'>\
                <a href='javascript:void(0)' class='jxEditor-unorderedlist' title='bullet' >l</a>\
                <a href='javascript:void(0)' class='jxEditor-link' title='link' >l</a>\
                <a href='javascript:void(0)' class='jxEditor-image' title='image' >l</a>\
              </span>\
            </div>\
          </div>");
         
        $('select', tb).change(function(){
            var index = this.selectedIndex;
            if( index!=0 ) {var selected = this.options[index].value;applyCommand(iframe, "formatblock", '<'+selected+'>');}
        });
        $('.jx-buttonset',tb).buttonset();
        $('.jxEditor-bold',tb).button();
        $('.jxEditor-bold',tb).click(function(){ applyCommand(iframe, 'bold');return false; });
        
        $('.jxEditor-italic',tb).button();
        $('.jxEditor-italic',tb).click(function(){ applyCommand(iframe, 'italic');return false; });
        
        $('.jxEditor-underline',tb).button();
        $('.jxEditor-underline',tb).click(function(){ applyCommand(iframe, 'underline');return false; });
        
        $('.jxEditor-unorderedlist',tb).button({icons: {primary: 'ui-icon-bullet'},text: false});
        $('.jxEditor-unorderedlist',tb).click(function(){ applyCommand(iframe, 'insertunorderedlist');return false; });
        
        $('.jxEditor-link',tb).button({icons: {primary: 'ui-icon-link'},text: false});
        $('.jxEditor-link',tb).click(function(){var p=prompt("URL:");if(p){applyCommand(iframe, 'CreateLink', p);}return false;});
        
        $('.jxEditor-image',tb).button({icons: {primary: 'ui-icon-image'},text: false})
        $('.jxEditor-image',tb).click(function(){var p=prompt("image URL:");if(p){applyCommand(iframe, 'InsertImage', p);}return false;});
        
        $('.jxEditor-disable',tb).button({icons: {primary: 'ui-icon-locked'},text: false})
        $('.jxEditor-disable',tb).click(function() {
            var txt = disableDesignMode(iframe);
            var edm = $("<a href='javascript:void(0)' class='jxEditor-disable' title='toggle mode' >toggle mode</a>");
            tb.empty().append(edm);
            edm.button({icons: {primary: 'ui-icon-unlocked'},text: false});
            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(){ 
            setSelectedType(getSelectionElement(iframe), select);
            return true;
        });
        iframeDoc.keyup(function(){ 
            setSelectedType(getSelectionElement(iframe), select);
            var body = $('body', iframeDoc);
            if(body.scrollTop()>0)
                iframe.height = Math.min(350, parseInt(iframe.height)+body.scrollTop());
            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 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;
    }
}

