/*jslint browser: true, white: true, onevar: true, undef: true, nomen: true, eqeqeq: true, plusplus: false,
  bitwise: true, regexp: true, newcap: true, immed: true, strict: true, maxerr: 4, maxlen: 110 */
/*global Ext, alert, confirm, window */

"use strict";

Ext.BLANK_IMAGE_URL = 'common/images/core/pixel.gif';

// Define the namespaces
var yam = {};
yam.shared = {};
yam.shared.subuser = {};
yam.mrn = {};
yam.mrn.subuser = {};
yam.mrn.classif = {};
yam.ptw = {};
yam.ptw.subuser = {};

//translations: http://www.arizonanativenet.com/CFIDE/scripts/ajax/ext/docs/output/ext-lang-it.jss.html
if (Ext.form.TextField) {
    Ext.apply(Ext.form.TextField.prototype, {
        minLengthText: "La lunghezza minima del campo risulta {0}",
        maxLengthText: "La lunghezza massima del campo risulta {0}",
        blankText: "Campo obbligatorio",
        regexText: "",
        emptyText: null
    });
}
if (Ext.MessageBox) {
    Ext.MessageBox.buttonText = {
        ok: "OK",
        cancel: "Annulla",
        yes: "S\u00EC",
        no: "No"
    };
}
if (Ext.grid.GridView) {
    Ext.apply(Ext.grid.GridView.prototype, {
        sortAscText: "Ordinamento crescente",
        sortDescText: "Ordinamento decrescente",
        lockText: "Blocca colonna",
        unlockText: "Sblocca colonna",
        columnsText: "Colonne"
    });
}

Ext.override(Ext.form.Checkbox, {
    onRender : function (ct, position) {
        Ext.form.Checkbox.superclass.onRender.call(this, ct, position);
        if (this.inputValue !== undefined) {
            this.el.dom.value = this.inputValue;
        }
        this.wrap = this.el.wrap({cls: 'x-form-check-wrap'});
        if (this.boxLabel) {
            this.wrap.createChild({
                tag: 'label',
                htmlFor: this.el.id,
                cls: 'x-form-cb-label',
                html: this.boxLabel
            });
        }
        if (this.checked) {
            this.setValue(true);
        } else {
            this.checked = this.el.dom.checked;
        }
        if (Ext.isIE && !Ext.isStrict) {
            this.wrap.repaint();
        }
        this.resizeEl = this.positionEl = this.wrap;
    }
});


function popupConfirm(confirm_msg) {
    if (confirm_msg.length > 0) {
        if (confirm(confirm_msg)) {
            window.location.href = window.location.href + "&confirm=Y";
        } else {
            window.location.href = window.location.href + "&confirm=N";
        }
    }
}

function popup(url, size) {
    if (!size) {
        size = "width=640,height=520";
    }
    window.open(url, "", size + ",resizable,scrollbars=yes");
}

function stopRKey(evt) {
    var evt2, node;
    evt2 = (evt) ? evt : ((event) ? event : null);
    node = (evt2.target) ? evt2.target : ((evt2.srcElement) ? evt2.srcElement : null);
    if ((evt2.keyCode === 13) && (node.type === "text"))  {
        return false;
    }
    return true;
}

document.onkeypress = stopRKey;

yam.alert = function (title, msg, success, callback) {
    var icon;
    if (success === undefined || success === true) {
        icon = Ext.Msg.INFO;
    } else {
        icon = Ext.Msg.WARNING;
    }
    Ext.Msg.show({
        title: title,
        msg: msg,
        minWidth: 380,
        modal: true,
        icon: icon,
        buttons: Ext.Msg.OK,
        fn: callback
    });
};
yam.shared.validateFileExtension = function (fileName) {
    if (fileName.length === 0) {
        return true;
    }
    var re = /\.(jpg|JPG|jpeg|JPEG)$/;
    return re.test(fileName);
};

/*
yam.shared.stripTags = function (input, allowed) {
    // making sure the allowed arg is a string containing only tags in lowercase (<a><b><c>)
    allowed = (((allowed || "") + "").toLowerCase().match(/<[a-z][a-z0-9]*>/g) || []).join(''); 
    var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi,
        commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;
    return input.replace(commentsAndPhpTags, '').replace(tags, function ($0, $1) {
        return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : '';
    });
};
*//* 
 * Common between Marine and PTW
 */

/** Init and Validation */
Ext.QuickTips.init();

yam.shared.specialCharText = "| ! £ $ % & / ( ) = ? ^ .,:; @ # * - _ { } [ ] &lt;&gt;";

/** Initialize the form validation rules.
 *  passwordVal, basicVal and cleanString helper function
 */
yam.shared.initValidation = function () {
    var specialCharReg, i;
    specialCharReg = /[\|!£$%&\/\(\)=\?\^\.,:;@#\*\-_\{\}\[\]<>]/;
    Ext.apply(Ext.form.VTypes, {
        emailText: 'Email non valida',
        passwordVal: function (value, field) {
            if (field.name === 'passwd2') { //we are in Password Confirm
                var pwd = field.ownerCt.ownerCt.getForm().findField('passwd1');
                this.passwordValText = 'Password e Conferma Password non coincidono';
                return (value === pwd.getValue());
            }
            for (i = 0; i < value.length; i++) {
                if (/[a-z0-9]/i.test(value[i]) || specialCharReg.test(value[i])) {
                    continue;
                }
                this.passwordValText = 'Solo lettere non accentate, numeri e ' + yam.shared.specialCharText;
                return false;
            }
            if (!/[0-9]/.test(value)) {
                this.passwordValText = 'Deve contenere almeno un numero';
                return false;
            }
            if (!/[a-z]/.test(value) || !/[A-Z]/.test(value)) {
                this.passwordValText = "Almeno una lettera maiuscola e una minuscola";
                return false;
            }
            if (!specialCharReg.test(value)) {
                this.passwordValText = "Almeno un carattere speciale: " + yam.shared.specialCharText;
                return false;
            }
            return true;
        },
        passwordValText: 'Password non valida',
        basicVal: function (value, field) {          
            if (/^\s/.test(value)) {
                this.basicValText = "Rimuovere gli spazi all'inizio del campo";
                return false;
            }
            return true;
        },
        basicValText: '',
        generateUsername: function (value, field) {
            var nameCmp, surnameCmp, usernameCmp, nameStr, surnameStr, usernameStr;
            if (/^\s/.test(value)) {
                this.basicValText = "Rimuovere gli spazi all'inizio del campo";
                return false;
            }
            if (field.ownerCt.ownerCt.id === 'createForm') {
                nameCmp = field.ownerCt.ownerCt.getForm().findField('name');
                surnameCmp = field.ownerCt.ownerCt.getForm().findField('surname');
                usernameCmp = field.ownerCt.ownerCt.getForm().findField('username');
                usernameStr = usernameCmp.getValue();
                //build the username only if we've the basic dealer code, otherwise refuse to mess up things!
                if (usernameStr.length >= 7) {
                    nameStr = this.cleanString(nameCmp.getValue());
                    surnameStr = this.cleanString(surnameCmp.getValue());
                    usernameStr = usernameCmp.getValue().substring(0, 7) + nameStr + surnameStr;
                    usernameCmp.setValue(usernameStr);
                }
            }
            return true;
        },
        cleanString: function (value) { //works in IE6, IE8, FF3.6 - be careful if you want to modify it!
            var step, out, curChar, i;
            step = value.trim().toLowerCase().replace(/à/g, 'a').replace(/è/g, 'e').replace(/ì/g, 'i')
            .replace(/ò/g, 'o').replace(/ù/g, 'u');
            out = "";
            curChar = "";
            for (i = 0; i < step.length; i++) {
                curChar = step.substring(i, i + 1);
                if (!/[0-9a-z]/.test(curChar)) {
                    continue;
                }
                out += curChar;
            }
            return out;
        }
    });
};
/**
 * Show a grid panel to configura parameters.
 * The build function accepts a configuration object that must have the following keys
 * title: panel title ex. 'Configurazione PTW', 'Configurazione Marine'
 * url: url for crud actions
 */
yam.shared.buildConfigPanel = function (cfg) {
    var configStore, configGridPanel, configPanel, helpHandler, renderDescription;
    //With every record change, the save() method of JsonStore initiates a request to the server
    configStore = new Ext.data.JsonStore({
        url: cfg.url,
        root: 'param',
        idProperty: 'name', //inherited from JsonReader, used to specify the id
        successProperty: 'success', //inherited from JsonReader, used to know whether a CRUD operat. succeded
        fields: ['name', 'setting', 'description'],
        writer: new Ext.data.JsonWriter()
    });
    //DataProxy this, String type, String action, Object options, Object response, Mixed arg
    function exception(dataProxy, type, action, options, response) {
        var msg;
        if (type === 'response') {
            msg = 'Errore';
        } else if (type === 'remote') {
            msg = response.raw.msg;
        }
        yam.alert('Dati non salvati', msg);
    }
    configStore.on('exception', exception, this);

    helpHandler = function () {
        var helpText = 'Soffermarsi con il mouse sopra una delle descrizioni per visualizzare il testo ' +
            'completo. Fare click su una delle impostazioni per modificarla, quindi premere Esc per ' +
            'annullare o Invio per confermare la modifica. Puoi anche confermare la modifica facendo click ' +
            'in un\'area libera della pagina.';
        yam.alert(cfg.title, helpText);
    };

    renderDescription = function (val, cell, record) {
        var cellText, maxLen = 50;
        if (val.length > maxLen) {
            cellText = val.substr(0, maxLen) + '...';
        } else {
            cellText = val;
        }
        return '<div qtip="' + val.replace(/"/g, "'") + '">' + cellText + '</div>';
    };

    configGridPanel = new Ext.grid.EditorGridPanel({
        id: 'configGridPanel',
        store: configStore,
        title: cfg.title,
        autoExpandColumn: 'description',
        renderTo: 'configDiv',
        //width: 650,
        height: 300,
        loadMask: true,
        clicksToEdit: 1,
        batchSave: false,
        columns: [
            {
                header: 'Parametro',
                width: 120,
                dataIndex: 'name',
                sortable: true
            },
            {
                id: 'name',
                header: 'Impostazione',
                width: 250,
                dataIndex: 'setting',
                sortable: true,
                editor: new Ext.form.TextField({
                    allowBlank: true
                })
            },
            {
                id: 'description',
                header: 'Descrizione',
                dataIndex: 'description',
                sortable: true,
                align: 'left',
                renderer: renderDescription.createDelegate(this)
            }
        ],
        tbar: [
            '->',  {
                iconCls: 'icon-information',
                text: 'Aiuto',
                handler: helpHandler,
                width: 100
            }
        ]
    });
    configStore.load();
};
/**
 * Build the external card layout for Marine or PTW subusers.
 * @param cfg configuration object
 *     cfg.title    the panel title
 */
yam.shared.subuser.buildCardPanel = function (cfg) {
    yam.shared.subuser.cardPanel = new Ext.Panel({
        id: 'cardPanel',
        title: cfg.title,
        renderTo: 'subadm',
        height: 'auto',
        layout: 'card',
        layoutOnTabChange: true,
        layoutConfig : {
            align : 'stretch'
        },
        activeItem: 'listPanel',
        items: [ 'listPanel', 'createPanel', 'modifyPanel' ]
    });
};
yam.shared.subuser.titles = ['---', 'Crea una Sottoutenza', 'Modifica una Sottoutenza'];

/**
 * Build a ListPanel for Marine or PTW subusers.
 * @param cfg configuration object
 *     cfg.listUrl    URL returning a JSON subuser list.
 *     cfg.deleteUrl  Ajax user delete action URL.
 *     cfg.introMsg   A message to write on top of the list grid as introduction.
 */
yam.shared.subuser.buildListPanel = function (cfg) {
    var columnModel, selModel, recordFields, remoteJsonStore, createHandler, modifyHandler,
        deleteHandler, helpHandler, tbar;

    columnModel = [ {
        header: 'ID',
        dataIndex: 'id_person',
        sortable: true,
        width: 50,
        resizable: true,
        hidden: true
    }, {
        header: 'Ragione Sociale',
        dataIndex: 'suborganization',
        sortable: true,
        hideable: false,
        width: 160
    }, {
        header: 'Cognome',
        dataIndex: 'surname',
        sortable: true,
        hideable: false,
        width: 85
    }, {
        header: 'Email',
        dataIndex: 'email',
        sortable: true,
        hideable: false,
        width: 150
    }, {
        header: 'Funzioni',
        dataIndex: 'groups',
        sortable: true,
        hideable: true,
        width: 200
    }, {
        header: 'Approv',
        dataIndex: 'approved',
        sortable: true,
        hideable: true,
        width: 47
    } ];

    selModel = new Ext.grid.RowSelectionModel({
        singleSelect: true
    });

    recordFields = [ 'id_person', 'suborganization', 'surname', 'email',  'groups', 'approved' ];

    remoteJsonStore = new Ext.data.JsonStore({
        fields: recordFields,
        url: cfg.listUrl,
        totalProperty: 'totalCount',
        root: 'records',
        id: 'jsublistStore',
        autoLoad: true,
        remoteSort: false
    });

    createHandler = function () {
        if (yam.shared.subuser.createPanel.organization.length === 0) { //organization name not yet loaded!
            yam.alert('Attendere Prego', 'Il caricamento del form non &egrave; completato. Se dopo alcuni ' +
                'secondi si ripresenta questo messaggio, provare a ricaricare la pagina.');
            return;
        }
        yam.shared.subuser.cardPanel.layout.setActiveItem('createPanel');
        yam.shared.subuser.cardPanel.setTitle(yam.shared.subuser.titles[1]);
    };

    modifyHandler = function () {
        var record, idPerson;
        record = selModel.getSelected();
        if (record === undefined) {
            Ext.MessageBox.alert("Nessun Utente Selezionato",
                "Per modificare un utente fare click sull\'utente e premere il pulsante Modifica.");
            return;
        }
        idPerson = record.get('id_person');
        if (record.get('approved') === 'No') {
            Ext.MessageBox.alert('Operazione non consentita',
                'Non &egrave; possibile modificare utenti non approvati');
        } else {
            Ext.getCmp('modifyPanel').idPerson = idPerson; //set the person to be loaded
            yam.shared.subuser.cardPanel.layout.setActiveItem('modifyPanel');
            yam.shared.subuser.cardPanel.setTitle(yam.shared.subuser.titles[2]);
        }
    };

    deleteHandler = function () {
        var record, idPerson;
        record = selModel.getSelected();
        if (record === undefined) {
            Ext.MessageBox.alert("Nessun Utente Selezionato",
                "Per eliminare un utente fare click sull\'utente e premere il pulsante Elimina.");
            return;
        }
        idPerson = record.get('id_person');
        Ext.MessageBox.confirm('Eliminazione Utente', 'Confermi l\'eliminazione dell\'utente?',
            function (result) {
                if (result === 'yes') {
                    Ext.Ajax.request({
                        params: { 'del': idPerson },
                        url: cfg.deleteUrl,
                        success: function (resp) {
                            var data = Ext.decode(resp.responseText);
                            yam.alert('Utente Eliminato', data.msg, true);
                        },
                        failure: function () {
                            yam.alert('Errore', 'Problema di connessione', true);
                        }
                    });
                    Ext.getCmp('sublist').getStore().reload();
                }
            });
    };

    helpHandler = function () {
        Ext.MessageBox.alert('Aiuto', 'Per creare un nuovo subutente premere il pulsante Crea, per ' +
            'modificare o eliminare un utente, selezionare la riga corrispondente prima di premere il ' +
            'pulsante Modifica o Elimina.');
    };

    tbar = [ {
        iconCls: 'icon-user-add',
        text: 'Crea',
        handler: createHandler,
        width: 100
    }, '-', {
        iconCls: 'icon-user-edit',
        text: 'Modifica ',
        handler: modifyHandler,
        width: 100
    }, '-', {
        iconCls: 'icon-user-delete',
        text: 'Elimina',
        handler: deleteHandler,
        width: 100
    }, '->', {
        iconCls: 'icon-information',
        text: 'Aiuto',
        handler: helpHandler,
        width: 100
    } ];

    yam.shared.subuser.listPanel = new Ext.Panel({
        layout: 'vbox',
        id: 'listPanel',
        height: 350,
        layoutConfig: {
            align: 'stretch'
        },
        items: [
            {
                xtype: 'label',
                html: '<p style="padding:8px">' + cfg.introMsg + '</p>'
            }, {
                xtype: 'grid',
                id: 'sublist',
                columns: columnModel,
                selModel: selModel,
                store: remoteJsonStore,
                loadMask: true,
                flex: 1,
                tbar: tbar
            }
        ]
    });

};

/*
 * Common items for CreatePanel and ModifyPanel. I wanted to use a parent class at first, but this approach
 * is simpler. I wrap the object in a function so I can create the Edit panel after the provinciaStore has
 * been created.
 */
yam.shared.subuser.buildEditPanel = function () {

    yam.shared.subuser.EditPanel =  {

        /** Tipologie di Utenza & Funzioni Aggiuntive */
        groupInfo: {
            xtype: 'panel',
            layout: 'hbox',
            flex: 1, //auto height
            frame: true,
            border: false,
            autoScroll: true,
            layoutConfig: {
                align: 'stretch',
                pack: 'start'
            },
            items: [
                {
                    xtype: 'fieldset',
                    title: 'Tipologie di Utenza',
                    border: true, //needed by IE, otherwise the label is split in two lines
                    frame: false,
                    width: 310,
                    labelWidth: 170,
                    defaults: {xtype: 'checkbox', labelSeparator: ''}
                },  {
                    xtype: 'fieldset',
                    title: 'Funzioni Aggiuntive',
                    border: true,
                    frame: false,
                    width: 310,
                    labelWidth: 170,
                    defaults: {xtype: 'checkbox', labelSeparator: ''}
                }
            ]
        },

        addressInfo:  {
            xtype: 'fieldset',
            title: 'Anagrafica Subutente',
            //minHeight: 280,
            flex: 0,
            border: true, //IE renders the title on two lines without border:true
            labelWidth: 180,
            frame: false,
            defaultType: 'field',
            defaults: {
                height: 20,
                anchor: '-60',
                xtype: 'textfield',
                labelSeparator: '',
                msgTarget: 'side',
                blankText : 'Obbligatorio',
                minLengthText : 'Minimo {0} caratteri',
                maxLengthText : 'Massimo {0} caratteri'
            },
            items: [
                {
                    xtype: 'spacer',
                    height: 15
                }, {
                    name: 'organization',
                    fieldLabel: 'Organizzazione',
                    value: '',
                    disabled: true
                }, {
                    fieldLabel: 'Ragione Sociale *',
                    name: 'suborganization',
                    minLength: 3,
                    maxLength: 128,
                    allowBlank: false,
                    vtype: 'basicVal'
                }, {
                    fieldLabel: 'Cognome *',
                    name: 'surname',
                    minLength: 2,
                    maxLength: 64,
                    allowBlank: false,
                    vtype: 'generateUsername' //will generate the username but only for the createPanel
                }, {
                    fieldLabel: 'Nome *',
                    name: 'name',
                    minLength: 2,
                    maxLength: 64,
                    allowBlank: false,
                    vtype: 'generateUsername' //will generate the username but only for the createPanel
                }, {
                    fieldLabel: 'Indirizzo *',
                    name: 'address',
                    minLength: 3,
                    maxLength: 240,
                    allowBlank: false,
                    vtype: 'basicVal'
                }, {
                    fieldLabel: 'CAP *',
                    name: 'postcode',
                    minLength: 5,
                    maxLength: 5,
                    anchor: '-310',
                    maskRe: /[0-9]/i,
                    allowBlank: false
                }, {
                    fieldLabel: 'Località *',
                    name: 'city',
                    minLength: 2,
                    maxLength: 64,
                    allowBlank: false,
                    vType: 'basicVal'
                }, {
                    fieldLabel: 'Provincia *',
                    name: 'provincia',
                    xtype: 'combo',
                    store: yam.shared.provinciaStore,
                    valueField: 'id',
                    displayField: 'name',
                    hiddenName: 'provinciaValue',
                    mode: 'local',
                    typeAhead: true,
                    forceSelection: true,
                    allowBlank: false,
                    anchor: '-200'
                }
            ]
        },

        authInfo: {
            xtype: 'fieldset',
            title: 'Informazioni di Accesso',
            minHeight: 150,
            flex: 1,
            border: true, //IE renders the title on two lines without border:true
            labelWidth: 180,
            frame: false,
            defaultType: 'field',
            defaults: {
                height: 20,
                anchor: '-200',
                xtype: 'textfield',
                labelSeparator: '',
                msgTarget: 'side',
                allowBlank: false,
                blankText : 'Obbligatorio',
                minLengthText : 'Minimo {0} caratteri',
                maxLengthText : 'Massimo {0} caratteri'
            },
            items: [
                {
                    xtype: 'spacer',
                    height: 15
                }, {
                    fieldLabel: 'Email * <span class="textmini">(riceve la mail di attivazione)</span>',
                    name: 'email',
                    vtype: 'email',
                    maxLength: 128
                }, {
                    fieldLabel: 'Nome Utente',
                    name: 'username',
                    disabled: true,
                    value: '',
                    allowBlank: true
                }, {
                    fieldLabel: 'Password *',
                    name: 'passwd1',
                    vtype: 'passwordVal',
                    minLength: 8,
                    maxLength: 32,
                    inputType: 'password'
                }, {
                    fieldLabel: 'Conferma Password *',
                    name: 'passwd2',
                    vtype: 'passwordVal',
                    maxLength: 32,
                    inputType: 'password'
                }
            ]
        },


        helpHandler: function () {
            var passwdRules = "La password deve essere composta da almeno 8 caratteri alfanumerici e " +
                "contenere una combinazione di lettere minuscole e maiuscole non accentate, e almeno un " +
                "numero e un carattere speciale tra i seguenti: " + yam.shared.specialCharText +
                " (ad es: ytZr750$). La password non pu&ograve; contenere il nome utente; vi consigliamo " +
                "di evitare il nome di familiari, date di nascita, etc. facilmente identificabili da " +
                "terzi. Vengono registrate le ultime 3 password, che non possono quindi venire reimpiegate.";
            Ext.Msg.alert("Regole per la generazione della password", passwdRules);
        },

        /**
         * Check that at least one checkbox is selected in the items of the cmpArray
         * @param cmpArray is an array of components, that we'll scan. We'll check all the items inside
         *     the components to see if at least one checkbox is selected
         * @return true if at least one checkbox was selected, false if they are all unselected
         */
        oneCheckBoxSelected: function (cmpArray) {
            var found = false, curCmp, i, j;
            for (i = 0; i < cmpArray.length; i++) {
                curCmp = cmpArray[i];
                for (j = 0; j < curCmp.items.length; j++) {
                    if (curCmp.get(j).checked === true) {
                        found = true;
                    }
                }
            }
            return found;
        }


    };

};

/**
 * Build a panel to create subusers for Marine or PTW.
 * @param cfg configuration object
 *     cfg.createUrl  Ajax action url to create an user
 */
yam.shared.subuser.buildCreatePanel = function (cfg) {
    var createForm, createSaveHandler, createCancelHandler;

    /**
     * Cancel clears the form and sends back to the subuser list
     */
    createCancelHandler = function () {
        createForm.getForm().reset();
        yam.shared.subuser.cardPanel.layout.setActiveItem('listPanel');
        yam.shared.subuser.cardPanel.setTitle(cfg.title);
    };

    /**
     * Save will check whether the form is valid before submitting the Ajax save request
     */
    createSaveHandler = function () {
        var isACheckBoxSelected, msg = "Perfavore completare il form. ", paramArr = {};
        //check that at least one checkbox is selected
        isACheckBoxSelected = yam.shared.subuser.EditPanel.oneCheckBoxSelected([
            Ext.getCmp('createForm').get(0).get(0), //Tipologie di utenza
            Ext.getCmp('createForm').get(0).get(1)  //Funzioni Aggiuntive
        ]);
        if (!isACheckBoxSelected) {
            msg += "Selezionare almeno una Tipologia o Funzione. ";
        }
        //if something is not valid, show an alert message and don't save the form
        if (!createForm.getForm().isValid() || !isACheckBoxSelected) {
            msg += "Posizionando il puntatore del mouse sopra i circoletti rossi &egrave; possibile " +
                "leggere i suggerimenti";
            yam.alert("Form non inviato", msg, false);
            return;
        }
        //Everything was ok, build the parameter object
        createForm.getForm().items.each(function (field) {
            paramArr[field.name] = field.getValue();
        });
        //Send the Ajax request to the server
        Ext.Ajax.request({
            url: cfg.createUrl,
            params: paramArr,
            success: function (resp) {
                var data;
                data = Ext.decode(resp.responseText);
                if (data.success === true) {
                    yam.alert('Subutente inserito', data.msg, true, function () {
                        yam.shared.subuser.cardPanel.layout.setActiveItem('listPanel');
                        Ext.getCmp('sublist').getStore().reload();
                    });
                } else {
                    yam.alert('Errore: subutente non inserito', data.msg, false);
                }
            },
            failure: function () {
                yam.alert("Errore", "Errore di connessione, è possibile riprovare", false);
            }
        });
    };


    createForm = new Ext.form.FormPanel({
        layout: 'vbox',
        id: 'createForm',
        flex: 1,
        layoutConfig: {
            align: 'stretch'
        },
        autoScroll: true,
        items: [
            yam.shared.subuser.EditPanel.groupInfo, {
                xtype: 'spacer',
                height: 5
            },
            yam.shared.subuser.EditPanel.addressInfo, {
                xtype: 'spacer',
                height: 5
            },
            yam.shared.subuser.EditPanel.authInfo
        ],
        buttons: [
            {
                text: 'Salva',
                handler: createSaveHandler
            }, {
                text: 'Annulla',
                handler: createCancelHandler
            }
        ],
        tbar: [
            {
                iconCls: 'icon-save',
                text: 'Salva',
                handler: createSaveHandler,
                width: 100
            }, '-',  {
                iconCls: 'icon-cancel',
                text: 'Annulla ',
                handler: createCancelHandler,
                width: 100
            }, '->',  {
                iconCls: 'icon-information',
                text: 'Aiuto',
                handler: yam.shared.subuser.EditPanel.helpHandler,
                width: 100
            }
        ]
    });

    yam.shared.subuser.createPanel = new Ext.Panel({
        id: 'createPanel',
        layout: 'vbox',
        height: 675,
        organization: '',
        baseUsername: '',
        listeners: {
            beforeshow: function () {
                Ext.getCmp('createForm').getForm().findField('organization').setValue(this.organization);
                Ext.getCmp('createForm').getForm().findField('username').setValue(this.baseUsername);
            }
        },
        layoutConfig: {
            align: 'stretch'
        },
        items: [
            {
                xtype: 'label',
                height: 46,
                flex: 0,
                html: '<p style="padding:8px">Selezionare tutte le Tipologie e Funzioni da attribuire ' +
            'all\'utente. Non sar&agrave; possibile modificarle finch&eacute; l\'utente non ' +
            'verr&agrave; attivato. Le sottoutenze sono soggette ad approvazione da parte di ' +
            'Yamaha.</p>'
            },
            createForm
        ]
    });

};


/**
 * Create a panel to modify subusers.
 * @param cfg configuration object
 *     cfg.loadUrl    Ajax action url to load an user
 *     cfg.modifyUrl  Ajax action url to modify an user
 */
yam.shared.subuser.buildModifyPanel = function (cfg) {

    var customiseEditPanel, modifyCancelHandler, modifySaveHandler, modifyForm, loadForm;

    /**
     * Change the original EditPanel template
     */
    customiseEditPanel = function () {
        var passwd1, passwd2;
        passwd1 = modifyForm.getForm().findField('passwd1');
        passwd2 = modifyForm.getForm().findField('passwd2');
        passwd1.fieldLabel = 'Modifica Password';
        passwd1.allowBlank = true;
        passwd2.fieldLabel = 'Conferma Modifica Password';
        passwd2.allowBlank = true;
        modifyForm.getForm().findField('surname').disabled = true;
        modifyForm.getForm().findField('name').disabled = true;
    };

    /**
     * Cancel clears the form and sends back to the subuser list
     */
    modifyCancelHandler = function () {
        modifyForm.getForm().reset();
        yam.shared.subuser.cardPanel.layout.setActiveItem('listPanel');
        yam.shared.subuser.cardPanel.setTitle(cfg.title);
    };

    modifySaveHandler = function () {
        var isACheckBoxSelected, msg = "Perfavore completare il form. ", paramArr = {};
        //check that at least one checkbox is selected
        isACheckBoxSelected = yam.shared.subuser.EditPanel.oneCheckBoxSelected([
            Ext.getCmp('modifyForm').get(0).get(0), //Tipologie di utenza
            Ext.getCmp('modifyForm').get(0).get(1)  //Funzioni Aggiuntive
        ]);
        if (!isACheckBoxSelected) {
            msg += "Selezionare almeno una Tipologia o Funzione. ";
        }
        //if something is not valid, show an alert message and don't save the form
        if (!modifyForm.getForm().isValid() || !isACheckBoxSelected) {
            msg += "Posizionando il puntatore del mouse sopra i circoletti rossi &egrave; possibile " +
                "leggere i suggerimenti";
            yam.alert("Form non inviato", msg, false);
            return;
        }
        //Everything was ok, build the parameter object
        paramArr.idPerson = yam.shared.subuser.modifyPanel.idPerson;
        modifyForm.getForm().items.each(function (field) {
            paramArr[field.name] = field.getValue();
        });
        //Send the Ajax request to the server
        Ext.Ajax.request({
            url: cfg.modifyUrl,
            params: paramArr,
            success: function (resp) {
                var data;
                data = Ext.decode(resp.responseText);
                if (data.success === true) {
                    yam.alert('Subutente modificato', data.msg, true, function () {
                        yam.shared.subuser.cardPanel.layout.setActiveItem('listPanel');
                        Ext.getCmp('sublist').getStore().reload();
                    });
                } else {
                    yam.alert('Errore: subutente non inserito', data.msg, false);
                }
            },
            failure: function () {
                yam.alert("Errore", "Errore di connessione, è possibile riprovare", false);
            }
        });
    };

    modifyForm = new Ext.form.FormPanel({
        layout: 'vbox',
        id: 'modifyForm',
        flex: 1,
        layoutConfig: {
            align: 'stretch'
        },
        autoScroll: true,
        items: [
            yam.shared.subuser.EditPanel.groupInfo, {
                xtype: 'spacer',
                height: 5
            },
            yam.shared.subuser.EditPanel.addressInfo, {
                xtype: 'spacer',
                height: 5
            },
            yam.shared.subuser.EditPanel.authInfo
        ],
        buttons: [
            {
                text: 'Salva',
                handler: modifySaveHandler
            }, {
                text: 'Annulla',
                handler: modifyCancelHandler
            }
        ],
        tbar: [
            {
                iconCls: 'icon-save',
                text: 'Salva',
                handler: modifySaveHandler,
                width: 100
            }, '-',  {
                iconCls: 'icon-cancel',
                text: 'Annulla ',
                handler: modifyCancelHandler,
                width: 100
            }, '->',  {
                iconCls: 'icon-information',
                text: 'Aiuto',
                handler: yam.shared.subuser.EditPanel.helpHandler,
                width: 100
            }
        ]
    });

    yam.shared.subuser.modifyPanel = new Ext.Panel({
        id: 'modifyPanel',
        layout: 'vbox',
        height: 670,
        organization: '',
        baseUsername: '',
        listeners: {
            beforeshow: function () {
                loadForm(this);
                Ext.getBody().mask('Caricamento in corso...');
            },
            beforerender: function () {
                customiseEditPanel();
            }
        },
        layoutConfig: {
            align: 'stretch'
        },
        items: [
            {
                xtype: 'label',
                height: 46,
                flex: 0,
                html: '<p style="padding:8px">Se si aggiungono nuove tipologie o funzioni non sar&agrave; ' +
                   'possibile utilizzarle fino a che non saranno approvate da Yamaha.</p>'
            },
            modifyForm
        ]
    });

    /**
     * Return a reference to provincia combobox.
     * The obvious modifyForm.findField('provincia') doesn't work, so I've resorted to this method
     */
    yam.shared.subuser.getProvinciaField = function () {
        var provinciaField;
        Ext.getCmp('modifyForm').getForm().items.each(function (field) {
            if (field.name === 'provincia') {
                provinciaField = field;
            }
        });
        return provinciaField;
    };

    yam.shared.subuser.setFields = function (myForm, data) {
        var i, checkBox;
        myForm.findField('organization').setValue(data.person.organization);
        myForm.findField('suborganization').setValue(data.person.suborganization);
        myForm.findField('surname').setValue(data.person.surname);
        myForm.findField('name').setValue(data.person.name);
        myForm.findField('address').setValue(data.person.address);
        myForm.findField('postcode').setValue(data.person.postcode);
        myForm.findField('city').setValue(data.person.city);
        yam.shared.subuser.getProvinciaField().setValue(data.person.provincia);
        myForm.findField('email').setValue(data.person.email);
        myForm.findField('username').setValue(data.person.username);
        for (i = 0; i < data.groupList.length; i++) {
            checkBox = myForm.findField('addgroup_' + data.groupList[i]);
            if (checkBox === null) {
                continue;
            }
            checkBox.setValue(true);
        }
    };

    loadForm = function (modifyPanel) {
        Ext.Ajax.request({
            params: {idPerson: modifyPanel.idPerson},
            url: cfg.loadUrl,
            success: function (resp) {
                var data, topPart, myForm;
                data = Ext.decode(resp.responseText);
                if (data.success === true) {
                    //the topPart is the enclosure containing the two checkboxes fieldSet
                    topPart = Ext.getCmp('modifyForm').get(0);
                    if (topPart.get(0).items.getCount() === 0) {
                        yam.shared.subuser.JSubInit.insertCheckBoxes(topPart.get(0), data.tipologie);
                    }
                    if (topPart.get(1).items.getCount() === 0) {
                        yam.shared.subuser.JSubInit.insertCheckBoxes(topPart.get(1), data.funzioni);
                    }
                    myForm = Ext.getCmp('modifyForm').getForm();
                    yam.shared.subuser.setFields(myForm, data);
                    Ext.getBody().unmask();
                    Ext.getCmp('modifyForm').doLayout();
                } else {
                    Ext.MessageBox.alert('Errore',
                        'Problema durante il caricamento dei dati, provare a ricaricare la pagina');
                }
            },
            failure: function () {
                Ext.MessageBox.alert('Errore',
                    'Problema durante il caricamento dei dati, provare a ricaricare la pagina');
            }
        });
    };

};
/**
 * Load organization, username, tipologie, funzioni for Marine or PTW
 * @param cfg configuration object
 *     cfg.initUrl  Ajax action url to load this info
 */
yam.shared.subuser.JSubInit = function (cfg) {
    Ext.Ajax.request({
        url: cfg.initUrl,
        success: function (resp) {
            var data;
            data = Ext.decode(resp.responseText);
            //createPanel will use beforeshow event to set the fields from this value. modifyPanel will load
            //this data with an Ajax call since has already to retrieve the subuser data.
            yam.shared.subuser.createPanel.organization = data.organization;
            yam.shared.subuser.createPanel.baseUsername = data.username + "_";
            yam.shared.subuser.JSubInit.insertCheckBoxes(Ext.getCmp('createForm').get(0).get(0),
                data.tipologie);
            yam.shared.subuser.JSubInit.insertCheckBoxes(Ext.getCmp('createForm').get(0).get(1),
                data.funzioni);
        },
        failure: function () {
            yam.alert("Errore", "Errore di connessione, provare a ricaricare la pagina", false);
        }
    });
};

/** Insert checkboxes in the fieldset
 *  @param fieldSet the Ext JS Component where to insert the checkboxes
 *  @param groups an array of groups. Each row represent a group with id_group in position 0 and group name
 *      in position 1
 */
yam.shared.subuser.JSubInit.insertCheckBoxes = function (fieldSet, groups) {
    var i;
    for (i = 0; i < groups.length; i++) {
        fieldSet.insert(fieldSet.items.length, {
            name: 'addgroup_' + groups[i][0], //id_group
            fieldLabel: '<span class="textmini">' + groups[i][1] + '</span>'
        });
    }
    //fieldSet.doLayout();
};

yam.shared.subuser.buildApprovePanel = function (cfg) {
    var pageSize = 20, selModel, store, grid, tbar, approveHandler, modifyHandler, helpHandler, myWin,
        bodyWidth, paramArr;

    approveHandler = function () {
        var record;
        record = selModel.getSelected();
        if (record === undefined) {
            Ext.MessageBox.alert("Nessun Utente Selezionato",
                "Per approvare un utente fare click sull\'utente e premere il pulsante Modifica.");
            return;
        }
        paramArr = {
            idPerson: record.get('id_person')
        };
        Ext.Ajax.request({
            url: cfg.approveUrl,
            params: paramArr,
            success: function (resp) {
                var data;
                data = Ext.decode(resp.responseText);
                if (data.success === 'true') {
                    yam.alert('Subutente approvato', data.msg, true, function () {
                        store.reload();
                    });
                } else {
                    yam.alert('Errore', data.msg, false);
                }
            },
            failure: function () {
                yam.alert("Errore", "Errore di connessione, è possibile riprovare", false);
            }
        });
    };

    modifyHandler = function () {
        var record, idPerson;
        record = selModel.getSelected();
        if (record === undefined) {
            Ext.MessageBox.alert("Nessun Utente Selezionato",
                "Per modificare un utente fare click sull\'utente e premere il pulsante Modifica.");
            return;
        }
        idPerson = record.get('id_person');
        window.location = cfg.modifyUrl + idPerson;
    };

    helpHandler = function () {
        yam.alert('Autorizzazione Sottoutenze',
            'Seleziona l\'utenza da autorizzare e premi Approva. Se l\'utenza &egrave; gi&agrave; stata ' +
            'approvata, viene rimandata la mail di attivazione al sottoutente e al concessionario. ' +
            'Utilizzare il pulsante in alto a destra della tabella per massimizzare la finestra. Fare ' +
            'click sulle intestazioni delle colonne per ordinare i dati. Utilizzare il menu a discesa a ' +
            'destra di ogni colonna per aggiungere o rimuovere colonne dalla vista.',
            true);
    };

    selModel = new Ext.grid.RowSelectionModel({
        singleSelect: true
    });
    
    store = new Ext.data.JsonStore({
        url: cfg.listUrl,
        root: 'users',
        idProperty: 'id_person',
        totalProperty: 'total',
        fields: ['id_person', 'code', 'organization', 'suborganization', 'surname', 'name', 'email', 
            'lastmail', 'address', 'city', 'enable', 'groups'],
        remoteSort: true
    });

    store.setDefaultSort('lastmail', 'asc');

    tbar = [ {
        iconCls: 'icon-save',
        text: 'Approva',
        handler: approveHandler,
        width: 100
    }, '-', {
        iconCls: 'icon-user-edit',
        text: 'Modifica',
        handler: modifyHandler,
        width: 100
    }, '->', {
        iconCls: 'icon-information',
        text: 'Aiuto',
        handler: helpHandler,
        width: 100
    } ];

    grid = new Ext.grid.GridPanel({
        store: store,
        selModel: selModel,
        columns: [
            { 
                header: 'ID',
                width: 40,
                dataIndex: 'id_person',
                sortable: true,
                hidden: true,
                align: 'right'
            }, {
                header: 'Cod',
                width: 40,
                dataIndex: 'code',
                sortable: true,
                hidden: true,
                align: 'right'
            }, {
                header: 'Dealer',
                width: 150,
                dataIndex: 'organization',
                sortable: true,
                align: 'left'
            }, {
                header: 'Rag. Sociale',
                width: 150,
                dataIndex: 'suborganization', 
                sortable: true,
                align: 'left'
            }, {
                header: 'Cognome',
                width: 75,
                dataIndex: 'surname',
                sortable: true,
                hidden: true,
                align: 'left'
            }, {
                header: 'Nome',
                width: 75,
                dataIndex: 'name',
                sortable: true,
                hidden: true,
                align: 'left'
            }, {
                header: 'Indirizzo',
                width: 120,
                dataIndex: 'address',
                sortable: false,
                hidden: true,
                align: 'left'
            }, {
                header: 'Località',
                width: 100,
                dataIndex: 'city',
                sortable: true,
                hidden: true,
                align: 'left'
            }, {
                header: 'Email',
                width: 120,
                dataIndex: 'email',
                sortable: true,
                hidden: true,
                align: 'left'
            }, {
                header: 'Approv',
                width: 55,
                dataIndex: 'lastmail',
                sortable: true,
                align: 'center'
            }, {
                header: 'Gruppi',
                width: 80,
                dataIndex: 'groups',
                sortable: false,
                id: 'groups',
                align: 'left'
            }, {
                header: 'Attiv',
                width: 45,
                dataIndex: 'enable',
                sortable: true,
                align: 'center'
            }
        ],
        autoExpandColumn: 'groups',
        //renderTo: 'authDiv',
        //width: 641,
        //height: 340,
        loadMask: true,
        columnLines: true,
        tbar: tbar,
        bbar: new Ext.PagingToolbar({
            pageSize: pageSize,
            store: store,
            displayInfo: true,
            displayMsg: 'Sottoutenze {0} - {1} di {2}',
            emptyMsg: "Nessuna sottoutenza trovata"
        })
    });

    bodyWidth = Ext.getBody().getWidth();

    myWin = new Ext.Window({
        title: 'Sottoutenze da autorizzare o autorizzate ma non attivate',
        layout: 'fit',
        x: (bodyWidth / 2 - 256),
        y: 335,
        height: 280,
        width: 645,
        closable: false,
        resizable: true,
        draggable: true,
        maximizable: true,
        items: grid
    });

    myWin.show();

    store.load({params: {start: 0, limit: pageSize}});
};

yam.mrn.subuser.Init = {
    run: function () {
        var cfg = {
            title:     'Gestione Sottoutenze Marine',
            initUrl:   'index.php?page=mrn_jsub_init',
            listUrl:   'index.php?page=mrn_jsublist',
            loadUrl:   'index.php?page=mrn_jsub_load',
            deleteUrl: 'index.php?page=mrn_jsub_delete',
            createUrl: 'index.php?page=mrn_jsub_create',
            modifyUrl: 'index.php?page=mrn_jsub_modify',
            introMsg:  'Gentile Concessionario, tramite questa amministrazione potrà ' +
              'creare sottoutenze con accesso limitato da assegnare ai suoi collaboratori o ad officine ' +
              'esterne. Le sottoutenze sono sottoposte ad approvazione da parte di Yamaha. Le ' +
              'sottoutenze non saranno modificabili prima dell\'approvazione e attivazione.'
        };
        yam.shared.initValidation();
        yam.shared.subuser.buildListPanel(cfg);
        yam.shared.buildProvinciaStore();
        yam.shared.subuser.buildEditPanel();
        yam.shared.subuser.buildCreatePanel(cfg);
        yam.shared.subuser.buildModifyPanel(cfg);
        yam.shared.subuser.buildCardPanel(cfg);
        yam.shared.subuser.JSubInit(cfg); //load organization, username, funzioni, tipologie
    }
};

yam.ptw.subuser.Init = {
    run: function () {
        var cfg = {
            title:     'Gestione Sottoutenze PTW',
            initUrl:   'index.php?page=user_jsub_init',
            listUrl:   'index.php?page=user_jsub_list',
            loadUrl:   'index.php?page=user_jsub_load',
            deleteUrl: 'index.php?page=user_jsub_delete',
            createUrl: 'index.php?page=user_jsub_create',
            modifyUrl: 'index.php?page=user_jsub_modify',
            introMsg:  'Gentile Concessionario, tramite questa amministrazione potr&agrave; creare ' +
                'sottoutenze con accesso limitato da assegnare ai suoi collaboratori o ad officine ' +
                'esterne. Un\'utenza di tipo officina &egrave; sottoposta ad approvazione da parte di ' +
                'Yamaha. Verr&agrave; inviata una mail di attivazione al Concessionario e al sottoutente. ' +
                'Seguire le istruzioni nella mail per attivare la sottoutenza.'
        };
        yam.shared.initValidation();
        yam.shared.subuser.buildListPanel(cfg);
        yam.shared.buildProvinciaStore();
        yam.shared.subuser.buildEditPanel();
        yam.shared.subuser.buildCreatePanel(cfg);
        yam.shared.subuser.buildModifyPanel(cfg);
        yam.shared.subuser.buildCardPanel(cfg);
        yam.shared.subuser.JSubInit(cfg); //load organization, username, funzioni, tipologie
    }
};

yam.mrn.classif.saveButtonHandler = function () {
    var theForm, pictureFileName, idModel, notes;
    theForm = yam.mrn.classif.theForm.getForm();
    idModel = theForm.findField('modelCombo').getValue();
    notes = theForm.findField('notes').getValue();
    pictureFileName = theForm.findField('picture').getValue();    
    if (idModel.length === 0) {
        Ext.MessageBox.alert('', 'Il Modello &egrave; obbligatorio');
        return;
    }
    //alert(yam.shared.stripTags(notes));
    if (!yam.shared.validateFileExtension(pictureFileName)) {
        Ext.MessageBox.alert('', "La fotografia deve essere in formato JPG");
        return;
    }
    theForm.on({
        actioncomplete: function (form, action) {
            if (action.type === 'submit') {
                //TODO: decode JSON and look for success variable
                window.location = 'index.php?page=mrn_classif';
            }
        }
    });
    theForm.submit({
        params: {action: 'newClassif', idModel: idModel},
        waitMsg: 'Invio dati in corso...'
    });
};

yam.mrn.classif.cancelButtonHandler = function () {
    window.location = 'index.php?page=mrn_classif';
};

yam.mrn.classif.deleteButtonHandler = function (selModel) {
    var record, idClassif;
    record = selModel.getSelected();
    if (record === undefined) {
        Ext.MessageBox.alert("Nessuna riga selezionata",
          "Per eliminare una disponibilit&agrave; fare click su una riga e premere il pulsante Elimina.");
        return;
    }
    idClassif = record.get('id');
    Ext.MessageBox.confirm('Eliminazione Disponibilit&agrave;',
        'Confermi l\'eliminazione della disponibilit&agrave;?',
        function (result) {
                    if (result === 'yes') {
                        Ext.Ajax.request({
                            params: { 'del': idClassif },
                            url: 'index.php?page=mrn_classif_del',
                            success: function (resp) {
                                var data = Ext.decode(resp.responseText);
                                yam.alert('Disponibilità Eliminata', data.msg, true);
                            },
                            failure: function () {
                                yam.alert('Errore', 'Problema di connessione', true);
                            }
                        });
                        Ext.getCmp('myGridPanel').getStore().reload();
                    }
                });
};

yam.mrn.classif.searchButtonHandler = function () {
    window.location = 'index.php?page=mrn_classif_search';
};/**
 * Create a form to insert a new classified.
 */
yam.mrn.classif.buildCreatePanel = function () {
    var store, modelloCombo, notes, picture, saveButton;
    store = yam.mrn.buildModelloStore();
    modelloCombo = new Ext.form.ComboBox({
        store: store,
        name: 'modelCombo',
        mode: 'local',
        fieldLabel: 'Modello',
        valueField: 'id',
        displayField: 'name',
        forceSelection: true,
        width: 500
    });
    notes = {
        xtype: 'htmleditor',
        name: 'notes',
        fieldLabel: 'Accessori e Condizioni',
        height: 200
    };
    picture = {
        xtype: 'textfield',
        fieldLabel: 'Fotografia',
        name: 'picture',
        allowBlank: true,
        inputType: 'file'
    };
    yam.mrn.classif.theForm = new Ext.form.FormPanel({
        renderTo: 'formDiv',
        id: 'theForm',
        width: 630,
        url: 'index.php?page=mrn_classif_save',
        method: 'POST',
        fileUpload: true,
        frame: true,
        items: [
            modelloCombo, notes, picture
        ],
        bbar: [
            { text: 'Salva', handler: yam.mrn.classif.saveButtonHandler,
                iconCls: 'icon-application_osx_add' }, '-',
            { text: 'Annulla', handler: yam.mrn.classif.cancelButtonHandler, 
                iconCls: 'icon-application_osx_stop' }, '-'
        ]
    });
};
/**
 * Build the list of dealer's classified
 */
yam.mrn.classif.buildMyList = function () {
    var store, selModel, grid, renderPicture, deleteButtonHandler;
    store = new Ext.data.JsonStore({
        url: 'index.php?page=mrn_classif_load',
        root: 'records',
        fields: [ 'id', 'date_ins', 'model', 'notes', 'thumb' ]
    });
    selModel = new Ext.grid.RowSelectionModel({
        singleSelect: true
    });
    renderPicture = function (value) {
        var picture = "<img src='" + value + "'/>";
        return picture;
    };
    deleteButtonHandler = function () {
        yam.mrn.classif.deleteButtonHandler(selModel);
    };
    grid = new Ext.grid.GridPanel({
        renderTo: 'myList',
        id: 'myGridPanel',
        store: store,
        columns: [
            {header: 'Id', width: 50, dataIndex: 'id', id: 'id', sortable: true, hidden: true},
            {header: 'Data', width: 80, dataIndex: 'date_ins', id: 'data_ins', sortable: true},
            {header: 'Modello', width: 300, dataIndex: 'model', id: 'model', sortable: true},
            {header: 'Note', width: 140, dataIndex: 'notes', id: 'notes', sortable: false},
            {header: 'Fotografia', width: 100, dataIndex: 'thumb', id: 'thumb', sortable: false,
              renderer: renderPicture}
        ],
        autoExpandColumn: 'model',
        height: 300,
        stripeRows: true,
        loadMask: true,
        selModel: selModel,
        tbar: {
            items: [
                {
                    text: 'Inserisci',
                    iconCls: 'icon-application_osx_add',
                    handler: function () {
                        window.location = 'index.php?page=mrn_classif_add';
                    }
                }, '-',
                {
                    text: 'Elimina',
                    iconCls: 'icon-application_osx_delete',
                    handler: deleteButtonHandler
                }, '-',
                {
                    text: 'Cerca',
                    iconCls: 'icon-application_form_magnify',
                    handler: yam.mrn.classif.searchButtonHandler
                }
            ]
        }
    });
    store.load();
};
/**
 * Build the Marine classified search form
 */
yam.mrn.classif.buildSearchPage = function () {
    var store, selModel, grid, renderPicture;
    store = new Ext.data.JsonStore({
        url: 'index.php?page=mrn_classif_load',
        root: 'records',
        fields: [ 'id', 'date_ins', 'model', 'notes', 'thumb' ]
    });
    selModel = new Ext.grid.RowSelectionModel({
        singleSelect: true
    });
    renderPicture = function (value) {
        return "<img src='" + value + "'/>";
    };
    grid = new Ext.grid.GridPanel({
        renderTo: 'searchDiv',
        id: 'myGridPanel',
        store: store,
        columns: [
            {header: 'Id', width: 50, dataIndex: 'id', id: 'id', sortable: true, hidden: true},
            {header: 'Data', width: 80, dataIndex: 'date_ins', id: 'data_ins', sortable: true, hidden: true },
            {header: 'Provincia', width: 60, dataIndex: 'provincia', id: 'provincia', sortable: true},
            {header: 'Modello', width: 300, dataIndex: 'model', id: 'model', sortable: true},
            {header: 'Note', width: 140, dataIndex: 'notes', id: 'notes', sortable: false},
            {header: 'Fotografia', width: 100, dataIndex: 'thumb', id: 'thumb', sortable: false,
              renderer: renderPicture}
        ],
        autoExpandColumn: 'model',
        height: 300,
        stripeRows: true,
        loadMask: true,
        selModel: selModel,
        tbar: {
            items: [
                {
                    text: 'Mie dispon.',
                    iconCls: 'icon-application_side_list',
                    handler: function () {
                        window.location = 'index.php?page=mrn_classif';
                    }
                }
            ]
        }
    });
    store.load();
};

yam.shared.buildProvinciaStore = function () {
    yam.shared.provinciaStore = new Ext.data.ArrayStore({
        fields: ['id', 'name'],
        data: [
            ["AG", "Agrigento (AG)"],
            ["AL", "Alessandria (AL)"],
            ["AN", "Ancona (AN)"],
            ["AO", "Aosta (AO)"],
            ["AR", "Arezzo (AR)"],
            ["AP", "Ascoli Piceno (AP)"],
            ["AT", "Asti (AT)"],
            ["AV", "Avellino (AV)"],
            ["BA", "Bari (BA)"],
            ["BT", "Barletta-Andria-Trani (BT)"],
            ["BL", "Belluno (BL)"],
            ["BN", "Benevento (BN)"],
            ["BG", "Bergamo (BG)"],
            ["BI", "Biella (BI)"],
            ["BO", "Bologna (BO)"],
            ["BZ", "Bolzano (BZ)"],
            ["BS", "Brescia (BS)"],
            ["BR", "Brindisi (BR)"],
            ["CA", "Cagliari (CA)"],
            ["CL", "Caltanissetta (CL)"],
            ["CB", "Campobasso (CB)"],
            ["CI", "Carbonia-Iglesias (CI)"],
            ["CE", "Caserta (CE)"],
            ["CT", "Catania (CT)"],
            ["CZ", "Catanzaro (CZ)"],
            ["CH", "Chieti (CH)"],
            ["CO", "Como (CO)"],
            ["CS", "Cosenza (CS)"],
            ["CR", "Cremona (CR)"],
            ["KR", "Crotone (KR)"],
            ["CN", "Cuneo (CN)"],
            ["EN", "Enna (EN)"],
            ["FM", "Fermo (FM)"],
            ["FE", "Ferrara (FE)"],
            ["FI", "Firenze (FI)"],
            ["FG", "Foggia (FG)"],
            ["FC", "Forli\' Cesena (FC)"],
            ["FR", "Frosinone (FR)"],
            ["GE", "Genova (GE)"],
            ["GO", "Gorizia (GO)"],
            ["GR", "Grosseto (GR)"],
            ["IM", "Imperia (IM)"],
            ["IS", "Isernia (IS)"],
            ["AQ", "L\'Aquila (AQ)"],
            ["SP", "La Spezia (SP)"],
            ["LT", "Latina (LT)"],
            ["LE", "Lecce (LE)"],
            ["LC", "Lecco (LC)"],
            ["LI", "Livorno (LI)"],
            ["LO", "Lodi (LO)"],
            ["LU", "Lucca (LU)"],
            ["MC", "Macerata (MC)"],
            ["MN", "Mantova (MN)"],
            ["MS", "Massa (MS)"],
            ["MT", "Matera (MT)"],
            ["VS", "Medio Campidano (VS)"],
            ["ME", "Messina (ME)"],
            ["MI", "Milano (MI)"],
            ["MO", "Modena (MO)"],
            ["MB", "Monza e Brianza (MB)"],
            ["NA", "Napoli (NA)"],
            ["NO", "Novara (NO)"],
            ["NU", "Nuoro (NU)"],
            ["OG", "Ogliastra (OG)"],
            ["OT", "Olbia-Tempio (OT)"],
            ["OR", "Oristano (OR)"],
            ["PD", "Padova (PD)"],
            ["PA", "Palermo (PA)"],
            ["PR", "Parma (PR)"],
            ["PV", "Pavia (PV)"],
            ["PG", "Perugia (PG)"],
            ["PU", "Pesaro (PU)"],
            ["PE", "Pescara (PE)"],
            ["PC", "Piacenza (PC)"],
            ["PI", "Pisa (PI)"],
            ["PT", "Pistoia (PT)"],
            ["PN", "Pordenone (PN)"],
            ["PZ", "Potenza (PZ)"],
            ["PO", "Prato (PO)"],
            ["RG", "Ragusa (RG)"],
            ["RA", "Ravenna (RA)"],
            ["RC", "Reggio Calabria (RC)"],
            ["RE", "Reggio Emilia (RE)"],
            ["RI", "Rieti (RI)"],
            ["RN", "Rimini (RN)"],
            ["RM", "Roma (RM)"],
            ["RO", "Rovigo (RO)"],
            ["SA", "Salerno (SA)"],
            ["SS", "Sassari (SS)"],
            ["SV", "Savona (SV)"],
            ["SI", "Siena (SI)"],
            ["SR", "Siracusa (SR)"],
            ["SO", "Sondrio (SO)"],
            ["TA", "Taranto (TA)"],
            ["TE", "Teramo (TE)"],
            ["TR", "Terni (TR)"],
            ["TO", "Torino (TO)"],
            ["TP", "Trapani (TP)"],
            ["TN", "Trento (TN)"],
            ["TV", "Treviso (TV)"],
            ["TS", "Trieste (TS)"],
            ["UD", "Udine (UD)"],
            ["VA", "Varese (VA)"],
            ["VE", "Venezia (VE)"],
            ["VB", "Verbania (VB)"],
            ["VC", "Vercelli (VC)"],
            ["VR", "Verona (VR)"],
            ["VV", "Vibo Valentia (VV)"],
            ["VI", "Vicenza (VI)"],
            ["VT", "Viterbo (VT)"]
        ]
    });
};

yam.mrn.buildModelloStore = function () {
    var modelloStore = new Ext.data.ArrayStore({
        fields: ['id', 'name'],
        data: [
            ["8", "CAPELLI  - CAP 18 - "],
            ["9", "CAPELLI  - CAP 19 OPEN - F115AETL"],
            ["6", "JEANNEAU CENTER CONSOLE - CAP CAMARAT 6.5 CC - F115 AETL"],
            ["7", "JEANNEAU CENTER CONSOLE - CAP CAMARAT 6.5 CC - F150 AETL"],
            ["1", "JEANNEAU CENTER CONSOLE - CAP CAMARAT 7.5 CC - 2xF150 AETL"],
            ["5", "JEANNEAU CENTER CONSOLE - CAP CAMARAT 7.5 CC - F200 CETX"],
            ["2", "JEANNEAU CENTER CONSOLE - CAP CAMARAT 7.5 CC - F225 FETX"],
            ["3", "JEANNEAU CENTER CONSOLE - CAP CAMARAT 7.5 CC - F250 DETX"],
            ["4", "JEANNEAU CENTER CONSOLE - CAP CAMARAT 7.5 CC - F300 BETX"]
        ]
    });
    return modelloStore;
};

