/* You should include the tiny_mce.js file before this one */
$j = jQuery.noConflict();

tinyMCE.init({
        "language": "es",
        "mode": "exact",
        "theme": "advanced",
        "width": "100%",
        "button_tile_map": true,
        "plugins": "preview,paste,fullscreen,yacoautoresize,safari,searchreplace",
        "theme_advanced_disable": "",
        "theme_advanced_buttons1": "formatselect,forecolor,backcolor,|,justifyleft,justifycenter,justifyright, justifyfull,|,bullist,numlist,|,outdent,indent",
        "theme_advanced_buttons2": "fontsizeselect,bold,italic,underline,removeformat",
        "theme_advanced_buttons3": "selectall,cut,copy,paste,pasteword,|, undo,redo,|,preview,|,link,image,code,hr,|,search,replace,|,fullscreen",
        "theme_advanced_buttons4": "",
        "theme_advanced_toolbar_location": "top",
        "theme_advanced_toolbar_align": "left",
        "extended_valid_elements": "hr[class|width|size|noshade],font[face|size|color|style],span[class|align|style]",
        "theme_advanced_resize_horizontal": false,
        "apply_source_formatting": false,
        "gecko_spellcheck": true,
        "editor_deselector": "mceNoEditor",
        "onchange_callback": "tinyMCE.triggerSave",
        "file_browser_callback": 'CustomFileBrowser',
        "relative_urls": false,
        "yacoautoresize_min_height": "200"
	    });

function trickTinyMenus(menu, dropmenu) {
    var translate_format_menus = $j("div.documentParameters div.translate_format_menus");

    dropmenu.onShowMenu.add(function(t) {
        $j('#menu_' + dropmenu.id + '_co').css('width', '300px');
        $j('#menu_' + dropmenu.id + '_tbl').css('width', '300px');
        $j.each(menu.items, function(index, item) {
            var translation = translate_format_menus.find('.' + item.value);
            if (translation.length) {
                item.title=translation.text();
                $j('#' + item.id + ' .mceText').attr('title', translation.attr('title'));
                $j('#' + item.id + ' .mceText').html(translation.text());
            }
        });
    });
}

function customCleanFormat(ed) {
    var button = $j("#"+ed.controlManager.get('removeformat').id);
    if (button.length) {
        var span = button.find('span');
        button.append(button.attr('title'));
        button.css('line-height', '20px').css('width', '150px');
        span.css('float', 'left').css('margin-right', '5px');
    }
}

function initInplaceEditSections(top_parent) {
        top_parent.find(".inplace-section .view").dblclick(function () {
	    var parent = $j(this).parents('.inplace-section');
	    $j(".save", parent).fadeOut();
	    $j(this).hide();
	    $j(".tools", parent).show();
	    var textarea_id = parent.attr("id").replace("section-", "textarea-");
	    tinyMCE.execCommand('mceAddControl', false, textarea_id);
            tinyMCE.get(textarea_id).settings['deactivate-yacoautoresize']=false;
            tinyMCE.get(textarea_id).settings['content_css']=$j("#tinycollabcss").text();
            tinyMCE.get(textarea_id).onInit.add(customCleanFormat);
            tinyMCE.get(textarea_id).controlManager.get('formatselect').onRenderMenu.add(trickTinyMenus);
	}).bind("mouseenter", function() {
             $j(this).addClass("inplaceeditable");
        }).bind("mouseleave", function() {
             $j(this).removeClass("inplaceeditable");
        });

        top_parent.find('.inplace-section .tools .cancel').click(function (){
	    var parent = $j(this).parents(".inplace-section");
            var cancelmsg = parent.find('.cancel_message').text();
            if (!confirm(cancelmsg)) {
                return false;
            }
	    var textarea_id = parent.attr("id").replace("section-", "textarea-");
	    $j(".save", parent).fadeOut();
	    //tinyMCE.execInstanceCommand(textarea_id, 'mceSetContent', false, parent.find('.hidden-textarea').html());
	    tinyMCE.get(textarea_id).setContent(parent.find('.hidden-textarea').html(), {format : 'html'});
	    tinyMCE.execCommand('mceRemoveControl', false, textarea_id);
	    $j(".tools", parent).hide();
	    $j(".view", parent).show();
	});

        top_parent.find('.inplace-section .tools .apply').click(function (){
	    var section = $j(this).parents(".inplace-section")
	    var section_id = section.attr("id").replace("section-", "");
	    var value = tinyMCE.activeEditor.getContent();
            var version = section.find(".version").val();
            var lang = $j(document).find('html').attr('xml:lang');
	    var data = {value: value, version: version, includelanguageinformstoken: lang};
	    var url = '/documentos/ajax/save_section/' + section_id + '/';
	    $j.post(url, data, function (data, textStatus) {
            if (data=='conflict') {
                alert(gettext("There is a conflict. Please take the changes you've made to somewhere safe, reload the page and merge them."));
            } else {
		        var textarea_id = 'textarea-' + section_id;
		        tinyMCE.get(textarea_id).save();
		        tinyMCE.execCommand('mceRemoveControl', false, textarea_id);
                section.find(".version").val(parseInt(version)+1);
		        $j(".tools", section).hide();
		        $j(".view", section).show().html(value);
		        $j(".save", section).fadeIn();
            		section.find('.hidden-textarea').html(value);
            }
		window.setTimeout(function() {$j(".save", section).fadeOut()},
				  2000);
	    });
	});
}

$j(document).ready(function() {initInplaceEditSections($j(document))});

