function AlbumPickShared(initOptions, slideshow){
    Ext.Msg.wait('Please wait...', 'Loading');
    var _self = this;
    this._settings = {};
    if(!canEdit){
      userLogin();
    }
    var windowHeight = 200;
    Ext.apply(this._settings, initOptions);
    
    var sm2 = new Ext.grid.CheckboxSelectionModel(
      {
        checkOnly: true, 
        dataIndex: 'checked'
      }
    );

    this.reader = new Ext.data.JsonReader({
              idProperty: 'albumID',
              root: 'albums'
            },[
              {name: 'id', mapping: 'id'},
              {name: 'albumID', mapping: 'albumID'},
              {name: 'schoolID', mapping: 'schoolID'},
              {name: 'checked', mapping: 'checked'},
              {name: 'owner', mapping: 'owner'},
              {name: 'title', mapping: 'title'},
              {name: 'desc', mapping: 'desc'},
              {name: 'count', mapping: 'count'},
              {name: 'album', mapping: 'album'}
            ]
          );

    this.shareStore = new Ext.data.GroupingStore({
          proxy: new Ext.data.HttpProxy ({
            url: '/ajax/gallery/getSharedAlbums.cfm'
          }),
          baseParams: {gcdID: _self._settings.gcdID, slideID: _self._settings.slideID, schoolID: _self._settings.schoolID},
          reader : this.reader,
          sortInfo: {field: 'owner', direction: 'ASC'},
          groupField: 'owner',
          listeners: {
            scope: this,
            'datachanged': function(store, record){              
              if(store.getCount() > 0){
                for(r = 0; r < store.getCount(); r++){
                  if(store.getAt(r).get('checked') == '1'){
                    this.shareGrid.getSelectionModel().selectRow(r, true);
                  }
                }
                this.shareGrid.getView().collapseAllGroups();
                this.modeSelect.setValue('rand')
                this.modeMax.setValue(15);
                
                if (this.reader.jsonData.settings){
                  if (this.reader.jsonData.settings.mode !='')
                    this.modeSelect.setValue(this.reader.jsonData.settings.mode);
                  if (this.reader.jsonData.settings.max !='')
                    this.modeMax.setValue(this.reader.jsonData.settings.max);
                }
              }
            },'load' : function(store, record){              
              //alert(store.getCount());
              if(store.getCount() > 0){
                
                store.filter([
                    {
                      property     : 'schoolID',
                      value        : 1,
                      anyMatch     : false,
                      caseSensitive: true,
                      exactMatch   : true
                    }
                  ]);
                for(r = 0; r < store.getCount(); r++){
                  if(store.getAt(r).get('checked') == '1'){
                    this.shareGrid.getSelectionModel().selectRow(r, true);
                  }
                }
                this.shareGrid.getView().collapseAllGroups();
                this.modeSelect.setValue('rand');

                this.modeMax.setValue(15);
                
                if (this.reader.jsonData.settings.mode !='')
                  this.modeSelect.setValue(this.reader.jsonData.settings.mode);
                if (this.reader.jsonData.settings.max !='')
                  this.modeMax.setValue(this.reader.jsonData.settings.max);

              }
            }
          }
        });

    this.shareGrid = new Ext.grid.GridPanel({
        store: this.shareStore,
        cm: new Ext.grid.ColumnModel([
            sm2,
            {header: "Album Name", width: 200, sortable: true, dataIndex: 'title'},
            {header: "#", width: 50, sortable: true, dataIndex: 'count'},
            {header: "Owner", width: 120, sortable: true, dataIndex: 'owner'},
            {header: "Location", width: 300, sortable: true, dataIndex: 'album'},            
            {header: "Description", width: 260, sortable: true, dataIndex: 'desc'}

        ]),
        view: new Ext.grid.GroupingView({
            forceFit:true,
            startCollapsed:true,
            groupTextTpl: '{text} ({[values.rs.length]} {[values.rs.length > 1 ? "Items" : "Item"]})'
        }),
        sm: sm2,
        columnLines: true
    });

    this.modeSelect = new Ext.form.ComboBox({
        store: new Ext.data.ArrayStore({
            fields: ['id', 'value'],
            data : Ext.comboStuff.slideshowMode
        }),
        hidden: !slideshow,
        hiddenName: 'modeAction',         
        editable: false,
        valueField: 'id',
        displayField: 'value',
        typeAhead: true,
        mode: 'local',
        triggerAction: 'all',
        forceSelection: true,
        selectOnFocus: true,
        width: 110,
        iconCls: 'no-icon'
    });
        
    this.schoolSelect = new Ext.form.ComboBox({
        store: new Ext.data.JsonStore({
            autoDestroy: true,
            url: '/ajax/login/getSchools.cfm',
            storeId: 'userSchoolStore',
            root: 'schools',
            idProperty: 'schoolID',
            fields: ['schoolID', 'userSchool']
        }),
        fieldLabel: 'School',
        hiddenId:'user_schoolID',
        hiddenName:'user_schoolName',        
        forceSelection: true,
        loadingText: 'Loading Schools...',
        valueField:'schoolID',
        displayField:'userSchool',
        typeAhead: true,
        mode: 'remote',
        triggerAction: 'all',
        emptyText:'Select a school...',
        selectOnFocus:true,
        width: 210,
        value: 1,
        iconCls: 'no-icon',
        listeners: {
          select: function(c, r, i){
            saveSection(false);
            var myGrid = _self.shareGrid;
            var store = myGrid.getStore();
            if(store.getCount() > 0){
              for(rr = 0; rr < store.getCount(); rr++){
                store.getAt(rr).set('checked', myGrid.getSelectionModel().isSelected(rr));
              }
            }
            store.filter([
              {
                property     : 'schoolID',
                value        : r.data.schoolID,
                anyMatch     : false,
                caseSensitive: true
              }
            ]);
          }
        }
    });

    
    this.modeMax = new Ext.form.ComboBox({
        store: new Ext.data.ArrayStore({
            fields: ['id', 'value'],
            data : Ext.comboStuff.slideshowMax
        }),
        hidden: !slideshow,
        hiddenName: 'maxPics',
        editable: false,
        valueField: 'id',
        displayField: 'value',
        typeAhead: true,
        mode: 'local',
        triggerAction: 'all',
        forceSelection: true,
        selectOnFocus: true,
        width: 80,
        iconCls: 'no-icon'
    });
    
    function saveSection(closeAfterSave){
      Ext.Msg.wait('Saving Selected Settings', 'Saving');
      var store = _self.shareGrid.getStore();
      var row = [];
      var sel = [];
      if(store.getCount() > 0){
        for(r = 0; r < store.getCount(); r++){
          row[r] = store.getAt(r).get('id');
          sel[r] = _self.shareGrid.getSelectionModel().isSelected(r);
        }
      }
      Ext.Ajax.request({
        url: '/ajax/gallery/linkGalleries.cfm',
        method: 'POST',
        params: {rows: row, sels: sel, gcdID: _self._settings.gcdID, slideID: _self._settings.slideID, schoolID: _self._settings.schoolID, mode: _self.modeSelect.getValue(), max: _self.modeMax.getValue()},
        success: function(){              
          Ext.Msg.hide();
          if(closeAfterSave) _self.win.close();
        },
        failure: function(){
          Ext.Msg.hide();
          Ext.Msg.alert('Error', 'There was an error saving your selection. Please try again');
        }
      });            
    }
    
    this.win = new Ext.Window({
      title: 'Available Albums',
      modal:true,
      minWidth:600,
      minHeight:300,
      /*tools:[{
              id:'gear',
              qtip: 'Configure Widget',
              handler: function(e, target, panel){
                //windowModuleConfig(panel);
                alert('Window Open Here');
              }
            }],*/
      width:600,
      height:420,
      maximizable: true,
      border: false,
      constrainHeader: true,
      layout: 'fit',
      items: this.shareGrid,
      listeners: {
        show: function(w){        
          _self.shareGrid.store.load();
          Ext.Msg.hide();
        }
      },
      tbar: [
        {text:'Create', tooltip: 'Create New Album', iconCls: 'iconGalleryAdd', handler: function(){
            var pID = 0;
            var gID = 0;
            AlbumCatEdit({photoID:pID, gcdID:0, albumID:gID, imageID:0, refreshStore: _self.shareGrid.getStore()});
          }
        },'-',
        {iconCls: 'file-refresh-icon', tooltip: 'Refresh Albums', handler: function(){
            _self.shareGrid.getStore().reload();
          }
        },'-',
        {iconCls: 'iconNodeCollapse', tooltip: 'Collapse all Groups', handler: function(){
            _self.shareGrid.getView().collapseAllGroups();
          }
        },{iconCls: 'iconNodeExpand', tooltip: 'Expand all Groups', handler: function(){
            _self.shareGrid.getView().expandAllGroups();
          }
        },'->'
				,{
            xtype: 'buttongroup',
            title: 'School',
            columns: 1,
            defaults: {
                scale: 'small'
            },
            items:[
                    _self.schoolSelect
                  ]
        }
				,{
            xtype: 'buttongroup',
            title: 'Settings',
            hidden: !slideshow,
            columns: 2,
            defaults: {
                scale: 'small'
            },
            items:[
                    _self.modeSelect,
                    _self.modeMax
                  ]
        }
      ],
      buttons: [
          {text:'Save', handler:function(){saveSection(true)} },
          {text:'Cancel', handler: function(){_self.win.close()}}
      ],
      buttonAlign:'center'
    });
    this.win.show(this);
    
}

function AlbumCatEdit(initOptions){
    if(!canEdit){
    userLogin();
    catWin.close();
    }
    var windowHeight = 180;

    var _self = this;
    var _settings = {};
    _settings.photoID = 0;
    _settings.updateTreeNode = false;
    _settings.updateStore = false;
    _settings.treeNode = {};
        
    Ext.apply(_settings, initOptions);
    
    if (initOptions.refreshStore)
      _settings.updateStore = true;
      
    if (initOptions.treeNode)
      _settings.updateTreeNode = true;
    
    /*if(_settings.photoID != 0)
        windowHeight = 350;*/
    
    function saveCategory(){
      PhotoInfoPanel.getForm().submit({
        clientValidation: true,
        url:'/ajax/gallery/uploadCat.cfm', 
        waitMsg:'Saving Information, Please Wait...',
        params: {
          ID: _settings.photoID,
          uimg: 1,
          max: 1,
          action: 'category',
          gcdID: _settings.gcdID,
          catID: _settings.albumID
        },
        errorReader : new Ext.data.JsonReader({
            root:'extra',
            successProperty:'success'
          }, ['ImageID','title','desc','newItem']),
        success: function(form, action) {
            if (_settings.updateStore){
              catWin.close();
              _settings.refreshStore.reload();
              return true;
            }
            if (_settings.updateTreeNode){
              if (_settings.photoID != 0){
                _settings.treeNode.setText(form.getValues().title);
              }else{
                _settings.treeNode.reload();
              }
              catWin.close();
              return true;
            }else{
              catWin.close();
              addGalItem(action.result.imageID, action.result.title, action.result.desc, action.result.imageName, action.result.newItem, _settings.gcdID, _settings.albumID, action.result.imageFFID);
            }
        },
        failure: function(form, action) {
          switch (action.failureType) {
              case Ext.form.Action.CLIENT_INVALID:
                  Ext.Msg.alert('Failure', 'Please verify fields are correct.');
                  break;
              case Ext.form.Action.CONNECT_FAILURE:
                  Ext.Msg.alert('Failure', 'Ajax communication failed');
                  break;
              case Ext.form.Action.SERVER_INVALID:
              default:
                  Ext.Msg.alert('Failure', action.result.msg);
          }
        }
      });
    }
    
    function addGalItem(id,title,desc,ImageName,newImage,gcdID,albumID,ffID) {
      window.location.reload(true);
    }

    var formItems = [];
    //if(_settings.photoID != 0)
    //formItems.push({xtype:'box',anchor:'',isFormField:true,fieldLabel:'Preview',autoEl:{tag:'div',style:'text-align:center',children:[{tag:'img',qtip:'You can also have a tooltip on the image',src:'/thumber.cfm?id='+_settings.imageID+'&w=150&h=112'}]}});
    //formItems.push({xtype: 'fileuploadfield', emptyText: 'Select a image', fieldLabel: 'Image', name: 'photoFile_1', allowBlank: true, buttonText: '', buttonCfg: {iconCls: 'file-upload-icon'}});
    formItems.push({fieldLabel: 'Title', anchor:'100%', name: 'title', maxLength:50, maxLengthText: 'Your Title Exceeds 50 Characters'});
    formItems.push({fieldLabel: 'Description', anchor:'100%', name: 'desc', xtype: 'textarea', maxLength:250, maxLengthText: 'Your Title Exceeds 250 Characters'});
    formItems.push({boxLabel: 'This gallery is Globally Shared', anchor:'0', name: 'shared', xtype: 'checkbox'});

    var xmlCols = [];
    xmlCols.push({name: 'title', mapping: 'title'});
    xmlCols.push({name: 'desc', mapping: 'content'});
    xmlCols.push({name: 'shared', mapping: 'shared'});

  
  var PhotoInfoPanel = new Ext.FormPanel({
        labelWidth: 75, // label settings here cascade unless overridden
        //frame:true,
        border: true,        
        padding: 10,
        width: 390,
        reader : new Ext.data.XmlReader({
                          record : 'result',
                          success : '@success'
                      }, xmlCols),
        defaults: {width: 230},
        defaultType: 'textfield',
        items: [
        formItems
        ],
        listeners:{
          render:function(el){
           el.getForm().load({url:'/ajax/gallery/getCatData.cfm?id='+_settings.photoID, waitMsg:'Loading Data....'});
           }
        }        
    });
      TitleBar = 'Add New Gallery';
    if(_settings.photoID > 0)
      TitleBar = 'Edit Gallery';
 var catWin = new Ext.Window({
          id: 'photoPanel_win_' + _settings.photoID,
          //stateID: 'photoPanel_win_' + _settings.photoID + '_NEW-1',
          //plain: true,
          title: TitleBar,
          width:390,
          minWidth: 390,
          modal: _settings.updateTreeNode,
          height:210,
          padding: 5,
          border: true,
          layout:'fit',
          closable: true,
          closeAction:'close',
          resizable: false,
          items: PhotoInfoPanel,
          buttons: [{
                      text: 'Save',
                      handler: function(){ saveCategory();}
                  },{
                      text: 'Cancel',
                      handler: function(){ catWin.close() }
                  }]
      });
      catWin.show(this);
      if (journeyHelper.isRunning){
        journeyHelper.setHelpTopic('gallery_upload');
        journeyHelper.showHelpTopic();
      }
};

Ext.namespace('Ext.comboStuff');

Ext.comboStuff.slideshowMode = [
        ['rand', 'Random Order'],
        ['new', 'Newest First'],
        ['old', 'Oldest First']
      ];
Ext.comboStuff.slideshowMax = [
        ['5', '5 Images'],
        ['10', '10 Images'],
        ['15', '15 Images'],
        ['20', '20 Images'],
        ['25', '25 Images']
      ];

