
/* Elisa Virtual Desktop Javascript file.
 *
 * Administrator pages.
 */


// GENERIC UTIL FUNCS
// ------------------------------------------------------------------
// returns the index of the column where the elem is located
function col_index(elem) {
    if (typeof elem == "string") {
        elem = $(elem);
    }

    var tr = traverseup(elem, "tr");
    var td = traverseup(elem, "td");
    if (td == undefined) {
        td = traverseup(elem, "th");
        var index = $("th", tr).index(td);
    } else
        var index = $("td", tr).index(td);

    return index;
}

// seebra stripes for table
function table_row_colorize(table) {
    $("tr.normal", table).removeClass("even");
    $("tr.normal:even", table).addClass("even");
}

// finds the desired parent element of elem, type or class
// (have no dot in classname!)
function traverseup(elem, classname) {
    if (typeof elem == "string") {
        elem = $(elem);
    }

    while (!(elem.is(classname) || elem.hasClass(classname)) &&
            !elem.is("body"))
        elem = elem.parent();

    if (elem.is("body"))
        return undefined;
    else
        return elem;
}


// ELISA FUNCS
// ------------------------------------------------------------------

// common functionality for all forms
function init_common_admin() {

    // work around for IE's lack of :focus CSS pseudoselector
    if($.browser.msie) {
        $('input[class="full text"], input[class="qf text"], input[class="text"]')
          .focus(function(){$(this).addClass('iefocus');})
          .blur(function(){$(this).removeClass('iefocus');});
    }

    // sorting columns
    $("thead a, thead div.sorticon").click(function(){
        var table = traverseup($(this), "table");
        if (table.hasClass("service"))
            return false;

        // toggle class
        var th = $(this).parent();
        var isup = th.hasClass("sortup");
        var tr = th.parent();

        $("th", tr).removeClass("sortup").removeClass("sortdown");
        th.addClass(isup ? "sortdown" : "sortup");

        table_sort(table);
        return false;
    });
    // filter columns
    $("input.qf").keyup(function(){
        var table = traverseup($(this), "table");
        table_filter(table);
    });
    $("a.checkfilter").click(function(){
        if ($(this).hasClass("disabled"))
            return false;

        var entity = traverseup($(this), "entity");

        $("a.checkfilter", entity).removeClass("selectedfilter");
        $(this).addClass("selectedfilter");

        var table = $("table:first", entity);
        table_filter(table);
        return false;
    });

    // delete entity button
    $("input.delete").click(function(){
        if (!confirm($("p#deletemsg").text()))
            return false;

        var form = $("form#hiddenform");
        $("input:last", form).attr("value", "delete");
        $(':submit', form).click();
        return false;
    });


    // search box enter
    $("div.searchbox input").keyup(function(e){
        // enter presses button
        if (e.keyCode == 13) {
            $(this).next("input").click();
        }
    });

    $("div.toptitle input").click(function(){
        var h = $(this).attr("href");
        if (h)
            location = h;
        return false;
    });

    // form block editing
    set_form_edit_handlers();

    // disable all blocks initially
    disable_controls();
}

// fetch user,group table data from server with ajax
var show_checkboxes = false;
var show_members = true;
function fetchdata(table, params) {
    if (typeof table == "string") {
        table = $(table);
    }
    $("div#ajaxdata").empty().load("ajaxquery.php", params, function(){
        $("tbody", table).empty().append($("div#ajaxdata tr"));

        //table_row_colorize(table);

        // sort and filter
        table_sort(table);
        table_filter(table);
        // update selection count
        table_counts(table);

        $("td.dofind", table).hide();
        if ($("tr.normal", table).length > 0)
            $("td.nonefound", table).hide();
        else
            $("td.nonefound", table).show();

        if (show_checkboxes) {
            $("td.checkbox", table).show();
        }
        $("a", table).click(function(){
            // do nothing in various cases
            var table = traverseup($(this), "wizard");
            if (table != undefined)
                return false;
            var p = traverseup($(this), "entity");
            if (p.hasClass("edited") || p.hasClass("nolink"))
                return false;

            // ok, just follow this link normally
            return true;
        });
        // checkbox clicking, synchronize 2 tables
        $("tbody input", table).click(function(){
            var p = traverseup($(this), "tr");
            var add = !p.hasClass("selected");
            p.toggleClass("selected");
            // get 2nd table
            var p2 = traverseup(table, "entity");
            var table2 = $("table:nth(1)", p2);
            synch_table2(p.clone(false), table2, add);
            return true;
        });
    });
}

// update selection counts of this table
function table_counts(table) {
    var p = traverseup(table, "entity");
    $("span.usercount", p).text("("+$("tr.user", table).length+")");
    $("span.groupcount", p).text("("+$("tr.group", table).length+")");
}

// synchs table2 with a row from table1
function synch_table2(tr, table, addrow) {
    // get id
    var id = $("td", tr).eq(0).text();
    // remove extra cols from row
    $("td:gt(3)", tr).remove();

    $("input", tr).attr("checked", "checked");

    // remove href from this tr
    $("a", tr).click(function() { return false;});

    // first remove this tr
    $("tbody tr", table).each(function() {
        var id2 = $("td", this).eq(0).text();
        if (id2 === id) {
            $(this).remove();
            return;
        }
    });
    // then add if necessary
    if (addrow) {
        $("tbody", table).append(tr);

        // and attach remove checkbox handler
        $("input", tr).click(function(){
            var table1 = $("table:first", traverseup($(this), "entity"));
            var p = traverseup($(this), "tr");

            // get id
            var id = $("td", p).eq(0).text();
            p.remove();

            // remove selection also from table1
            $("tbody tr", table1).each(function() {
                var id2 = $("td", this).eq(0).text();
                if (id2 === id) {
                    $(this).removeClass("selected");
                    $("input", this).removeAttr("checked");
                }
            });

            // count
            var c = $("tbody tr", table).length;
            $("div.rpane:first span.count").text(c);

            return true;
        });
    }
    // count
    var c = $("tbody tr", table).length;
    $("div.rpane:first span.count").text(c);
}

// picks the ids of the member table and sends them to the server
// via the hidden form
function send_member_table_data(form) {
    var id_array = [];

    $("table#table2 tbody tr").each(function() {
        var id = $("td", this).eq(0).text();
        id_array.push(id);
    });
    var val = id_array.toString()

    // write ids and submit form
    $("input[name=val]", form).attr("value", val);
    $(':submit', form).click();
}

// picks the rights values from columns and sends them to the server
// via the hidden form
function send_rights_table_data(form) {
    var id_array = [];

    $("table#table3 tbody tr").each(function() {
        var id = $("td", this).eq(0).text();
        $("input", this).each(function() {
            if ($(this).attr("checked")) {
                id_array.push(id+"-"+$(this).val());
            }
        });
    });
    var val = id_array.toString()

    // write ids and submit form
    $("input[name=val]", form).attr("value", val);
    $("input:last", form).attr("value", "setrights");
    $(':submit', form).click();
}

function disable_controls() {
    $("div.data input, div.data select, div.data textarea")
        .attr("disabled", "disabled");
    // but quick filter always on, and inputs with enabled-class
    $("input.qf").removeAttr("disabled");
    $("div.data input.enabled").removeAttr("disabled");
}

function set_form_edit_handlers() {

    // generic open/cancel/save logic

    $("h3 a").click(function(){
        var p = traverseup($(this), "entity");
        if (p.hasClass("edited"))
            return false;
        p.toggleClass("opened");
        return false;
    });
    $("input.edit").click(function(){
        if ($("div.edited").length > 0)
            return false;
        var p = traverseup($(this), "entity");
        $("div.entity div.disabled").show();
        disable_controls();
        $("div.disabled", p).hide();
        $("div.shadow", p).hide();
        $("input, select, textarea", p).removeAttr("disabled");
        p.addClass("opened").addClass("edited");
        $("input[type=text]:first", p).focus();
        return false;
    });
    $("input.cancel").click(function(){
        var p = traverseup($(this), "entity");
        $("div.entity div.disabled").hide();
        p.removeClass("edited").removeClass("adding").removeClass("removing");
        $("div.shadow").show();
        disable_controls();
        return false;
    });
    $("input.save").click(function(){
        var p = traverseup($(this), "entity");
        $(':submit', p).click();
        return false;
    });
    $("input.create").click(function(){
        var p = traverseup($(this), "form");
        //$(':submit', p).click();
        send_member_table_data(p);
        return false;
    });
    $("input.cancelpage").click(function(){
        history.back();
        return false;
    });
    $("input.createservice").click(function(){
        location = "admin-wiz1-service.php";
        return false;
    });

    // adding removing members logic

    $("input.addmember").click(function(){
        var p = traverseup($(this), "entity");
        var table = $("table:first", p);
        var table2 = $("table:nth(1)", p);
        p.addClass("adding");
        // copy existing table rows
        $("div#backup").append($("tr.normal", table));
        // show add msg
        $("td.dofind", table).show();
        // set cmd
        var form = $("form#hiddenform");
        $("input:last", form).attr("value", "addmember");
        // show checkboxes
        show_checkboxes = true;
        $("th.checkbox, td.checkbox", p).show();
        // clear table2
        $("tbody", table2).empty();
        $("div.rpane:first span.count").text("0");
        table_counts(table);

        // focus
        $("input[type=text]:first", p).focus();
        return false;
    });
    $("input.delmember").click(function(){
        var p = traverseup($(this), "entity");
        var table = $("table:first", p);
        var table2 = $("table:nth(1)", p);
        p.addClass("removing");
        // copy existing table rows
        $("div#backup").append($("tr.normal", table).clone(true));
        // hide add msg
        $("td.dofind", table).hide();
        // set cmd
        var form = $("form#hiddenform");
        $("input:last", form).attr("value", "delmember");
        // show checkboxes
        show_checkboxes = true;
        $("th.checkbox, td.checkbox", p).show();
        // clear table2
        $("tbody", table2).empty();
        $("div.rpane:first span.count").text("0");
        table_counts(table);
        return false;
    });
    $("input.cancelsplit").click(function(){
        var p = traverseup($(this), "entity");
        var table = $("table:first", p);
        // restore original table rows
        $("tbody", table).empty();
        $("tbody", table).append($("div#backup tr.normal"));
        // hide checkboxes
        show_checkboxes = false;
        $("th.checkbox, td.checkbox", p).hide();
        $("td.dofind", table).hide();
        table_counts(table);
        return false;
    });
    $("input.savemember").click(function(){
        var form = $("form#hiddenform");
        send_member_table_data(form);
        return false;
    });
}

// sort the table based on current sort column
function table_sort(table) {
    var tr = $("thead tr", table);
    var index = 0;
    var isup = false;
    $("th", tr).each(function() {
        var t = $(this);
        if (t.hasClass("sortup") || t.hasClass("sortdown")) {
            if (t.hasClass("sortdown"))
                isup = true;
            return false; // same as break
        }
        index++;
    });

    // first prepare group-name relationships
    $("tbody tr.group", table).each(function() {
        var t = $(this);
        var first = $("td.first", t);
        var span = $("span.hid", first);
        var t = span.text();
        if (isup)
            t=t.replace("0000", "zzzz");
        else
            t=t.replace("zzzz", "0000");

        span.text(t);
    });

    // sort them
    var ord = !isup ? "asc" : "desc";
    $("tr", table).tsort("td:eq("+index+")", {order:ord});
}

// quick filter table, all columns
function table_filter(table) {
    if (typeof table == "string") {
        table = $(table);
    }
    // first show all
    $("tr.normal", table).removeClass("hid");

    // hide members
    table_hide_members(table);

    // go through all column filters
    var i = 0;
    $("th", table).each(function() {
        var t = $(this);
        var str = $("input:text", t).val();
        if (str)
            table_col_quick_filter(table, str, i);
        i++;
    });

    if (!show_members)
        $("tr.member", table).addClass("hid");
}

// hide individual table rows
function table_col_quick_filter(table, str, col) {
    $("tr.normal", table).each(function() {
        var t = $(this);
        var match = $("td", t).eq(col).text().toLowerCase().match(str);

        if (!match)
            t.addClass("hid");
    });
}

// show/hide users/groups/members
//function table_showhide(table, showgroups, showmembers, showusers) {
function table_hide_members(table) {
    var showgroups = 0;
    var showusers = 0;
    var showmembers = 0;
    var found = 0;

    var entity = traverseup(table, "entity");
    $("a.checkfilter", entity).each(function() {
        found = 1;

        if ($(this).hasClass("selectedfilter")) {
            var param = $(this).attr("id");
            if (param == "user")
                showusers = 1;
            else if (param == "group") {
                showgroups = 1;
                showmembers = 1;
            }
            return false;
        }
    });

    if (!found)
        return;

    if (showgroups)
        $("tr.group", table).removeClass("hid");
    else
        $("tr.group", table).addClass("hid");
    if (showusers)
        $("tr.user", table).removeClass("hid");
    else
        $("tr.user", table).addClass("hid");
    if (showmembers)
        $("tr.member, tr.membergroup", table).removeClass("hid");
    else
        $("tr.member, tr.membergroup", table).addClass("hid");
}



// PAGE ENTRY POINTS
// ------------------------------------------------------------------
function init_admin_main() {
    init_common_admin();

}

function init_admin_users() {
    init_common_admin();

    $("input.fetchdata").click(function(){
        fetchdata("table#table1", {n: -1});
        return false;
    });
    fetchdata("table#table1", {n: -1});
}

function init_admin_edituser() {
    init_common_admin();

    $("input.fetchdata").click(function(){
        fetchdata("table#table1", {group: 1});
        return false;
    });
    fetchdata("table#table1", {group: 1});
}

function init_admin_editgroup() {
    init_common_admin();

    $("input.fetchdata").click(function(){
        fetchdata("table#table1", {group: 0});
        return false;
    });
    fetchdata("table#table1", {group: 0});
}

function init_admin_editsubgroup() {
    init_common_admin();

    $("div.entity1 input.fetchdata").click(function(){
        fetchdata("table#tablep1", {group: 0});
        return false;
    });
    fetchdata("table#tablep1", {group: 0});

    $("div.entity2 input.fetchdata").click(function(){
        fetchdata("table#table1", {group: 0});
        return false;
    });
    fetchdata("table#table1", {group: 0});
}

function init_admin_newuser() {
    init_common_admin();

    show_checkboxes = true;
    $("input.fetchdata").click(function(){
        fetchdata("table#table1", {group: 1});
        return false;
    });

    $("input, select").removeAttr("disabled");
    $("input[type=text]:first").focus();
    // show checkboxes
    $("th.checkbox, td.checkbox").show();

}

function init_admin_newgroup() {
    init_common_admin();

    show_checkboxes = true;
    $("input.fetchdata").click(function(){
        fetchdata("table#table1", {group: 0});
        return false;
    });

    $("input, select, textarea").removeAttr("disabled");
    $("input[type=text]:first").focus();
    // show checkboxes
    $("th.checkbox, td.checkbox").show();
}

function init_admin_newserv() {
    init_common_admin();
}

function init_admin_serv() {
    init_common_admin();

    $("input.saverights").click(function(){
        var form = $("form#hiddenform");
        send_rights_table_data(form);
        return false;
    });

    $("input.fetchdata").click(function(){
        fetchdata("table#table1", {group: 0});
        return false;
    });
    fetchdata("table#table1", {group: 0});

    // prevent rights table anchors when editing
    $("table#table3 a").click(function(){
        var p = traverseup($(this), "entity");
        if (p.hasClass("edited") || p.hasClass("nolink"))
            return false;
        return true;
    });
}

function init_admin_vd() {
    init_common_admin();
}


function init_admin_services() {
    init_common_admin();

    // debug data: clone td
    var t = $("table.tilattavissa");
    for(i=0; i < 2; i++) {
        var e = $("td:first", t).clone(false);
        $("tr", t).append(e);
    }
    for(i=0; i < 3; i++) {
        var e = $("tr:first", t).clone(false);
        $("tbody", t).append(e);
    }

    $("table.tilattavissa input").click(function() {
        location = "admin-wiz1-service.php";
        return false;
    });
}

function init_admin_delete() {
    init_common_admin();

    show_checkboxes = true;
    show_members = false;
    $("input.fetchdata").click(function(){
        fetchdata("table#table1", {group: 0});
        return false;
    });

    var form = $("form#hiddenform");
    $("input:last", form).attr("value", "delete");

    $("input, select, textarea").removeAttr("disabled");
    $("input[type=text]:first").focus();
    $("th.checkbox, td.checkbox").show();

    $("input.destroy").click(function(){
        if (!confirm($("p#deletemsg").text()))
            return false;

        var form = $("form#hiddenform");
        send_member_table_data(form);
        return false;
    });
    $("div.searchbox").show();

}

function init_admin_wizard() {
    init_common_admin();

    show_checkboxes = true;
    $("input.fetchdata").click(function(){
        fetchdata("table#table1", {n: -1});
        return false;
    });

    $("div.buttons a").click(function(){
        // XXX should really do a form submit here!
        // just following anchor in this demo!
        var h = $(this).attr("href");
        if (h)
            location = h;
        return false;
    });

    // show checkboxes
    $("th.checkbox, td.checkbox").show();
    $("input").removeAttr("disabled");
    if (location.pathname.indexOf("wiz2") > 0) {
        $("a.checkgroup").hide();
    }
    $("input[type=text]:first").focus();
}

function init_admin_wizard_matrix() {
    init_common_admin();

    $("input").removeAttr("disabled");
    $("body").append("<div class='tabletip'></div>");

    $("table.wiz").mousemove(function(e){
        var targ = $(e.target);
        if (!(targ.is("td.cent") || targ.is("input"))) {
            return false;
        }
        $("td.hi, th.hi").removeClass("hi");

        var elem = $(targ);
        var table = traverseup(elem, "table");
        var tr = traverseup(elem, "tr");
        var i = col_index(elem);
        var t1 = $("td:nth(2)", tr).text();
        var t2 = $("th:nth("+i+")", table).text();

        var tip = $("div.tabletip");
        tip.text(t1+" - "+t2);

        // hilight row and cols
        $("td", tr).addClass("hi");
        $("th:nth("+i+")", table).addClass("hi");
        $("tr", table).each(function() {
            $("td:nth("+i+")", this).addClass("hi");
        });

        // move tip
        x = e.pageX + 15;
        y = e.pageY + 5;
        $("div.tabletip").css({"left":x, "top":y});

        return false;
    });

    // show/hide tip
    $("table.wiz").hover(
          function () {
            $("div.tabletip").show();
          },
          function () {
            $("div.tabletip").hide();
          }
    );
}

function init_admin_wizard_service() {
    init_common_admin();

    show_checkboxes = true;
    $("input.fetchdata").click(function(){
        fetchdata("table#table1", {n: -1});
        return false;
    });

    $("div.buttons a").click(function(){
        // XXX should really do a form submit here!
        // just following anchor in this demo!
        var h = $(this).attr("href");
        if (h)
            location = h;
        return false;
    });

    $("td a").click(function(){
        return false;
    });

    // show checkboxes
    $("th.checkbox, td.checkbox").show();
    $("input").removeAttr("disabled");
    if (location.pathname.indexOf("wiz2") > 0) {
        $("a.checkgroup").hide();
    }
    $("input[type=text]:first").focus();
}

function init_admin_serv_folders() {
    init_common_admin();
}


