      var userStore2 = new Ext.data.Store({
          url: '/ajax/login/getUsersAssign.cfm',
          reader : new Ext.data.JsonReader({
              root : 'users'
            },[
              {name: 'id', mapping: 'id'},
              {name: 'username', mapping: 'username'},
              {name: 'fullname', mapping: 'fullname'},
              {name: 'email', mapping: 'email'}
            ]
          )
      });
      userStore2.load();
        
      function assignTeacher(el){
        assignUser(el);
      }
            
      function initializePatientDragZone(v) {
        v.dragZone = new Ext.dd.DragZone(v.getEl(), {
          getDragData: function(e) {
            var sourceEl = e.getTarget(v.itemSelector, 10);
            if (sourceEl) {
              d = sourceEl.cloneNode(true);
              d.id = Ext.id();
              return v.dragData = {
                sourceEl: sourceEl,
                repairXY: Ext.fly(sourceEl).getXY(),
                ddel: d,
                patientData: v.getRecord(sourceEl).data
              }
            }
          },
          getRepairXY: function() {
            return this.dragData.repairXY;
          }
        });
      }
      
      function initializeHospitalDropZone(g) {
        g.dropZone = new Ext.dd.DropZone(g.getEl(), {
          getTargetFromEvent: function(e) {
            return e.getTarget('.hospital-target');
          },
          onNodeEnter : function(target, dd, e, data){ 
            Ext.fly(target).addClass('hospital-target-hover');
          },
          onNodeOut : function(target, dd, e, data){ 
            Ext.fly(target).removeClass('hospital-target-hover');
          },
          onNodeOver : function(target, dd, e, data){ 
            return Ext.dd.DropZone.prototype.dropAllowed;
          },
          onNodeDrop : function(target, dd, e, data){
            Ext.Msg.alert('Adding '+CS2.studentVerbage(), 'Dropped '+CS2.studentsVerbage()+' ' + data.patientData.fullname);
            return true;
          }
        });
      }
      
      function assignStudents(el){

        var thumbTemplate = new Ext.XTemplate(
          '<tpl for=".">',
            '<div class="thumb-wrap hospital-target" id="user_{id}">',
            '<div class="thumb"><img src="{image}" title="{username}"></div>',
            '<span>{fullname}</span></div>',
          '</tpl>'
        );
        thumbTemplate.compile();
        
        var thumbTemplate2 = new Ext.XTemplate(
          '<tpl for=".">',
            '<div class="thumb-wrap hospital-target" id="user_{id}">',
            '<div class="thumb"><img src="{image}" title="{username}"></div>',
            '<span><span class="ufirst">{fullname}</span><span class="utype"> &bull; '+CS2.studentsVerbage()+'</span></span><br class="clear" /></div>',
          '</tpl>'
        );
        thumbTemplate2.compile();
        var currentUsers = new Ext.data.Store({
              autoLoad: true,
              url: '/ajax/siteconfig/gcd/getGCDUsers.cfm?id='+el.attributes.gcd_id+'&pt=entire&pn=',
              reader : new Ext.data.JsonReader({
                  root : 'users'
                },[
                  {name: 'id', mapping: 'id'},
                  {name: 'username', mapping: 'username'},
                  {name: 'fullname', mapping: 'fullname'},
                  {name: 'email', mapping: 'email'},
                  {name: 'image', mapping: 'image'}
                ]
              )
          });
          
        var userList = new Ext.DataView({
          tpl: thumbTemplate,
          singleSelect: true,
          cls: 'hospital-target',
          id: 'img-chooser-view',
          overClass:'x-view-over',
          itemSelector: 'div.thumb-wrap',
          emptyText : '<div style="padding:10px;">No images match the specified filter</div>',
          store: currentUsers,
          listeners: {
            render : function(dv){ initializePatientDragZone(dv); initializeHospitalDropZone(dv); }
          }
        });
        var studentList = new Ext.DataView({
          tpl: thumbTemplate2,
          singleSelect: true,
          cls: 'hospital-target',
          id: 'students-chooser-view',
          overClass:'x-view-over',
          itemSelector: 'div.thumb-wrap',
          emptyText : '<div style="padding:10px;">No images match the specified filter</div>',
          store: userStore,
          listeners: {
            render : function(dv){ initializePatientDragZone(dv); initializeHospitalDropZone(dv); }
          }
        });
        
        var usersLeft = new Ext.Panel({
          region: 'center',
          layout: 'border',
          border: true,
          items: [
            {
              region: 'north',
              margins:'-1 -1 0 -1',
              bodyStyle: 'padding: 5px; text-align: center;',
              cmargins:'3 3 3 3', 
              border: true, 
              html: '<strong>Currently Enrolled</strong>'
            },{autoScroll: true, region: 'center', border: false, items: userList}]
        });
        
        var usersRight = new Ext.Panel({
          region: 'east',
          width: 230,
          maxWidth: 430,
          minWidth: 230,
          split: true,
          layout: 'border',
          border: true,
          items: [
            {
              region: 'north',
              margins:'-1 -1 0 -1',
              bodyStyle: 'padding: 5px; text-align: center;',
              cmargins:'3 3 3 3', 
              border: true, 
              html: '<strong>All '+CS2.studentsVerbage()+'</strong>'
            },{autoScroll: true, region: 'center', border: false, items: studentList}]
        });
        
        var userAssigner = new Ext.Window({
            title: "Assign Users to this " + (el.attributes.data_type == 'department' ? 'Department' : 'Class'),
            layout: 'border',
            width: 555,
            height: 400,
            border:false,
            modal: true,
            maximizable: true,
            closeAction: 'close',
            items: [usersLeft, usersRight],
            buttons: [
                {
                  text: 'Assign',
                  handler: function(){
                    var datas = tehAssignForm.getForm().getValues();
                    el.attributes.user_fullname = $('assignUserNameField').value;
                    el.setText(el.attributes.title + ' (' + el.attributes.user_fullname + ')');
                    el.attributes.user_id = datas.assignUserField;
                    userAssigner.close();
                  }
                }, {text: 'Cancel', handler: function(){ userAssigner.close(); }}
              ],
            keys: [
                    {
                      key: 27, // Esc key
                      handler: function(){ userAssigner.close(); },
                      scope: this
                    }
                  ]
          });
        userAssigner.show();
      }
  
      var gcdMenu = new Ext.menu.Menu({
                                        items: [
                                                  {
                                                    id: 'mnu_item-edit_gcditem',
                                                    iconCls: 'cpi_userSettings',
                                                    text: 'Properties'
                                                  },{
                                                    id: 'mnu_item-edit_gcdassign-teacher',
                                                    iconCls: 'iconUser',
                                                    text: 'Assign '+CS2.teacherVerbage()+'..'
                                                  },{
                                                    id: 'mnu_item-edit_gcdassign-students',
                                                    iconCls: 'cpi_ugUsers',
                                                    text: 'Assign '+CS2.studentsVerbage()+'...'
                                                  },'-',{
                                                    id: 'mnu_item-edit_gcddelete',
                                                    text: 'Delete Item',
                                                    iconCls: 'file-permdelete-icon',
                                                    disabled: true
                                                  }
                                                ],
                                        listeners: {
                                          itemclick: function(item) {
                                            var n = item.parentMenu.contextNode;
                                            switch (item.id) {
                                              case 'mnu_item-edit_gcditem':
                                                if (n.parentNode) {
                                                  if (n.attributes.data_type=='department'){
                                                        setTimeout(function(){
                                                          callEditor({navigationContextNode: n, editorDataID: n.attributes.gcd_id, editorType: 'Department', editorModal: true});
                                                        }, 100);
                                                  }else if (n.attributes.data_type=='class'){
                                                      setTimeout(function(){
                                                        callEditor({navigationContextNode: n, editorDataID: n.attributes.gcd_id, editorType: 'Class', editorModal: true});
                                                      }, 100);
                                                  }else if (n.attributes.data_type=='header'){
                                                      setTimeout(function(){
                                                        callEditor({navigationContextNode: n, editorDataID: n.attributes.gcd_id, catType: n.attributes.cat_type, editorType: 'header', editorModal: true});
                                                      }, 100);
                                                  }
                                                }
                                                break;
                                              case 'mnu_item-edit_gcdassign-teacher':                        
                                                assignTeacher(n);
                                                break;
                                              case 'mnu_item-edit_gcdassign-students':                        
                                                //assignStudents(n);
                                                launchModule('userGroups', [n.attributes.gcd_id])
                                                //new windowGCDUserAssign(n).show();
                                                break;
                                              case 'mnu_item-edit_gcddelete':                        
                                                if (n.attributes.data_type=='header'){
                                                  msgTitle = 'Delete Header?';
                                                  msgStr = 'You are about to delete a category. This will also remove sub-menus. Are you sure you want to do this?';
                                                }else{
                                                  msgTitle = 'Delete Page?';
                                                  msgStr = 'You are about to delete an entire department! This will also delete the content. Are you sure you want to do this?';
                                                }
                                                if (n.parentNode) {
                                                  Ext.Msg.show({
                                                    title: msgTitle,
                                                    msg: msgStr,
                                                    buttons: Ext.Msg.YESNO,
                                                    fn: function(btn){
                                                      if (btn == 'yes'){
                                                        n.attributes.deleted=true;
                                                        n.getUI().hide();
                                                      }
                                                    },
                                                    icon: Ext.MessageBox.QUESTION
                                                  });
                                                }
                                                break;
                                            }
                                          }
                                        }
                                      });
                                      
      function windowGCDEditor(initOptions){
        var _self = this;
        this._settings = {};
        Ext.apply(this._settings, initOptions);
        var loadMode = this._settings.loadMode;
        var gcdType = this._settings.gcdType;
        
        var loading = 2;
        
        if (!canEdit)
          return false;

        this.tree2 = new Ext.tree.TreePanel({
              id : gcdType == 'dept' ? 'mainDepartmentList_adder' : 'mainClassList_adder',
              useArrows:true,
              autoScroll:true,
              animate:true,
              height:200,
              region: 'center',
              enableDD:true,
              //tbar: [{text: 'Add'},{text: 'Rename'},{text: 'Delete'}],
              containerScroll: true,
              rootVisible: false,
              root: { nodeType: 'async', allowDrop: false},
              dataUrl : '/ajax/siteconfig/moduleList.cfm?mode='+(gcdType == 'dept' ? 'dept' : 'class'),
              listeners: {
                load: function(node){
                  loading--;
                  if (loading < 1)
                    Ext.Msg.hide();
                },
                checkchange: function(node, checked){
                  if(checked){
                    node.getUI().addClass('complete');
                  }else{
                    node.getUI().removeClass('complete');
                  }
                }
              }
          });

        this.tree = new Ext.tree.TreePanel({                    
              useArrows:true,
              id : gcdType == 'dept' ? 'mainDepartmentEditor' : 'mainClassEditor',
              autoScroll:true,
              animate:true,
              region: 'center',
              enableDD:true,
              containerScroll: true,
              rootVisible: false,
              root: { nodeType: 'async'},
              dataUrl : gcdType == 'dept' ? '/ajax/siteconfig/gcd/DepartmentNodes.cfm?schoolID=' +this._settings.schoolID : '/ajax/siteconfig/gcd/ClassNodes.cfm?schoolID=' +this._settings.schoolID,
              //contextMenu: gcdMenu,
              listeners: {
                load: function(node){
                  loading--;
                  if (loading < 1)
                    Ext.Msg.hide();
                },
                contextmenu: function(node, e) {
                  node.select();
                  var c = gcdMenu;
                  c.contextNode = node;
                  c.findById('mnu_item-edit_gcditem').setDisabled(node.attributes.data_type=="header" && node.attributes.gcd_id==0);
                  c.findById('mnu_item-edit_gcdassign-teacher').setDisabled(node.attributes.data_type=="header");
                  c.findById('mnu_item-edit_gcdassign-students').setDisabled(node.attributes.data_type=="header");
                  c.findById('mnu_item-edit_gcddelete').setDisabled(node.attributes.dontCreate);
                  c.showAt(e.getXY());
                },
                beforenodedrop: function(e){
                  if(e.dropNode.attributes.data_type=="header" && e.target.getDepth() > 1){
                    e.cancel=true;
                    return false;
                  }else if(e.dropNode.attributes.data_type=="header" && e.target.getDepth() == 1 && e.point=="append"){
                    e.cancel=true;
                    return false;
                  }else if(e.dropNode.attributes.data_type!="header" && e.target.getDepth() == 1 && e.point!="append"){
                    e.cancel=true;
                    return false;
                  }
                  if (e.source.tree.id!=e.tree.id){
                    var newEl = e.dropNode.clone();
                    newEl.leaf=false;
                    newEl.getUI().toggleCheck(true);                    
                    e.dropNode = newEl;
                    if (newEl.attributes.data_type=='header'){
                        setTimeout(function(){
                          Ext.Msg.prompt('New Category', 'Please enter a name for this Category:', function(btn, text){
                            if (btn == 'ok' && text.trim()){
                              e.dropNode.setText(text);
                            }else{
                              e.dropNode.remove();
                              //e.target.removeChild(e.dropNode);
                              //if (e.dropNode) // make sure it's gone!
                              //  e.target.removeChild(e.dropNode);
                            }
                          }, this, false, '');
                        }, 100);
                    }else if (newEl.attributes.data_type=='department'){
                        newEl.leaf=true;
                        setTimeout(function(){
                          callEditor({navigationContextNode: newEl, editorDataID: 0, editorType: 'Department', editorModal: true});
                        }, 100);
                    }else if (newEl.attributes.data_type=='class'){
                        newEl.leaf=true;
                        setTimeout(function(){
                          callEditor({navigationContextNode: newEl, editorDataID: 0, editorType: 'Class', editorModal: true});
                        }, 100);
                    }
                  }
                },
                checkchange: function(node, checked){
                  if(checked){
                    node.getUI().addClass('complete');
                  }else{
                    node.getUI().removeClass('complete');
                  }
                }
              }
          });
        var treeLeft = new Ext.Panel({
          border: false,
          margins:'0 0 0 0',
          region: 'center',
          layout: 'border',
          items: [
            {
              region: 'north', 
              margins:'0 0 -1 0',
              baseCls: 'siteConfigHeaderTab',
              cmargins:'3 3 3 3', 
              border: true, 
              html: '<strong>Current '+(gcdType == 'dept' ? 'Department' : 'Class')+' Configuration</strong>'
            },this.tree]
        });
        var treeRight = new Ext.Panel({
          border: false,
          region: 'east',
          layout: 'border',
          margins:'0 0 0 5',
          cmargins:'3 3 3 3',
          width: 230,
          items: [
            {
              region: 'north', 
              margins:'0 0 -1 0',
              baseCls: 'siteConfigHeaderTab',
              cmargins:'3 3 3 3', 
              border: true, 
              html: '<strong>Available Options</strong>'
            },{
              region: 'south', 
              margins:'10 10 10 10',
              cmargins:'3 3 3 3',
              baseCls: 'x-plain', 
              border: true, 
              html: '<strong>Drag & Drop above options</strong> to create and activate them.'
            },this.tree2]
        });
        var navInfo = 'Changes will be applied when you click \'Save\' below.';
        this.treeHolder = new Ext.Panel({
          border: false,          
          layout: 'fit',
          bodyStyle: 'background: #DFE8F6',
          id: (gcdType == 'dept' ? 'tabDepartmentEditor' : 'tabClassEditor'),
          items: new Ext.Panel({
              border: false,
              ref : 'borderLayout',
              layout: 'border',
              items: [
                {
                  region: 'south',
                  collapsible: true,
                  margins:'5 0 0 0',
                  cmargins: '5 0 0 0',
                  title: 'Help',
                  collapsed: true,
                  border: true, 
                  html: '<div class="siteConfigInfo"><div class="siteConfigHeader">Organize your '+(gcdType == 'dept' ? 'department' : 'class')+' list here.</div><div class="siteConfigText">'+navInfo+'</div></div>'
                },
                treeLeft,
                treeRight]
              })
        });
        
        

        var winNavEdit = new Ext.Window({
              minWidth:600,
              minHeight:400,
              width:600,
              height:500,
              title: gcdType == 'dept' ? 'Department Editor' : 'Class Editor',
              iconCls: gcdType == 'dept' ? 'cpi_departmentManager' : 'cpi_classesManager',
              constrainHeader:true,
              layout:'fit',
              closeAction:'close',
              modal:true,
              closable:true,
              border:true,
              resizable:false,
              defaults: {autoScroll:true, padding: 5},
              items: this.treeHolder,
              bodyStyle: 'background: #ddd;',
              tools:[{
                id:'help',
                handler: function(event, toolEl, panel){
                  //alert(_self.treeHolder.borderLayout.layout.south.panel.toSource());
                  _self.treeHolder.borderLayout.layout.south.panel.toggleCollapse(true);
                }
              }],
              listeners: {
                render: function(){
                  Ext.Msg.wait('Loading '+ (gcdType == 'dept' ? 'Department' : 'Class') + '...', 'Please wait');
                }
              },
              buttons: [{
                text: 'Save',
                handler: function(){
                
                  var tmpSerial = new Ext.tree.JsonTreeSerializer(_self.tree, { nodeFilter: function(node) {
                      return true;
                    }});
                  Ext.Ajax.request({
                    url: '/ajax/siteconfig/gcd/updateGCD.cfm?mode='+ (gcdType == 'dept' ? 'dept' : 'class'),
                    method: 'POST',
                    params: { deptData : Base64.encode(tmpSerial.toString()), schoolID: currentSchool.id},
                    reader : new Ext.data.JsonReader({
                    success : '@success'
                    }),
                    success: function(response, opts) {
                      var obj = Ext.decode(response.responseText);
                      if (obj.success){
                        //_self._settings.sc.triggerReload();
                        Ext.Msg.hide();
                        winNavEdit.close();
                        window.location.reload(true);
                      }else{
                        Ext.Msg.alert('Whoops!', 'There was an error saving the '+ (gcdType == 'dept' ? 'Department' : 'Class') + ' Configuration.');
                      }
                    },
                    failure: function(response, opts) {
                      Ext.Msg.alert('Whoops!', 'There was an error saving the '+ (gcdType == 'dept' ? 'Department' : 'Class') + ' Configuration.');
                    }
                  });
                }
              },{ text: 'Cancel', handler: function(){ winNavEdit.close(); } }]
          });
          winNavEdit.show(this);
      }
      
      
      
reportingIn('gcdTab');

