$j = jQuery.noConflict();

var main_window="div#opi-comment-window";
var ajax_loaders="div#opi-comment-window div.ajax-loader";
var comment_zone="div#opi-comment-window div.opi-block-comments div.opi-content-zone";
var form_zone="div#opi-comment-window div.opi-block-comment-form div.opi-content-zone";

function showFolder() {
    folder = $j(this).attr("name");
    $j("div#opi-comment-window ul.opi-folder-nav li.active").removeClass("active");
    $j("div.opi-folder").hide();
    $j(this).parent("li").addClass("active");
    $j("div."+folder).show();
    return false;
}

function initFolders() {
    $j(ajax_loaders).show();
    $j("div.opi-folder").hide();
    $j("div#opi-comment-window ul.opi-folder-nav li.active").removeClass("active");
    $j("div#opi-comment-window ul.opi-folder-nav li a[name='opi-block-comments']").parent("li").addClass("active");
    $j("div#opi-comment-window div.opi-block-comments").show();
}

function initButtons() {
    $j("div#opi-comment-window h1 span.close").click(hideComments);
    $j("div#opi-comment-window ul.opi-folder-nav a").click(showFolder);
}

function deleteComment() {
    message = $j(this).siblings("div.document-comment-confirm-delete").text();
    if (!confirm(message)) return false;

    section = $j("div#opi-comment-window").siblings(".opi-comment-ico");
    $j("div#opi-comment-window div.opi-block-comments div.ajax-loader").show();
    $j.post("/documentos/ajax/delete_comment/"+$j(this).attr("name")+'/',{});
    updateNumComments(section);
    initCommentZone(section);
}

function markAsDone() {
    $j(this).parent("span.state").hide();
    $j(this).parent("span.state").siblings("span.mini-ajax-loader").show();
    $j(this).parent("span.state").load("/documentos/ajax/set_integrated_comment/"+$j(this).attr("name")+'/',{}, function() {
            $j(this).siblings("span.mini-ajax-loader").hide();
            $j(this).show();
    });
}

function initCommentZone(section) {
    var hash = gen_uuid();
    $j(comment_zone).load("/documentos/ajax/get_comments_for_section/"+section.attr("name")+'/?hash='+hash, function() {
        $j("div#opi-comment-window div.opi-block-comments div.ajax-loader").hide();
        $j(comment_zone).find('input.markdone').click(markAsDone);
        $j(comment_zone).find('input.delete').click(deleteComment);
        /* Votaciones */
        $j(comment_zone + " .votes").voting({
                    'post_msg': 'Voto:',
                    'effect': 'hide-and-show'
        });
    });
}

function updateNumComments(section) {
    $j.get("/documentos/ajax/get_number_of_comments_for_section/"+section.attr("name")+'/', function(data) {
        section.text(data);
    });
}

function getSectionURL() {
    return "/documentos/ajax/add_comment_for_section/";
}

function getFormData() {
    var textarea_value = $j(form_zone + " form textarea").val();
    var data = {comment: textarea_value};

    var anon_name = $j(form_zone + " form input#id_anon_name");
    if (anon_name.length == 1)
        data["anon_name"] = anon_name.val();

    var anon_email = $j(form_zone + " form input#id_anon_email");
    if (anon_email.length == 1)
        data["anon_email"] = anon_email.val();

    return data;
}
function requestAddComment() {
    section = $j(this).data('section');
    
    $j("div#opi-comment-window div.opi-block-comment-form div.ajax-loader").show();
    tinyMCE.execCommand('mceRemoveControl', false, textarea_id);
    textarea_id =  $j(form_zone).find("form").find("textarea").attr("id");
    var textarea_value = $j(form_zone).find("form").find("textarea").val();
    var data = getFormData();
    data['section'] = section.attr("name");
    var url = getSectionURL();
    $j(form_zone).load(url, data, function(response, stat, xhr) {
        initCommentZone(section);
        $j("div#opi-comment-window div.opi-block-comment-form div.ajax-loader").hide();
        if (!(/ul class="errorlist"/.test(response))) {
            $j("div#opi-comment-window ul.opi-folder-nav a[name=opi-block-comments]").click();
        }
        form = $j(form_zone).find("form");
        form.data('section', section);
        $j(form_zone).find("form").submit(requestAddComment);
        textarea_id =  $j(form_zone).find("form").find("textarea").attr("id");
        tinyMCE.execCommand('mceAddControl', false, textarea_id);
        updateNumComments(section);
            });
    return false;
}


function gen_uuid() {
    var uuid = "";
    for (var i = 0; i < 16; i++) {
        uuid += Math.floor(Math.random() * 16).toString(16);
    }
    return uuid;
}

function initFormZone(section) {
    var url = getSectionURL() + "?section=" + section.attr("name")

    $j(form_zone).load(url, function() {
        $j("div#opi-comment-window div.opi-block-comment-form div.ajax-loader").hide();
        form = $j(form_zone).find("form");
        form.data('section', section);
        textarea_id = form.find("textarea").attr("id");
        tinyMCE.execCommand('mceAddControl', false, textarea_id);
        $j(form_zone).find("form").submit(requestAddComment);
    });
}

function initWindow(section) {
    $j("div.open-comments").css('z-index','1');
    $j("div.open-comments").removeClass('open-comments');
    $j(main_window).remove().insertAfter(section).show();
    section.parents("div.opi-section").addClass('open-comments');
    section.parents("div.opi-section").css('z-index','50');
}

function showComments() {
    hideComments();
    initFolders();
    initWindow($j(this));
    initButtons();
    initCommentZone($j(this));
    initFormZone($j(this));
    return false;
}

function hideComments() {
    $j(form_zone).find('textarea').each(function() {
        tinyMCE.execCommand('mceRemoveControl', false, $j(this).attr('id'));
    });
    $j("div.open-comments").css('z-index','1');
    $j("div.open-comments").removeClass('open-comments');
    $j(main_window).hide();
}

function addNewSection() {
    $j(this).unbind('click');
    $j(this).bind('click', function() { return false; });
    actual_section = $j(this).parents("div.main-section-div");
    section_id = actual_section.attr('id').replace('section_','');
    var ajax = $j(this).find('img');
    ajax.show();
    $j.ajax({
        type: "GET",
        cache: false,
        url: "/documentos/ajax/add_section_after/" + section_id + "/", 
        success: function(html) {
            next_section = actual_section.parents('div.opi-section').after(html).next();
            next_section.hide().show("slow").find("div.section-inplacetranslation").dblclick(translateSection);
            if (typeof(initInplaceEditSections)!='undefined')
                initInplaceEditSections(next_section)
            next_section.find(".votes").voting({
                    'post_msg': 'Voto:',
                    'effect': 'hide-and-show'
            });
            initManagement();
            ajax.hide();
            return false;
        },
        error: function() {
            initManagement();
            ajax.hide();
            return false;
        }
    });
    return false;
}

function removeSection() {
    actual_section = $j(this).parents("div.main-section-div");
    section_id = actual_section.attr('id').replace('section_','');
    message = $j(this).parents().siblings("div.document-section-confirm-delete").text();
    if (!confirm(message)) return false;
    $j.get("/documentos/ajax/delete_section/" + section_id + "/", function(data) {
        actual_section.parent('div.opi-section').remove();
        if ($j("div.main-section-div").length <= 1) {
            $j("div.document-section-management a.document-section-delete-link").parent("dd").hide();
        }
    });
    return false;
}

function closeTranslationDiv() {
    actual_section = $j(this).parents("div.main-section-div");
    translation_div = $j(this).parents("div.document-section-translation-div");
    textarea_id = translation_div.find("textarea[name=translation]").attr('id');
    tinyMCE.execCommand('mceRemoveControl', false, textarea_id);
    canonical_textarea = translation_div.find("textarea[name=canonical]");
    if (canonical_textarea.length)
        tinyMCE.execCommand('mceRemoveControl', false, canonical_textarea.attr('id'));
    translation_div.html('');
    translation_div.hide();
    actual_section.parents('div.opi-section').css('z-index', '1');
    return false;
}

function submitTranslation() {
    actual_section = $j(this).parents("div.main-section-div");
    section_id = actual_section.attr('id').replace('section_','');
    translation_div = $j(this).parents("div.document-section-translation-div");
    translation_div_bak = translation_div;
    form = translation_div.find("form");
    textarea = translation_div.find("textarea[name=translation]");
    tinyMCE.execCommand('mceRemoveControl', false, textarea.attr('id'));
    var version = actual_section.find(".version").val();
    data = {translation: textarea.val(), version: version, posting: 1};
    canonical_textarea = translation_div.find("textarea[name=canonical]");
    if (canonical_textarea.length){
        tinyMCE.execCommand('mceRemoveControl', false, canonical_textarea.attr('id'));
        data["canonical"]=canonical_textarea.val();
    }
    $j.ajax({
        type: "POST",
        url: "/documentos/ajax/translate_section/" + section_id + "/", 
        cache: false,
        data: data,
        success: function(html) {
            tinyMCE.execCommand('mceRemoveControl', false, textarea.attr('id'));
            if (canonical_textarea.length)
                tinyMCE.execCommand('mceRemoveControl', false, canonical_textarea.attr('id'));
            translation_div.html(html);
            initTranslationDiv(translation_div);
            raw_section_div = actual_section.find("div.raw-section");
            raw_section_div.load("/documentos/ajax/get_section/" + section_id + "/", function() {
                raw_section_div.find("div.section-inplacetranslation").dblclick(translateSection);
                raw_section_div.find("div.section-inplacetranslation").bind("mouseenter", function() {
                     $j(this).addClass("inplaceeditable");
                }).bind("mouseleave", function() {
                     $j(this).removeClass("inplaceeditable");
                });
                if (typeof(initInplaceEditSections)!='undefined')
                    initInplaceEditSections(actual_section);
            });
            return false;
        },
        error: function() {
            tinyMCE.execCommand('mceRemoveControl', false, textarea.attr('id'));
            if (canonical_textarea.length)
                tinyMCE.execCommand('mceRemoveControl', false, canonical_textarea.attr('id'));
            translation_div = translation_div_bak;
            initTranslationDiv(translation_div);
            raw_section_div = actual_section.find("div.raw-section");
            raw_section_div.load("/documentos/ajax/get_section/" + section_id + "/", function() {
                raw_section_div.find("div.section-inplacetranslation").dblclick(translateSection);
                raw_section_div.find("div.section-inplacetranslation").bind("mouseenter", function() {
                     $j(this).addClass("inplaceeditable");
                }).bind("mouseleave", function() {
                     $j(this).removeClass("inplaceeditable");
                });
                if (typeof(initInplaceEditSections)!='undefined')
                    initInplaceEditSections(actual_section);
            });
            footer_div = $j("div.translation-div-footer");
            footer_div.remove();
            alert(gettext("There is a conflict. Please take the changes you've made to somewhere safe, reload the page and merge them."));
            return false;
        }
    });
}

function setFixedMenus(menu, dropmenu) {
    if (typeof(dropmenu)!='undefined') {
        dropmenu.onShowMenu.add(setFixedMenus);
    } else {
        if (tinymce.isIE6) return;
        var x, y, ch=22;
        if (typeof(menu.settings.offset_x)!='undefined') {
            x = menu.settings.offset_x;
            y = menu.settings.offset_y + ch;
            if (tinymce.isIE) {
                x = x - $j(window).scrollLeft();
                y = y - $j(window).scrollTop();
            }
        } else {
            var button = tinymce.DOM.get(menu.id);
            x = $j(button).offset().left - $j(window).scrollLeft();
            y = $j(button).offset().top - $j(window).scrollTop() + ch;
        }
        $j('#menu_' + menu.id).css('position', 'fixed').css('left', x).css('top', y);
        $j('#' + menu.id + '_menu').css('position', 'fixed').css('left', x).css('top', y);
    }
}

function customizeTranslationEditor(editor) {
    editor.settings['deactivate-yacoautoresize']=true;
    editor.settings['content_css']=$j("#tinycollabcss").text();
    editor.onInit.add(customCleanFormat);
    editor.controlManager.get('formatselect').onRenderMenu.add(trickTinyMenus);
}

function initTranslationDiv(translation_div) {
    translation_div.find(".close-translation-div").click(closeTranslationDiv);
    translation_div.find(".submit-translation").click(submitTranslation);
    textarea_id = translation_div.find("textarea[name=translation]").attr('id');
    tinyMCE.execCommand('mceAddControl', false, textarea_id);
    customizeTranslationEditor(tinyMCE.get(textarea_id));
    canonical_textarea = translation_div.find("textarea[name=canonical]");
    fixTranslationPosition(translation_div);
    if (canonical_textarea.length) {
        tinyMCE.execCommand('mceAddControl', false, canonical_textarea.attr('id'));
        customizeTranslationEditor(tinyMCE.get(canonical_textarea.attr('id')));
    }
}

function fixTranslationPosition(div) {
    var container = $j(div);
    container.css('position', 'absolute').css('left', '0px').css('top', '0px');

    var width = container.width();
    var full_width = $j(window).width();
    var full_height = $j(window).height();
    var height = container.height();
    var initleft = $j(div).offset().left;
    var inittop = $j(div).offset().top;
    var left = (full_width-width)/2 - initleft;
    var top = $j(window).scrollTop() + (full_height - height)/2 -inittop;

    if (left<-initleft) left = -initleft;
    if (top<-inittop) top = -inittop;

    container.css('left', left);
    container.css('top', top);
}

function translateSection() {
    actual_section = $j(this).parents("div.main-section-div");
    section_id = actual_section.attr('id').replace('section_','');
    translate_div = actual_section.find("div.document-section-translation-div:hidden");
    if (!translate_div.length) {
	fixTranslationPosition(actual_section.find("div.document-section-translation-div"));
        return false;
    }
    $j.ajax({
        type: "GET",
        cache: false,
        url: "/documentos/ajax/translate_section/" + section_id + "/", 
        success: function(html) {
            translate_div.html(html);
            actual_section.parents('div.opi-section').css('z-index', '50');
            translate_div.show();
            initTranslationDiv(translate_div);
            return false;
        },
        error: function() {
            return false;
        }
    });
    return false;
}

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 initInplaceSectionEdition() {
    var gen_section = $j(this).parents("div.main-section-div");
    var actual_section = gen_section.find('.inplace-section')
    var section_view = actual_section.find(".view");
    actual_section.find(".save").fadeOut();
    section_view.hide();
    actual_section.find(".tools").show();
    var textarea_id = actual_section.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).controlManager.get('formatselect').onRenderMenu.add(trickTinyMenus);
    return false;
}


function questionChangeLang() {
    var message = $j("div.documentParameters div.documentChangeLangInfo").text();
    if (confirm(message)) {
        $j(this).parent('form').submit();
    }
    return false;
}

function moveSectionFadeIn() {
    $j(this).fadeOut();
    $j(this).parent().find("form").fadeIn();
    return false;
}

function moveSectionFadeOut() {
    $j(this).parent().fadeOut();
    $j(this).parent().parent().find("a").fadeIn();
    return false;
}

function moveSectionSubmit() {
    var new_position = $j(this).parent().find("input#id_new_position").val();
    if(!parseInt(new_position) && parseInt("0") != 0){
        alert(gettext("Enter a number"));
        return false;
    }
    return true;
}

function initManagement() {
    $j("div.document-section-management a.document-section-add-link").unbind('click');
    $j("div.document-section-management a.document-section-delete-link").unbind('click');
    $j("div.document-section-management a.document-section-move-link").unbind('click');
    $j("div.document-section-management a.document-section-translate-link").unbind('click');
    $j("div.document-section-management a.document-section-edit-link").unbind('click');
    $j("div.section-inplacetranslation").unbind('dblclick');
    $j("div.opi-comment-bar .opi-comment-ico").unbind('click');
    $j("div.document-section-management a.document-section-add-link").click(addNewSection);
    $j("div.document-section-management a.document-section-delete-link").click(removeSection);
    $j("div.document-section-management a.document-section-move-link").click(moveSectionFadeIn);
    $j("div.document-section-management dd.contentview-move input[type=submit]").click(moveSectionSubmit);
    $j("div.document-section-management dd.contentview-move input[type=button]").click(moveSectionFadeOut);
    $j("div.document-section-management a.document-section-translate-link").click(translateSection);
    $j("div.document-section-management a.document-section-edit-link").click(initInplaceSectionEdition);
    $j("div.document-section-management a.document-section-change-lang-link").click(questionChangeLang);
    $j("div.section-inplacetranslation").dblclick(translateSection);
    $j("div.section-inplacetranslation").bind("mouseenter", function() {
         $j(this).addClass("inplaceeditable");
    }).bind("mouseleave", function() {
         $j(this).removeClass("inplaceeditable");
    });
    if ($j("div.main-section-div").length > 1) {
        $j("div.document-section-management a.document-section-delete-link").parent("dd").show();
    }
    $j("div.opi-comment-bar .opi-comment-ico").click(showComments);
}

function checkForOpenedEditors() {
    var editing_sections = $j("div.main-section-div div.tools:visible");
    var translating_sections = $j("div.document-section-translation-div:visible");
    if (editing_sections.length || translating_sections.length) {
        var message = $j("div.documentParameters div.editing-sections").text();
        return message;
    }
}

$j(document).ready(function() {
    initManagement();
    $j("a.document-section-edit-trigger").eq(0).trigger('click').each(function() {
        $j("div.history-collapsable-table").hide();
        $j(window).scrollTop($j(this).parents('.main-section-div').offset().top);
    });
    $j(window).unload(checkForOpenedEditors);
    window.onbeforeunload = checkForOpenedEditors;
});

