// create namespace
Ext.namespace('cs_community');
cs_community.app = function() {	
	// private vars
	var navPanel;
	var currentImage=0;
	var galleryArr=new Array();
	var gCurrentX;
	var userForm;
	var maxThumbShows=3;
	var thumbStart=0;
	var thumbWidth=64;
	var imageForm;
	var selectedImageId=0;
    return {
        // public methods
        init: function(itm) {
			Ext.QuickTips.init();
			Ext.form.Field.prototype.msgTarget = 'side';			
			cs_community.app.createNav(itm);
		},
		createNav : function(itm) {
			Ext.get('menu_item_home').on('click', function() {
				cs_community.app.loadPage('index.cfm');
			});
			Ext.get('menu_item_forum').on('click', function() {
				cs_community.app.loadPage('forum/index.cfm');
			});
			Ext.get('menu_item_photogallery').on('click', function() {
				cs_community.app.loadPage('photo-gallery.cfm');
			});
			Ext.get('menu_item_mediadocs').on('click', function() {
				cs_community.app.loadPage('resources.cfm');
			});
			Ext.get('menu_item_myprofile').on('click', function() {
				cs_community.app.loadPage('my-profile.cfm');
			});
			Ext.get('menu_item_logout').on('click', function() {
				cs_community.app.loadPage('index.cfm?logout=true');
			});
			if (itm=="uploadimage" || itm=="gallery" || itm=="thumbs") {
				Ext.get('upload_image').on('click', function() {
					cs_community.app.loadPage('upload-image.cfm');
				});
				cs_community.app.loadSearchForm('community_menu_imagesearch', 'imageSearchForm', '/community/search-results.cfm');
				if (itm=="uploadimage") {
					cs_community.app.uploadImage();
				}
			}
			if (itm=="mediadocs" || itm=="uploadmedia" || itm=="searchresultsmedia") {
				Ext.get('upload_media').on('click', function() {
					cs_community.app.loadPage('upload-resource.cfm');
				});
				cs_community.app.loadSearchForm('community_menu_mediasearch', 'mediaSearchForm', '/community/search-results-resources.cfm');
				if (itm=="uploadmedia") {
					cs_community.app.uploadMedia();
				}
			}
			if (itm=="myprofile") {
				cs_community.app.loadProfileForm();
			}
			
			if (itm=="thumbs") {
				cs_community.app.loadThumbsPage();
			}
		},
		loadThumbsPage : function() {
			Ext.apply(Ext.QuickTips.getQuickTip(), {
				maxWidth: 200,
				minWidth: 100,
				showDelay: 50,
				trackMouse: true
			});
		},
		loadPage : function(page) {
			document.location.href='/community/'+page;
		},
		loadProfileForm : function() {
			
			Ext.apply(Ext.form.VTypes, {
		  
			password: function(val, field) {
				if (field.initialPassField) {
					var pwd = Ext.getCmp(field.initialPassField);
					return (val == pwd.getValue());
				}
					return true;
				},
				passwordText: 'Passwords do not match'
			});							  
											  
			leaDS = new WM_objects.basicStore({
				url	   : '../../rpc/json/index2.cfm?method=leas.view',
				fields : ['leaid', 'lea'],
				id	   : 'leaid'
			});
			
			doSubmit = function() {
				var formPanel = Ext.getCmp('userProfileForm');
				if (formPanel.getForm().isValid()) {
					Ext.getCmp('btn_updateprofile').setDisabled(true);
					formPanel.getForm().submit({waitMsg: 'Saving...'});
				} else {
					Ext.Msg.alert('Invalid Action', 'Please complete the highlighted fields.');
				}
			}
			
			userForm = new Ext.form.FormPanel({	
				url		      : '../../rpc/json/index2.cfm?method=users.save',
				baseParams	  : {"JsonType":"form"},
				labelWidth	  : 110,
				bodyStyle	  : 'padding:5px',
				buttonAlign	  : 'left',
				width		  : 400,
				border		  : false, 
				id			  : 'userProfileForm',
				renderTo	  : 'upload_image_form',
				items : [
					{
						xtype 	   	  : 'textfield',
						fieldLabel 	  : 'Username',
						name	  	  : 'username',
						id		      : 'username',
						allowBlank 	  : false,
						emptyText     : 'Enter username...',
						blankText  	  : 'Enter username',
						minLength     : 4,
    					minLengthText : 'Enter username - minimum 4 characters (A-Z,0-9)',
    					maxLength	  : 16,
    					maxLengthText : 'Enter username - maximum 16 characters (A-Z,0-9)',
						vtype		  : 'alphanum',
						width	      : 180
					},
					{
						fieldLabel	  : 'Password',
						name		  : 'password',
						id            : 'password',
						xtype		  : 'textfield',
						width         : 180,
						allowBlank    : false,
						autoCreate    : {tag: "input", type: "text", maxlength: "16"},
    					minLength	  : 4,
    					minLengthText : 'Enter password - minimum 4 characters (A-Z,0-9)',
    					maxLength	  : 16,
    					maxLengthText : 'Enter password - maximum 16 characters (A-Z,0-9)',
						vtype         : 'alphanum',
    					inputType     : 'password',
						blankText  	  : 'Enter password'
					},
					{
						fieldLabel		 : 'Confirm password',
						name			 : 'password2',
						id				 : 'password2',
						xtype		  	 : 'textfield',
						width			 : 180,
						allowBlank		 : false,
						autoCreate		 : {tag: "input", type: "text", maxlength: "16"},
    					minLength		 : 4,
    					minLengthText	 : 'Confirm password - minimum 4 characters (A-Z,0-9)',
    					maxLength		 : 16,
    					maxLengthText	 : 'Confirm password - maximum 16 characters (A-Z,0-9)',
    					inputType		 : 'password',
    					initialPassField : 'password',
						blankText  	     : 'Confirm password'
					},
					{
						fieldLabel : 'Firstname',
						xtype	   : 'textfield',
						name	   : 'firstname',
						id		   : 'firstname',
						width	   : 180,
						allowBlank : false,
						blankText  : 'Enter first name',
						emptyText  : 'Enter first name...'
					},
					{
						fieldLabel : 'Surname',
						xtype	   : 'textfield',
						name	   : 'surname',
						id		   : 'surname',
						width	   : 180,
						allowBlank : false,
						blankText  : 'Enter surname',
						emptyText  : 'Enter surname...'
					},
					{
						fieldLabel : 'Email',
						xtype	   : 'textfield',
						name	   : 'email',
						id		   : 'email',
						width	   : 180,
						vtype	   : 'email',
						allowBlank : false,
						emptyText  : 'Enter a valid email address...',
						blankText  : 'Enter a valid email address'
					},
					{
						fieldLabel	   : 'Region',
						xtype		   : 'combo',
						hiddenName	   : 'pleaid',
						id			   : 'leaid',
						name		   : 'leaid',
						store		   : leaDS,
						mode		   : 'local',
						triggerAction  : 'all',
						forceSelection : true,
						valueField	   : 'leaid',
						displayField   : 'lea',
						width		   : 180,
						allowBlank	   : false,
						emptyText	   : 'Select a region...',
						blankText	   : 'Select a region'
					},{
						fieldLabel : 'Show email',
						xtype	   : 'checkbox',
						name	   : 'showemail',
						id		   : 'showemail'
					},
					{
						fieldLabel   : 'Receive newsletter',
						xtype	     : 'checkbox',
						name	     : 'receivenewsletter',
						id		     : 'receivenewsletter',
						allowBlank   : false,
						checked		 : true
					}
				],
				buttons: [
					{
						text	 : 'Update Profile',
						minWidth : 100,
						id		 : 'btn_updateprofile',
						style	 : 'margin-left:114px',
						handler  : doSubmit
					}
				],
				listeners : {
					render:function() {
						this.form.load({
							url		: '../../rpc/json/index2.cfm?method=users.read',
							params  : {"JsonType":"tree"},
							waitMsg : 'Loading..',
							success : function() {
								Ext.getCmp('password2').vtype='password';
							}
						});  			
					}
				},
				keys : [{
					key : Ext.EventObject.ENTER,
					fn  : doSubmit
				}]
			});
			
			userForm.on("actioncomplete", cs_community.app.formSuccessUser);
			userForm.on("actionfailed", cs_community.app.formFailedUser);
		},
		loadSearchForm : function(renderTo, id, action) {
			cs_community.app.loadStores();
			
			doSubmit = function() {
				var formPanel = Ext.getCmp(id);
				formPanel.submit();	
			}
			
			var searchForm = new Ext.form.FormPanel({
				labelAlign	: 'top',
				labelWidth	: 85, // label settings here cascade unless overridden
				border		: false,
				id			: id,
				bodyStyle	:'padding:5px',
				width		: 172,
				defaultType : 'textfield',
				buttonAlign :'left',        
				onSubmit	: Ext.emptyFn,
				submit: function() {
					this.getForm().getEl().dom.action = action;
					this.getForm().getEl().dom.method = 'GET';
					this.getForm().getEl().dom.submit();
				},
				items: [
					{
						hideLabel	   : true,
						xtype		   : 'combo',
						hiddenName	   : 's_categoryid',
						store		   : categoryDS,
						mode		   : 'local',
						triggerAction  : 'all',
						forceSelection : true,
						valueField	   : 'categoryid',
						displayField   : 'category',
						width		   : 162,
						emptyText	   : 'All categories...',
						editable	   : false
					},
					{
						hideLabel	   : true,
						xtype		   : 'combo',
						hiddenName	   : 's_leaid',
						store		   : leaDS,
						mode		   : 'local',
						triggerAction  : 'all',
						forceSelection : true,
						valueField	   : 'leaid',
						displayField   : 'lea',
						width		   : 162,
						emptyText	   : 'All regions...',
						editable	   : false
					},
					{
						hideLabel	   : true,
						xtype	   	   : 'combo',
						hiddenName	   : 's_subjectid',
						store		   : subjectDS,
						mode		   : 'local',
						triggerAction  : 'all',
						valueField	   : 'subjectid',
						displayField   : 'subject',
						width		   : 162,
						emptyText	   : 'All subjects...',
						editable	   : false
					},
					{
						hideLabel	   : true,
						xtype		   :'combo',
						hiddenName	   : 's_levelid',
						store		   : levelDS,
						mode		   : 'local',
						triggerAction  : 'all',
						forceSelection : true,
						valueField	   : 'levelid',
						displayField   : 'level',
						emptyText	   : 'All levels...',
						width		   : 162,
						editable	   : false
					},{
						hideLabel  : true,
						width	   : 162,
						name	   : 'searchfield',
						id		   : 'searchfield',
						emptyText  : 'Enter keyword(s)...',
						allowBlank : false
				}],
				buttons:[
					{
						minWidth : 162,
						text	 : 'Search',
						handler  : doSubmit
					}
				],
				keys : [{
					key : Ext.EventObject.ENTER,
					fn  : doSubmit
				}]
			});
			
			searchForm.render(renderTo);
		},
		loadGallery : function() {
			Ext.Ajax.request({
				url	   	 : '../../rpc/json/index2.cfm?method=images.view',
				method 	 : 'POST',
				scope    : cs_community.app,
				callback : function(opts,suss,resp){
					result = Ext.util.JSON.decode(resp.responseText);
					for (x=0;x<result.data.length;x++) {
						galleryArr[galleryArr.length] = new cs_community.app.image(result.data[x].imageid, result.data[x].name, result.data[x].fullimage, result.data[x].filename, result.data[x].description, result.data[x].lea, result.data[x].subjects, result.data[x].level, result.data[x].fullname, result.data[x].userid);
					} 	
					cs_community.app.setupGallery();
				}
			}); 
		},
		gup : function(name) {
			name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
			var regexS = "[\\?&]"+name+"=([^&#]*)";
			var regex = new RegExp( regexS );
			var results = regex.exec( window.location.href );
			if( results == null )
				return "";
			else
				return results[1];
		},
		setupGallery : function() {
			var id=cs_community.app.gup('imageid');
			selectedImageId=0;
			for (x=0;x<galleryArr.length;x++) {
				if (id==galleryArr[x].imageid) {
					selectedImageId=x;
					break;	
				}	
			}
			if (galleryArr.length!=0) {
				
				// if theres more than 3 images then show right arrow
				if (galleryArr.length>3) {
					Ext.get('arrow_right').show();	
				}
			
				// get first image
				Ext.getDom('image_main_id').src=galleryArr[selectedImageId].fullimage;			
				Ext.get('text_description').update(galleryArr[selectedImageId].description);
				Ext.get('text_lea').update(galleryArr[selectedImageId].lea);
				Ext.get('text_subject').update(galleryArr[selectedImageId].subject);
				Ext.get('text_level').update(galleryArr[selectedImageId].level);
				Ext.get('text_fullname').update(galleryArr[selectedImageId].fullname);
				
				Ext.get('image_main').show();
				
				var len=galleryArr.length;
				if (len==1) {
					photos="1 photo";
				} else {
                	photos=len+" photos";
                }
				Ext.getDom('image_count').innerHTML="<a href='community/browse-image-thumbs.cfm'>Browse "+photos+"</a>";
				// load tooltip for thumbnails
				new Ext.ToolTip({
					target: 'image_count',
					html: 'You can view all thumbnails by clicking here',
					title: 'Thumbnail view',
					trackMouse:true
				})
				
				if (Ext.isGecko3 || Ext.isSafari3) {
					var posW=7;
					var posH=7;
				} else {
					var posW=5;
					var posH=5;
				}
				
				Ext.get('image_thumbs2').setLeft(Ext.get('image_nav').getXY()[0]+posW);
				Ext.get('image_thumbs2').setTop(Ext.get('image_nav').getXY()[1]+posH);
				
				window.onresize=function(){
					Ext.getDom('image_thumbs2').style.display='none';
					var x=Ext.get('image_nav').getXY()[0]+posW;
					var y=Ext.get('image_nav').getXY()[1]+posH;
					Ext.get('image_thumbs2').setLeft(x);
					Ext.get('image_thumbs2').setTop(y);
					Ext.getDom('image_thumbs2').style.display='block';
				}
				
				// attach to click event
				Ext.get('page_left').on('click', cs_community.app.pageLeft, this);
				Ext.get('page_right').on('click', cs_community.app.pageRight, this);
				
				cs_community.app.loadImageThumbs();
			} 
		},
		pageLeft : function() {
			if (currentImage>3) {
				Ext.get('arrow_right').show();	
				gCurrentX=gCurrentX+60;
				var xY=Ext.get('image_thumbs').getXY();
				Ext.get('image_thumbs').stopFx();	
				Ext.get('image_thumbs').shift({ x: gCurrentX, duration:0.2, easing:'easeIn' });
				currentImage--;
			} 
			if (currentImage==3) {
				Ext.get('arrow_left').hide();		
			}
		},
		pageRight : function() {
			
			if (currentImage < galleryArr.length) {
				
				// show left arrow
				Ext.get('arrow_left').show();	
				
				gCurrentX=gCurrentX-60;
				if (Ext.get('image_'+currentImage)==null) {
					var dh = Ext.DomHelper;
					var list = dh.append('image_thumbs', {
						id: 'imagethumb_'+currentImage, tag: 'div', cls: cls
					});
					var list = dh.append('imagethumb_'+currentImage, {
						id: 'image_'+currentImage, tag: 'img', src:galleryArr[currentImage].filename, style:'visibility:hidden'
					});
					
					thumbStart = thumbStart+thumbWidth;
					Ext.get('image_thumbs').setWidth(thumbStart);
					
					window['imagebtn_'+currentImage] = Ext.get('image_'+currentImage);
					window['imagebtn_'+currentImage].on('click', cs_community.app.loadImage, this);
					window['imagebtn_'+currentImage].on('mouseover', cs_community.app.imageMouseOver, this);
					window['imagebtn_'+currentImage].stopFx();											 					
					window['imagebtn_'+currentImage].syncFx().fadeIn({block:true,useDisplay:true,duration: 1,callback:function(){}});
				}
				
				var xY=Ext.get('image_thumbs').getXY();
				Ext.get('image_thumbs').stopFx();	
				Ext.get('image_thumbs').shift({ x: gCurrentX,duration:0.2, easing:'easeIn' });
				
				currentImage++;
			} 
			if (currentImage==galleryArr.length) {
				Ext.get('arrow_right').hide();
			}
		},
		loadImageThumbs : function() {
			var dh = Ext.DomHelper;
			if (galleryArr.length<maxThumbShows) {
				maxThumbShows=galleryArr.length;
			}
			for (x=0;x<maxThumbShows;x++) {
				if (x==0) {
					cls='imagethumb imagethumbnopad';
				} else {
					cls='imagethumb';
				}
				var list = dh.append('image_thumbs', {
					id: 'imagethumb_'+x, tag: 'div', cls: cls
				});
				var list = dh.append('imagethumb_'+x, {
					id: 'image_'+x, tag: 'img', src:galleryArr[x].filename, style:'visibility:hidden'
				});
				thumbStart = thumbStart+thumbWidth;
				Ext.get('image_thumbs').setWidth(thumbStart);
				
				window['imagebtn_'+x] = Ext.get('image_'+x);
				window['imagebtn_'+x].on('click', cs_community.app.loadImage, this);
				window['imagebtn_'+x].on('mouseover', cs_community.app.imageMouseOver, this);
				window['imagebtn_'+x].stopFx();																						 																										 				window['imagebtn_'+x].syncFx().fadeIn({block:true,useDisplay:true,duration: 1,callback:function(){}});
				if (currentImage!=3) {
					currentImage++;
				}
			}
			gCurrentX=Ext.get('image_thumbs').getXY()[0];
			
			if (selectedImageId!=0) {
				for (x=0;x<selectedImageId;x++) {
					cs_community.app.pageRight();
				}
			}
		},
		imageMouseOver : function(btn,e) {
			Ext.get(e.id).stopFx();																						 																										 			Ext.get(e.id).syncFx().fadeOut({block:true,useDisplay:true,endOpacity:.2,duration: 0.3,callback:function(){
				Ext.get(e.id).syncFx().fadeIn({block:true,useDisplay:true,duration: 0.3,callback:function(){}});
			}});
		},
		loadImage : function(btn,e) {
			Ext.getDom('image_main_id').style.visibility='hidden';
			Ext.getDom('image_main_id').src=galleryArr[e.id.split('_')[1]].fullimage;
			Ext.getDom('text_description').innerHTML=galleryArr[e.id.split('_')[1]].description;
			Ext.getDom('text_lea').innerHTML=galleryArr[e.id.split('_')[1]].lea;
			Ext.getDom('text_subject').innerHTML=galleryArr[e.id.split('_')[1]].subject;
			Ext.getDom('text_level').innerHTML=galleryArr[e.id.split('_')[1]].level;
			Ext.getDom('text_fullname').innerHTML=galleryArr[e.id.split('_')[1]].fullname;		
			Ext.get('image_main_id').show();
		},
		image : function(imageid, name, fullimage, filename, description, lea, subject, level, fullname, userid) {
			this.imageid = imageid;
			this.name = name;
			this.fullimage = fullimage;
			this.filename = filename; 
			this.description = description; 
			this.lea = lea; 
			this.subject = subject; 
			this.level = level; 
			this.fullname = fullname; 
			this.userid = userid; 
		},
		loadStores : function() {
			categoryDS = new WM_objects.basicStore({
				url	   : '../../rpc/json/index2.cfm?method=categories.view',
				fields : ['categoryid', 'category'],
				id	   : 'categoryid'
			});	
			subjectDS = new WM_objects.basicStore({
				url	   : '../../rpc/json/index2.cfm?method=subjects.view',
				fields : ['subjectid', 'subject'],
				id	   : 'subjectid'
			});	
			levelDS = new WM_objects.basicStore({
				url	   : '../../rpc/json/index2.cfm?method=levels.view',
				fields : ['levelid', 'level'],
				id	   : 'levelid'
			});	
			leaDS = new WM_objects.basicStore({
				url	   : '../../rpc/json/index2.cfm?method=leas.view',
				fields : ['leaid', 'lea'],
				id	   : 'leaid'
			});
		},
		uploadImage : function() {
			cs_community.app.loadStores();
			
			doSubmit = function() {
				var formPanel = Ext.getCmp('imageUploadForm');
				if (formPanel.getForm().isValid()) {
					if (Ext.getCmp('agree').getValue()) {
						Ext.getCmp('btn_upload').setDisabled(true);
						formPanel.getForm().submit({waitMsg: 'Uploading...'});
					} else {
						Ext.Msg.alert('Action', 'You must agree that you have permission to use this image');
					}
				} else {
					Ext.Msg.alert('Invalid Action', 'Please complete the highlighted fields.');
				}	
			}
			
			imageForm = new Ext.form.FormPanel({  
				fileUpload	: true, 
				url			: '../../rpc/json/index2.cfm?method=images.save',
				baseParams	: {jsonType:'form'},
				border		: false, 
				buttonAlign : 'left',
				bodyStyle   : 'padding:5px',
				id		    : 'imageUploadForm',
				labelWidth	: 100,
				items : [			
					{
						xtype : 'hidden',
						name  : 'filefield',
						id    : 'filefield',
						value : 'image'					 
					},
					{
						xtype	       : 'fileuploadfield',
						id             : 'image',
						name	       : 'image',
						width          : 210,
						allowBlank     : false,
						emptyText      : 'Select an image...',
						blankText      : 'Select an image',
						fieldLabel     : 'Image (<span class=\'bluei\'>i</span>)',
						buttonCfg: {
							text    : '',
							iconCls : 'icon_image'
						},
						invalidText    : 'File type must be: .png, .gif, .jpg',
						validateOnBlur : true,
						validator: function(value){
							value = value.toLowerCase();
							value = value.substring(value.lastIndexOf('.')+1, value.length);
							ret = value=='png' || value=='gif' || value=='jpg';
							return ret;
						},
						tooltipText    : "<br />Click the folder icon to browse your computer for an image. Images can be one of the following:<br /><br />JPG<br />GIF<br />PNG",
						tooltipTitle   : 'Selecting an image',
						listeners      : {
							render : setFormFieldTooltip
						}								
					},
					{
						xtype 		 : 'textfield',
						fieldLabel   : 'Name (<span class=\'bluei\'>i</span>)',
						name	     : 'name',
						id		     : 'name',
						allowBlank   : false,
						emptyText    : 'Enter image name...',
						blankText    : 'Enter image name',
						width	     : 210,
						tooltipText  : "<br />Give the image a meaningful name<br />e.g. Photo of class 2P2",
						tooltipTitle : 'Naming your image',
						listeners    : {
							render : setFormFieldTooltip
						}
					},
					{
						xtype	     : 'textarea',
						fieldLabel   : 'Description (<span class=\'bluei\'>i</span>)',
						name	     : 'description',
						id		     : 'description',
						width	     : 210,
						emptyText    : 'Enter a description...',
						blankText    : 'Enter a description',
						allowBlank   : false,
						tooltipText  : "<br />Give the image a meaningful description. It's good practice to include keywords that users may use to find an image.",
						tooltipTitle : 'Image description',
						listeners    : {
							render : setFormFieldTooltip
						}
					},{
						fieldLabel	   : 'Category (<span class=\'bluei\'>i</span>)',
						xtype		   : 'combo',
						hiddenName	   : 'pcategoryid',
						id	   		   : 'categoryid',
						name	   	   : 'categoryid',
						store		   : categoryDS,
						mode		   : 'local',
						triggerAction  : 'all',
						forceSelection : true,
						valueField	   : 'categoryid',
						displayField   : 'category',
						width		   : 210,
						allowBlank	   : false,
						emptyText	   : 'Select a category...',
						blankText	   : 'Select a category',
						editable	   : false,
						tooltipText    : "<br />Select a category for the image.",
						tooltipTitle   : 'Image category',
						listeners      : {
							render : setFormFieldTooltip
						}
					},{
						fieldLabel	   : 'Region (<span class=\'bluei\'>i</span>)',
						xtype		   : 'combo',
						hiddenName	   : 'pleaid',
						id			   : 'leaid',
						name		   : 'leaid',
						store		   : leaDS,
						mode		   : 'local',
						triggerAction  : 'all',
						forceSelection : true,
						valueField	   : 'leaid',
						displayField   : 'lea',
						typeAhead	   : true,
						width		   : 210,
						allowBlank	   : false,
						emptyText	   : 'Select a region...',
						blankText	   : 'Select a region',
						editable	   : false,
						tooltipText    : "<br />Please choose the relevant region for this image.",
						tooltipTitle   : 'Select a region',
						listeners	   : {
							render : setFormFieldTooltip
						}
					},
					{
						fieldLabel	   : 'Subjects / Areas of learning (<span class=\'bluei\'>i</span>):<br /><br /><i>Hold CTRL to select more than one</i>.',
						labelSeparator : '',
						xtype		   : 'multiselect',
						hiddenName	   : 'psubjectid',
						multiSelect	   : true,
						id			   : 'subjectids',
						name		   : 'subjectids',
						store		   : subjectDS,
						mode		   : 'local',
						triggerAction  : 'all',
						valueField	   : 'subjectid',
						displayField   : 'subject',
						allowBlank	   : false,
						emptyText	   : 'Select a subject...',
						blankText	   : 'Select a subject',
						typeAhead	   : true,
						width		   : 210,
						height		   : 100,
						tooltipText    : "<br />Please select the subject(s) this image fits into. You can select more than one subject by holding the CTRL button on your keyboard and then selecting the subjects.",
						tooltipTitle   : 'Selecting subject(s)',
						listeners	   : {
							render : setFormFieldTooltip
						}
					},
					{
						fieldLabel	   : 'Level (<span class=\'bluei\'>i</span>)',
						xtype		   : 'combo',
						hiddenName	   : 'plevelid',
						id			   : 'levelid',
						name		   : 'levelid',
						store		   : levelDS,
						mode		   : 'local',
						triggerAction  : 'all',
						forceSelection : true,
						valueField	   : 'levelid',
						displayField   : 'level',
						allowBlank	   : false,
						emptyText	   : 'Select a level...',
						blankText	   : 'Select a level',
						typeAhead	   : true,
						width		   : 210,
						editable	   : false,
						tooltipText    : "<br />Please select the level this image fits into.",
						tooltipTitle   : 'Selecting a level',
						listeners	   : {
							render : setFormFieldTooltip
						}
					},{
						boxLabel   : 'I have permission to use this image',
						labelStyle : 'display:none',
						xtype	   : 'checkbox',
						name	   : 'agree',
						id		   : 'agree'
					}
				],
				buttons : [
					{
						text    : 'Upload image',
						style   : 'margin-left:105px;',
						id		: 'btn_upload',
						handler : doSubmit
					}
				],
				keys : [{
					key : Ext.EventObject.ENTER,
					fn  : doSubmit
				}]
			});
			imageForm.render('upload_image_form');
			
			imageForm.on("actioncomplete", cs_community.app.formSuccessImage);
			imageForm.on("actionfailed", cs_community.app.formFailedImage);
		},
		uploadMedia : function() {
			cs_community.app.loadStores();
			
			doSubmit = function() {
				var formPanel = Ext.getCmp('mediaUploadForm');
				if (formPanel.getForm().isValid()) {
					if (Ext.getCmp('agree').getValue()) {
						Ext.getCmp('btn_upload_media').setDisabled(true);
						formPanel.getForm().submit({waitMsg: 'Uploading...'});
					} else {
						Ext.Msg.alert('Action', 'You must agree that you have permission to use this document');
					}
				} else {
					Ext.Msg.alert('Invalid Action', 'Please complete the highlighted fields.');
				}	
			}
			
			mediaForm = new Ext.form.FormPanel({  
				fileUpload	: true, 
				url			: '../../rpc/json/index2.cfm?method=media.save',
				baseParams	: {jsonType:'form'},
				border		: false, 
				buttonAlign : 'left',
				bodyStyle   : 'padding:5px',
				id		    : 'mediaUploadForm',
				labelWidth	: 100,
				items : [			
					{
						xtype : 'hidden',
						name  : 'filefield',
						id    : 'filefield',
						value : 'media'					 
					},
					{
						xtype	       : 'fileuploadfield',
						id             : 'media',
						name	       : 'media',
						width          : 210,
						allowBlank     : false,
						emptyText      : 'Select a document...',
						blankText      : 'Select a document',
						fieldLabel     : 'Document (<span class=\'bluei\'>i</span>)',
						buttonCfg: {
							text    : '',
							iconCls : 'icon_media'
						},
						invalidText	   : 'File type must be: .doc, .pdf, .xls, .ppt',
						validateOnBlur : true,
						validator: function(value){
							value = value.toLowerCase();
							value = value.substring(value.lastIndexOf('.')+1, value.length);
							ret = value=='doc' || value=='pdf' || value=='xls' || value=='ppt';
							return ret;
						},
						tooltipText    : "<br />Click the folder icon to browse your computer for a document. Resource documents can be one of the following:<br /><br />Microsoft Word<br />Microsoft Excel<br />Microsoft PowerPoint<br />Adobe Acrobat (PDF)",
						tooltipTitle   : 'Selecting a document',
						listeners      : {
							render : setFormFieldTooltip
						}								
					},
					{
						xtype 		 : 'textfield',
						fieldLabel   : 'Name (<span class=\'bluei\'>i</span>)',
						name	     : 'name',
						id		     : 'name',
						allowBlank   : false,
						emptyText    : 'Enter document name...',
						blankText    : 'Enter document name',
						width	     : 210,
						tooltipText  : "<br />Give the document a meaningful name<br />e.g. Beginners guide to...",
						tooltipTitle : 'Naming your document',
						listeners    : {
							render : setFormFieldTooltip
						}
					},
					{
						xtype	     : 'textarea',
						fieldLabel   : 'Description (<span class=\'bluei\'>i</span>)',
						name	     : 'description',
						id		     : 'description',
						width	     : 210,
						emptyText    : 'Enter a description...',
						blankText    : 'Enter a description',
						allowBlank   : false,
						tooltipText  : "<br />Give the document a meaningful description. It's good practice to include keywords that users may use to find a document.",
						tooltipTitle : 'Document description',
						listeners    : {
							render : setFormFieldTooltip
						}
					},{
						fieldLabel	   : 'Category (<span class=\'bluei\'>i</span>)',
						xtype		   : 'combo',
						hiddenName	   : 'pcategoryid',
						id	   		   : 'categoryid',
						name	   	   : 'categoryid',
						store		   : categoryDS,
						mode		   : 'local',
						triggerAction  : 'all',
						forceSelection : true,
						valueField	   : 'categoryid',
						displayField   : 'category',
						width		   : 210,
						allowBlank	   : false,
						emptyText	   : 'Select a category...',
						blankText	   : 'Select a category',
						editable	   : false,
						tooltipText    : "<br />Select a category for the document.",
						tooltipTitle   : 'Resource document category',
						listeners      : {
							render : setFormFieldTooltip
						}
					},{
						fieldLabel	   : 'Region (<span class=\'bluei\'>i</span>)',
						xtype		   : 'combo',
						hiddenName	   : 'pleaid',
						id			   : 'leaid',
						name		   : 'leaid',
						store		   : leaDS,
						mode		   : 'local',
						triggerAction  : 'all',
						forceSelection : true,
						valueField	   : 'leaid',
						displayField   : 'lea',
						typeAhead	   : true,
						width		   : 210,
						allowBlank	   : false,
						emptyText	   : 'Select a region...',
						blankText	   : 'Select a region',
						editable	   : false,
						tooltipText    : "<br />Please choose the relevant region for this document.",
						tooltipTitle   : 'Select a region',
						listeners	   : {
							render : setFormFieldTooltip
						}
					},
					{
						fieldLabel	   : 'Subjects / Areas of learning (<span class=\'bluei\'>i</span>):<br /><br /><i>Hold CTRL to select more than one</i>.',
						labelSeparator : '',
						xtype		   : 'multiselect',
						hiddenName	   : 'psubjectid',
						multiSelect	   : true,
						id			   : 'subjectids',
						name		   : 'subjectids',
						store		   : subjectDS,
						mode		   : 'local',
						triggerAction  : 'all',
						valueField	   : 'subjectid',
						displayField   : 'subject',
						allowBlank	   : false,
						emptyText	   : 'Select a subject...',
						blankText	   : 'Select a subject',
						typeAhead	   : true,
						width		   : 210,
						height		   : 100,
						tooltipText    : "<br />Please select the subject(s) this document fits into. You can select more than one subject by holding the CTRL button on your keyboard and then selecting the subjects.",
						tooltipTitle   : 'Selecting subject(s)',
						listeners	   : {
							render : setFormFieldTooltip
						}
					},
					{
						fieldLabel	   : 'Level (<span class=\'bluei\'>i</span>)',
						xtype		   : 'combo',
						hiddenName	   : 'plevelid',
						id			   : 'levelid',
						name		   : 'levelid',
						store		   : levelDS,
						mode		   : 'local',
						triggerAction  : 'all',
						forceSelection : true,
						valueField	   : 'levelid',
						displayField   : 'level',
						allowBlank	   : false,
						emptyText	   : 'Select a level...',
						blankText	   : 'Select a level',
						typeAhead	   : true,
						width		   : 210,
						editable	   : false,
						tooltipText    : "<br />Please select the level this document fits into.",
						tooltipTitle   : 'Selecting a level',
						listeners	   : {
							render : setFormFieldTooltip
						}
					},{
						boxLabel   : 'I have permission to use this document',
						labelStyle : 'display:none',
						xtype	   : 'checkbox',
						name	   : 'agree',
						id		   : 'agree'
					}
				],
				buttons : [
					{
						text    : 'Upload document',
						style   : 'margin-left:105px;',
						id		: 'btn_upload_media',
						handler : doSubmit
					}
				],
				keys : [{
					key : Ext.EventObject.ENTER,
					fn  : doSubmit
				}]
			});
			mediaForm.render('upload_media_form');
			
			mediaForm.on("actioncomplete", cs_community.app.formSuccessMedia);
			mediaForm.on("actionfailed", cs_community.app.formFailedMedia);
		},
		formSuccessUser : function(form,action) {
			// Only enable the submit button if the load worked
			if(action.type == 'load'){
			} 
			if(action.type == 'submit') {
				// If the responseText is a null string, Ext doesnt raise an error so trap it here 
				// as an error because it should be some json.
				if(action.response.responseText == '') {
					Ext.MessageBox.alert('Error', 'Form empty');
					Ext.getCmp('btn_updateprofile').setDisabled(false);
				} else {
					Ext.MessageBox.alert('Action', 'Your profile has been successfully updated.');
					Ext.getCmp('btn_updateprofile').setDisabled(false);
				}
			}
		},		
		formFailedUser : function(form,action) {
			if(action.type == 'load') { // Handle the LOAD errors
				if (action.failureType == "connect") { 
					Ext.MessageBox.alert('Error', 'Server connection error');
					Ext.getCmp('btn_updateprofile').setDisabled(false);
				} else {
					if (action.response.responseText != '') {
						var result = Ext.decode(action.response.responseText);
						if(result && result.msg) {            
							Ext.MessageBox.alert('Error', action.result.msg);						
							Ext.getCmp('btn_updateprofile').setDisabled(false);
						} else {
							Ext.MessageBox.alert('Error', 'Success missing '+'Action type='+action.type+', '+failureType+'='+action.failureType);	
							Ext.getCmp('btn_updateprofile').setDisabled(false);
						}
					} else {
						Ext.MessageBox.alert('Error', 'Form submit empty');
						Ext.getCmp('btn_updateprofile').setDisabled(false);
					}
				}
			} 
			if(action.type == 'submit') { // Handle the SUBMIT errors
				if (action.failureType == "connect") { 
					Ext.MessageBox.alert('Error', 'Form submit empty');
					Ext.getCmp('btn_updateprofile').setDisabled(false);
				} else {
					if (action.failureType == "server") { 
					} else {    
						var result = Ext.decode(action.response.responseText); 
						if(result && result.msg) {            
							Ext.MessageBox.alert('Error', action.result.msg);
							Ext.getCmp('btn_updateprofile').setDisabled(false);
						} else {
							Ext.MessageBox.alert('Error', 'Unknown error ='+action.type+', '+failureType+'='+action.failureType);
							Ext.getCmp('btn_updateprofile').setDisabled(false);
						}
					}
				}  
			}
		},
		formSuccessImage : function(form,action) {
			if(action.type == 'submit') {
				if(action.response.responseText == '') {
					Ext.MessageBox.alert('Error', 'Form empty');
					Ext.getCmp('btn_upload').setDisabled(false);
				} else {
					imageForm.getForm().reset();
					var result = Ext.decode(action.response.responseText);
					if (result.moderated==1) {
						Ext.MessageBox.alert('Action', 'Your image has been successfully uploaded. Your image<br />will be moderated before it appears in the gallery.');
					} else {
						Ext.MessageBox.alert('Action', 'Your image has been successfully uploaded and is available to view immediately.');	
					}
					Ext.getCmp('btn_upload').setDisabled(false);
				}
			}
		},		
		formFailedImage : function(form,action) {
			if(action.type == 'load') { // Handle the LOAD errors
				if (action.failureType == "connect") { 
					Ext.MessageBox.alert('Error', 'Server connection error');
					Ext.getCmp('btn_upload').setDisabled(false);
				} else {
					if (action.response.responseText != '') {
						var result = Ext.decode(action.response.responseText);
						if(result && result.msg) {            
							Ext.MessageBox.alert('Error', action.result.msg);						
							Ext.getCmp('btn_upload').setDisabled(false);
						} else {
							Ext.MessageBox.alert('Error', 'Success missing '+'Action type='+action.type+', '+failureType+'='+action.failureType);	
							Ext.getCmp('btn_upload').setDisabled(false);
						}
					} else {
						Ext.MessageBox.alert('Error', 'Form submit empty');
						Ext.getCmp('btn_upload').setDisabled(false);
					}
				}
			} 
			if(action.type == 'submit') { // Handle the SUBMIT errors
				if (action.failureType == "connect") { 
					Ext.MessageBox.alert('Error', 'Form submit empty');
					Ext.getCmp('btn_upload').setDisabled(false);
				} else {
					if (action.failureType == "server") { 
					} else {    
						var result = Ext.decode(action.response.responseText); 
						if(result && result.msg) {            
							Ext.MessageBox.alert('Error', action.result.msg);
							Ext.getCmp('btn_upload').setDisabled(false);
						} else {
							Ext.MessageBox.alert('Error', 'Unknown error ='+action.type+', '+failureType+'='+action.failureType);
							Ext.getCmp('btn_upload').setDisabled(false);
						}
					}
				}  
			}
		},
		formSuccessMedia : function(form,action) {
			if(action.type == 'submit') {
				// If the responseText is a null string, Ext doesnt raise an error so trap it here 
				// as an error because it should be some json.
				if(action.response.responseText == '') {
					Ext.MessageBox.alert('Error', 'Form empty');
					Ext.getCmp('btn_upload_media').setDisabled(false);
				} else {
					mediaForm.getForm().reset();
					var result = Ext.decode(action.response.responseText);
					if (result.moderated==1) {
						Ext.MessageBox.alert('Action', 'Your document has been successfully uploaded. Your document<br />will be moderated before it appears in the library.');
					} else {
						Ext.MessageBox.alert('Action', 'Your document has been successfully uploaded and is available to view immediately.');	
					}
					Ext.getCmp('btn_upload_media').setDisabled(false);
				}
			}
		},		
		formFailedMedia : function(form,action) {
			if(action.type == 'load') { // Handle the LOAD errors
				if (action.failureType == "connect") { 
					Ext.MessageBox.alert('Error', 'Server connection error');
					Ext.getCmp('btn_upload_media').setDisabled(false);
				} else {
					if (action.response.responseText != '') {
						var result = Ext.decode(action.response.responseText);
						if(result && result.msg) {            
							Ext.MessageBox.alert('Error', action.result.msg);						
							Ext.getCmp('btn_upload_media').setDisabled(false);
						} else {
							Ext.MessageBox.alert('Error', 'Success missing '+'Action type='+action.type+', '+failureType+'='+action.failureType);	
							Ext.getCmp('btn_upload_media').setDisabled(false);
						}
					} else {
						Ext.MessageBox.alert('Error', 'Form submit empty');
						Ext.getCmp('btn_upload_media').setDisabled(false);
					}
				}
			} 
			if(action.type == 'submit') { // Handle the SUBMIT errors
				if (action.failureType == "connect") { 
					Ext.MessageBox.alert('Error', 'Form submit empty');
					Ext.getCmp('btn_upload_media').setDisabled(false);
				} else {
					if (action.failureType == "server") { 
					} else {    
						var result = Ext.decode(action.response.responseText); 
						if(result && result.msg) {            
							Ext.MessageBox.alert('Error', action.result.msg);
							Ext.getCmp('btn_upload_media').setDisabled(false);
						} else {
							Ext.MessageBox.alert('Error', 'Unknown error ='+action.type+', '+failureType+'='+action.failureType);
							Ext.getCmp('btn_upload_media').setDisabled(false);
						}
					}
				}  
			}
		}	
	}
}();