Ext.namespace('com.evoca.groups');

var groupID;
var userID;
var groupStore;
var columnModel;
var grid;
//TODO: (TF) Hook up email support
com.evoca.groups.renderGroupGrid = function(root, divID, userIDParam, limit, gridTitle, isPublicView, searchTerm, gridWidth) {
	Ext.state.Manager.setProvider(new Ext.state.CookieProvider())

	if(gridWidth == null || gridWidth <= 0)
		gridWidth = 780;
	
	log('isPublicView: ' + isPublicView);
	if(isPublicView == null || isPublicView != false)
		isPublicView = true;
	
	log('isPublicView: ' + isPublicView);
	userID = userIDParam;
	this.root = root;
	this.limit = limit;

	// Initialize quicktips
	Ext.QuickTips.init();
			
	Ext.apply(Ext.QuickTips.getQuickTip(), {
		maxWidth: 200,
		minWidth: 100,
		showDelay: 50,
		trackMouse:  true
	});
			
	userID = userIDParam;
	
	if(!Ext.isGecko) {
		var publicPrivateData = [
			[0, '', 'no_display'],
			[0, 'Public', 'security_public_icon'],
			[1, 'Semi-Public', 'security_semi_icon'],
			[2, 'Private', 'security_private_icon']
		];
	}
	else {
		var publicPrivateData = [
			[0, 'Public', 'security_public_icon'],
			[1, 'Public', 'security_semi_icon'],
			[2, 'Private', 'security_private_icon']
		];
	}
	
	var enableDisableData = [
		['true', 'Enabled'],
		['false', 'Disabled']
	];

	var nameValueReader = new Ext.data.ArrayReader({}, [
		{name: 'value'},
		{name: 'name'},
		{name: 'css'} // The css to apply to the item
	]);
	
	this.publicPrivateStore = new Ext.data.Store({
		id: 0,
		reader: nameValueReader,
		data: publicPrivateData
	});
	publicPrivateStore = this.publicPrivateStore;
	
	var groupUtils = new com.evoca.groups.GroupUtils();

	this.groupStore = groupUtils.getGroupStore(root, userID, true, limit, isPublicView, searchTerm); 
	groupStore = this.groupStore;
	
	this.enableDisableStore = new Ext.data.Store({
		reader: nameValueReader,
		data: enableDisableData
	});
	
	this.publicPrivateStore = new Ext.data.Store({
		id: 0,
		reader: nameValueReader,
		data: publicPrivateData
	});
	
	var deleteColumn = new com.evoca.groups.deleteColumn({
		id: 'delete',
		width: 40,
		header: 'Delete',
		sortable: false
	});
	
	var imageColumn = new com.evoca.groups.imageColumn({
		id: 'imageColumn',
		width: 40,
		scope: this,
		sortable: false,
		header: 'Image',
		dataIndex: 'groupID',
		css: (Ext.isChrome || Ext.isSafari) ? 'width: 40px !important;' : ''
	});
	
	var emailColumn = new com.evoca.groups.emailColumn({
		id: 'email',
		width: 40,
		scope: this,
		header: 'Email',
		sortable: false,
		css: (Ext.isChrome || Ext.isSafari) ? 'width: 40px !important;' : ''
	});
	
	var viewDetailsColumn = new com.evoca.groups.viewDetailsColumn({
		id: 'viewDetails',
		width: 45,
		scope: this,
		header: 'View',
		sortable: false
	});
	
	var securityEditor = new Ext.form.ComboBox({
		id: 'securityEditor',
		readOnly: true,
		listWidth: 50,
		store: publicPrivateStore,
		valueField: 'value',
		displayField: 'name',
		mode: 'local',
		triggerAction: 'all',
		editable: false,
		scope: this,
		tpl: '<tpl for="."><div class="x-combo-list-item"><div class="{css}">&nbsp;</div></div></tpl>'

	});
	
	var shareEditor =   new Ext.form.TextField({
		allowBlank: true,
		id: 'shareURLEditor',
		boxMaxWidth: 10,
		grow: false,
		readOnly: true,
		selectOnFocus: true,
		validateOnBlur: false
	});
	
	var descriptionEditor =   new Ext.form.TextArea({
		allowBlank: true,
		id: 'descEditorID',
		blankText: 'Please enter a description.',
		autoHeight: true
	});
	
	var nameEditor = new Ext.form.TextField({
		allowBlank: false,
		id: 'nameEditorID',
		blankText: 'Please enter a name.'
	});
	
	
	var secWidth = 50;
	
	if(Ext.isIE)
		secWidth = secWidth + 3;
	
	var cssWidth = '  ';
	if(Ext.isChrome || Ext.isSafari) {
		cssWidth = ' width: ' + (secWidth + 1) + 'px !important; ';
	}
	
	
	columnModel = new Ext.grid.ColumnModel([
	    viewDetailsColumn,
		{id:'groupName',header: 'Name', sortable: true, dataIndex: 'groupName', editor: nameEditor, renderer: function(v, params, record){
	    	
	    	if(!record.get('isAdmin'))
	    		params.attr += 'ext:qtip=\"You are a member of \'' + record.get('groupName') + '\'. To quit the group, click on the minus sign in the \'Delete\' column. <br /><br />Note:<br />You may only edit groups you own.\"';
	    	
	    	return v;
		}},
		{id:'description',header: 'Description', width: 80, sortable: true, dataIndex: 'description', editor: descriptionEditor, renderer: function(v,params,record){
			if(!record.get('isAdmin'))
	    		params.attr += 'ext:qtip=\"You are a member of \'' + record.get('groupName') + '\'. To quit the group, click on the minus sign in the \'Delete\' column. <br /><br />Note:<br />You may only edit groups you own.\"';
			
			return v;
		}},
		{id:'privacyLevel', header: 'Security', sortable: true, css: cssWidth, width: secWidth, dataIndex: 'privacyLevel', editor: securityEditor, renderer: function(v,params,record){
			log("secLeve: " + v);
			
			if(!record.get('isAdmin'))
	    		params.attr += 'ext:qtip=\"You are a member of \'' + record.get('groupName') + '\'. To quit the group, click on the minus sign in the \'Delete\' column. <br /><br />Note:<br />You may only edit groups you own.\"';
			
			if(v != 2 && v != 1) {
				params.css += ' security_public_icon';
				v = '<span class="security_public_icon">&nbsp;</span>';
			}
			else if(v == 1) {
				params.css += ' security_semi_icon';
				v = '<span class="security_semi_icon">&nbsp;</span>';
			}
			else {
				params.css += ' security_private_icon';
				v = '<span class="security_private_icon">&nbsp;</span>';
			}

			return '&#160;';
		}},
		imageColumn,
		emailColumn,
		{id: 'shareURL', header: 'Share link', css: 'width: 110px !important;', width: 110, sortable: false, editor: shareEditor, renderer:function(v, params, record) {
			
			var retVal = record.get('shortShareURL');
			//var retVal = record.get('shareURL');
			
			if(retVal == null || retVal == '') {
				var src = root + "images/progressBars/small-round-orange.gif";
				
				retVal = '<img src="' + src + '" />';
			}
			
			return retVal;
		}},
		{id:'recordingCount',header: 'Recordings', width: 70, sortable: true, dataIndex: 'recordingCount', renderer: function(v, params, record) {
			return '<center>' + v + '</center>';
		}},
		{id: 'date', header: 'Date', width: 55, sortable: true, dataIndex: 'timestamp', /*editor: dateEditor,*/ renderer:function(v, params, record) {
			log('date: ' + v);
			if(typeof v == "string")
				v = parseInt(v, 10);
			
			var date = new Date(v);
			
			return Ext.util.Format.dateRenderer('m.d.y').apply(this, [date]);
		}},
		{id:'recordingsDuration',header: 'Length', width: 50, sortable: true, dataIndex: 'recordingsDuration', renderer: function(v, params, record) {
			var min = Math.floor(v/60);
			var sec = v - (min * 60);
			return min + ":" + sec + " m";
		}},
		{id:'membersCount',header: 'Members', width: 58, sortable: true, dataIndex: 'membersCount', renderer: function(v, params, record) {
			return '<center><a style="text-decoration: none" href="' + root + 'groups/group_members.jsp?gid=' + record.get('groupID') + '">' + v + '</a></center>';
		}},
		deleteColumn
	]);
	
	var title = 'My groups';
	
	if(gridTitle != null && gridTitle != '') {
		title = gridTitle;
	}

	this.groupSearchBox = new Ext.form.TextField({
		xtype: 'textfield',
		name: 'groupSearchField',
		id: 'groupSearchField',
		emptyText: 'Search text fields',
		enableKeyEvents: true,
		scope: this,
		value: searchTerm,
		listeners: {
			'specialkey' : {
				fn: function(me, event) {
					if(event.getKey() == event.ENTER) {
						// The user pressed the enter key
						searchTerm = null;
						
						var e = event;
						if($('groupSearchField') && $('groupSearchField').value && $('groupSearchField').value != 'Search text fields') {
							searchTerm = $('groupSearchField').value;
						}
						
						grid.store.load({params:{start:0, limit: limit, searchTerm: searchTerm}});
					}
				}
			}
		}
	});
	
	var groupTopToolbar = new Ext.Toolbar({
		items:[
			'->',
			this.groupSearchBox,
			{
				text: 'Search',
				scope: this,
				handler: function() {
					searchTerm = null;
					
					if($('groupSearchField') && $('groupSearchField').value && $('groupSearchField').value != 'Search text fields') {
						searchTerm = $('groupSearchField').value;
					}
					
					this.groupStore.load({params:{start:0, limit: limit, searchTerm: searchTerm}});
					
				}
			}
		]
	});
	
	var pageToolbar = new Ext.PagingToolbar({
		pageSize: limit,
		store: this.groupStore,
		displayInfo: true,
		displayMsg: 'Displaying groups {0} - {1} of {2}',
		emptyMsg: "No groups to display"
	});
	
	pageToolbar.on('change', function(toolbar, pageData){
		Ext.state.Manager.getProvider().set('groupActivePage', pageData.activePage - 1);
	});
	
	this.grid = new Ext.grid.EditorGridPanel({
		ds: this.groupStore,
		id: 'maingroupTable',
		cm: columnModel,
		stripeRows: true,
		frame: true,
		autoExpandColumn: 'groupName',
		autoHeight: true,
		width: gridWidth,
		title: title,
		stateful: false, // TODO: (TF) Turn statefulness back on
		//stateful: true,
		stateId: 'groupgrid',
		scope: this,
		clicksToEdit: 1,
		tbar: groupTopToolbar,
		bbar: pageToolbar
	});
	
	grid = this.grid;
	
	grid.render(divID);
	
	if(isPublicView) {
		// Remove columns
		grid.removeColumn('delete');
		grid.removeColumn('privacyLevel');
		
		//remove editors
		grid.removeColumnEditor("description");
		grid.removeColumnEditor("groupName");
	}
	
	function cellClick(grid, rowIndex, columnIndex, e, parent) {
		log('entered cellClick');
		var columnObj = grid.getColumnModel().config[columnIndex];
		
		record = grid.getStore().getAt(rowIndex);
		
		groupID = record.get('groupID');
		
		if(columnObj.handleClick) {
			log('\tcalling columns handleClick...');
			columnObj.handleClick(grid, rowIndex, columnIndex, e, this);
		}
		
		log('leaving cellClick');
	}
	
	grid.on('cellclick', cellClick);
	
	// This listener will auto-update whenever any cell is changed
	grid.on('validateedit', function(e) {
		groupUtils.updateGroup(root, groupID, e.field, e.value);
	});
};

com.evoca.groups.deleteColumn = function(config){
	Ext.apply(this, config);
	if(!this.id){
		this.id = Ext.id();
	}
};
	
com.evoca.groups.deleteColumn.prototype ={
	renderer : function(v, p, record){
		log(record.get("groupName") + ', admin: ' + record.get('isAdmin'));
		
		
		if(record.get('isAdmin')) {
			p.css += ' delete-column';
			p.attr += 'ext:qtip=\"Delete \'' + record.get('groupName') + '\'.\"';
		}
		else {
			p.css += ' remove-column';
			p.attr += 'ext:qtip=\"Quit \'' + record.get('groupName') + '\'.\"';
		}
		
		return '&#160;';
	},
	
	handleClick : function(grid, rowIndex, columnIndex, e) {
		var record = grid.getStore().getAt(rowIndex);
		
		var msg = 'Are you sure you want to delete the group: ' + record.get('groupName') + '?';
		var url = root + 'Request?action=deleteGroup&groupID=' + record.get('groupID');
		var failMsg = 'The group could not be deleted.';
		
		if(!record.get('isAdmin')) {
			msg = 'Are you sure you want to quit the group: ' + record.get('groupName') + '?';
			failMsg = 'Unable to remove you from that group. Please try again later.';
		}
		
		Ext.Msg.show({
			title: 'Delete',
			buttonAlign: 'center',
			buttons: Ext.Msg.YESNO,
			msg: msg,
			fn: function(btn, text) {
				if(btn == 'yes') {
					Ext.Ajax.request({
						url: url,
						success: function(response) {
							grid.store.remove(record);
						}, 
						failure: function(){
							Ext.Msg.show({
								title: 'Failure',
								buttonAlign: 'center',
								buttons: Ext.Msg.OK,
								msg: failMsg,
								fn: function() {
									this.hide();
									window.location.reload();
								},
								scope: this
							});
						},
						scope: this
					});
				}
			},
			scope: this
		});
	}
};

com.evoca.groups.viewDetailsColumn = function(config){
	Ext.apply(this, config);
	if(!this.id){
		this.id = Ext.id();
	}
};
	
com.evoca.groups.viewDetailsColumn.prototype ={
	renderer : function(v, p, record){
		p.css += ' view-detail-column';
		p.attr += 'ext:qtip=\"View all recordings for \'' + record.get('groupName') + '\'.\"';
		return '&#160;';
	},
	
	handleClick : function(grid, rowIndex, columnIndex, e) {
		var record = grid.getStore().getAt(rowIndex);
		
		var url = ''
		if(!isPublicView) {
			url =  root + 'mygroups/group.jsp?gid=' + record.get('groupID');
		}
		else {
			url =  root + 'groups/group.jsp?gid=' + record.get('groupID');
		}
		
		window.location = url;
	}
};

com.evoca.groups.imageColumn = function(config){
	Ext.apply(this, config);
	if(!this.id){
		this.id = Ext.id();
	}
};
	
com.evoca.groups.imageColumn.prototype ={
	renderer : function(v, p, record){
		if(record.get('hasPhoto') == 1) {
			p.css += ' image-column';
			var qtip = '<img height=\'140\' src=\'' + root + 'ImageRetriever?oid=G' + record.get('groupID') + '\' />';
			p.attr = 'ext:qtip="' + qtip + '"';
		}
		else {
			p.css += ' image-column-disabled';
		}
		
		if(!record.get('isAdmin'))
    		p.attr += 'ext:qtip=\"You are a member of \'' + record.get('groupName') + '\'. To quit the group, click on the minus sign in the \'Delete\' column. <br /><br />Note:<br />You may only edit groups you own.\"';
		
		return '&#160;';
	},
	handleClick : function(grid, rowIndex, columnIndex, e) {
		var record = grid.getStore().getAt(rowIndex);
		if(!isPublicView && record.get('isAdmin')) {
			var window = new com.evoca.groups.ImageManagementWindow(record);
			window.show();
		}
	}
};

com.evoca.groups.emailColumn = function(config){
	Ext.apply(this, config);
	if(!this.id){
		this.id = Ext.id();
	}
};

com.evoca.groups.emailColumn.prototype ={
	renderer : function(v, p, record){
		p.css += ' email-column';
		p.attr += 'ext:qtip=\"Email \'' + record.get('groupName') + '\'.\"';
		return '&#160;';
	},
	
	handleClick : function(grid, rowIndex, columnIndex, e) {
		var record = grid.getStore().getAt(rowIndex);
		
		sendGroupToAFriend(root, record.get('groupID'));
	}
};











/**
 * Image management window
 */
com.evoca.groups.ImageManagementWindow = function(record) {
	var editLocation = root + 'mygroups/editgroup.jsp?gid=' + record.get('groupID');
	var img = '<center><img align="center" height="500" src="' + root + 'ImageRetriever?oid=G' + record.get('groupID') + '"></center>';
	var html = '<center><a href="javascript:window.location=\'' + editLocation + '\'">';
	
	html += "Insert or replace image"
	html += '</a></center><br />';
	html += img;
	html += '<div style="text-align: center; font-weight: bold;padding-top: 10px;padding-bottom: 10px;">';
	html += '</div>';

	var form = new Ext.FormPanel({
		html: html
	});

	com.evoca.groups.ImageManagementWindow.superclass.constructor.call(this, {
		title: 'Image for \'' + record.get('title') + '\'',
		id: 'ev-manage-image-window-group',
		autoHeight: true,
		audoWidth: false,
		autoScroll: true,
		border: false,
		bodyStyle:'position:relative;background:transparent;padding:10px;',
		html: html,
		titleBar: true,
		modal: true,
		plain:true,
		stateful: false,
		closable: true,
		buttons:[{
			text: 'Close',
			scope: this,
			handler: function() {
				this.destroy();
			}
		}],
		scope: this
	});
	
	if(Ext.isGecko2) {
		this.setWidth(600);
	}
}

Ext.extend(com.evoca.groups.ImageManagementWindow, Ext.Window, {

});


com.evoca.groups.GroupUtils = function() {
	/**
	 * Returns a group list object based off xml string
	 */
	this.createGroupRecord = function() {
		var groupRecord = Ext.data.Record.create([
			{name: 'groupID'},
			{name: 'groupName'},
			{name: 'friendlyName'},
			{name: 'recordingCount', type: 'int'},
			{name: 'recordingsDuration', type: 'int'},
			{name: 'description'},
			{name: 'privacyLevel'},
			{name: 'hasPhoto'},
			{name: 'shareURL'},
			{name: 'isAdmin'},
			{name: 'shortShareURL'},
			{name: 'timestamp'},
			{name: 'membersCount'}
		]);
		
		return groupRecord;
	},
	
	this.getGroupStore = function(root, userID, includeShortShareURL, limit, isPublicView, searchTerm) {
		log('getGroupStore isPublicView: ' + isPublicView);
		
		if(isPublicView == null || isPublicView != false)
			isPublicView = true;
		
		log('getGroupStore isPublicView: ' + isPublicView);
		
		if(limit == null || limit < 0)
			limit = 999999;
		
		var extraParams = 'includePrivateGroups=' + !isPublicView;
		
		var url = root + 'Request?action=getGroups&userID=' + userID + '&' + extraParams;
	
		var store = new Ext.data.Store({
			url: url,
			autoLoad: false,
			remoteSort: true,
			reader: new Ext.data.XmlReader({
				record : 'group',
				totalRecords: 'totalGroups'
			}, this.createGroupRecord())
		});
		
		var state = Ext.state.Manager.getProvider();
		
		var start = Ext.state.Manager.getProvider().get('groupActivePage');
		
		if(start == null || start <= 0)
			start = 0;
		
		var sort = null;//state.sort.field;
		var dir = null;//state.sort.direction;
		
		if(state && state.state && state.state.groupgrid && state.state.groupgrid.sort) {
			if(state.state.groupgrid.sort.field)
				sort = state.state.groupgrid.sort.field;
			
			if(state.state.groupgrid.sort.direction)
				dir = state.state.groupgrid.sort.direction;
		}
		
		if(sort == null || sort == '')
			sort = 'groupName';
		
		if(dir == null || dir == '')
			dir = 'ASC';
		
		start = start * limit;
		
		store.load({params:{start:start, limit:limit, sort: sort, dir: dir, searchTerm: searchTerm}});

		if(includeShortShareURL) {
			store.on('load', function(store, records, options){
				store.each(function(record){
					if(!record.get('shortShareURL')) {
						//var url = root + 'Request?action=getShareURL&groupID=' + record.get('groupID') + '&shorten=true&userID=' + userID;
						var url = root + 'Request?action=getShareURL&groupID=' + record.get('groupID') + '&shorten=false&userID=' + userID;
						Ext.Ajax.request({
							url: url,
							success: function(response) {
								record.set('shortShareURL', response.responseText);
								record.commit();
							}, 
							failure: function(response){
								record.set('shortShareURL', 'Currently unavailable');
								record.commit();
							},
							scope: this
						});
					}
				});
			});
		}
		
		return store;
	}
	
	this.updateGroup = function(root, groupID, field, value) {
		if(groupID && field) {
			var update = false;
			switch(field) {
				case "description":
					params = Ext.urlEncode({'description': value});
					update = true;
					break;
				case "groupName":
					params = Ext.urlEncode({'groupName': value});
					update = true;
					break;
				case "privacyLevel":
					params = Ext.urlEncode({'privacyLevel': value});
					update = true;
					break;
			}

			if(update) {
				var url = root + 'Request?action=updateGroup&' + params + '&groupID=' + groupID + '&userID=' + userID;
				
				Ext.Ajax.request({
					url: url,
					success: function(response) {
						if(field == "privacyLevel") {
							var src = root + "images/progressBars/small-round-orange.gif";
							var img = '<img src="' + src + '" />';
							
							record.set('shortShareURL', img);
							
							var url = root + 'Request?action=getShareURL&groupID=' + record.get('groupID') + '&shorten=true&userID=' + userID;
							
							Ext.Ajax.request({
								url: url,
								success: function(response) {
									record.set('shortShareURL', response.responseText);
								}, 
								failure: function(response){
									record.set('shortShareURL', 'Currently unavailable');
								},
								scope: this
							});
						}
						record.commit(); // Commit the change
					}, 
					failure: function(response){
						record.reject(); // reject the changes
						
						var res = response.responseText;
						
						Ext.Msg.show({
							title:'Unable to update the group. ',
							msg: res,
							buttons: Ext.Msg.OK,
							animEl: 'elId',
							icon: Ext.MessageBox.ERROR
						});
					},
					scope: this
				});
			}
		}
	};
};

Ext.override(Ext.data.Store, {
    /**
     * Sort by multiple fields in the specified order.
     * @param {Array} An Array of field sort specifications, or, if ascending
     * sort is required on all columns, an Array of field names. A field specification
     * looks like:<pre><code>
{
    field: 'orderNumber',
    direction: 'ASC'
}
</code><pre>

	You have to manually call the sortByFields function
     */
    sortByFields: function(fields) {
        
//      Collect sort type functions,
//      Convert string field names to field+direction spec objects.
        var st = [];
        for (var i = 0; i < fields.length; i++) {
            if (typeof fields[i] == 'string') {
                fields[i] = {
                    field: fields[i],
                    direction: 'ASC'
                };
            }
            st.push(this.fields.get(fields[i].field).sortType);
        }

        var fn = function(r1, r2) {
            var result;
            for (var i = 0; !result && i < fields.length; i++) {
                var v1 = st[i](r1.data[fields[i].field]);
                var v2 = st[i](r2.data[fields[i].field]);
                result = (v1 > v2) ? 1 : ((v1 < v2) ? -1 : 0);
                if (fields[i].direction == 'DESC') result = -result;
            }
            return result;
        };
        this.data.sort('ASC', fn);
        if(this.snapshot && this.snapshot != this.data){
            this.snapshot.sort('ASC', fn);
        }
        this.fireEvent("datachanged", this);
    }
});





Ext.override(Ext.data.Record, {
	asXml : function(rowIndex) {
		var r = this.store.reader.meta;
		var elName = r.record;
		var result = "<" + elName + " id=\"" + this.id + "\">";
		this.fields.each(function(f) {
			result += "<" + f.name;
			if (f.type && f.type !== "auto") {
				result += " type=\"" + f.type + "\"";
			}
			result += ">";
			
			var tmpName = this.get(f.name);
			
			if(Ext.type(tmpName) == "object") {
				//console.log(f.name + ' is an object of length: ' + tmpName.getCount());
				for(var i = 0; i < tmpName.getCount(); i++) {
					//console.log(tmpName.getAt(i).asXml());
				}
				result += "@@@@@ it's a store??? " + tmpName.length;
			}
			else
				result += tmpName;
				
			result += "</" + f.name + ">";
		}, this);
		return result + "</" + elName + ">";
	}
});

Ext.override(Ext.data.Store,{
	addField: function(field){
		field = new Ext.data.Field(field);
		this.recordType.prototype.fields.replace(field);
		if(typeof field.defaultValue != 'undefined'){
			this.each(function(r){
				if(typeof r.data[field.name] == 'undefined'){
					r.data[field.name] = field.defaultValue;
				}
			});
		}
	},
	removeField: function(name){
		this.recordType.prototype.fields.removeKey(name);
		this.each(function(r){
			delete r.data[name];
			if(r.modified){
				delete r.modified[name];
			}
		});
	}
});

Ext.override(Ext.grid.ColumnModel,{
	addColumn: function(column, colIndex){
		if(typeof column == 'string'){
			column = {header: column, dataIndex: column};
		}
		var config = this.config;
		this.config = [];
		if(typeof colIndex == 'number'){
			config.splice(colIndex, 0, column);
		}else{
			colIndex = config.push(column);
		}
		this.setConfig(config);
		return colIndex;
	},
	removeColumn: function(colIndex){
		var config = this.config;
		this.config = [config[colIndex]];
		config.splice(colIndex, 1);
		this.setConfig(config);
	},
	removeColumnEditor: function(colIndex){
		if(colIndex != null && colIndex >= 0) {
			this.setEditor(colIndex, null);
		}
	},
	hideColumn: function(colIndex){
		if(colIndex != null && colIndex > 0) {
			//alert('hiding column: ' + colIndex);
			var config = this.config;
			this.config = [config[colIndex]];
			//console.log('before: ' + config);
			//config.splice(colIndex, 1);
			config[colIndex].hidden = true;
			//console.log('after: ' + config);
			this.setConfig(config);
		}
	},
	isCellEditable: function(colIndex, rowIndex) {
		log('entered isCellEditable');
		
		var loc = window.location.href;
		var suffix = "mygroups/index.jsp";
		//alert((loc.match(suffix + "$") == suffix) + ' ' + loc);
		
		var retVal = true;
		
		var colModel = grid.getColumnModel();
		log('\tcolModel: ' + colModel);
		log('\tcell editor: ' + colModel.getCellEditor(colIndex, rowIndex));
		var columnObj = colModel.config[colIndex];
		
		var record = grid.getStore().getAt(rowIndex);
		
		if(loc.match(suffix + "$") == suffix) {
			// We are on the "mygroups/index.jsp" page
			log('\tcolumnObj.id: ' + columnObj.id);
			log('\tgroupName: ' + record.get('groupName') + ', isAdmin: ' + record.get('isAdmin'));
			log('\tgrid: ' + grid);
			log('\tcolumnModel: ' + columnModel);
			if(columnObj.id == 'shareURL') {
				retVal = true;
			}
			else if(record.get('groupID') != null && columnObj.id != 'shareURL' && !record.get('isAdmin')) {
				retVal = false;
			}
			else {
				retVal = (this.config[colIndex].editable || (typeof this.config[colIndex].editable == "undefined" && this.config[colIndex].editor)) ? true : false;
			}
			
			
			log('leaving isCellEditable retVal: ' + retVal);
		}
		else {
			//alert(columnObj.id );
			if(record.get('ownerID') == userID) {
				retVal = (this.config[colIndex].editable || (typeof this.config[colIndex].editable == "undefined" && this.config[colIndex].editor)) ? true : false;
			}
			else if(columnObj.id == 'shareURL' || columnObj.id == 'post' || columnObj.id == 'embedCode') {
				
			}
			else {
				retVal = false;
			}
		}
		return retVal;
	}
});

Ext.override(Ext.grid.GridPanel,{
	addColumn: function(field, column, colIndex){
		if(!column){
			if(field.dataIndex){
				column = field;
				field = field.dataIndex;
			} else{
				column = field.name || field;
			}
		}
		this.store.addField(field);
		return this.colModel.addColumn(column, colIndex);
	},
	removeColumn: function(name, colIndex){
		this.store.removeField(name);
		if(typeof colIndex != 'number'){
			colIndex = this.colModel.getIndexById(name);
		}
		
		if(colIndex >= 0){
			this.colModel.removeColumn(colIndex);
		}
	},
	hideColumn: function(name, colIndex){
		this.store.removeField(name);
		if(typeof colIndex != 'number'){
			colIndex = this.colModel.getIndexById(name);
		}
		
		if(colIndex >= 0){
			this.colModel.hideColumn(colIndex);
		}
	},
	removeColumnEditor: function(name, colIndex){
		if(typeof colIndex != 'number'){
			colIndex = this.colModel.getIndexById(name);
		}
		
		if(colIndex >= 0){
			this.colModel.removeColumnEditor(colIndex);
		}
	}
});
// end of file
