/*
 * 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) {
	var toolbar;
	var iframe = false;

    if(document.designMode || document.contentEditable) {
        $(this).each( function(){
            var textarea = $(this);
            iframe = 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
        var iframe = document.createElement("iframe");
        iframe.frameBorder=0;
        iframe.frameMargin=0;
        iframe.framePadding=0;
		iframe.scrolling="no";
        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).attr('viewwith','rte');
        textarea.after(iframe);
        var css = "";
        if(css_url)
            var css = "<link type='text/css' rel='stylesheet' href='"+css_url+"' />"
        var content = textarea.html();
		
		
		// replace embeded video in content with video images 
		// split into array of content blocks each starting with the id of the youtube video.
				
		var contentArray = content.split(/<object/i);
		// we assume the content starts with text not video.
		var contentWithImg = contentArray[0];

		// now starting from the second part of the content, which is a video section,
		// go through each part and replace with img with appropriate video id.
		
		for(var i=1; i<contentArray.length; i++) {
			// grab the youtube id, which ends with '"'
			var subContentArray = contentArray[i].split(/\/v\//);
			var strIndex = subContentArray[1].search(/&/);
			var videoId = subContentArray[1].slice(0, strIndex);
			// now construct img containing appropriate youtube id.
			var imgString = '<img src="/images/video.png?'+videoId+'">';			
			// get rid of the end of the object tag.
			var endIndex = contentArray[i].search(/object>/i);
			var remainderContent = contentArray[i].slice(endIndex+7);			
			// and now splice together the embed content with the remainder.
			contentWithImg += imgString + remainderContent;						
		}
		
        // Mozilla need this to display caret
        if($.trim(contentWithImg)=='')
            contentWithImg = '<br>';
        var doc = "<html><head>"+css+"</head><body class='frameBody clearfix'>"+contentWithImg+"</body></html>";
        tryEnableDesignMode(iframe, doc, function() {
			toolbar = toolbar(iframe);
            $(iframe).before(toolbar);
            textarea.remove();
        });
		
		//alert("hello");
		// wait for document to be loaded and then set the height of the frame to be the same as the document.
		setTimeout(function(){setHeight(iframe)}, 100);
		return iframe;
    }
    
    function disableDesignMode(iframe, submit) {
	
		// remove toolbar
		$(iframe).parent().children().filter('.rte-toolbar').remove();
	
        var content = iframe.contentWindow.document.getElementsByTagName("body")[0].innerHTML;
		
		// replace video images in content with embeded video
		// split into array of content blocks each starting with the id of the youtube video.
		var contentArray = content.split(/<img src=\"\/images\/video.png\?/i);
		// we assume the content starts with text not video.
		var contentWithVideo = contentArray[0];

		
		// now starting from the second part of the content, which is a video section,
		// go through each part and replace with embed statement with appropriate video link.
		for(var i=1; i<contentArray.length; i++) {
			// grab the youtube id, which ends with '"'
			var strIndex = contentArray[i].search(/"/);
			var videoId = contentArray[i].slice(0, strIndex);						
			// now construct embed object containing appropriate youtube id.
			
			// not using old embed method.
//			var embedString = '<object width="200" height="175"><param name="movie" value="http://www.youtube.com/v/'+videoId+'&hl=en&fs=1"></param><param name="allowFullScreen" value="true"></param><embed src="http://www.youtube.com/v/'+videoId+'&hl=en&fs=1" type="application/x-shockwave-flash" allowfullscreen="true" width="200" height="175"></embed></object>';			

			// using new object only method.
			var objectString = '<object width="230" height="197" type="application/x-shockwave-flash" data="http://www.youtube.com/v/'+videoId+'&hl=en&fs=1" width="320" height="240"><param name="movie" value="http://www.youtube.com/v/'+videoId+'&hl=en&fs=1"><param name="loop" value="false"><param name="allowFullScreen" value="true"></param></object>';
			
			// get rid of the end of the image tag.
			var endIndex = contentArray[i].search(/>/);
			var remainderContent = contentArray[i].slice(endIndex+1);			
			// and now splice together the embed content with the remainder.
			contentWithVideo += objectString + remainderContent;			
		}
		
		
        if(submit==true)
            var textarea = $('<input type="hidden" />');
        else
            var textarea = $('<div></div>');
        textarea.html(contentWithVideo);
		textarea.attr('editwith','rte');
        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();
			
    }
    
    function toolbar(iframe) {
		var iconPath = "/js/lib/jquery/rte/";
/*		
        var tb = $("<div class='rte-toolbar'><div>\
            <p>\
                <select>\
                    <option value=''>Bloc style</option>\
                    <option value='p'>Paragraph</option>\
                    <option value='h3'>Title</option>\
                </select>\
            </p>\
            <p>\
                <a href='#' class='bold'><img src='"+iconPath+"bold.gif' alt='bold' /></a>\
                <a href='#' class='italic'><img src='"+iconPath+"italic.gif' alt='italic' /></a>\
            </p>\
            <p>\
                <a href='#' class='unorderedlist'><img src='"+iconPath+"unordered.gif' alt='unordered list' /></a>\
                <a href='#' class='link'><img src='"+iconPath+"link.png' alt='link' /></a>\
                <a href='#' class='image'><img src='"+iconPath+"image.png' alt='image' /></a>\
                <a href='#' class='video'><img src='"+iconPath+"youtubeCropIcon.png' alt='video' /></a>\
                <a href='#' class='disable'><img src='"+iconPath+"close.gif' alt='close rte' /></a>\
            </p></div></div>");
*/			
        var tb = $("<div class='rte-toolbar'><div>\
            <p>\
                <select>\
                    <option value=''>Bloc style</option>\
                    <option value='p'>Paragraph</option>\
                    <option value='h3'>Title</option>\
                </select>\
            </p>\
            <p>\
                <a href='#' class='bold'></a>\
                <a href='#' class='italic'></a>\
            </p>\
            <p>\
                <a href='#' class='unorderedlist'></a>\
                <a href='#' class='link'></a>\
                <a href='#' class='image'></a>\
                <a href='#' class='video'></a>\
            </p></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(){ 
            var p=prompt("URL:");
            if(p)
                formatText(iframe, 'CreateLink', p);
            return false; });
        $('.image', tb).click(function(){ 
            var p=prompt("image URL:");
            if(p) {
                formatText(iframe, 'InsertImage', p);				
				// set the align to left on the image.
				$(iframe).contents().find("img[src='"+p+"']").attr("align","right");
				setHeight(iframe);
			}
            return false; });
        $('.video', tb).click(function(){ 
            var p=prompt("Video URL:");
            if(p) {
				var videoId = (p.split(/=/))[1];
                formatText(iframe, 'InsertImage', '/images/video.png?'+videoId);
				setHeight(iframe);
			}
            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); setHeight(iframe);  return true;});
        
        return tb;
    }


	function setHeight(e){
		if(e.contentDocument){
			e.height = e.contentDocument.body.offsetHeight + 20;
		} else {
			e.height = e.contentWindow.document.body.scrollHeight;
		}
	}

	
    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;
    }
	if(iframe) return (function(){ disableDesignMode(iframe); return false; });
	return false;
}
