CS2.Delete.UserLDAPLink = function(initOptions){
    var _self = this;
    this.settings = {};
    Ext.apply(this.settings, initOptions);
    this.win = new Ext.Window({
        title: 'Unlink LDAP from '+CS2.cyberschoolSiteVerbage()+' Account',
        width:420,
        resizable: false,
        cls: 'x-window-dlg',
        iconCls: 'cpi_connectUser',
        constrainHeader: true,
        layout: 'fit',
        plain: true,
        bodyStyle: 'font-size: 13px; padding: 10px;',
        html: new Ext.XTemplate(
          '<div class="x-dlg-icon">',
            '<div class="ext-mb-icon ext-mb-warning"></div>',
            '<div class="ext-mb-content">',
              '<span class="ext-mb-text">',
                '<strong>Are you sure you want to remove the LDAP link to this account?</strong><br /><br />Once unlinked, the specified user(s) may not be able to login without administrative intervention if the user has not specified a '+CS2.cyberschoolSiteVerbage()+' password.',
              '</span>',
            '</div>',
            '<div class="x-clear"></div>',
          '</div>'
        ).apply(),
        buttons: [{
            text:'Unlink (3)',
            ref: '../DeleteButton',
            disabled:true,
            handler: function(){
              userData = [];
              Ext.each(_self.settings.users, function(user, index) {
                userData.push(user.data.username);
              });
              Ext.Msg.wait('Please wait...', 'Unlinking User'+(userData.length==1?'':'s')+' from LDAP');
              var params = {users: Ext.util.JSON.encode(userData)};
              Ext.Ajax.request({
                 url: '/ajax/siteconfig/userGroups/unlinkUsersFromLDAP.cfm',
                 method: 'POST',
                 'params': params,
                 reader : new Ext.data.JsonReader({
                  success : '@success'
                 }),
                 success: function(response, opts) {
                  _self.settings.mainContainerObj.dataStoreImport.load();
                  _self.settings.mainContainerObj.dataStoreSync.load();
                  _self.win.close();
                  Ext.Msg.hide();
                 },
                 failure: function(response, opts) {
                    Ext.Msg.alert('Error Unlinking Users', 'There was an error un-linking the users from LDAP"');
                 }
              });
              
            }
        },{
            text: 'Cancel',
            handler: function(){
                this.ownerCt.ownerCt.hide();
            }
        }]
    });
    this.win.show(this);
    setTimeout(function(){ _self.win.DeleteButton.setText('Unlink (2)'); }, CS2.countDownSpeed * 1);
    setTimeout(function(){ _self.win.DeleteButton.setText('Unlink (1)'); }, CS2.countDownSpeed * 2);
    setTimeout(function(){ _self.win.DeleteButton.setText('Unlink'); _self.win.DeleteButton.enable(); }, CS2.countDownSpeed * 3);
};

CS2.Create = {};
CS2.Create.UserLDAPLink = function(initOptions){
    var _self = this;
    this.settings = {};
    Ext.apply(this.settings, initOptions);

    this.userCombo = new Ext.form.ComboBox({
                                  hideLabel: true,
                                  anchor: '0',
                                  store: new Ext.data.Store({
                                    url: '/ajax/login/getUsersLDAP.cfm',
                                    reader : new Ext.data.JsonReader({
                                        root : 'users'
                                      },[
                                        {name: 'id', mapping: 'id'},
                                        {name: 'username', mapping: 'username'},
                                        {name: 'fullname', mapping: 'fullname'},
                                        {name: 'email', mapping: 'email'}
                                      ]
                                    )
                                  }),
                                  forceSelection: true,
                                  loadingText: 'Loading Users...',
                                  itemSelector: 'div.search-item',
                                  tpl:new Ext.XTemplate(
                                    '<tpl for="."><div class="search-item">',
                                      '<h3><span>{fullname}</span></h3><strong>{username}</strong> &bull; {email}',
                                    '</div></tpl>'
                                  ),
                                  hiddenName: 'assignUserField',
                                  valueField: 'id',
                                  displayField: 'fullname',
                                  typeAhead: true,
                                  mode: 'remote',
                                  triggerAction: 'all',
                                  emptyText:'Select a user...',
                                  selectOnFocus:true,
                                  listeners: {
                                    select: function(c, r, i){
                                      _self.win.importButton.setDisabled(false);
                                    },
                                    change: function(c, n, o){
                                      if (!n || n=='')
                                        _self.win.importButton.setDisabled(true);
                                    }
                                  }
                              });

      this.mainOptions = new Ext.form.FieldSet({
          title: 'Select a User to Assign LDAP',
          autoHeight: true,
          layout: 'form',
          items: [this.userCombo]
      });

      this.win = new Ext.Window({
        title: 'User LDAP Connector',
        iconCls: 'cpi_connectUser',
        layout:'fit',
        resizable: false,
        padding: 5,
        width: 300,
        height: 140,
        modal: true,
        constrainHeader:true,
        items: this.mainOptions,
        buttons: [{
            text: 'Attach',
            disabled: true,
            ref: '../importButton', 
            handler: function(){
              Ext.Msg.wait('Please wait...', 'Linking User to LDAP');
              var params = {sync: _self.settings.user[0].data.username, user: _self.userCombo.getValue()};
              Ext.Ajax.request({
                 url: '/ajax/siteconfig/userGroups/connectUserToLDAP.cfm',
                 method: 'POST',
                 'params': params,
                 reader : new Ext.data.JsonReader({
                  success : '@success'
                 }),
                 success: function(response, opts) {
                  _self.settings.mainContainerObj.dataStoreImport.load();
                  _self.settings.mainContainerObj.dataStoreSync.load();
                  _self.win.close();
                  Ext.Msg.hide();
                 },
                 failure: function(response, opts) {
                    Ext.Msg.alert('Error Linking User to LDAP', 'There was an error linking User to LDAP"');
                 }
              });
            }
          },{
            text: 'Cancel',
            handler: function(){
              _self.win.close();
            }
          }
        ],
        bbar: this.mainStatus
      });
      this.win.show(this);
};


var unsyncdMenuManager = function(item){
  var n = item.parentMenu.userSelections;
  var e = item.parentMenu.mainContainerObj;

  switch (item.menuID) {
    case 'linkLDAP':
      new CS2.Create.UserLDAPLink({user: n, mainContainerObj: e});
      break;
  }
};
var unsyncdMenu = new Ext.menu.Menu({
                                items:[
                                        {
                                          menuID: 'linkLDAP',
                                          ref: 'linkLDAP',
                                          iconCls: 'cpi_connectUser',
                                          text: 'Manually Link to...'
                                        }
                                      ],
                                listeners: { itemclick: unsyncdMenuManager }
                              });

var syncdMenuManager = function(item){
  var n = item.parentMenu.userSelections;
  var e = item.parentMenu.mainContainerObj;
  switch (item.menuID) {
    case 'unlinkLDAP':
      new CS2.Delete.UserLDAPLink({users: n, mainContainerObj: e});
      break;
  }
};
var syncdMenu = new Ext.menu.Menu({
                                items:[
                                        {
                                          menuID: 'unlinkLDAP',
                                          ref: 'unlinkLDAP',
                                          iconCls: 'cpi_disconnectUser',
                                          text: 'Unlink LDAP'
                                        }
                                      ],
                                listeners: { itemclick: syncdMenuManager }
                              });
  
  function windowUserImporter(initOptions){
    var _self = this;
    this._settings = {};
    Ext.apply(this._settings, initOptions);

    this.tpl = new Ext.XTemplate(
      '<div class="cpThumbs">',
		    '<tpl for=".">',
          '<div class="thumb-wrap">',
      	    '<div class="thumb cp_{bigIcon}"></div>',
            '<span class="x-editable">{name}</span>',
          '</div>',
        '</tpl>',
        '<div class="x-clear"></div>',
      '</div>'
  	);
  	
  	var allFields = [
                 {name: 'userID', type: 'int'},
                 {name: 'username'},
                 {name: 'last_sync', type: 'date', dateFormat: 'Y-m-d H:i:s.u'},
                 {name: 'linked', type: 'bool'},
                 {name: 'cs_username'},
                 {name: 'cs_userid'},
                 {name: 'fName'},
                 {name: 'lName'},
                 {name: 'display'},
                 {name: 'email'},
                 {name: 'dn'},
                 {name: 'homeDrive'},
                 {name: 'homephone'},
                 {name: 'c'},
                 {name: 'company'},
                 {name: 'department'},
                 {name: 'location'},
                 {name: 'manager'},
                 {name: 'mobile'},
                 {name: 'postalCode'},
                 {name: 'st'},
                 {name: 'streetAddress'},
                 {name: 'telephoneNumber'},
                 {name: 'l'},
                 {name: 'o'},
	
                 {name: 'objectCategory'},
                 {name: 'objectClass'},
                 {name: 'profilePath'},
                 {name: 'userPrincipalName'},
                 {name: 'physicalDeliveryOfficeName'},

                 {name: 'sAMAccountName'},
                 {name: 'userAccountControl'}
        ];

    this.dataStoreImport = new Ext.data.GroupingStore({
      url: '/ajax/siteconfig/userGroups/getLDAPUsers.cfm?type=import',
      sortInfo: {field:'username', direction:'ASC'},
      autoLoad: {params:{start:0, limit:25, filter:''}},
      reader: new Ext.data.JsonReader({
        root: 'users',        
        successProperty: 'success',
        idProperty: 'userID',
        fields: allFields
      }),
      listeners:{
        beforeload: function(store, options) {
          Ext.Msg.wait('Connecting to Active Directory... please wait.', 'Fetching Users...');
        },
        load: function(store, records, options) {
          Ext.Msg.hide();
        },
        loadexception: function(store, options, response, error) {
          var o = Ext.util.JSON.decode(response.responseText);
          Ext.Msg.alert('Fetching Users Failed', o.msg);
        }
      }
    });
    this.dataStoreSync = new Ext.data.GroupingStore({
      url: '/ajax/siteconfig/userGroups/getLDAPUsers.cfm?type=sync',
      sortInfo: {field:'username', direction:'ASC'},
      autoLoad: {params:{start:0, limit:25, filter:''}},
      reader: new Ext.data.JsonReader({
        root: 'users',
        successProperty: 'success',
        idProperty: 'userID',
        fields: allFields
      })
    });

    this.importStatus = new Ext.ux.StatusBar({
      defaultText: '0 selected users',
      text: '0 selected users'
    });
    this.syncStatus = new Ext.ux.StatusBar({
      defaultText: '0 selected users',
      text: '0 selected users'
    });

    var smImport = new Ext.grid.CheckboxSelectionModel({
        	checkOnly: true,
          listeners: {
            selectionchange: function(sm){
              var sels = sm.getSelections();
              _self.importGrid.importButton.setDisabled(sm.getCount() == 0);
              var userCnt = sm.getCount();
              _self.importStatus.setStatus({
                              text: userCnt + ' selected user' + (userCnt !=1 ? "s" : "")
                          });
            }
          }
        });
    var smSync = new Ext.grid.CheckboxSelectionModel({
        	checkOnly: true,
          listeners: {
            selectionchange: function(sm){
              var sels = sm.getSelections();
              _self.syncGrid.syncButton.setDisabled(sm.getCount() == 0);
              var userCnt = sm.getCount();
              _self.syncStatus.setStatus({
                              text: userCnt + ' selected user' + (userCnt !=1 ? "s" : "")
                          });
            }
          }
        });

    
    this.importGrid = new Ext.grid.GridPanel({
        title: 'Import',        
        border: false,
        store: this.dataStoreImport,
        columns: [
            smImport,
            {header: "AD Username", width: 200, sortable: true, dataIndex: 'username'},
            {header: "Email", width: 200, sortable: true, dataIndex: 'email'},
            {header: "First Name", width: 100, sortable: true, dataIndex: 'fName'},
            {header: "Last Name", width: 100, sortable: true, dataIndex: 'lName'},
            {header: "Display", width: 200, sortable: true, dataIndex: 'display'}
        ],
        tbar: [
          {
            text: 'Import Users',
            iconCls: 'cpi_importUser',
            ref: '../importButton', 
            disabled: true,
            handler: function(){
              var selMod = _self.importGrid.getSelectionModel();
              new windowApplyGroups({users: selMod.getSelections(), mainContainerObj: _self});
            }
          },'-',{
            text: 'Refresh',
            iconCls: 'file-refresh-icon',
            ref: '../refreshButton',
            handler: function(){
              _self.dataStoreImport.load();
              _self.dataStoreSync.load();
            }
          }
        ],
        sm: smImport,
        stripeRows: true,
        bbar: this.importStatus,
        listeners: {
          rowcontextmenu: function(g,rI,e){
            e.stopEvent();
            var selMod = _self.importGrid.getSelectionModel();
            sels = selMod.getSelections();
            unsyncdMenu.linkLDAP.setDisabled(sels.length!=1);
            unsyncdMenu.userSelections = sels;
            unsyncdMenu.mainContainerObj = _self;
            unsyncdMenu.showAt(e.getXY());
          }
        }
    });
    this.syncGrid = new Ext.grid.GridPanel({
        title: 'Sync\'d',
        border: false,
        store: this.dataStoreSync,
        columns: [
            smSync,
            {header: "AD Username", width: 180, sortable: true, dataIndex: 'username'},
            {header: "CS Username", width: 130, sortable: true, dataIndex: 'cs_username'},
            {header: "Last Sync", width: 140, sortable: true, dataIndex: 'last_sync'},
            {header: "Email", width: 150, sortable: true, dataIndex: 'email'},
            {header: "First Name", width: 100, sortable: true, dataIndex: 'fName'},
            {header: "Last Name", width: 100, sortable: true, dataIndex: 'lName'},
            {header: "Display", width: 200, sortable: true, dataIndex: 'display'}
        ],
        tbar: [
          {
            text: 'Re-Sync Users',
            iconCls: 'cpi_syncUser',
            ref: '../syncButton', 
            disabled: true,
            handler: function(){
              var selMod = _self.syncGrid.getSelectionModel();
              new windowSyncUsers({users: selMod.getSelections(), mainContainerObj: _self});
            }
          },'-',{
            text: 'Refresh',
            iconCls: 'file-refresh-icon',
            ref: '../refreshButton',
            handler: function(){
              _self.dataStoreImport.load();
              _self.dataStoreSync.load();
            }
          }
        ],
        sm: smSync,
        stripeRows: true,
        bbar: this.syncStatus,
        listeners: {
          rowcontextmenu: function(g,rI,e){
            e.stopEvent();
            var selMod = _self.syncGrid.getSelectionModel();
            sels = selMod.getSelections();
            syncdMenu.unlinkLDAP.setDisabled(sels.length==0);
            syncdMenu.userSelections = sels;
            syncdMenu.mainContainerObj = _self;
            syncdMenu.showAt(e.getXY());
          }
        }
    });

    this.win = new Ext.Window({
      title: 'User Import',
      iconCls: 'cpi_ugImport',
      layout:'fit',
      resizable: true,
      maximizable: true,
      padding: 5,
      width: 650,
      height: 500,
      modal: true,
      constrainHeader:true,
      listeners: {
        show: function(win){
          Ext.Msg.hide();
        }
      },
      items: new Ext.TabPanel({
        plain: true,
        activeTab: 0,  
        region: 'center',
        items: [this.importGrid, this.syncGrid]
      })
    });
    this.win.show(this);

  }
  
  function windowApplyGroups(initOptions){
    var _self = this;
    this._settings = {};
    Ext.apply(this._settings, initOptions);

    this.groupStore = new Ext.data.GroupingStore({
      url: '/ajax/siteconfig/userGroups/getUserGroups.cfm',
      sortInfo: {field:'groupName', direction:'ASC'},      
      autoLoad: {params:{}},
      reader: new Ext.data.JsonReader({
        root: 'groups',        
        idProperty: 'groupID',
        fields: [
                 {name: 'groupID', type: 'int'},
                 {name: 'groupName'},
                 {name: 'groupCount'}
        ]
      })
    });
  
    this.mainStatus = new Ext.ux.StatusBar({
      defaultText: 'Ready',
      text: 'Assigning 0 Groups to the ' + _self._settings.users.length + ' selected user' + (_self._settings.users.length !=1 ? "s" : "")
    });
  
    var sm = new Ext.grid.CheckboxSelectionModel({
        	checkOnly: true,
          listeners: {
            selectionchange: function(sm){
              var sels = sm.getSelections();
              var cnt = sm.getCount();
              var userCnt = _self._settings.users.length;
              _self.mainStatus.setStatus({
                              text: 'Assigning ' + cnt + ' Group' + (cnt !=1 ? "s" : "") + ' to the ' + userCnt + ' selected user' + (userCnt !=1 ? "s" : "")
                          });
            }
          }
        });
        
    this.schoolList = new Ext.form.ComboBox({
                                  hideLabel: true,
                                  anchor: '0',
                                  hiddenId:'user_schoolID',
                                  hiddenName:'user_schoolName',
                                  store: new Ext.data.JsonStore({
                                      autoDestroy: true,
                                      url: '/ajax/login/getSchools.cfm',
                                      storeId: 'userSchoolStore',
                                      root: 'schools',
                                      idProperty: 'schoolID',
                                      fields: ['schoolID', 'userSchool']
                                  }),
                                  forceSelection: true,
                                  loadingText: 'Loading '+CS2.schoolsVerbage()+'...',
                                  valueField:'schoolID',
                                  displayField:'userSchool',
                                  typeAhead: true,
                                  mode: 'remote',
                                  triggerAction: 'all',
                                  emptyText:'Select a '+CS2.schoolSubsiteVerbage()+'...',
                                  selectOnFocus:true,
                                  listeners: {
                                    select: function(c, r, i){
                                      _self.win.importButton.setDisabled(false);
                                    },
                                    change: function(c, n, o){
                                      if (!n || n=='')
                                        _self.win.importButton.setDisabled(true);
                                    }
                                  }
                              });        
    
    this.mainGrid = new Ext.grid.GridPanel({
                      border: true,
                      height: 190,
                      width: 254,
                      store: this.groupStore,
                      columns: [
                          sm,
                          {header: "Group", width: 150, sortable: true, dataIndex: 'groupName'},
                          {header: "User Count", width: 100, sortable: true, dataIndex: 'groupCount'}
                      ],
                      sm: sm,
                      stripeRows: true
                    });
        
    this.mainHolder = [
      new Ext.form.FieldSet({
        title: CS2.schoolSubsiteVerbage()+' to Accept Import',
        autoHeight: true,
        layout: 'form',
        items: [this.schoolList]
      }),
      new Ext.form.FieldSet({
        title: 'Apply the following Groups',
        autoHeight: true,
        layout: 'form',
        collapsible: true,
        collapsed: true,
        items: [this.mainGrid]
      })
    ];
      

    this.win = new Ext.Window({
      title: 'User LDAP Import',
      iconCls: 'cpi_importUser',
      layout:'fit',
      resizable: false,
      padding: 5,
      width: 300,
      height: 400,
      modal: true,
      constrainHeader:true,
      items: this.mainHolder,
      buttons: [{
          text: 'Import!',
          disabled: true,
          ref: '../importButton', 
          handler: function(){
            var gSM = _self.mainGrid.getSelectionModel();
            userData = [];
            Ext.each(_self._settings.users, function(user, index) {
              userData.push(user.data);
            });
            groupData = [];
            Ext.each(gSM.getSelections(), function(group, index) {
              groupData.push(group.data);
            });
            
            Ext.Msg.wait('Please wait...', 'Importing '+(userData.length)+' User'+(userData.length==1?'':'s'));
            var params = {schoolID: _self.schoolList.getValue(), users: Ext.util.JSON.encode(userData), groups: Ext.util.JSON.encode(groupData)};
            Ext.Ajax.request({
               url: '/ajax/siteconfig/userGroups/importUsersFromLDAP.cfm',
               method: 'POST',
               'params': params,
               reader : new Ext.data.JsonReader({
                success : '@success'
               }),
               success: function(response, opts) {
                _self._settings.mainContainerObj.dataStoreImport.load();
                _self._settings.mainContainerObj.dataStoreSync.load();
                _self.win.close();
                Ext.Msg.hide();
               },
               failure: function(response, opts) {
                  Ext.Msg.alert('Error Importing User'+(userData.length==1?'':'s'), 'There was an error importing the users from LDAP"');
               }
            });
          }
        },{
          text: 'Cancel',
          handler: function(){
            _self.win.close();
          }
        }
      ],
      bbar: this.mainStatus
    });
    this.win.show(this);

  }

  function windowSyncUsers(initOptions){
    var _self = this;
    this._settings = {};
    Ext.apply(this._settings, initOptions);

    this.groupStore = new Ext.data.GroupingStore({
      url: '/ajax/siteconfig/userGroups/getUserGroups.cfm',
      sortInfo: {field:'groupName', direction:'ASC'},      
      autoLoad: {params:{}},
      reader: new Ext.data.JsonReader({
        root: 'groups',        
        idProperty: 'groupID',
        fields: [
                 {name: 'groupID', type: 'int'},
                 {name: 'groupName'},
                 {name: 'groupCount'}
        ]
      })
    });
  
    this.mainStatus = new Ext.ux.StatusBar({
      defaultText: 'Ready',
      text: 'Syncronizing ' + _self._settings.users.length + ' selected user' + (_self._settings.users.length !=1 ? "s" : "")
    });

    this.checkGroup = new Ext.form.CheckboxGroup({
                        hideLabel: true,
                        ref: '../checkGroup',
                        itemCls: 'x-check-group-alt',
                        columns: 1,
                        items: [
                          {boxLabel: 'Display Name', name: 'display', checked: true},
                          {boxLabel: 'Email Address', name: 'email', checked: true},
                          {boxLabel: 'Home Phone', name: 'homephone', checked: true},
                          {boxLabel: 'Mobile Phone', name: 'mobile', checked: true},
                          {boxLabel: 'Home Address', name: 'streetAddress', checked: true},
                          {boxLabel: 'City', name: 'l', checked: true},
                          {boxLabel: 'State', name: 'st', checked: true},
                          {boxLabel: 'ZIP', name: 'postalCode', checked: true}
                        ]
                      });

    this.mainOptions = new Ext.form.FieldSet({
        title: 'Select the Data to Synchronize',
        autoHeight: true,
        layout: 'form',
        items: [_self.checkGroup]
    });

    this.win = new Ext.Window({
      title: 'User LDAP Sync',
      iconCls: 'cpi_importUser',
      layout:'fit',
      resizable: false,
      padding: 5,
      width: 300,
      height: 345,
      modal: true,
      constrainHeader:true,
      items: this.mainOptions,
      buttons: [{
          text: 'Synchronize!',
          ref: '../importButton', 
          handler: function(){
            var gSM = _self.checkGroup;
            userData = [];

            Ext.each(_self._settings.users, function(user, index) {
              userData.push(user.data);
            });
            syncData = [];
            Ext.each(gSM.getValue(), function(group, index) {
              syncData.push(group.name);
            });
            Ext.Msg.wait('Please wait...', 'Synchronizing '+(userData.length)+' User'+(userData.length==1?'':'s'));
            var params = {users: Ext.util.JSON.encode(userData), sync: Ext.util.JSON.encode(syncData)};
            Ext.Ajax.request({
               url: '/ajax/siteconfig/userGroups/syncUsersFromLDAP.cfm',
               method: 'POST',
               'params': params,
               reader : new Ext.data.JsonReader({
                success : '@success'
               }),
               success: function(response, opts) {
                _self._settings.mainContainerObj.dataStoreImport.load();
                _self._settings.mainContainerObj.dataStoreSync.load();
                _self.win.close();
                Ext.Msg.hide();
               },
               failure: function(response, opts) {
                  Ext.Msg.alert('Error Synchronizing User'+(userData.length==1?'':'s'), 'There was an error synchronizing the users from LDAP"');
               }
            });
          }
        },{
          text: 'Cancel',
          handler: function(){
            _self.win.close();
          }
        }
      ],
      bbar: this.mainStatus
    });
    this.win.show(this);

  }

reportingIn('userImport');

