// vk-view-mbf:

/*
Syntaxprüfung mit jslint:
java -cp jslint/rhino-1.7.jar \
  org.mozilla.javascript.tools.shell.Main jslint/jslint.js vk-view-mbf.js
*/

/*jslint newcap: false */
/*global $: false, VKView: false
 */

var VKViewInfo = function (conf) {
    var that = VKView(conf),
    buttonCont,
    textCont,
    textContParentDisplay,
    infoTextIsHere = false,

    infoTextLoad = function (catId) {
        $.ajax({url:  'cat-info.html',
                type: 'GET',
                dataType: 'html',
                data: { c: catId },
                success: function (info) {
                    $("div.infoTxt div", textCont).html(info);
                    infoTextIsHere = true;
                },
                error: function (xhr, status, exception) {
                    // alert('cat-'+args["cat"].id+' error: "'+status+'"');
                    $("div.infoTxt", textCont).
                    html('Kataloginfo konnte nicht geladen werden.');
                }
            });
    },

    info = function (event) {
        var inf;
        if (textCont.parent().css('display') !== 'none') {
            textCont.parent().css('display', 'none');
        }
        else {
            textCont.parent().css('display', textContParentDisplay);
            if (!infoTextIsHere) {
                infoTextLoad(conf.cat.id);
            }
        }
        return (false);
    },

    create = function () {
        var html, inf;
        html = 
        //'<td class="info">' + "\n" + 
          '<a title="Infos über den Katalog bzw. Datenbank" ' + 
             'href="#">' + "\n" + 
            '<img src="images/i.gif">' + "\n" + 
        '<\/a>' + "\n";
        //'<\/td>' + "\n";
        buttonCont = conf.buttonCont;
        buttonCont.append(html);
        $("a", buttonCont).bind("click", info);
        textCont = conf.textCont;
        textContParentDisplay = textCont.parent().css('display');
        textCont.parent().css('display', 'none');
        inf =
        '<div class="infoTxt">' +
          '<a class="close" href="#">' +
            '<img src="images/zu.gif" alt="Schliessen" ' +
                 'align="right" border="0" title="Schliessen">' +
          '<\/a>' + 
          '<div>' +
            '<img src="images/waits.gif">' +
          '<\/div>' +
          conf.text +
        '<\/div>';
        textCont.append(inf);
        $('a.close', textCont).bind("click", info);
    },

    vk_delete = function () {
    };

    that.create = create;
    that.vk_delete = vk_delete;

    create();

    return (that);
};


var VKViewCatSel = function (confP) {
    var that = VKView(confP),
    cat,
    conf = confP,
    container,
    infoContainer,
    txts,
    lengthCnt,
    mode = conf.menu.selectionGet(),
    matCheck = function () {
        /*
        var mats = conf.mat.matsGet();
        // if (cat.isSelected()) {
        // alert("update catSelView of cat "+cat.id+" hint=mat");
        if ((mode === "simpleSearch") || (mats === null)) {
            // container.removeClass("nomat"); // kann IE nicht, deshalb:
            container.css("background-color", "#ffffff");
            container.removeAttr("title");
        }
        else {
            if (cat.hasMats(mats)) {
		// container.removeClass("nomat"); // kann IE nicht, deshalb:
                container.css("background-color", "#ffffff");
                container.removeAttr("title");
            }
            else {
		// container.addClass("nomat"); // kann IE nicht, deshalb:
                container.css("background-color", "#E8CCCC");
                container.attr("title", 
                               "Materialsuche wird nicht unterstützt " +
                               "oder ist noch nicht angeschlossen");
            }
        }
        */
    },
    datesCheck = function () {
        var catDates = conf.cat.conf.dates,
        ok, date = $("input#qx_date").val(), dates;
        //alert(date);
        if (date.match(/^\s*$/)) {
            dates = '';
        }
        else if (date.match(/-/)) {
            dates = 'yi';
        }
        else {
            dates = 'y';
        } 
        if (dates === '') {
            ok = true;
        }
        else if (!catDates) {
            ok = false;
        } 
        else if (catDates.match('^' + dates + '')) {
            ok = true;
        }
        else {
            ok = false;
        }
        if (ok) {
            // container.removeClass("nomat"); // kann IE nicht, deshalb:
            container.css("background-color", "#ffffff");
            container.removeAttr("title");
        }
        else {
            // container.addClass("nomat"); // kann IE nicht, deshalb:
            container.css("background-color", "#E8CCCC");
            if (dates === 'y') {
                container.attr("title", 
                               'Jahr Sucheinschränkung wird ' +
                               'nicht unterstützt');
            }
            else { // 'yi'
                container.attr("title", 
                               'Sucheinschränkung auf einen Zeitbereich ' +
                               'wird nicht unterstützt');
            }
        }
    },
    create = function () {
        var catId, checked, disabled, html, visibility;
        cat = conf.cat;
        catId = cat.id;
        checked = (cat.isSelected()) ? ' checked="checked"' : '';
        visibility = (cat.isSelected()) ? '' : ' style="visibility: hidden;"';
        disabled = '';
        html =
                '<tr class="vkBox cat" name="vkCatSel">' + "\n" + 
                //'<div>' + "\n" + 
                    '<td class="nav">' + "\n";
	    if (!cat.isIndexCat()) {
		html +=
                      '<a href="#vkCatHits-' + catId + '" ' + 
                         'title="Zur Trefferliste" >' + 
                        '<img src="images/arrow-down.png"' + visibility + '>' + 
                      '<\/a>' + "\n";
		}
	html +=
                    '<\/td>' + "\n" + 
                    '<td class="sel">' + "\n" + 
                      '<input type="checkbox"' + checked + disabled + 
                             ' name="cats" ' + 'value="' + catId + '"' + 
                             ' id="cat-sel-' + catId + '">' + "\n" + 
                    '<\/td>' + "\n" + 
                    '<td class="info"><\/td>' + "\n" + 
                    '<td class="name">' + "\n" + 
                    //'<label for="cat-sel-' + catId + '">' + "\n" + 
                        cat.nameGet() + "\n" + 
                    //'<\/label>' + "\n" + 
                    '<\/td>' + "\n" + 
                    '<td class="cnt"><\/td>' + "\n" + 
                //'<\/div>' + "\n" + 
                '<\/tr>' + "\n" + 
                '<tr class="infoTxt"><td colspan="5"><\/td><\/tr>' + "\n";
        conf.container.append($(html));
        container = $('tr.vkBox[name=vkCatSel]', conf.container).last();
        infoContainer = $('tr.infoTxt', conf.container).last();
	if (cat.urlGet() === '') {
	    html = '';
	}
	else {
	    html =  
              '<a class="externerLink" target="_blank" ' + 
                 'href="' + cat.urlGet() + '" ' + 
                 'title="' + t('Externer Link') + ': ' + 
                 cat.nameGet().replace(new RegExp('<[^>]+>', 'g'), '') +
                  '">' + 
                  '» ' + t('Direkt zu diesem Katalog') + '<\/a>';
          //'<\/div>';
	}
        VKViewInfo({cat: cat,
                    buttonCont: $("td.info", container).last(),
                    cont: conf.container,
                    text: html,
                    textCont: $("td", infoContainer)});
        lengthCnt = $("td.cnt", container);
        conf.cat.updateableAdd(that);
        conf.mat.updateableAdd(that);
        conf.menu.updateableAdd(that);
        conf.queryVwA.updateableAdd(that);
        $('input:checkbox', container).bind("update", function (event) {
                var checked = this.checked;
                cat.select(checked);
                matCheck();
                datesCheck();
            });
        txts = conf.lang.attach(container);
        conf.queryHistory.updateableAdd(that);
        datesCheck();
    },
    vk_delete = function () {
        conf.lang.detach(txts);
        infoContainer.remove();
        container.remove();
    },
    update = function (src, args) {
        var cats, hint, i, length, select, combiMode;
        hint = args ? (args.hint ? args.hint : null) : null;	
        if (hint === 'hits') {
            $('td.cnt', container).empty();
        }
        else if (hint === 'mat') {
            matCheck();
        }
        else if (hint === 'dates') {
            //alert(args.dates);
            datesCheck();
        }
        else if (hint === 'menu') {
            mode = conf.menu.selectionGet();
            matCheck();
            datesCheck();
        }
        else if (hint === 'searching') {
            $('td.cnt', container).html('<img src="images/waits.gif">');
        }
        else if (hint === 'search-error') {
            $('td.cnt', container).text('E');
        }
        else if ((hint === "query-history") ||
                 (hint === "query-history-select")) {
            cats = src.sel().catsGet();
            select = false;
            for (i = 0; i < cats.length; i += 1) {
                if (cat === cats[i]) {
                    select = true;
                    break;
                }
            }
	    if ($.isCombiSearch()) {
		combiMode = conf.menuCombiSearch.selectionGet();
		if (cat.isIndexCat() && (combiMode === 'indexSearch')) {
		    cat.select(select);
		}
		else if (!cat.isIndexCat() && (combiMode === 'externSearch')) {
		    cat.select(select);
		}
	    }
	    else {
		cat.select(select);
	    }
        }

        if (cat.isSelected()) {
            length = cat.hitsLengthGet();
            if (length !== null) {
                /*
                if (length > 1000) {
                    length = '>1000';
                }
                */
                lengthCnt.html(length);
            }
            $('td.nav img', container).css('visibility', 'visible');
            $('td.sel input', container).attr('checked', 'checked');
        }
        else {
            lengthCnt.html('');
            $('td.nav img', container).css('visibility', 'hidden');
            $('td.sel input', container).removeAttr('checked');
        }
    },
    updateLength = function (length) {
        lengthCnt.html(length);
    };

    that.create = create;
    that.vk_delete = vk_delete;
    that.update = update;
    that.updateLength = updateLength;

    create();

    return (that);
};


var VKViewCatsSelTree = function (conf) {
    var that = VKView(conf),
    combiMode = conf.combiMode,
    catsSelCnt,
    treeCnt,
    txts,
    cats_tree_create = function (cnt, tree, cats, depth, id) {
        var cat, catId, catIds, catSelVw, child, children,
        cnt2, cnt3, cnt4, html, i, info, len,
        lid, name, select, text, url;
        lid = depth * 10 + id;
        select = '<input type="checkbox" id="cat-sel-' + lid + '">' + "\n";
        name = tree.name;
        info = tree.info;
        url = tree.url;
        html =
          '<tr class="li-' + lid + ' grp d' + depth + '">' + "\n";              
        if (name) {
            html += 
              '<td class="nav">' + "\n";
	    if (!($.isCombiSearch() && (combiMode === 'indexSearch'))) {
            html += 
                '<a href="#">' + 
                  '<img src="images/arrow-down.png" ' + 
                       'style="visibility: hidden;">' + 
                '<\/a>' + "\n";
	    }
            html += 
              '<\/td>' + "\n";
	    html += 	    
              '<td class="sel">' + "\n" + 
                select + 
              '<\/td>' + "\n";
            html += 
                '<td class="info"><\/td>' + "\n";
            html += 
                '<td class="name">' + "\n" + 
                //'<label for="cat-sel-' + lid + '">' + "\n" + 
                    name + "\n" + 
                //'<\/label>' + "\n" + 
                '<\/td>' + "\n";
            html += 
                '<td class="cnt"><\/td>' + "\n";
            if (info) {
                html += 
                '<tr class="infoTxt"><td colspan="5"><\/td><\/tr>' + "\n";
            }
            /*
            if (info) {
                html += 
                '<div class="info"><\/div>' + "\n";
            }
            html += 
              '<\/div>' + "\n";
            if (info) {
                html += 
                '<div class="infoTxt"><\/div>' + "\n";
            }
            */
        }
        catIds = tree.catIds;
        children = tree.children;
        html +=
        '<\/tr>' + "\n";
        cnt.append($(html));
        if (info) {
            text = info;
            if (name && url && (!($url === ''))) {
                text +=
              '<br><br>' + 
              '<a class="externerLink" target="_blank" ' + 
                 'href="' + url + '" ' + 
                 'title="Externer Link: ' + name + '">' + 
                '» Direkt zum Katalog ' + name + '<\/a>';
            }
            cnt2 = $("tr.li-" + lid, cnt);
            VKViewInfo({buttonCont:  $("td.info", cnt).last(),
                        cont: cnt,
                        text: text,
                        textCont: $('tr.infoTxt td', conf.cnt).last()});
        }
        if (catIds) {
            /*
            cnt2 = $("li.li-" + lid, cnt);
            html =
              '<ul' + "\n";
            html +=
              '<\/ul>' + "\n";
            cnt2.append($(html));
            */
            len = catIds.length;
            //cnt3 = $("ul", cnt2);
            for (i = 0; i < len; i += 1) {
                catId = catIds[i];
                /*
                html =
                '<tr class="cat" id="' + catId + '"><\/tr>' + "\n";
                cnt.append($(html));
                cnt4 = $("tr#" + catId, cnt);
                */
                cat = cats.catGetById(catId);
                catSelVw = VKViewCatSel({cat: cat,
                                         container: cnt,
                                         lang: conf.lang,
                                         mat: conf.mat,
					 menuCombiSearch: conf.menuCombiSearch,
                                         menu: conf.menu,
                                         queryHistory: conf.queryHistory,
                                         queryVwA: conf.queryVwA});
            }
        }
        if (children) {
            //cnt2 = $("li.li-" + lid, cnt);
            len = children.length;
            for (i = 0; i < len; i += 1) {
                child = children[i];
                cats_tree_create(cnt, child, cats, depth + 1, i + 1);
            }
        }
    },
    create = function () {
        var cat, catContainer, catId, cats, catsList, catSelVw, html, id,
        tree, style;

	if ($.isCombiSearch()) {
            conf.menuCombiSearch.updateableAdd(that);
	    cats = (combiMode === 'indexSearch')
		    ? conf.indexCats : conf.cats;
	    conf.indexCats.catGetById('index').updateableAdd(that);
	}
	else {
            cats = conf.cats;
	}

        tree = cats.catsTreeConfGet();

        style = "";
        /*
        if (conf.lang.keys().length <= 1) {
            style = ' style="position: relative; top: -2.6em"';
        }
        */
        html = 
        '<div class="vkBox" name="vkCatsSel"' + style + '>\n';
        html += 
        '<button class="del">' + t('Auswahl löschen') + '<\/button>' + "\n";

        html +=
        '<table id="cats_tree">' + "\n"  + 
        '<\/table>' + "\n";

        html += 
	'<br>' +
        '<div>' + 
          '<img src="images/noYaMS-mbf-' + $.getFach() + '-poweredBy' +
	             '.png" alt="noYaMS-Logo" ' + 
               'align="right" border="0" ' + 
               'title="noYaMS - not only Yet another Metasearch Software">' +
        '<\/div>\n';

        html += 
        '<\/div>\n';

	conf.container.append($(html));
	/*
        // Katalogauswahl NICHT für die Indexsuche anzeigen
        if (combiMode !== 'indexSearch') {
            conf.container.append($(html));
        }
	*/

        catsSelCnt = $("div.vkBox[name=vkCatsSel]", conf.container);

        treeCnt = $("table#cats_tree", catsSelCnt);

        cats_tree_create(treeCnt, tree, cats, 0, 1);

        $('label', treeCnt).css('cursor', 'pointer');
        $('input', treeCnt).css('cursor', 'pointer');

        $('input:checkbox', treeCnt).click(function (event) {
                var checked, checkboxes, classes, depth, m, start, stop;
                if (this === event.target) {
                    checked = this.checked;
                    classes = $(this).parent().parent().attr('class');
                    if ((m = classes.match('\\bd(\\d)\\b')) !== null) {
                        depth = m[1];
                    }
                    else {
                        if (!this.disabled) {
                            this.checked = checked;
                            $(this).trigger('update', this);
                        }
                        return (true);
                    }
                    start = false;
                    stop = false;
                    checkboxes = $("table#cats_tree input:checkbox");
                    checkboxes.each(function (n) {
                            var d = null;
                            if (stop) {
                                return;
                            }
                            if (start) {
                                classes = 
                                    $(this).parent().parent().attr('class');
                                if ((m = classes.match('\\bd(\\d)\\b')) !== null) {
                                    d = m[1];
                                    if (d <= depth) {
                                        stop = true;
                                        return;
                                    }
                                    else {
                                        if (!this.disabled) {
                                            this.checked = checked;
                                        }
                                    }
                                }
                                if (!this.disabled) {
                                    this.checked = checked;
                                    $(this).trigger('update', this);
                                }
                            }
                            if (this === event.target) {
                                start = true;
                            }
                        });
                }
            });

        // txts = lang.attach(treeCnt);

        $("button.del", catsSelCnt).bind('click', function () {
                var checkboxes, checked;
                checkboxes = $("input:checkbox", treeCnt);
                checked = false;
                checkboxes.each(function (n) {
                        if (!this.disabled) {
                            this.checked = checked;
                            $(this).trigger('update', this);
                        }
                    });         
            });
    },
    vk_delete = function () {
        // lang.detach(txts);
	if ($.isCombiSearch()) {
	    conf.indexCats.catGetById('index').updateableRemove(that);
            conf.menuCombiSearch.updateableRemove(that);
	}
        //treeCnt.remove();
	catsSelCnt.remove();
    },
    update = function (src, args) {
	var combiModeC = conf.menuCombiSearch.selectionGet(),
        hint = args ? args.hint : null, hits, cat_fc, i, id, c, cat, cats;
	if (combiModeC !== combiMode) {
	    combiMode = combiModeC;
	    vk_delete();
	    create();
	}
	if (hint === 'hits') {
	    hits = src.hitsGet();
	    cats = conf.indexCats.listGet();
	    for (i = 0; i < cats.length; i++) {
		cat = cats[i].hitsLengthSet(0);
	    }
	    if (hits.facet_counts && hits.facet_counts.facet_fields.cat_fc) {
		cat_fc = hits.facet_counts.facet_fields.cat_fc;
		for (i = 0; i < cat_fc.length; i += 2) {
		    id = cat_fc[i];
		    c = cat_fc[i+1];
		    cat = conf.indexCats.catGetById(id);
		    cat.hitsLengthSet(c);
		}
	    }
	    for (i = 0; i < cats.length; i++) {
		cats[i].updateUpdateables('', {});
	    }
	}
    };

    that.create = create;
    that.vk_delete = vk_delete;
    that.update = update;

    create(conf.container);

    return (that);
};
