﻿Ext.onReady(function () {
    Ext.ns('extManager');
    
    Ext.state.Manager.setProvider(new Ext.state.CookieProvider());

    extManager.interfaceStore = new Ext.data.JsonStore({
        id: 'interfaceStore',
        root: 'interfaces',
        fields: ['interfaceID', 'interfaceName', 'interfaceURL']
    });

    extManager.teamStore = new Ext.data.JsonStore({
        root: 'teams',
        fields: ['teamName']
    });

    extManager.Panel = new Ext.Panel({
        cls: 'loginPanel',
        renderTo: 'login',
        border: false,
        height: 35,
        items: [
            {
                id: 'usernamePanel',
                width: 140,
                cls: 'loginbox',
                items: [{
                    xtype: 'textfield',
                    id: 'username',
                    name: 'username',
                    stateful: true,
                    stateEvents: ['valid', 'blur'],
                    emptyText: ' ',
                    emptyClass: 'usernameTextbox',
                    getState: function () {
                        return { value: this.getValue() };
                    },
                    width: 140,
                    enableKeyEvents: true,
                    listeners: {
                        keydown: function (tf, e) {
                            if (e.keyCode == 13) Ext.getCmp('main-toolbar-button-ok').fireEvent('click', null);
                        }
                    }
                }]
            },
            {
                id: 'passwordPanel',
                width: 170,
                cls: 'loginbox',
                items: [{
                    xtype: 'textfield',
                    id: 'password',
                    name: 'password',
                    inputType: 'password',
                    emptyText: ' ',
                    emptyClass: 'passwordTextbox',
                    width: 170,
                    enableKeyEvents: true,
                    listeners: {
                        keydown: function (tf, e) {
                            if (e.keyCode == 13) Ext.getCmp('main-toolbar-button-ok').fireEvent('click', null);
                        }
                    }
                }]
            },
            {
                id: 'okPanel1',
                cls: 'loginbutton',
                width: 25,
                items: [{
                    xtype: 'button',
                    id: 'main-toolbar-button-ok',
                    buttonId: 'buttonOKHTML',
                    iconCls: 'loginbuttonOk',
                    width: 22,
                    //overCls: 'loginbuttonCancel',
                    listeners: {
                        click: function () {
                            Ext.Ajax.request({
                                url: baseUrl + 'ajax/Login.ashx',
                                method: 'POST',
                                params: {
                                    action: 'Login',
                                    username: Ext.getCmp('username').getValue(),
                                    password: Ext.getCmp('password').getValue()
                                },
                                callback: function (opt, success, resp) {
                                    Ext.getCmp('cancelPanel').show();
                                    var jsonResponse = Ext.util.JSON.decode(resp.responseText);
                                    if (jsonResponse.error) {
                                        alert(jsonResponse.error);
                                    } else {
                                        extManager.interfaceStore.loadData(jsonResponse.data);
                                        _authTicket = jsonResponse.data.authTicket;
                                        if (jsonResponse.data.interfaces.length == 1) {
                                            extManager.selectInterface(jsonResponse.data.interfaces[0].interfaceID);
                                        } else {
                                            var ddInterface = Ext.getCmp('selectInterface');
                                            Ext.getCmp('passwordPanel').hide();
                                            Ext.getCmp('okPanel1').hide();
                                            ddInterface.setValue(extManager.interfaceStore.getAt(0).data['interfaceID']);
                                            Ext.getCmp('interfaceSelectionPanel').show();
                                            ddInterface.focus(true);
                                            Ext.getCmp('okPanel2').show();
                                        }
                                    }
                                }
                            });
                        }
                    }
                }]
            },
            {
                id: 'interfaceSelectionPanel',
                width: 170,
                cls: 'loginbox',
                hideMode: 'offsets',
                hidden: true,
                items: [{
                    xtype: 'combo',
                    id: 'selectInterface',
                    name: 'selectInterface',
                    fieldLabel: '&nbsp;',
                    width: 170,
                    store: extManager.interfaceStore,
                    displayField: 'interfaceName',
                    valueField: 'interfaceID',
                    typeAhead: true,
                    mode: 'local',
                    forceSelection: true,
                    allowBlank: false,
                    blankText: 'Please select a website',
                    editable: false,
                    selectOnFocus: true,
                    triggerAction: 'all',
                    enableKeyEvents: true,
                    listeners: {
                        keydown: function (tf, e) {
                            if (e.keyCode == 13) {
                                tf.onViewClick(false);
                                Ext.getCmp('main-toolbar-button-ok2').fireEvent('click', null);
                            }
                        }
                    }
                }]
            },
            {
                id: 'okPanel2',
                width: 25,
                hidden: true,
                cls: 'loginbutton',
                items: [{
                    xtype: 'button',
                    id: 'main-toolbar-button-ok2',
                    buttonId: 'buttonOK2HTML',
                    iconCls: 'loginbuttonOk',
                    listeners: {
                        click: function () {
                            extManager.selectInterface(Ext.getCmp('selectInterface').getValue());
                        }
                    }
                }]
            },
            {
                id: 'teamSelectionPanel',
                width: 170,
                cls: 'loginbox',
                hideMode: 'offsets',
                hidden: true,
                items: [{
                    xtype: 'combo',
                    id: 'selectTeam',
                    name: 'selectTeam',
                    width: 170,
                    store: extManager.teamStore,
                    displayField: 'teamName',
                    typeAhead: true,
                    mode: 'local',
                    forceSelection: true,
                    allowBlank: false,
                    blankText: 'Please select a team',
                    editable: false,
                    selectOnFocus: true,
                    triggerAction: 'all',
                    enableKeyEvents: true,
                    listeners: {
                        keydown: function (tf, e) {
                            if (e.keyCode == 13) {
                                tf.onViewClick(false);
                                Ext.getCmp('main-toolbar-button-ok3').fireEvent('click', null);
                            }
                        }
                    }
                }]
            },
            {
                id: 'okPanel3',
                width: 25,
                cls: 'loginbutton',
                hidden: true,
                items: [{
                    xtype: 'button',
                    iconCls: 'loginbuttonOk',
                    id: 'main-toolbar-button-ok3',
                    buttonId: 'buttonOK3HTML',
                    listeners: {
                        click: function () {
                            extManager.selectTeam(Ext.getCmp('selectTeam').getValue());
                        }
                    }
                }]
            },
            {
                id: 'cancelPanel',
                width: 25,
                cls: 'loginbutton',
                hidden: false,
                disabled: false,
                items: [{
                    xtype: 'button',
	                id: 'main-toolbar-button-cancel',
                    iconCls: 'loginbuttonCancel',
				    listeners: {
				        click: function (b) {
				            Ext.getCmp('interfaceSelectionPanel').hide();
				            Ext.getCmp('teamSelectionPanel').hide();
				            Ext.getCmp('okPanel2').hide();
				            Ext.getCmp('okPanel3').hide();
				            Ext.getCmp('password').setValue('');
				            Ext.getCmp('passwordPanel').show();
				            Ext.getCmp('okPanel1').show();
				            Ext.getCmp('cancelPanel').show();
				        }
				    }
                }]
            }
        ]
    })

    extManager.selectInterface = function(i) {
        _interfaceID = i;
        // _interfaceURL = extManager.interfaceStore.getById(i).data['interfaceURL'];

        var iid = extManager.interfaceStore.data['interfaceID'];


        var ii = 0;
        extManager.interfaceStore.each(function(rec){
            if (_interfaceID === extManager.interfaceStore.data.items[ii].data['interfaceID']){
                _interfaceURL = extManager.interfaceStore.data.items[ii].data['interfaceURL'];
            }
            ii+=1;
        });

//            _interfaceURL = extManager.interfaceStore.data.items[i].data['interfaceURL']
	
        if (_pid != 0) _interfaceURL = _interfaceURL.replace(/CaseManager\.aspx/, 'CaseDetails.aspx?id=' + _pid);
        Ext.Ajax.request({
            url: baseUrl + 'ajax/Login.ashx',
            method: 'POST',
            params: {
                action: 'SelectInterface',
                interfaceid: _interfaceID,
                username: Ext.getCmp('username').getValue(),
                password: Ext.getCmp('password').getValue()
            },
            callback: function (opt, success, resp) {
                var jsonResponse = Ext.util.JSON.decode(resp.responseText);
                if (jsonResponse.error) {
                    alert(jsonResponse.error);
                } else {
                    if (jsonResponse.data.teams.length == 0) {
                        var url = _interfaceURL + (_interfaceURL.indexOf('?') == -1 ? '?' : '&') + Ext.urlEncode({
                            AuthTicket: jsonResponse.data.authTicket,
                            TeamID: 0,
                            TeamName: '',
                            TSOSUSerid: jsonResponse.data.tsosUserID
                        });
                        document.location.href = url;
                    } else {
                        if (jsonResponse.data.teams.length == 1) {
                            extManager.selectTeam(jsonResponse.data.teams[0].teamName);
                        } else {
                            var ddTeam = Ext.getCmp('selectTeam');
                            extManager.teamStore.loadData(jsonResponse.data);
                            Ext.getCmp('passwordPanel').hide();
                            Ext.getCmp('okPanel1').hide();
                            Ext.getCmp('interfaceSelectionPanel').hide();
                            Ext.getCmp('okPanel2').hide();
                            ddTeam.setValue(extManager.teamStore.getAt(0).data['teamName']);
                            Ext.getCmp('teamSelectionPanel').show();
                            ddTeam.focus(true);
                            Ext.getCmp('okPanel3').show();
                        }
                    }
                }
            }
        });
    }

    extManager.selectTeam = function(t) {
        Ext.Ajax.request({
            url: baseUrl + 'ajax/Login.ashx',
            method: 'POST',
            params: {
                action: 'SelectTeam',
                teamName: t,
                interfaceid: _interfaceID,
                username: Ext.getCmp('username').getValue(),
                password: Ext.getCmp('password').getValue()
            },
            callback: function (opt, success, resp) {
                var jsonResponse = Ext.util.JSON.decode(resp.responseText);
                if (jsonResponse.error) {
                    alert(jsonResponse.error);
                } else {
                    var url = _interfaceURL + (_interfaceURL.indexOf('?') == -1 ? '?' : '&') + Ext.urlEncode({
                        AuthTicket: jsonResponse.data.authTicket,
                        TeamID: jsonResponse.data.teamID,
                        TeamName: jsonResponse.data.teamName,
                        TSOSUSerid: jsonResponse.data.tsosUserID
                    });
                    document.location.href = url;
                }
            }
        });
    }

    Ext.getCmp('username').getValue()==''?Ext.getCmp('username').focus():Ext.getCmp('password').focus();
});
