/**
 * Tenhaven abc website - site specific funcs
 * 
 * These funcs are executed on page load, at bottom, for the specified pages. This may be specific for certain
 * templates, or template hierarchies.
 */


function logToPage(msg) {
    var logdiv = $("#log");
    if (logdiv.length > 0) {
        logdiv.append(msg + "<br />");
        logdiv.animate({ scrollTop: logdiv.attr("scrollHeight") - logdiv.height() }, 0);
    }
}


function eatClicks(elem, e) {
    elem.blur();
    e.preventDefault();
    return false;
}


function cssRule(w) {
    var s = document.styleSheets;
    for(i=0;i<s.length;i++) {
        var r = s[i].cssRules;
        if(r == undefined) {
            r = s[i].rules;
            if(r == undefined)
                continue;
        }
        for(j=0;j<r.length;j++) {
            if(r[j].selectorText == w)
                return r[j];
        }
    }
    return null;
}


function page_base__foot(logout_title, logout_msg, logout_url) {
    try {
        $("#mainHeader").offset({top:46, left:$(window).width() - $("#mainHeader").width()});
    } catch (err) {
        log("failed to offset mainHeader... now what?");
    }
    
    try {
        /* huge distance to avoid actual dragging (just exploit draggable for style) */
        $("#mainTabBar").tabs().find(".ui-tabs-nav").sortable({axis: "x", distance: 9999});
    } catch(err) {
        log("failed to tabify mainTabBar... now what?");
    }
    
    makeLogoutDialog("logoutLink", logout_title, logout_msg, logout_url);
    
    $(document).keyup(function(e) {
        var tag = document.activeElement.tagName;
        if (tag == "INPUT" || tag == "TEXTAREA")
            return;
        /*if (e.which == 116 || (e.which == 82 && e.ctrlKey)) {   // page refresh
            e.preventDefault();
            alert("Muh!");
            return false;
        }*/
        /*else if (e.which == 46) {   // entf
        }*/
        /*else if (e.which == 67) {   // 'c'
        }*/
        /*else {
            console.log('unhandled .keyup() with key:', e.which, '   ctrl:', e.ctrlKey, ', alt:', e.altKey, ', shift:', e.shiftKey, ', meta:', e.metaKey);
        }*/
    });
    
    
    /*window.onbeforeunload = function() {
        return "Bitte prüfen, ob von dieser Seite wegnavigiert werden soll.";
    }*/
}


/**
 * Take care that Portlets belonging to some menu link are automatically
 * shown/hidden whenever the menu-link is entered/exited.
 */
function show_autoshow_portlets(active_menulink) {
    log("show_autoshow_portlets(active_menulink=", active_menulink.attr("href"), "):");
    var autoshow = $(document).data("autoshow_portlets");
    //log("                                 autoshow:", autoshow);
    if (autoshow) {
        autoshow.forEach(function(portlet) {
            try {
                if ($(portlet).data("autoshow_menu_entry")[0] != active_menulink[0]) {
                    log("* ", $(portlet).data("autoshow_menu_entry").attr("href"), ": ", $(portlet), " HIDE");
                    $(portlet).hide();
                }
                else {
                    log("* ", $(portlet).data("autoshow_menu_entry").attr("href"), ": ", $(portlet), " SHOW");
                    $(portlet).show();
                }
            }
            catch (e) {
                // nop
            }
        });
    }
}


function portal__foot(current_category_id, current_article_id) {
    log("portal__foot(category=", current_category_id, ", article=", current_article_id, ")");
    
    // menu item change code
    $(".menuNavigation .menu-link").click(function() {
        log("--- .menu-link clicked:", $(this), " ----------------------------------------------------------------");
        
        var that = $(this),
            href = that.attr("href").replace("#", ""),
            delim = href.indexOf("__"),
            cat = href.slice(0, delim),
            art = href.slice(delim+2, href.length),
            current_cat_column = $("#" + cat + " .content_column");
        
        log("now: cat=", cat, " art=", art, " column=", current_cat_column);
        
        $("a.menu-link").css("color", "black");
        that.css("color", "red");

        // show/hide autoshow portlets based on the clicked menu link
        show_autoshow_portlets(that);
        
        // hide ALL portlets on new category column.
        current_cat_column.data("active_menulink", that);
        current_cat_column.find(".portlet").hide();
        
        // let last clicked menu-link remember it was last clicked
        current_cat_column.find(".menu-link").data("last_clicked", false);
        that.data("last_clicked", true);
        
        // find the portlet that is to be shown
        var portlet = $("#content-div-" + href);
        if (portlet.length>0) {
            // if the portlet is already there, just show it!
            portlet.show();
            
            // FIXME re-init stuff here...?
            log("portlet is just shown again:", portlet);
        }
        else {
            if ($(this).hasClass("into-whole-tab")) {
                alert("would load whole tab");
            }
            else {
                s = '<div class="portlet fixed minimal" id="content-div-' + href + '">' +
                    '<a name="content-div-' + href + '" />' +
                    '<div class="portletTitleBar ui-widget-header ui-corner-top">&nbsp;</div>' +
                    '<div class="portletContent ui-widget-content ui-corner-bottom">' +
                    '</div></div>';
                
                log("*** portlet for", href, "is not there yet - load it from URL! ***");
                
                var new_portlet = $(s).appendTo(current_cat_column);
                var portlet_content = new_portlet.find(".portletContent");
                portlet_content.load("/content/" + cat + "/" + art + "?portlet", function(response, status) {
                    // log(status);
                    // log(response);
                });
            }
        }
        
        // hide/show subarticle menulinks based on clicked link
        var the_p = that.closest("p");
        if (!the_p.hasClass("menuNavigation_subArticle")) {
            $(".menuNavigation_subArticle").hide();
            var name = the_p.attr("name");
            $("p.menuNavigation_subArticle[name='s-a-" + name + "']").show();
        }
        
        // prevent default link behaviour (focus)
        $(this).blur();
        return false; 
    });
    
    // impressum-link (and co)
    $("a.impressumLink").click(function(e) {
        alertFancy("<div id='impressumDialogContent'><"+"/div>", "Impressum",
                   "impressumFancyDiag", 500, 600);
        $("#impressumDialogContent").load("/impressum?portlet");
        return eatClicks($(this), e);
    });
    
    $("a.agbLink").click(function(e) {
        alertFancy("<div id='agbDialogContent'><"+"/div>", "Allgemeine Gesch&auml;ftsbedingungen",
                   "agbFancyDiag", 500, 600);
        $("#agbDialogContent").load("/agb?portlet");
        return eatClicks($(this), e);
    });
    
    $("a.datenschutzLink").click(function(e) {
        alertFancy("<div id='datenschutzDialogContent'><"+"/div>", "Datenschutz-Informationen",
                   "datenschutzFancyDiag", 500, 600);
        $("#datenschutzDialogContent").load("/datenschutz?portlet");
        return eatClicks($(this), e);
    });
    
    // hide all subarticles on page load (subarticles of the current article aside.)
    $(".menuNavigation_subArticle").hide();
    $(".menuNavigation_subArticle[name='s-a-" + current_article_id + "']").show();
    
    // in case we got loaded with a predefined article, determine if that article IS a subarticle or HAS subarticles
    // - in both cases, subarticles must be shown (loaded article's children or siblings)
    $("p.menuNavigation_subArticle[name='s-a-" + current_article_id + "']").show();
    
    var ml = $("p.menuNavigation_subArticle > a.menu-link[name='menu_link_" + current_category_id + "_" + current_article_id + "']");
    if (ml.length > 0) {
        ml = ml.closest(".menuNavigation_subArticle");
        $(".menuNavigation_subArticle[name='" + ml.attr("name") + "']").show();
    }
    
    $("a.menu-link").css("color", "black");
    $("a.menu-link[name='menu_link_" + current_category_id + "_" + current_article_id + "']").css("color", "red");
}


function _after_tab_load(panel) {
    log("after_tab_load(): panel =", panel);
    $("a.menu-link").css("color", "black");
    var auto_activated = undefined;
    $.each($(panel).find(".menu-link"), function(i, o) {
        o = $(o);
        if (o.data("last_clicked") === true) {
            // trigger a new click on the last-clicked menu-item on that tab (to make portlets show/hide, etc.!)
            o.click();
            o.css("color", "red");
            auto_activated = o;
        }
    });
    if (auto_activated == undefined) {
        // no menu-item was auto-activated - activate the 1st one.
        $(panel).find(".menu-link:first").css("color", "red");
    }
}


function portal_base__foot(cat) {
    log("portal_base__foot(cat=", cat, ")");
    
    // select the tab that was chosen via URL
    $("#mainTabBar .mainTabs_TabBar a[href=#c-h-" + cat + "]").click();
    $("#mainHeadImageChanger .changeable-header-image#c-h-" + cat).show();
    
    // tab change code
    $('#mainTabBar').bind('tabsselect', function(event, ui) {
        if ($(ui.panel).children().length == 0) {
            $(ui.panel).load("/content/" + $(ui.panel).attr("id") + "?tabcontent", function(response, status) {
                if (status == "success") {
                    _after_tab_load(ui.panel);
                }
            });
        }
        else {
            _after_tab_load(ui.panel);
        }
        
        $("#mainHeadImageChanger .changeable-header-image:visible").hide('fade', 5000);
        $("#mainHeadImageChanger .changeable-header-image#c-h-" + $(ui.panel).attr("id")).show('fade', 5000);
        
        return true;
    });
}


function r_a_w_base__foot(current_cat, current_art) {
    log("r_a_w_base__foot(category=", current_cat, ", article=", current_art, ")");
    
    if ($(document).data("autoshow_portlets") == undefined)
        $(document).data("autoshow_portlets", []);
    
    var help_portlet = $("#app_wiz_form_help_portlet");
    var autoshow_portlets = $(document).data("autoshow_portlets");
    if (autoshow_portlets.indexOf(help_portlet) == -1) {
        help_portlet.data("autoshow_menu_entry", $(".menu-link[href='#" + current_cat + "__" + current_art + "']"));
        autoshow_portlets.push(help_portlet);
    }
}


function wiz_multirowwidget_make_del_button(obj) {
    var obj = $(obj);
    obj.button({
        "icons": {
            primary: "ui-icon-trash"
        }
    }).click(function(e) {
        $(this).blur();
        
        try {
            var doomed_row = $(this).closest("tr"),
                mytable = doomed_row.closest("table");
            
            doomed_row.remove();
            
            var widgets = $(mytable).find("td > input,select,button").filter("[name!='']"),
                basename = widgets.filter(":first").attr("name"),
                _m = basename.match(/(.*)(\d+)/);
            
            basename = _m[1];
            $.each(widgets, function(i,o) {
                $(o).attr("name", basename + i);
            });
        }
        catch (err) {
            log(err);
        }
        
        // done!
        e.preventDefault();
        return false;
    });
}


function r_a_w__foot(next_step, prev_step, reset_title, reset_msg, reset_yes, reset_no, current_category_id, current_article_id) {
    log("r_a_w__foot(next_step=", next_step, ", prev_step=", prev_step,
        ", category=", current_category_id,", article=", current_article_id, ")");
    
    // ----
    var current_form_id = "#ra_wiz_form_" + current_category_id + "_" + current_article_id;
    var portlet_content = $(current_form_id).closest(".portletContent");
    
    log("current ra wiz form:", $(current_form_id));
    log(".portletContent found:", portlet_content);
    
    // make wizard form in current portlet to uniquely ID'd one.
    $("#app_wiz_form_content").removeAttr("id");
    portlet_content.attr("id", "app_wiz_form_content");
    
    var help_portlet = $("#app_wiz_form_help_portlet");
    if (help_portlet.length == 0) {
        s = '<div id="app_wiz_form_help_portlet" class="portlet fixed">'
          + '    <div class="portletTitleBar ui-widget-header ui-corner-top">Ausfüllhilfe</div>'
          + '    <div id="app_wiz_form_help" class="portletContent ui-widget-content ui-corner-bottom" style="min-height: 180px">'
          + '        <p style="color:#909090">In diesem Abschnitt wird Ihnen stets ein erläuternder Text zu dem'
          + '            gerade angewählten Eingabefeld angezeigt.</p>'
          + '        <p style="color:#909090">Falls eine Eingabe fehlt, unvollständig ist oder ein ungültiger Wert eingegeben'
          + '            wurde, wird das entsprechende Eingabefeld gesondert hervorgehoben und ein'
          + '            Hinweis direkt im Fragebogen angezeigt.</p>'
          + '    </div>'
          + '</div>'
        help_portlet = $(s);
        
        // insert help-portlet on top of right column.
        var ccat_area_sel = "div.portletArea[name='" + current_category_id + "'] ";
        var right_topmost_portlet = $(ccat_area_sel + "div[name='rechts'] .portletContainer .portlet:first");
        if (right_topmost_portlet.length != undefined)
            help_portlet.insertBefore(right_topmost_portlet).show();
        else {
            right_topmost_portlet = $(ccat_area_sel + "div[name='rechts'] .portletContainer .legal-stuff");
            if (right_topmost_portlet != undefined)
                help_portlet.insertBefore(right_topmost_portlet).show();
            else
                help_portlet.appendTo(ccat_area_sel + "div[name='rechts'] .portletContainer").show();
        }
        
        // remember portlets to hide on menu navigation
        if ($(document).data("autoshow_portlets") == undefined)
            $(document).data("autoshow_portlets", []);
        
        var autoshow_portlets = $(document).data("autoshow_portlets");
        
        if (autoshow_portlets.indexOf(help_portlet) == -1) {
            var menu_entry = $(".menu-link[name='menu_link_" + current_category_id + "_" + current_article_id + "']");
            help_portlet.data("autoshow_menu_entry", menu_entry);
            autoshow_portlets.push(help_portlet);
            log("added", help_portlet, "to autoshow_portlets (", menu_entry, ")");
        }
    }
    
    help_portlet.show();
    // ----
    
    $("#_" + current_category_id + "_" + current_article_id + "_RAW_form_submitButton").hide();
    $("#app_wiz_form_content form button,input[type='submit']").button();
    $("#app_wiz_form_content form button[name='wizard_next_step']")
        .button("option", "icons", {secondary: "ui-icon-triangle-1-e"});
    $("#app_wiz_form_content form button[name='wizard_prev_step']")
        .button("option", "icons", {primary: "ui-icon-triangle-1-w"});
    
    $(".defaultaccordion").accordion();
    
    var additional_section = $("#sectioned-select-multiple-section-99");
    if (additional_section != null) {
        $("#RA_Wiz_Quals-more_qual_entry").appendTo(additional_section);
    }
    
    $("#app_wiz_form_content form div.field_errors:not(:empty)")
        .parent().children("input")
        .css({background: "#ffffff"})
        .animate({backgroundColor: "#ffaaaa"}, 3000);
    
    $(".wizardProgressBar_Button,button[name='wizard_jump_to_step'],button[name='wizard_next_step'],button[name='wizard_prev_step'],button[name='wizard_reset']")
        .click(function() {
        var that = $(this);
        that.blur();
        
        if (that.attr("name") == "wizard_next_step") {
            $("#app_wiz_form_content form").ajaxSubmit({
                type: "POST",
                data: {portlet: 'true', wizard_next_step: next_step},
                success: function(response, status, xhrObj, wrappedFormElement) {
                    if (status == "success") {
                        $("#app_wiz_form_content").html(response);
                    }
                    else {
                        // TODO show error message!!
                    }
                }
            });
            
            // prevent default submittage behaviour (cause we just did that via ajax!)
            return false;
        }
        else if (that.attr("name") == "wizard_prev_step") {
            $("#app_wiz_form_content form").ajaxSubmit({
                type: "POST",
                data: {portlet: 'true', wizard_jump_to_step: prev_step},
                success: function(response, status, xhrObj, wrappedFormElement) {
                    if (status == "success") {
                        $("#app_wiz_form_content").html(response);
                    }
                    else {
                        // TODO show error message!!
                    }
                }
            });
            return false;
        }
        else if (that.attr("name") == "wizard_reset") {
            var result = null;
            fadingModalCallbackDialog({
                id: "confirm_wizard_reset_dialog",
                title: reset_title,
                msg: reset_msg,
                btn1: {
                    title: reset_yes,
                    func: function() {
                        $("#app_wiz_form_content form").ajaxSubmit({
                            type: "POST",
                            data: {portlet: 'true', wizard_reset: 'true'},
                            success: function(response, status, xhrObj, wrappedFormElement) {
                                $("#app_wiz_form_content").html(response);
                            }
                        })
                    }
                },
                btn2: {
                    title: reset_no,
                    func: function() {
                    }
                }              
            });
            return false;
        }
        else if (that.attr("name") == "wizard_jump_to_step") {
            $("#app_wiz_form_content form").ajaxSubmit({
                type: "POST",
                data: {portlet: 'true', wizard_jump_to_step: that.attr("value")},
                success: function(response, status, xhrObj, wrappedFormElement) {
                    if (status == "success") {
                        $("#app_wiz_form_content").html(response);
                    }
                    else {
                        // TODO show error message!!
                    }
                }
            });
        }
        else {
            var href = that.attr("href");
            try {
                var idx = href.indexOf("step=") + 5;
                href = href.slice(idx);
                
                $("#app_wiz_form_content form").ajaxSubmit({
                    type: "POST",
                    data: {portlet: 'true', wizard_jump_to_step: href},
                    success: function(response, status, xhrObj, wrappedFormElement) {
                        if (status == "success") {
                            $("#app_wiz_form_content").html(response);
                        }
                        else {
                            // TODO show error message!!
                        }
                    }
                });
            }
            catch (e) {
                log("error while parsing step from href:", e);
            }
        }
        return false;
    });
    
    // wizard form multirow widgets: add / remove row buttons
    $("button.multiwidget_row_button[href='#add']").button({
        "icons": {
            primary: "ui-icon-plus"
        }
    }).click(function(e) {
        $(this).blur();
        
        try {
            // add another row!
            var table = $(this).closest("table"),
                new_row = table.find("tr[name!='control_row'][name!='header_row']:last").clone().appendTo(table),
                new_input = new_row.find("input"),
                new_select = new_row.find("select"),
                new_del_btn = new_row.find("button.multiwidget_row_button[href='#del']");
            
            table.find("tr[name='control_row']").appendTo(table); // move control row to bottom
            
            new_input.attr("value", "");
            new_select.attr("value", "0");
            
            function _fudge_with_name(name) {
                var _m = name.match(/(.*)(\d+)/),
                    basename = _m[1],
                    idx = parseInt(_m[2]) + 2;
                return basename + idx;
            }
            
            try {
                new_input.attr("name", _fudge_with_name(new_input.attr("name")));
                new_input.attr("id", _fudge_with_name(new_input.attr("id")));
                new_select.attr("name", _fudge_with_name(new_select.attr("name")));
                new_select.attr("id", _fudge_with_name(new_select.attr("id")));
            }
            catch (err) {
                log("error while fudging with field names in multiwidget row...");
            }
            
            if (new_del_btn.length == 0) {
                log("need to add new delete button!");
                new_del_btn = $("<button class='multiwidget_row_button' href='#del'>&nbsp;</button>");
                new_del_btn.appendTo(new_row.find("td:last > div:last"));
            }
            
            // make the "-"-button work
            wiz_multirowwidget_make_del_button(new_del_btn);
        }
        catch (err) {
            log("oh noes!");
        }
        
        // done!
        e.preventDefault();
        return false;
    });
    
    wiz_multirowwidget_make_del_button("button.multiwidget_row_button[href='#del']");
}

