﻿/*!
* Ext JS Library 3.3.1
* Copyright(c) 2006-2010 Sencha Inc.
* licensing@sencha.com
* http://www.sencha.com/license
*/


// vim: ts=4:sw=4:nu:fdc=4:nospell
/**
* Search plugin for Ext.grid.GridPanel, Ext.grid.EditorGrid ver. 2.x or subclasses of them
*
* @author    Ing. Jozef Sakalos
* @copyright (c) 2008, by Ing. Jozef Sakalos
* @date      17. January 2008
* @version   $Id: Ext.ux.grid.Search.js 11 2008-02-22 17:13:52Z jozo $
* 
* @author    Ing. Christophe Irles (filter mode options added)
* @date      11. March 2008
*
* @license Ext.ux.grid.Search is licensed under the terms of
* the Open Source LGPL 3.0 license.  Commercial use is permitted to the extent
* that the code/component(s) do NOT become part of another Open Source or Commercially
* licensed development library or toolkit without explicit permission.
* 
* License details: http://www.gnu.org/licenses/lgpl.html
*/

Ext.namespace('Ext.ux', 'Ext.ux.grid');

/**
* @class Ext.ux.grid.Search
* @extends Ext.util.Observable
* @param {Object} config configuration object
* @constructor
*/
Ext.ux.grid.Search = function (config) {
    Ext.apply(this, config);
    Ext.ux.grid.Search.superclass.constructor.call(this);
}; // eo constructor

Ext.extend(Ext.ux.grid.Search, Ext.util.Observable, {
    /**
    * @cfg {String} searchText Text to display on menu button
    */
    searchText: 'Search'
    /**
    * @cfg {String} searchTipText Text to display as input tooltip. Set to '' for no tooltip
    */
    , searchTipText: 'Type a text to search and press Enter'
    /**
    * @cfg {String} selectAllText Text to display on menu item that selects all fields
    */
    , selectAllText: 'Select All'
    /**
    * @cfg {String} position Where to display the search controls. Valid values are top and bottom (defaults to bottom)
    * Corresponding toolbar has to exist at least with mimimum configuration tbar:[] for position:top or bbar:[]
    * for position bottom. Plugin does NOT create any toolbar.
    */
    , position: 'bottom'
    /**
    * @cfg {String} iconCls Icon class for menu button (defaults to icon-magnifier)
    */
    , iconCls: 'icon-magnifier'
    /**
    * @cfg {String/Array} checkIndexes Which indexes to check by default. Can be either 'all' for all indexes
    * or array of dataIndex names, e.g. ['persFirstName', 'persLastName']
    */
    , checkIndexes: 'all'
    /**
    * @cfg {Array} disableIndexes Array of index names to disable (not show in the menu), e.g. ['persTitle', 'persTitle2']
    */
    , disableIndexes: []

    /**
    * @cfg {String} dateFormat how to format date values. If undefined (the default) 
    * date is formatted as configured in colummn model
    */
    , dateFormat: undefined
    /**
    * @cfg {Boolean} showSelectAll Select All item is shown in menu if true (defaults to true)
    */
    , showSelectAll: true
    /**
    * @cfg {String} mode Use 'remote' for remote stores or 'local' for local stores. If mode is local
    * no data requests are sent to server the grid's store is filtered instead (defaults to 'remote')
    */
    , mode: 'remote'
    /**
    * @cfg {Number} width Width of input field in pixels (defaults to 100)
    */
    , width: 100
    /**
    * @cfg {String} xtype xtype is usually not used to instantiate this plugin but you have a chance to identify it
    */
    , xtype: 'gridsearch'
    /**
    * @cfg {Object} paramNames Params name map (defaults to {fields:'fields', query:'query'}
    */
    , paramNames: {
        fields: 'fields'
        , query: 'query'
    }
    /**
    * @cfg {String} shortcutKey Key to fucus the input field (defaults to r = Sea_r_ch). Empty string disables shortcut
    */
    , shortcutKey: 'r'
    /**
    * @cfg {String} shortcutModifier Modifier for shortcutKey. Valid values: alt, ctrl, shift (defaults to alt)
    */
    , shortcutModifier: 'alt'

    /**
    * @cfg {Boolean} showAdvancedFilters Display the advanced filter options
    */
    , showAdvancedFilters: true
    /**
    * @cfg {String} advancedFilterSet Used to specify the filter mode 'contain' or 'begin' 
    */
    , advancedFilterSet: 'contain'
    /**
    * @cfg {String} containFilterText Text to display for the 'contain' sort mode
    */
    , containFilterText: 'Search on the whole contain'
    /**
    * @cfg {String} beginFilterText Text to display for the 'begin' sort mode
    */
    , beginFilterText: 'Search on the beginning only'
    /**
    * @cfg {String} shortcutModifier Modifier for shortcutKey. Valid values: alt, ctrl, shift (defaults to alt)
    */
    , shortcutModifier: 'alt'
    /**
    * @cfg {String} shortcutModifier Modifier for shortcutKey. Valid values: alt, ctrl, shift (defaults to alt)
    */
    , shortcutModifier: 'alt'
    /**
    * @cfg {String} shortcutModifier Modifier for shortcutKey. Valid values: alt, ctrl, shift (defaults to alt)
    */
    , shortcutModifier: 'alt'

    /**
    * @cfg {String} align 'left' or 'right' (defaults to 'left')
    */
    /**
    * @cfg {Number} minLength force user to type this many character before he can make a search
    */

    // {{{
    /**
    * private
    * @param {Ext.grid.GridPanel/Ext.grid.EditorGrid} grid reference to grid this plugin is used for
    */
    , init: function (grid) {
        this.grid = grid;

        // do our processing after grid render and reconfigure
        grid.onRender = grid.onRender.createSequence(this.onRender, this);
        grid.reconfigure = grid.reconfigure.createSequence(this.reconfigure, this);
    } // eo function init
    // }}}
    // {{{
    /**
    * private add plugin controls to <b>existing</b> toolbar and calls reconfigure
    */
    , onRender: function () {
        var grid = this.grid;
        var tb = 'bottom' == this.position ? grid.bottomToolbar : grid.topToolbar;

        // add menu
        this.menu = new Ext.menu.Menu();

        // handle position
        if ('right' === this.align) {
            tb.addFill();
        }
        else {
            tb.addSeparator();
        }

        // add menu button
        tb.add({
            text: this.searchText
            , menu: this.menu
            , iconCls: this.iconCls
        });

        // add input field (TwinTriggerField in fact)
        this.field = new Ext.form.TwinTriggerField({
            width: this.width
            , selectOnFocus: undefined === this.selectOnFocus ? true : this.selectOnFocus
            , trigger1Class: 'x-form-clear-trigger'
            , trigger2Class: 'x-form-search-trigger'
            , onTrigger1Click: this.onTriggerClear.createDelegate(this)
            , onTrigger2Click: this.onTriggerSearch.createDelegate(this)
            , minLength: this.minLength
        });

        // install event handlers on input field
        this.field.on('render', function () {
            this.field.el.dom.qtip = this.searchTipText;

            // install key map
            var map = new Ext.KeyMap(this.field.el, [{
                key: Ext.EventObject.ENTER
                , scope: this
                , fn: this.onTriggerSearch
            }, {
                key: Ext.EventObject.ESC
                , scope: this
                , fn: this.onTriggerClear
            }]);
            map.stopEvent = true;
        }, this, { single: true });

        tb.add(this.field);

        // reconfigure
        this.reconfigure();

        // keyMap
        if (this.shortcutKey && this.shortcutModifier) {
            var shortcutEl = this.grid.getEl();
            var shortcutCfg = [{
                key: this.shortcutKey
                , scope: this
                , stopEvent: true
                , fn: function () {
                    this.field.focus();
                }
            }];
            shortcutCfg[0][this.shortcutModifier] = true;
            this.keymap = new Ext.KeyMap(shortcutEl, shortcutCfg);
        }
    } // eo function onRender
    // }}}
    // {{{
    /**
    * private Clear Trigger click handler
    */
    , onTriggerClear: function () {
        this.field.setValue('');
        this.field.focus();
        this.onTriggerSearch();
    } // eo function onTriggerClear
    // }}}
    // {{{
    /**
    * private Search Trigger click handler (executes the search, local or remote)
    */
    , onTriggerSearch: function () {
        if (!this.field.isValid()) {
            return;
        }
        var val = this.field.getValue();
        var store = this.grid.store;
        var advancedFilterSet = 'contain';

        // grid's store filter
        if ('local' === this.mode) {
            if (this.showAdvancedFilters) {
                this.menu.items.each(function (item) {
                    if (item.checked && item.id == 'begin') advancedFilterSet = item.id;
                });
            }

            store.clearFilter();
            if (val) {
                store.filterBy(function (r) {
                    var retval = false;
                    this.menu.items.each(function (item) {
                        if (!item.checked || retval || item.group != null) {
                            return;
                        }
                        var rv = r.get(item.dataIndex);
                        rv = rv instanceof Date ? rv.format(this.dateFormat || r.fields.get(item.dataIndex).dateFormat) : rv;
                        var re = (advancedFilterSet == 'begin') ? (new RegExp('^' + val, 'i')) : (new RegExp(val, 'gi'));
                        retval = re.test(rv);
                    }, this);
                    if (retval) {
                        return true;
                    }
                    return retval;
                }, this);
            }
            else {
            }
        }
        // ask server to filter records
        else {
            // clear start (necessary if we have paging)
            if (store.lastOptions && store.lastOptions.params) {
                store.lastOptions.params[store.paramNames.start] = 0;
            }

            // get fields to search array and filter mode
            var fields = [];
            var advancedFilterSet = 'contain';
            this.menu.items.each(function (item) {
                if (item.checked && item.group == null) {
                    fields.push(item.dataIndex);
                }
                if (item.checked && item.id == 'begin') {
                    advancedFilterSet = item.id;
                }
            });


            // add fields, query and filter mode to baseParams of store
            delete (store.baseParams[this.paramNames.fields]);
            delete (store.baseParams[this.paramNames.query]);
            if (store.lastOptions && store.lastOptions.params) {
                delete (store.lastOptions.params[this.paramNames.fields]);
                delete (store.lastOptions.params[this.paramNames.query]);
                if (showAdvancedFilters) delete (store.lastOptions.params[this.paramNames.filterMode]);
            }
            if (fields.length) {
                store.baseParams[this.paramNames.fields] = Ext.encode(fields);
                store.baseParams[this.paramNames.query] = val;
                if (showAdvancedFilters) store.baseParams[this.paramNames.filterMode] = advancedFilterSet;
            }

            // reload store
            store.reload();
        }

    } // eo function onTriggerSearch
    // }}}
    // {{{
    /**
    * @param {Boolean} true to disable search (TwinTriggerField), false to enable
    */
    , setDisabled: function () {
        this.field.setDisabled.apply(this.field, arguments);
    } // eo function setDisabled
    // }}}
    // {{{
    /**
    * Enable search (TwinTriggerField)
    */
    , enable: function () {
        this.setDisabled(false);
    } // eo function enable
    // }}}
    // {{{
    /**
    * Enable search (TwinTriggerField)
    */
    , disable: function () {
        this.setDisabled(true);
    } // eo function disable
    // }}}
    // {{{
    /**
    * private (re)configures the plugin, creates menu items from column model
    */
    , reconfigure: function () {
        var field = this.field;
        var minLength = this.minLength;
        var advancedFilterSet = this.advancedFilterSet;
        // {{{
        // remove old items
        var menu = this.menu;
        menu.removeAll();

        // add advanced sort items plus separator
        if (this.showAdvancedFilters) {
            menu.add(new Ext.menu.CheckItem({
                text: this.containFilterText
                , checked: (advancedFilterSet === 'contain')
                , group: 'advancedFilter'
                , hideOnClick: false
                , id: 'contain'
                , handler: function (item) {
                    field.minLength = minLength;
                }
            }));
            menu.add(new Ext.menu.CheckItem({
                text: this.beginFilterText
                , checked: (advancedFilterSet === 'begin')
                , group: 'advancedFilter'
                , hideOnClick: false
                , id: 'begin'
                , handler: function (item) {
                    field.minLength = null;
                }
            }), '-');
        }

        // add Select All item plus separator
        if (this.showSelectAll) {
            menu.add(new Ext.menu.CheckItem({
                text: this.selectAllText
                , checked: !(this.checkIndexes instanceof Array)
                , hideOnClick: false
                , handler: function (item) {
                    var checked = !item.checked;
                    item.parentMenu.items.each(function (i) {
                        if (item !== i && i.setChecked && i.group == null) {
                            i.setChecked(checked);
                        }
                    });
                }
            }), '-');
        }

        // }}}
        // {{{
        // add new items
        var cm = this.grid.colModel;
        Ext.each(cm.config, function (config) {
            var disable = false;
            if (config.header && config.dataIndex) {
                Ext.each(this.disableIndexes, function (item) {
                    disable = disable ? disable : item === config.dataIndex;
                });
                if (!disable) {
                    menu.add(new Ext.menu.CheckItem({
                        text: config.header
                        , hideOnClick: false
                        , checked: 'all' === this.checkIndexes
                        , dataIndex: config.dataIndex
                    }));
                }
            }
        }, this);
        // }}}
        // {{{
        // check items
        if (this.checkIndexes instanceof Array) {
            Ext.each(this.checkIndexes, function (di) {
                var item = menu.items.find(function (itm) {
                    return itm.dataIndex === di;
                });
                if (item) {
                    item.setChecked(true, true);
                }
            }, this);
        }
        // }}}

    } // eo function reconfigure
    // }}}

}); // eo extend

function XML2JS(xmlDoc, containerTag) {
    var output = new Array();
    var rawData = xmlDoc.getElementsByTagName(containerTag)[0];
    var i, j, oneRecord, oneObject;
    var nbRow = rawData.childNodes.length;
    if (rawData.childNodes.length > 0)
        nbRow = nbRow - 4;
    for (i = 0; i < nbRow; i++) {
        if (rawData.childNodes[i].nodeType == 1) {
            oneRecord = rawData.childNodes[i];
            oneObject = output[output.length] = new Array();
            for (j = 0; j < oneRecord.childNodes.length; j++) {
                if (oneRecord.childNodes[j].nodeType == 1) {
                    if (oneRecord.childNodes[j].firstChild != null) {
                        if (oneRecord.childNodes[j].textContent) {
                            oneObject[j] = oneRecord.childNodes[j].textContent
                        }
                        else {
                            oneObject[j] = oneRecord.childNodes[j].firstChild.nodeValue;
                        }
                    }
                    else
                        oneObject[j] = '';
                }
            }
        }
    }
    return output;
}


function openEmailPopup(unid, db_path) {
    if (db_path != '') {
        db_path = db_path.toString().substring(4);
        var left = (screen.width / 2) - (800 / 2);
        var top = (screen.height / 2) - (600 / 2);
        window.open('http://' + portalPath + skinPath + 'redirectc.aspx?UNID=' + unid + '&DB=' + db_path, 'Email', 'height=600, width=800, toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, directories=no, status=no,top=' + top + ', left=' + left);
    }
    else {
        document.URL = 'http://' + portalPath + unid;
    }
}



    //begin repertoire
    //var buttonRep = Ext.get('repertoireTelephonique');
    var winRep;


    var storeRep = new Ext.data.GroupingStore({
        // load using HTTP
        url: 'http://' + portalPath + skinPath + 'xml/phone_numbers.xml',
        groupField: 'Site',
        remoteSort: true,
        // the return will be XML, so lets set up a reader
        reader: new Ext.data.XmlReader({
            // records will have an "Item" tag
            record: 'Num',
            id: 'Matricule',
            totalRecords: '@TotalResults'
        }, [
        // set up the fields mapping into the xml doc
        // The first needs mapping, the others are very basic

               'NomPrenom', 'Num1', 'Num2', 'NumSDA', 'Site', 'NumIP'
           ])
    });




    //buttonRep.on('click', myFunction1);
    function ShowPhoneNumbersPopup() {
        if (winRep)
        { }
        else {

            storeRep.load();

            var gridRep = new Ext.grid.GridPanel({
                store: storeRep,
                trackMouseOver: false,
                disableSelection: true,
                loadMask: true,
                columns: [
            { header: "Nom et prénom", width: 180, dataIndex: 'NomPrenom', sortable: true },
            { header: "Numéro 1", width: 75, dataIndex: 'Num1', sortable: true },
            { header: "Numéro 2", width: 75, dataIndex: 'Num2', sortable: true },
            { header: "Site", width: 100, dataIndex: 'Site', sortable: true, hidden: true },
            { header: "Numéro SDA", width: 100, dataIndex: 'NumSDA', sortable: true },
            { header: "Numéro IP", width: 100, dataIndex: 'NumIP', sortable: true }
        ],
                view: new Ext.grid.GroupingView({
                    forceFit: true,
                    groupTextTpl: '{text} ({[values.rs.length]} {[values.rs.length > 1 ? "Items" : "Item"]})'
                }),
                renderTo: 'example-grid',
                width: 540,
                height: 500,
                animCollapse: false,
                iconCls: 'icon-grid',
                tbar: [],
                plugins: [new Ext.ux.grid.Search({
                    mode: 'local'
            , iconCls: false
            , dateFormat: 'm/d/Y'
            , minLength: 2
            , position: 'top'
                })]

            });
            // 

            winRep = new Ext.Window({
                // applyTo:'hello-win',
                layout: 'fit',
                width: 700,
                height: 500,
                closeAction: 'close',
                plain: true,
                //closable: false,
                items: gridRep,
                listeners: {
                    close: function () {
                        //win.close();
                        winRep = null;
                    }
                },
                buttons: [{
                    text: 'Fermer',
                    handler: function () {
                        winRep.close();
                        winRep = null;
                    }
                }]
            });
            // 
            winRep.show(this);

        };
        storeRep.load();
    }

    //end repertoire
    Ext.onReady(function () {
    var win;
    //var button = Ext.get('unreadMailNb'); //-----> Get button to attach notif icon
    var nameRecord;
    try //Internet Explorer
		{
        nameRecord = Ext.data.Record.create([
             { name: 'Expediteur', mapping: 0 },
             { name: 'Subject', mapping: 1 },
             { name: 'DeliveredDate', mapping: 2 },
             { name: 'Body', mapping: 3 },
             { name: 'UNID', mapping: 4 }
         ]);

        xmldoc = new ActiveXObject("Microsoft.XMLDOM");
        xmldoc.async = false;
        if (oldNewMailXmlData != '')
            xmldoc.loadXML(oldNewMailXmlData);
        else
            xmldoc.loadXML('<?xml version="1.0" ?><root></root>');
    }
    catch (e) {
        try //Firefox, Mozilla, Opera, etc.
	    	{
            nameRecord = Ext.data.Record.create([
                 { name: 'Expediteur', mapping: 1 },
                 { name: 'Subject', mapping: 3 },
                 { name: 'DeliveredDate', mapping: 5 },
                 { name: 'Body', mapping: 7 },
                 { name: 'UNID', mapping: 9 }
             ]);

            parser = new DOMParser();
            if (oldNewMailXmlData != '')
                xmldoc = parser.parseFromString(oldNewMailXmlData, "text/xml");
            else
                xmldoc = parser.parseFromString('<?xml version="1.0" ?><root></root>', "text/xml");
        }
        catch (e) {
            alert(e.message);
            return;
        }
    }
    /*if (oldNewMailXmlData != '')
    xmldoc = GetXmlDocument(xmldoc, oldNewMailXmlData);
    else
    xmldoc = GetXmlDocument(xmldoc, '<?xml version="1.0" ?><root></root>');*/
    var array = XML2JS(xmldoc, 'root');
    var arrayReader = new Ext.data.ArrayReader({}, nameRecord);
    var memoryProxy = new Ext.data.MemoryProxy(array);
    store = new Ext.data.Store({
        reader: arrayReader,
        proxy: memoryProxy
    });

    function renderTopic(value, p, record) {
        var db_path = '';
        var obj = xmldoc.getElementsByTagName('DBPath').item(0);
        if (obj != null) {
            if (obj.textContent)
                db_path = obj.textContent;
            else
                db_path = obj.text;
        }
        //alert(record.data['Body']);
        return '<b><a style="font-family:tahoma,arial,verdana,sans-serif;color:#385F95;font-size:11px;font-weight:bold;" href="javascript:javascript:openEmailPopup(\'' + record.data.UNID.toString() + '\',\'' + db_path + '\');">' + value + '</a></b><div style="font-family:tahoma;color:#385F95;font-size:10px;">' + record.data.Expediteur + '</div>';
    }

    //button.on('mouseover', myFunction); ---> Set Unread Mail
    function myFunction() {
        if (win)
        { }
        else {
            try //Internet Explorer
		    {
                xmldoc = new ActiveXObject("Microsoft.XMLDOM");
                xmldoc.async = false;
                if (oldNewMailXmlData != '')
                    xmldoc.loadXML(oldNewMailXmlData);
                else
                    xmldoc.loadXML('<?xml version="1.0" ?><root></root>');
            }
            catch (e) {
                try //Firefox, Mozilla, Opera, etc.
	    	    {
                    parser = new DOMParser();
                    if (oldNewMailXmlData != '')
                        xmldoc = parser.parseFromString(oldNewMailXmlData, "text/xml");
                    else
                        xmldoc = parser.parseFromString('<?xml version="1.0" ?><root></root>', "text/xml");
                }
                catch (e) {
                    return;
                }
            }

            array = XML2JS(xmldoc, 'root');
            arrayReader = new Ext.data.ArrayReader({}, nameRecord);
            memoryProxy = new Ext.data.MemoryProxy(array);
            store = new Ext.data.Store({
                reader: arrayReader,
                proxy: memoryProxy
            });
            store.setDefaultSort('DeliveredDate', 'desc');
            store.load();

            var grid = new Ext.grid.GridPanel({
                store: store,
                columns: [
                                { id: 'topic', header: "Message", width: 320, dataIndex: 'Subject', sortable: true, renderer: renderTopic },
                                { header: "Date", width: 120, dataIndex: 'DeliveredDate', sortable: true }
                            ], viewConfig: {
                                forceFit: true,
                                enableRowBody: true,
                                showPreview: false,
                                getRowClass: function (record, rowIndex, p, store) {
                                    if (this.showPreview) {
                                        p.body = '<p>' + record.data.Body + '</p>';
                                        return 'x-grid3-row-expanded';
                                    }
                                    return 'x-grid3-row-collapsed';
                                }
                            }, bbar: new Ext.PagingToolbar({
                                pageSize: 25,
                                store: store,
                                displayInfo: true,
                                displayMsg: '{2} élément(s)',
                                emptyMsg: "Pas de messages",
                                items: [
                                    '-', {
                                        pressed: false,
                                        enableToggle: true,
                                        text: 'Afficher aperçu',
                                        cls: 'x-btn-text-icon details',
                                        toggleHandler: function (btn, pressed) {
                                            var view = grid.getView();
                                            view.showPreview = pressed;
                                            view.refresh();
                                        }
                                    }]
                            }),
                renderTo: 'example-grid',
                width: 900,
                height: 700,
                title: 'Courriers non lus (les 10 derniers jours)',
                trackMouseOver: false,
                disableSelection: true,
                loadMask: false
            });

            win = new Ext.Window({
                // applyTo:'hello-win',
                layout: 'fit',
                width: 700,
                height: 500,
                closeAction: 'close',
                plain: true,
                items: grid,
                listeners: {
                    close: function () {
                        win = null;
                    }
                },
                buttons: [{
                    text: 'Fermer',
                    handler: function () {
                        win.close();
                        win = null;
                    }
                }]
            });
            //win.on('beforeclose', new function () { try { if (win) { win = null; } } catch (e) { } });
            win.show(this);

        };
    }
    store.setDefaultSort('DeliveredDate', 'desc');
    store.load();
});
