// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
var current    = {};
var currentRel = {};
var cmsCurrent = "";

$(function() {

    $(".cms-rte").mouseenter(function() {
        var offset = $(this).offset();
        $("#cms-click").show();
        $("#cms-click").css("top", offset.top);
        $("#cms-click").css("left", offset.left-3);
        $("#cms-click").css("height", $(this).height());
        $("#cms-click").css("width", $(this).width());
        $("#cms-click p").text($(this).attr("title"));
        $("#cms-click").show();
        current    = $(this);
    });

    $("#cms-click").mouseleave(function() {    
        $("#cms-click").hide();
    });

    $("#cms-click").click(function() {
        var height = current.height();
        var width = current.width();
        cmsCurrent = current
        currentRel = current.attr("rel");
        current.wymeditor({
            html: current.html().replace(/<\/?(span|canvas)[^>]+>/gim, ""),
            stylesheet: ['stylesheets/screen.css', 'stylesheets/application.css'],
            classesHtml: "",
            height: 500,
            toolsItems: [
            {'name': 'Bold', 'title': 'Strong', 'css': 'wym_tools_strong'}, 
            {'name': 'Italic', 'title': 'Emphasis', 'css': 'wym_tools_emphasis'},
            {'name': 'CreateLink', 'title': 'Link', 'css': 'wym_tools_link'},
            {'name': 'Unlink', 'title': 'Unlink', 'css': 'wym_tools_unlink'},
            {'name': 'InsertImage', 'title': 'Image', 'css': 'wym_tools_image'},
            {'name': 'InsertOrderedList', 'title': 'Ordered_List',
            'css': 'wym_tools_ordered_list'},
            {'name': 'InsertUnorderedList', 'title': 'Unordered_List',
            'css': 'wym_tools_unordered_list'},
            {'name': 'Paste', 'title': 'Paste_From_Word',
            'css': 'wym_tools_paste'},
            {'name': 'Undo', 'title': 'Undo', 'css': 'wym_tools_undo'},
            {'name': 'Redo', 'title': 'Redo', 'css': 'wym_tools_redo'}
            ]

        });
        $("iframe").css("height", height+25);
        $(".wym_area_main").append('<div class="cms-close" onclick="cms_close()">Close</div>');
        $(".wym_area_main").append('<div class="cms-save" onclick="cms_save()">Save</div>');
        $("#cms-click").hide();
    });

});

function cms_save() {
    $.post("/cms/contents", {
            content: jQuery.wymeditors(0).xhtml(),
            name: currentRel
    }, function(data) {
       window.location.reload();
    }, "json");
}

function cms_close() {
    $('.cms-rte').show();
    $('.wym_box').hide();
}