

function CustomFileBrowser(field_name, url, type, win) {

    var cmsURL = '/admin/filebrowser/?pop=2';
    cmsURL = cmsURL + '&type=' + type;

    tinyMCE.activeEditor.windowManager.open({
        file: cmsURL,
        width: 900,
        height: 500,
        resizable: 'yes',
        scrollbars: 'yes',
        inline: 'no',  // This parameter only has an effect if you use the inlinepopups plugin!
        close_previous: 'no'
    }, {
        window: win,
        input: field_name,
        editor_id: tinyMCE.selectedInstance.editorId
    });
    return false;
}



function setup_tinymce(options) {

    var settings = $.extend({
        mode : 'exact',
        theme : 'advanced',
        language : 'sv',
        skin: 'o2k7',
		external_link_list_url : "/cms/jseditorlistofmenus",
        content_css: '/media/css/typography.css,/media/c/barnangen.all.css,/media/css/hostit.css',
        theme_advanced_toolbar_location : 'top',
        theme_advanced_toolbar_align : 'left',
        theme_advanced_buttons1 : 'fullscreen,separator,preview,separator,cut,copy,paste,pasteword,selectall,separator,undo,redo,separator,search,replace,separator,code,separator,cleanup,separator,bold,italic,underline,strikethrough,separator,forecolor,backcolor,separator,justifyleft,justifycenter,justifyright,justifyfull,separator,help',
        theme_advanced_buttons2 : 'removeformat,styleselect,formatselect,separator,bullist,numlist,outdent,indent,separator,link,unlink,anchor',
        theme_advanced_buttons3 : 'separator,image,media,insertdate,inserttime,separator,tablecontrols,separator,template,advhr,visualaid,separator,charmap,emotions,iespell,separator,print,pastetext,pasteword,selectall',
        auto_cleanup_word : true,
        plugins : 'table,save,advhr,advimage,advlink,emotions,iespell,insertdatetime,preview,searchreplace,print,contextmenu,fullscreen,media,paste,template',
        plugin_insertdate_dateFormat : '%Y-%m-%d',
        plugin_insertdate_timeFormat : '%H:%M:%S',
        extended_valid_elements : 'iframe[src|width|height|name|align|style],a[name|href|title|onclick|target|class],img[class|src|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name|style],hr[class|width|size|noshade],font[face|size|color|style],span[class|align|style]',
        fullscreen_settings : {
            theme_advanced_path_location : 'top',
            theme_advanced_buttons1 : 'fullscreen,separator,preview,separator,cut,copy,paste,pasteword,selectall,separator,undo,redo,separator,search,replace,separator,code,separator,cleanup,separator,bold,italic,underline,strikethrough,separator,forecolor,backcolor,separator,justifyleft,justifycenter,justifyright,justifyfull,separator,help',
            theme_advanced_buttons2 : 'removeformat,styleselect,formatselect,separator,bullist,numlist,outdent,indent,separator,link,unlink,anchor',
            theme_advanced_buttons3 : 'sub,sup,separator,image,media,insertdate,inserttime,separator,tablecontrols,separator,template,advhr,visualaid,separator,charmap,emotions,iespell,separator,print'
        },
		  template_templates : [
        {
            title : "Tipsruta",
            src : "/media/templatefortipsruta-tinymce/div-tipsruta.html",
            description : "Lägger till en tipsruta"
        },
    ],
        theme_advanced_toolbar_location : 'external',
        cleanup: true,
        verify_html: true,
        file_browser_callback: 'CustomFileBrowser',
        relative_urls: false,
        paste_auto_cleanup_on_paste : true,
        paste_remove_styles: true,
        init_instance_callback: function(inst) {
            $('iframe').attr('allowTransparency', 'true');
            $('iframe').css('background-color', 'transparent');
    }}, options);

    tinyMCE.init(settings);
}

$(function() {
	
	$(".toolbar_edit").unbind('click');
    $(".toolbar_cancel").unbind('click');
	$(".toolbar_save").unbind('click');
	
    function make_id($main) {
        return $main.attr('id') + '_edit';
    }

    function showEditor(content_div)
    {
        var $main = $(content_div);
        var $content = $main.find('.content');

        var content_name = $main.attr('id').replace(/^content_/, '');

        $.get('/cms/api/get_content/',{
            flatpage_id: FLATPAGE_ID,
            name: content_name
        }, function(html) {
            var width = $content.width();
            var height = $content.height();
            var id = make_id($main);

            $content.hide().after($('<textarea>').css('visibility', 'hidden').attr('name', id).attr('id', id).text(html));
            $main.data('changed', false);
            setTimeout(function() {

                var global = (typeof TINYMCE_GLOBAL == 'undefined' ? {} : TINYMCE_GLOBAL)
                var local = {};

                if (typeof TINYMCE_OPTIONS != 'undefined' && typeof TINYMCE_OPTIONS[content_name] != 'undefined') {
                    local = TINYMCE_OPTIONS[content_name]; // god bless dict.get('key', default)
                }

                var options = $.extend({
                    elements: id,
                    width: width,
                    height: height,
					body_class: "content_"+ content_name,
                    onchange_callback: function(){
                        $main.data('changed', true);
                    }
                }, global, local);

                setup_tinymce(options);
            }, 0);

            $main.find('.toolbar_cancel, .toolbar_save').show();
            $main.find('.toolbar_edit').hide();
			//$('#subNav').hide();

        }, 'html');
    }

    function hideEditor($main) {
        var id = make_id($main);
        var ed = tinyMCE.get(id);
        if (typeof(ed) == 'undefined')
            return;

        tinyMCE.execCommand('mceRemoveControl', false, id);
        $('#' + id).remove();
        $main.find('.content').show();
        $main.find('.toolbar_cancel, .toolbar_save').hide();
        $main.find('.toolbar_edit').show();
		//$('#subNav').show();
    }

    function save($main) {
        var id = make_id($main);
        var ed = tinyMCE.get(id);
        if (typeof(ed) == 'undefined')
            return;

        ed.setProgressState(1);
        var content = ed.getContent();

        name = $main.attr('id').replace(/^content_/, "");

        $.post('/cms/api/update_content/',{
            flatpage_id: FLATPAGE_ID,
            name: name,
            content: content
        }, function(){
            $main.find('.content').html(content);
            hideEditor($main);
        });
    }

    $('.toolbar_edit').click(function () {
        showEditor($(this).parent().parent().parent());
        return false;
    });

    $('.toolbar_cancel').click(function() {
        $main = $($(this).parent().parent().parent());

        if ($main.data('changed')) {
            if (!confirm('Vill du verkligen avbryta? Dina ändringar kommer att gå förlorade om du fortsätter.'))
                return false;
        }

        hideEditor($main);
        return false;
    });

    $('.toolbar_save').click(function() {
        save($($(this).parent().parent().parent()));
        return false;
    })
});

