﻿Ext.namespace('FinnKodeWeb');

FinnKodeWeb.PanelSynonyms = function(config) {
    config = config || {};

    var tpl = new Ext.XTemplate(
        '<table style="font: normal 11px tahoma,arial,helvetica,sans-serif;">',
        '<tr><th>Nr</th><th>Bokseksjon</th><th>Nøkkelord</th><th>Synonymer</th></tr>',
        '<tpl for=".">',
            '<tr valign="top">',
                '<td nowrap>{#}</td>',
                '<td nowrap>{bookSectionName}</td>',
                '<td nowrap>{keyword}</td>',
                '<td nowrap>{synonymList}</td>',
            '</tr>',
        '</tpl>',
      '</table>'
    );
    tpl.compile();

    var xmlStore = new Ext.data.XmlStore({
        autoDestroy: true,
        storeId: 'synonymsStore',
        record: 'bookSection/entry',
        url: 'FinnKodeWS/ReportService.svc/GetSynonyms',
        fields: [
            { name: 'keyword' },
            {
                name: 'bookSectionName',
                convert: function(v, rec) {
                    return rec.parentNode.getAttribute('commonName');
                }
            },
            {
                name: 'synonymList',
                convert: function(v, rec) {
                    var synonymList = rec.childNodes[1].firstChild.nodeValue;
                    for (var idx = 2; idx < rec.childNodes.length; idx++) {
                        synonymList += ', ' + rec.childNodes[idx].firstChild.nodeValue;
                    }
                    return synonymList;
                }
            }
        ]
    });

    var failureFunction = function() {
        Ext.Msg.show({
            title: 'Vis synonymer',
            msg: 'Vis synonymer feilet',
            buttons: Ext.Msg.OK,
            icon: Ext.Msg.ERROR
        });
    };

    var afterLoadFunction = function(r, options, success) {
        if (!success) {
            failureFunction();
        }
    };

    Ext.apply(config, {
        listeners: {
            activate: {
                fn: function() {
                    xmlStore.load({
                        callback: afterLoadFunction,
                        scope: this,
                        add: false
                    });
                },
                single: true
            }
        },
        items: new Ext.DataView({
            store: xmlStore,
            tpl: tpl,
            loadingText: 'Laster synonymer. Dette tar litt tid... '
        })
    });
    FinnKodeWeb.PanelSynonyms.superclass.constructor.call(this, config);
};

Ext.extend(FinnKodeWeb.PanelSynonyms, Ext.Panel);
