Ext.HtmlImage = Ext.extend(Ext.util.Observable, {
	// Image language text
	langTitle: 'Insert Image',
    urlSizeVars: ['width','height'],
    basePath: 'image.php',
    init: function(cmp){
        this.cmp = cmp;
        this.cmp.on('render', this.onRender, this);
        this.cmp.on('initialize', this.onInit, this, {delay:100, single: true});
    },
    onEditorMouseUp : function(e){
        Ext.get(e.getTarget()).select('img').each(function(el){
            var w = el.getAttribute('width'), h = el.getAttribute('height'), src = el.getAttribute('src')+' ';
            src = src.replace(new RegExp(this.urlSizeVars[0]+'=[0-9]{1,5}([&| ])'), this.urlSizeVars[0]+'='+w+'$1');
            src = src.replace(new RegExp(this.urlSizeVars[1]+'=[0-9]{1,5}([&| ])'), this.urlSizeVars[1]+'='+h+'$1');
            el.set({src:src.replace(/\s+$/,"")});
        }, this);
        
    },
    onInit: function(){
        Ext.EventManager.on(this.cmp.getDoc(), {
			'mouseup': this.onEditorMouseUp,
			buffer: 100,
			scope: this
		});
    },
    onRender: function() {
        var btn = this.cmp.getToolbar().addButton({
            iconCls: 'x-image-link',
            handler: this.selectImage,
            scope: this,
            tooltip: {
                title: this.langTitle
            },
            overflowText: this.langTitle
        });
    },
    selectImage: function() {
    	/*Ext.MessageBox.show({
            title: 'Address',
            msg: 'Please enter your image address link (http://mysite/myimage.jpg):',
            width:600,
            buttons: Ext.MessageBox.OKCANCEL,
            scope: this,
            fn: function showResultText(btn, text){
            	if (btn=="ok")
            		this.cmp.insertAtCursor("<img src='"+ text + "'>");
            },
            multiline: true 
        });*/
    	 
    	FOS.Organiser.Event.editorImageFor = this;
    	
    	   fp =   new Ext.Window({
    		 title: 'File Upload Form',
    		id: 'image-loader-window',
    		 items:{
    			 xtype: 'form',
    			    id: 'upload-form',
             fileUpload: true,
             width: 500,
             frame: true,
             height: 500,
            
             autoHeight: true,
             bodyStyle: 'padding: 10px 10px 0 10px;',
             labelWidth: 50,
             defaults: {
                 anchor: '95%',
                 allowBlank: false,
                 msgTarget: 'side'
             },
             items: [ {
                 xtype: 'fileuploadfield',
                 id: 'form-file',
                 emptyText: 'Select an image',
                 fieldLabel: 'Photo',
                 name: 'photo-path',
                 buttonText: 'Select image' 
             }],
             buttons: [{
                 text: 'Save',
                 handler: function(){
                     if(Ext.getCmp('upload-form').getForm().isValid()){
                    	 Ext.getCmp('upload-form').getForm().submit({
     	                     url: 'actions/ip.php', 
     	                    waitMsg: 'Uploading your photo...',
     	                    success: function(fp, o){
     	                        //Ext.MessageBox('Success', 'Processed file "'+o.result.file+'" on the server');
     	                    	 Ext.getCmp('image-loader-window').close();
     	                    	FOS.Organiser.Event.editorImageFor.cmp.insertAtCursor("<img src='"+ o.result.file + "'>");
     	                       
     	                      
     	                       
     	                    }
     	                });
                     }
                 }
             },{
                 text: 'Reset',
                 handler: function(){
                     fp.getForm().reset();
                 }
             }]
         }}
    	 );
    	 
    	 fp.show();
    	 
    }
});
FOS.Organiser.Event.isStandAlone = false;
panelContainer = 'organiserMainTab';
FOS.Organiser.Event.isSaved = false;


FOS.Organiser.Event.ageCategoryStore = new Ext.data.JsonStore({
    url: 'data.php',
    baseParams: {
        set: 'age_category'
    
    },
    root: 'data',
    fields: [{
        name: 'age_category_id'
    }, {
        name: 'age_category_description'
    }]
});
 
 
FOS.Organiser.Event.answerTypes = [['BOOL','Yes/No'], ['TEXT', 'Text'], ['INT', 'Number'],['CBOX', 'Mandatory Tick Box'], ['TSHI', 'T-Shirt (S,M,L,XL)']];

FOS.Organiser.Event.answerTypeStore = new Ext.data.ArrayStore({
	id: 'answerTypeId',
	fields: [{
        name: 'answerTypeId'
    }, {
        name: 'type'
    }]
});

FOS.Organiser.Event.answerTypeStore.loadData(FOS.Organiser.Event.answerTypes);

 

FOS.Organiser.Event.travelStore = new Ext.data.JsonStore({
    url: 'action.php',
    baseParams: {
        module: 'event_travel',
        uniqueGroupId: 2,
        eventId :  FOS.Organiser.Event.eventId
    },
    id: 'id',
    root: 'data',
    writer: new Ext.data.JsonWriter({
        encode: true,
        writeAllFields: true // write all fields, not just those that changed
    }),
    listeners: {
    	'save' : function (s,b,d) { 
    	
   	 if (FOS.Organiser.Event.isNewTravel == true)
   	 {
   		 Ext.getCmp('travelGrid').getStore().load({params: {eventId: FOS.Organiser.Event.eventId}, callback: function() {
   			 Ext.getCmp('travelGrid').startEditing(0, 1);
   			 FOS.Organiser.Event.isNewTravel = false;
   		 }});
   	 }
   	
   }
   },
    autoSave: true,
    root: 'data',
    fields: [
    {
        name: 'id'
    }, {name : 'title'}, 
    {
        name: 'description'
    }, {
        name: 'price'
    },  {name : 'eventId'}, {
        name: 'uniqueGroupId'
    },{
        name: 'supplierProductCode'
    }]
});

FOS.Organiser.Event.rentalStore = new Ext.data.JsonStore({
    url: 'action.php',
    baseParams: {
	module: 'event_rental' ,
    uniqueGroupId: 4,
    eventId :  FOS.Organiser.Event.eventId
    },
    id: 'id',
    root: 'data',
    writer: new Ext.data.JsonWriter({
        encode: true,
        writeAllFields: true // write all fields, not just those that changed
    }),
    listeners: {
    	'save' : function (s,b,d) { 
    	
    	 if (FOS.Organiser.Event.isNewRental == true)
    	 {
    		 Ext.getCmp('rentalGrid').getStore().load({params: {eventId: FOS.Organiser.Event.eventId}, callback: function() {
    			 Ext.getCmp('rentalGrid').startEditing(0, 1);
    			 FOS.Organiser.Event.isNewRental = false;
    		 }});
    	 }
    	
    }
    },
    autoSave: true,
    root: 'data',
    fields: [
    {
        name: 'id'
    }, {name : 'title'}, 
    {
        name: 'description'
    }, {
        name: 'price'
    },  {name : 'eventId'}, {
        name: 'uniqueGroupId'
    },{
        name: 'supplierProductCode'
    }]
});

FOS.Organiser.Event.merchandiseStore = new Ext.data.JsonStore({
    url: 'action.php',
    baseParams: {
		module: 'event_merchandise',
		uniqueGroupId: 0,
		eventId :  FOS.Organiser.Event.eventId
    },
    id: 'id',
    root: 'data',
    writer: new Ext.data.JsonWriter({
        encode: true,
        writeAllFields: true // write all fields, not just those that changed
    }),
    listeners: {
    	'save' : function (s,b,d) { 
    	
    	 if (FOS.Organiser.Event.isNewMerchandise == true)
    	 {
    		 Ext.getCmp('merchandiseGrid').getStore().load({params: {eventId: FOS.Organiser.Event.eventId}, callback: function() {
    			 Ext.getCmp('merchandiseGrid').startEditing(0, 1);
    			 FOS.Organiser.Event.isNewMerchandise = false;
    		 }});
    	 }
    	
    }
    },
    root: 'data',
    fields: [
    {
        name: 'id'
    }, {name : 'title'}, 
    {
        name: 'description'
    }, {
        name: 'price'
    },  {name : 'eventId'},{
        name: 'uniqueGroupId'
    },{
        name: 'supplierProductCode'
    }]
});


FOS.Organiser.Event.entryStore = new Ext.data.JsonStore({
    url: 'action.php',
    baseParams: {
		module: 'event_race_entry' ,
		uniqueGroupId: 1,
		eventId :  FOS.Organiser.Event.eventId
    },
    id: 'id',
    root: 'data',
    writer: new Ext.data.JsonWriter({
        encode: true,
        writeAllFields: true // write all fields, not just those that changed
    }),
    listeners: {
    	'save' : function (s,b,d) { 
    	
    	 if (FOS.Organiser.Event.isNewEntry == true)
    	 {
    		 Ext.getCmp('entryGrid').getStore().load({params: {eventId: FOS.Organiser.Event.eventId}, callback: function() {
    			 Ext.getCmp('entryGrid').startEditing(0, 1);
    			 FOS.Organiser.Event.isNewEntry = false;
    		 }});
    	 }
    	
    }
    },
    root: 'data',
    fields: [
    {
        name: 'id'
    }, {name : 'title'}, 
    {
        name: 'description'
    }, {
        name: 'price'
    }, {name : 'eventId'}, {
        name: 'uniqueGroupId'
    },{
        name: 'supplierProductCode'
    }]
});

FOS.Organiser.Event.questionStore = new Ext.data.JsonStore({
    url: 'action.php',
    baseParams: {
		module: 'event_question' ,
		eventId :  FOS.Organiser.Event.eventId
    },
    id: 'id',
    root: 'data',
    writer: new Ext.data.JsonWriter({
        encode: true,
        writeAllFields: true // write all fields, not just those that changed
    }),
    root: 'data',
    listeners: {
    	'save' : function (s,b,d) { 
    	
    	 if (FOS.Organiser.Event.isNewQuestion == true)
    	 {
    		 Ext.getCmp('questionGrid').getStore().load({params: {eventId: FOS.Organiser.Event.eventId}, callback: function() {
    			 Ext.getCmp('questionGrid').startEditing(0, 1);
    			 FOS.Organiser.Event.isNewQuestion = false;
    		 }});
    	 }
    	
    }
    },
    fields: [
    {
        name: 'id'
    }, {name : 'question'}, 
    {
        name: 'eventId' 
    }, {
        name: 'answerTypeId' }, {name: 'required'}]
});

FOS.Organiser.Event.productColumns = [{
    header: 'Id',
    width: 50,
  hidden:true,    dataIndex: 'id'
},  {
	    header: 'Title',
	    width: 170,
	    editable: true,
	    editor: new Ext.form.TextField({selectOnFocus:true}),
	    sortable: true,
	    dataIndex: 'title'
	}, {
	    header: 'Description',
	    width: 170,
	    editable: true,
	    hidden:false,
	    editor: new Ext.form.TextField({selectOnFocus:true}),
	    sortable: true,
	    dataIndex: 'description'
	}, {
	    header: 'Price',
	    editable: true,
	    editor: new Ext.form.TextField({height: 200, width: 200}),
	    width: 75,
	    sortable: true,
	    dataIndex: 'price'
	}, {
	    header: 'Group',
	    width: 150,
	    hidden: true,
	    
	    dataIndex: 'uniqueGroupId' 
	}, {
	    header: 'EventId', hidden: true,
	       dataIndex: 'eventId', width: 150
	}, {
	    header: 'Supplier Code', editable: true,
	    editor: new Ext.form.TextField({selectOnFocus:true}),
	    sortable: true,
	       dataIndex: 'supplierProductCode', width: 120
	}
];

function renderQuestionType (id) {
    try {
		switch (id) {
		case 'TEXT':
			return 'Text';
			break;
		case 'BOOL':
			return 'Yes/No';
			break;
		case 'INT':
			return 'Number';
			break;
		case 'TSHI':
			return 'T Shirt (S,M,L,XL)';
			break;
		case 'CBOX':
			return 'Mandatory Tick Box';
			break;
		} 
	}
	catch (e) {
		
		//alert ('kkk')
;	} 
       
}


// create the Grid
FOS.Organiser.Event.questionGridViewConfig = {
    xtype: 'editorgrid',
    store: FOS.Organiser.Event.questionStore,
    id: 'questionGrid',
    hidden : false,
    frame: true,
    //autoWidth: true,
    border: true,
    selModel : new Ext.grid.RowSelectionModel({singleSelect: true}),

    clicksToEdit: 1,
    tbar: [{
        text: 'Add',
        icon: 'resources/icons/add.png',handler: function(){
			// access the Record constructor through the grid's store
			var EntryFeeType = Ext.getCmp('questionGrid').getStore().recordType;
			var newRaceEntryRecord = new EntryFeeType({
				 
				question: 'Please specify question',
				answerTypeId: 'TEXT',
				eventId : FOS.Organiser.Event.eventId,
				required: 1
				
			});
			FOS.Organiser.Event.isNewQuestion = true;
			
			Ext.getCmp('questionGrid').stopEditing();
			Ext.getCmp('questionGrid').getStore().insert(0, newRaceEntryRecord);
			
			
		}
    }, {
        text: 'Remove',
        icon: 'resources/icons/delete.png',
        	 scope: this,
             handler: function(){
         		var index = Ext.getCmp('questionGrid').getSelectionModel().getSelected();
     	        
         		if (!index) {
     	            return false;
     	        }
         		var rec = Ext.getCmp('questionGrid').getStore().getById(index.data.id);
             
         		Ext.getCmp('questionGrid').getStore().remove(rec);
         }}],
  
    columns: [{
        header: 'Id',
        width: 170,
        editable: false,
        sortable: true,
        hidden: true,
        dataIndex: 'id'
    },{
        header: 'Question',
        width: 170,
        editable: true,
        editor: new Ext.form.TextField({selectOnFocus:true}),
        sortable: true,
        dataIndex: 'question'
    },  {
        header: 'Answer type',
        width: 150,
        hidden: false,
        sortable: true,
        editor: new Ext.form.ComboBox({
            typeAhead: true,
            triggerAction: 'all',
            mode: 'local', 
        	store: FOS.Organiser.Event.answerTypeStore,
			displayField: 'type',
			editable: false,
			valueField: 'answerTypeId'	
        }),
        editable: true,
        renderer: renderQuestionType,
        dataIndex: 'answerTypeId' 
    }],
    stripeRows: true,
    
    height: 200,
   
    title: 'Race specific questions'
};


// create the Grid
FOS.Organiser.Event.entryGridViewConfig = {
    xtype: 'editorgrid',
    store: FOS.Organiser.Event.entryStore,
    id: 'entryGrid',
    hidden : false,
    frame: true,
    border: true,
    selModel : new Ext.grid.RowSelectionModel({singleSelect: true}),

    clicksToEdit: 1, 
    tbar: [{
        text: 'Add Race Entry',
        icon: 'resources/icons/add.png',handler: function(){
			// access the Record constructor through the grid's store
			var EntryFeeType = Ext.getCmp('entryGrid').getStore().recordType;
			var newRaceEntryRecord = new EntryFeeType({
				 
				title: 'Non Affiliated race entry',
				description: '',
				uniqueGroupId: 1, // Race Entry
				price: 0.99,
				eventId :  FOS.Organiser.Event.eventId,
				supplierProductCode : ''
				 
			});
			Ext.getCmp('entryGrid').stopEditing();
			FOS.Organiser.Event.isNewEntry = true;
			Ext.getCmp('entryGrid').getStore().insert(0, newRaceEntryRecord);
			
			
		}
    }, {
        text: 'Remove Race Entry',
        icon: 'resources/icons/delete.png',
        	 scope: this,
             handler: function(){
         		var index = Ext.getCmp('entryGrid').getSelectionModel().getSelected();
     	        
         		if (!index) {
     	            return false;
     	        }
         		var rec = Ext.getCmp('entryGrid').getStore().getById(index.data.id);
             
         		Ext.getCmp('entryGrid').getStore().remove(rec);
         }}],
  
    colModel: new Ext.grid.ColumnModel({columns: [{
        header: 'Id',
        width: 50,
      hidden:false,    dataIndex: 'id'
    },  {
    	    header: 'Title',
    	    width: 170,
    	    editable: true,
    	    editor: new Ext.form.TextField({selectOnFocus:true}),
    	    sortable: true,
    	    dataIndex: 'title'
    	}, {
    	    header: 'Description',
    	    width: 170,
    	    editable: true,
    	    hidden:true,
    	    editor: new Ext.form.TextField({selectOnFocus:true}),
    	    sortable: true,
    	    dataIndex: 'description'
    	}, {
    	    header: 'Price',
    	    editable: true,
    	    editor: new Ext.form.TextField({height: 200, width: 200}),
    	    width: 75,
    	    sortable: true,
    	    dataIndex: 'price'
    	}, {
    	    header: 'Group',
    	    width: 150,
    	    hidden: true,
    	    
    	    dataIndex: 'uniqueGroupId' 
    	}, {
    	    header: 'EventId', hidden: true,
    	       dataIndex: 'eventId', width: 150
    	}, {
    	    header: 'Supplier Code', editable: true,
    	    editor: new Ext.form.TextField({selectOnFocus:true}),
    	    sortable: true,
    	       dataIndex: 'supplierProductCode', width: 120
    	}
    ]}),
    stripeRows: true,
    
    height: 200,
    //width: 570,
    title: 'Race entry types for this event'
};



// create the Grid
FOS.Organiser.Event.rentalGridViewConfig = {
    xtype: 'editorgrid',
    store: FOS.Organiser.Event.rentalStore,
    id: 'rentalGrid',
    hidden : true,
    frame: true,
    border: true,

    selModel : new Ext.grid.RowSelectionModel({singleSelect: true}),
	clicksToEdit : 1,
    tbar: [{
        text: 'Add',
        icon: 'resources/icons/add.png',handler: function(){
			// access the Record constructor through the grid's store
			var Product = Ext.getCmp('rentalGrid').getStore().recordType;
			var newMerchandise = new Product({
				 
				title: 'GPS',
				description: 'GPS Monitior',
				price: 0.99,
				uniqueGroupId: 4,
				eventId :  FOS.Organiser.Event.eventId
				 
			});
			FOS.Organiser.Event.isNewRental = true;
			Ext.getCmp('rentalGrid').stopEditing();
			Ext.getCmp('rentalGrid').getStore().insert(0, newMerchandise);
			 
		}
    }, {
        text: 'Remove',
        icon: 'resources/icons/delete.png',
        scope: this,
        handler: function(){
    		var index = Ext.getCmp('rentalGrid').getSelectionModel().getSelected();
	        
    		if (!index) {
	            return false;
	        }
    		var rec = Ext.getCmp('rentalGrid').getStore().getById(index.data.id);
        
    		Ext.getCmp('rentalGrid').getStore().remove(rec);
    }}],
    colModel: new Ext.grid.ColumnModel({columns: [{
        header: 'Id',
        width: 50,
      hidden:true,    dataIndex: 'id'
    },  {
    	    header: 'Title',
    	    width: 170,
    	    editable: true,
    	    editor: new Ext.form.TextField({selectOnFocus:true}),
    	    sortable: true,
    	    dataIndex: 'title'
    	}, {
    	    header: 'Description',
    	    width: 170,
    	    editable: true,
    	    hidden:true,
    	    editor: new Ext.form.TextField({selectOnFocus:true}),
    	    sortable: true,
    	    dataIndex: 'description'
    	}, {
    	    header: 'Price',
    	    editable: true,
    	    editor: new Ext.form.TextField({height: 200, width: 200}),
    	    width: 75,
    	    sortable: true,
    	    dataIndex: 'price'
    	}, {
    	    header: 'Group',
    	    width: 150,
    	    hidden: true,
    	    
    	    dataIndex: 'uniqueGroupId' 
    	}, {
    	    header: 'EventId', hidden: true,
    	       dataIndex: 'eventId', width: 150
    	}, {
    	    header: 'Supplier Code', editable: true,
    	    editor: new Ext.form.TextField({selectOnFocus:true}),
    	    sortable: true,
    	       dataIndex: 'supplierProductCode', width: 120
    	}
    ]}),
    stripeRows: true,
    height: 200,
   // width: 570,
    title: 'Items available for rental'
};
  
// create the Grid
FOS.Organiser.Event.travelGridViewConfig = {
    xtype: 'editorgrid',
    store: FOS.Organiser.Event.travelStore,
    id: 'travelGrid',
    hidden : true,
    frame: true,
    border: true,
    selModel : new Ext.grid.RowSelectionModel({singleSelect: true}),
	clicksToEdit : 1,
    tbar: [{
        text: 'Add Travel',
        icon: 'resources/icons/add.png',handler: function(){
			// access the Record constructor through the grid's store
			var TravelItem = Ext.getCmp('travelGrid').getStore().recordType;
			var newTravelItem = new TravelItem({
				 
				title: 'Travel from a to b',
				eventId: FOS.Organiser.Event.eventId,
				description: '1 seat on a bus from from a to b',
				price: 0.99,
				uniqueGroupId : 2 // travel group
			 
				 
			});
			FOS.Organiser.Event.isNewTravel = true;
			
			Ext.getCmp('travelGrid').stopEditing();
			Ext.getCmp('travelGrid').getStore().insert(0, newTravelItem);
			 
		}
    }, {
        text: 'Remove Travel',
        icon: 'resources/icons/delete.png',
        scope: this,
        handler: function(){
    		var index = Ext.getCmp('travelGrid').getSelectionModel().getSelected();
	        
    		if (!index) {
	            return false;
	        }
    		var rec = Ext.getCmp('travelGrid').getStore().getById(index.data.id);
        
    		Ext.getCmp('travelGrid').getStore().remove(rec);
    }
    }],
    colModel: new Ext.grid.ColumnModel({columns: FOS.Organiser.Event.productColumns}),
    stripeRows: true,
    
    height: 200,
   // width: 570,
    title: 'Event Specific Travel'
};


// create the Grid
FOS.Organiser.Event.merchandiseGridViewConfig = {
    xtype: 'editorgrid',
    store: FOS.Organiser.Event.merchandiseStore,
    id: 'merchandiseGrid',
    hidden : false,
    frame: true,
    border: true,
    selModel : new Ext.grid.RowSelectionModel({singleSelect: true}),
	clicksToEdit : 1,
    tbar: [{
        text: 'Add Product',
        icon: 'resources/icons/add.png',handler: function(){
			// access the Record constructor through the grid's store
			var Product = Ext.getCmp('merchandiseGrid').getStore().recordType;
			var newMerchandise = new Product({
				 
				title: 'Product title',
				description: 'Description of product e.g. T-Shirt',
				price: 0.99,
				eventId :  FOS.Organiser.Event.eventId,
				uniqueGroupId : 0, // no group as such,
				supplierProductCode : ''
				 
			});
			
			FOS.Organiser.Event.isNewMerchandise = true;
			
			Ext.getCmp('merchandiseGrid').stopEditing();
			Ext.getCmp('merchandiseGrid').getStore().insert(0, newMerchandise);
			 
		}
    }, {
        text: 'Remove Product',
        icon: 'resources/icons/delete.png',
        scope: this,
        handler: function(){
    		var index = Ext.getCmp('merchandiseGrid').getSelectionModel().getSelected();
	        
    		if (!index) {
	            return false;
	        }
    		var rec = Ext.getCmp('merchandiseGrid').getStore().getById(index.data.id);
        
    		Ext.getCmp('merchandiseGrid').getStore().remove(rec);
    }
    }],
    colModel: new Ext.grid.ColumnModel({columns: [{
        header: 'Id',
        width: 50,
      hidden:true,    dataIndex: 'id'
    },  {
    	    header: 'Title',
    	    width: 170,
    	    editable: true,
    	    editor: new Ext.form.TextField({selectOnFocus:true}),
    	    sortable: true,
    	    dataIndex: 'title'
    	}, {
    	    header: 'Description',
    	    width: 170,
    	    editable: true,
    	    hidden:false,
    	    editor: new Ext.form.TextField({selectOnFocus:true}),
    	    sortable: true,
    	    dataIndex: 'description'
    	}, {
    	    header: 'Price',
    	    editable: true,
    	    editor: new Ext.form.TextField({height: 200, width: 200}),
    	    width: 75,
    	    sortable: true,
    	    dataIndex: 'price'
    	}, {
    	    header: 'Group',
    	    width: 150,
    	    hidden: true,
    	    
    	    dataIndex: 'uniqueGroupId' 
    	}, {
    	    header: 'EventId', hidden: true,
    	       dataIndex: 'eventId', width: 150
    	}, {
    	    header: 'Supplier Code', editable: true,
    	    editor: new Ext.form.TextField({selectOnFocus:true}),
    	    sortable: true,
    	       dataIndex: 'supplierProductCode', width: 120
    	}]}),
    stripeRows: true,
    height: 200,
    title: 'Event Specific Merchandise'
};



FOS.Organiser.Event.store = new Ext.data.JsonStore({
    url: 'data.php',
    baseParams: {
        set: 'organiser',
        subSet: 'events'
    },
    root: 'data',
    fields: [{
        name: 'event_id'
    }, {
        name: 'event_name'
    }, {
        name: 'event_type'
    }, {
        name: 'event_date'
    }]
});

// //



FOS.Organiser.Event.orgnaniserStore = new Ext.data.JsonStore({
    url: 'data.php',
    baseParams: {
        set: 'organisers'
    
    },
    root: 'data',
    fields: [{
        name: 'organiser_id'
    }, {
        name: 'name'
    }]
});

// ;

FOS.Organiser.Event.typeStore = new Ext.data.JsonStore({
    url: 'php/getEventTypes.php',
    root: 'data',
    fields: [{
        name: 'type_id'
    }, {
        name: 'description'
    }]
});






FOS.Organiser.Event.subTypeStore = new Ext.data.JsonStore({
    url: 'php/getEventSubTypes.php',
    root: 'data',
    fields: [{
        name: 'sub_type_id'
    }, {
        name: 'type_id'
    }, {
        name: 'description'
    }, {
        name: 'swim_distance'
    }, {
        name: 'bike_distance'
    }, {
        name: 'run_distance'
    }, {
        name: 'run_distance_1'
    }]
});

FOS.Organiser.Event.typeStore.load();
FOS.Organiser.Event.orgnaniserStore.load();
FOS.Organiser.Event.subTypeStore.load();

FOS.Organiser.Event.showToolBar = function(){
    Ext.getCmp('event-profile-toolbar').show();
    
    
};

FOS.Organiser.Event.toolbarConfig = {
    id: 'event-profile-toolbar',
    items: [{
        text: 'Back',
        icon: 'resources/icons/arrow_left.png',
        handler: function(){
            FOS.Organiser.Dashboard.navigateBack();
            
            
        }
    } , { text: 'Save', 
    	icon :
    
		  'resources/icons/disk.png', id: 'saveNewEvent', disabled: false,
		 handler: function(btn){ FOS.Organiser.Event.save();
		  }},{ text: 'Delete', icon :
			  'resources/icons/medal_gold_delete.png', id:
			  'deleteCurrentEvent', handler: function(btn){
			  FOS.Organiser.Event.destroy();
			   }}
		  
		  
    ]
};


FOS.Organiser.Event.viewConfig =   {
     
    xtype: 'form',
   frame: false,

    border: false,
    renderTo : 'eventPanel',
    id: 'eventDetail',
     
    labelWidth: 150,
    labelAlign: 'top',
    defaults: {
        selectOnFocus: true
    },
    
    items: [{
        xtype: 'textfield',
        fieldLabel: 'Event Name *',
        width: 300,
        id: 'eventName',
        name: 'eventName',
        allowBlank: false,
        listeners: {
            'focus': function(){
                Ext.getCmp('help-box-en').show();
            },
            'blur': function(){
                // Ext.getCmp('help-box-en').hide();
            }
        }
    
    }, {
        xtype: 'box',
     
        hidden: true,
        cls: 'help-box',
        id: 'help-box-en',
        autoEl: {
            html: '<b>Help tip:</b> Enter the name of the event as you would like it to appear in the event list'
        }
    }, {
        xtype: 'combo',
        hidden: true,
        id: 'ageCategoryId',
        //fieldLabel: 'Age Category ',
        store: FOS.Organiser.Event.ageCategoryStore,
        valueField: 'age_category_id',
        displayField: 'age_category_description',
        mode: 'local',
        editable: false,
        triggerAction: 'all',
        width: 300,
        listeners: {
            'focus': function(){
                Ext.getCmp('help-box-ag').show();
            },
            'blur': function(){
                // Ext.getCmp('help-box-ag').hide();
            }
        }
    }, {
        xtype: 'box',
        
        cls: 'help-box',
        id: 'help-box-ag',
        hidden: true,
        autoEl: {
            html: '<b>Help tip:</b> Select the Age Categories that will be used at this event i.e. what group a participant will be in on the day of the race M18-29, F30-39'
        }
    }, {
        xtype: 'combo',
        id: 'typeId',
        editable: false,
        fieldLabel: 'Event Type *',
        store: FOS.Organiser.Event.typeStore,
        valueField: 'type_id',
        displayField: 'description',
        mode: 'local',
        triggerAction: 'all',
        allowBlank: false,
        width: 300,
        listeners: {
            'focus': function(){
                Ext.getCmp('help-box-et').show();
            },
            'blur': function(){
                // Ext.getCmp('help-box-et').hide();
            }
        }
    }, {
        xtype: 'box',
    
        cls: 'help-box',
        id: 'help-box-et',
        hidden: true,
        autoEl: {
            html: '<b>Help tip:</b> Select the type of sport for this event. If the sport is not in the list then please send an email to support@fullonsport.co.uk, with the details of the sport and we can then set it up.'
        }
    }, {
        xtype: 'combo',
        fieldLabel: 'Event Sub Type *',
        id: 'subTypeId',
        editable: false,
        store: FOS.Organiser.Event.subTypeStore,
        valueField: 'sub_type_id',
        allowBlank: false,
        displayField: 'description',
        mode: 'local',
        triggerAction: 'all',
        width: 300,
        listeners: {
            'focus': function(){
                Ext.getCmp('help-box-est').show();
            },
            'blur': function(){
                // Ext.getCmp('help-box-est').hide();
            },
            'select': function(cbo, rec, idx){
            
            
                FOS.Organiser.Event.toggleDistances(rec.data.type_id);
                
                Ext.getCmp('swimDistance').setValue(rec.data.swim_distance);
                Ext.getCmp('bikeDistance').setValue(rec.data.bike_distance);
                Ext.getCmp('runDistance').setValue(rec.data.run_distance);
                Ext.getCmp('runDistance1').setValue(rec.data.run_distance_1);
                
                
            }
            
        }
    }, {
        xtype: 'box',
      
        hidden: true,
        cls: 'help-box',
        id: 'help-box-est',
        autoEl: {
            html: '<b>Help tip:</b> The event sub type is generally the event distance.  You MUST select from the list. Please contact support@fullonsport.co.uk if you would like to add an additional sub type or distance.'
        }
    }, {
        xtype: 'textfield',
        id: 'runDistance1',
        hidden: true,
        
        fieldLabel: 'Duathlon Run Distance 1',
        listeners: {
            'focus': function(){
                Ext.getCmp('help-box-rd1').show();
            },
            'blur': function(){
                Ext.getCmp('help-box-rd1').hide();
            }
        }
    }, {
        xtype: 'box',
       
        hidden: true,
        cls: 'help-box',
        id: 'help-box-rd1',
        autoEl: {
            html: '<b>Help tip:</b> This is the distance for the first run split of a duathlon.'
        }
    }, {
        xtype: 'textfield',
        id: 'swimDistance',
        hidden: true,
        
        fieldLabel: 'Swim Distance',
        listeners: {
            'focus': function(){
                Ext.getCmp('help-box-sd').show();
            },
            'blur': function(){
                // Ext.getCmp('help-box-sd').hide();
            }
        }
    }, {
        xtype: 'box',
        hidden: true,
        cls: 'help-box',
        id: 'help-box-sd',
        autoEl: {
            html: '<b>Help tip:</b> This is the swim distance for either a triathlon or swim race'
        }
    }, {
        xtype: 'textfield',
        id: 'bikeDistance',
        hidden: true,
        
        fieldLabel: 'Bike Distance',
        listeners: {
            'focus': function(){
                Ext.getCmp('help-box-bd').show();
            },
            'blur': function(){
                // Ext.getCmp('help-box-bd').hide();
            }
        }
    }, {
        xtype: 'box',
       
        hidden: true,
        cls: 'help-box',
        id: 'help-box-bd',
        autoEl: {
            html: '<b>Help tip:</b> This is the bike distance for either a triathlon or cycling race'
        }
    }, {
        xtype: 'textfield',
        id: 'runDistance',
        hidden: true,
        
        fieldLabel: 'Run Distance',
        listeners: {
            'focus': function(){
                Ext.getCmp('help-box-rd2').show();
            },
            'blur': function(){
                // Ext.getCmp('help-box-rd2').hide();
            }
        }
    }, {
        xtype: 'box',
       
        hidden: true,
        cls: 'help-box',
        id: 'help-box-rd2',
        autoEl: {
            html: '<b>Help tip:</b> This is the run distance for either a triathlon or running race'
        }
    }, {
        xtype: 'combo',
        fieldLabel: 'Organiser *',
        id: 'organiserId',
        editable: false,
        store: FOS.Organiser.Event.orgnaniserStore,
        valueField: 'organiser_id',
        displayField: 'name',
        mode: 'local',
        allowBlank: false,
        triggerAction: 'all',
        width: 300,
        listeners: {
            'focus': function(){
                Ext.getCmp('help-box-o').show();
            },
            'blur': function(){
                // Ext.getCmp('help-box-o').hide();
            }
        }
    }, {
        xtype: 'box',
     
        hidden: true,
        cls: 'help-box',
        id: 'help-box-o',
        autoEl: {
            html: '<b>Help tip:</b> Select the organiser of the event. If you are an administrator for more than one organiser then please select the correct organiser for this event.'
        }
    }, {
        xtype: 'datefield',
        fieldLabel: 'Event Date',
        allowBlank: false,
        width: 120,
        id: 'eventDate',
        format: 'd/M/Y',
        selectOnFocus: true,
        listeners: {
            'focus': function(){
                Ext.getCmp('help-box-ed').show();
            },
            'blur': function(){
                // Ext.getCmp('help-box-ed').hide();
            }
        }
    
    },  {
        xtype: 'box',
     
        hidden: true,
        cls: 'help-box',
        id: 'help-box-ed',
        autoEl: {
            html: '<b>Help tip:</b> This is the actual date of the event. It must be a date in the future from today.'
        }
    }, {
        xtype: 'box',
     
        hidden: true,
        cls: 'help-box',
        id: 'help-box-noword',
        autoEl: {
            html: '<b>Help tip:</b> <b>PLEASE DO NOT PASTE TEXT FROM ANY EXTERNAL APPLICAITONS SUCH AS MICROSOFT WORD - IT WILL NOT WORK </b>'   }
    }, {
        xtype: 'htmleditor',
        height: 400,
         anchor: '100%', 
        fieldLabel: 'Event Profile',
        id: 'profile',
        allowBlank: true,
        autoScroll: true,
        enableFont: true,
        enableFormat: true,
        enableFontSize: true,
        enableLinks: true,
        enableColors: true,
        enableAlignments: true,
        enableSourceEdit: true,
        enableLists: true,
        plugins: new Ext.HtmlImage,
        listeners: {
            'activate': function(){
                Ext.getCmp('help-box-ep').show();
            },
            'blur': function(){
                // Ext.getCmp('help-box-ep').hide();
            }
        }
    }, {
        xtype: 'box',
        hidden: true,
      
        cls: 'help-box',
        id: 'help-box-ep',
        autoEl: {
            html: '<b>Help tip:</b> This can include information such as terrain, number of water stations, start time, discipline distances etc'
        }
    }, {
    
        xtype: 'box',
        id: 'accept-online-bookings',
        hidden: true,
        closeble: true,
        cls: 'help-box2',
        autoEl: {
            html: 'To manage your participants and accept payments online with no fuss, all you need to do is click the checkbox below and complete the entry fees form!'
        }
    }, {
        xtype: 'htmleditor',
        
        anchor: '100%', 
        id: 'entryInformation',
        height: 400,
        fieldLabel: 'Entry Information',
       allowBlank: true,
        autoScroll: true,
        enableFont: true,
        enableFormat: true,
        enableFontSize: true,
        enableLinks: true,
        enableColors: true,
        enableAlignments: true,
        enableSourceEdit: true,
        enableLists: true,
     plugins: new Ext.HtmlImage
    
    }, {
        xtype: 'box',
        cls: 'help-box',
       
        id: 'help-box-ei',
        autoEl: {
            html: '<b>Help Tip:</b> This box should include the information that you want to be seen by the competitors, such as race fees, age categories, prizes and closing dates.'
        }
    }, {
        xtype: 'htmleditor',
        height: 400,
         anchor: '100%', 
        fieldLabel: 'Race Day Registration Information',
        id: 'registrationInformation',
        allowBlank: true,
        autoScroll: true,
        enableFont: true,
        enableFormat: true,
        enableFontSize: true,
        enableLinks: true,
        enableColors: true,
        enableAlignments: true,
        enableSourceEdit: true,
        enableLists: true,
         plugins: new Ext.HtmlImage,
        listeners: {
            'activate': function(){
                Ext.getCmp('help-box-ri').show();
            },
            'blur': function(){
                Ext.getCmp('help-box-ri').hide();
            }
        }
    }, {
        xtype: 'box',
        cls: 'help-box',
        hidden: true,
   
        id: 'help-box-ri',
        autoEl: {
            html: '<b>Help Tip:</b> This can include information such as start time of registration, registration process and registration closing time.'
        }
    }, {
        xtype: 'htmleditor',
        id: 'locationInformation',
        anchor: '100%', 
    height: 400,
        fieldLabel: 'Location Information',
        allowBlank: true,
        autoScroll: true,
        enableFont: true,
        enableFormat: true,
        enableFontSize: true,
        enableLinks: true,
        enableColors: true,
        enableAlignments: true,
        enableSourceEdit: true,
        enableLists: true,
         plugins: new Ext.HtmlImage,
        listeners: {
            'activate': function(){
                Ext.getCmp('help-box-li').show();
            },
            'blur': function(){
                Ext.getCmp('help-box-li').hide();
            }
        }
    }, {
        xtype: 'box',
    
        hidden: true,
        cls: 'help-box',
        id: 'help-box-li',
        autoEl: {
            html: '<b>Help Tip:</b> This can include information such as directions to the event, notable landmarks or turning points.'
        }
    }, {
        xtype: 'htmleditor',
        anchor: '100%', 
        id: 'registrationMessage',
        height: 200,
        fieldLabel: 'Registration Message',
       allowBlank: true,
        autoScroll: true,
        enableFont: true,
        enableFormat: true,
        enableFontSize: true,
        enableLinks: true,
        enableColors: true,
        enableAlignments: true,
        enableSourceEdit: true,
        enableLists: true,
        listeners: {
            'activate': function(){
                Ext.getCmp('help-box-rm').show();
            },
            'blur': function(){
                Ext.getCmp('help-box-rm').hide();
            }
        }
    }, {
        xtype: 'box',
      
        hidden: true,
        cls: 'help-box',
        id: 'help-box-rm',
        autoEl: {
            html: '<b>Help Tip:</b>This message is only included at the point of participant registration. It might include special notices about additional terms and conditions such as the donation of the entry fee to charity and/or the reclaiming of tax for UK residents'
        }
    },   {
        xtype: 'box',
        hidden: true,
        cls: 'help-box2',
        id: 'help-box-online',
        autoEl: {
            html: '<b>Help tip:</b>If you want to take online entries through the Full On Sport website, then please check the box below and follow instructions.'
        }
    }, {
        xtype: 'fieldset',
        title: ' Accept entries through Full On Sport Ltd',
        checkboxToggle: true,
        collapsed: true,
        border: false,
        hidden: true,
    	frame: false,
        collapsible: false,
        id: 'acceptOnlineBookings',
        cls: 'ls',
        listeners: {
    		'click' : function () {
    			FOS.Organiser.Event.showBookingGrids(true);
    		}
    	},
    	 
        items: [ {
            xtype: 'textfield',
            id: 'maxNoParticipants',
            fieldLabel: 'Enter the maximum number of participants the event can support'
        }, {
            xtype: 'checkbox',
            id: 'requireEstimateSwimTime',
            boxLabel: 'Check this to prompt participant for estimate swim time during registration process.'
        }, {
            xtype: 'checkbox',
            id: 'requireEstimateBikeTime',
            boxLabel: 'Check this to prompt participant for estimate bike time during registration process.'
        }, {
            xtype: 'checkbox',
            id: 'requireEstimateRunTime1',
            boxLabel: 'Check this to prompt participant for estimate of first run split of a duathlon during registration process.'
        }, {
            xtype: 'checkbox',
            id: 'requireEstimateRunTime',
            boxLabel: 'Check this to prompt participant for estimate run time (second split of duathlon) during registration process.<br /><br />'
        }, {
            xtype: 'box',
            autoEl: {
                html: '<br />'
            }
        },  {
            xtype: 'box',
            hidden: false,
            cls: 'help-box2',
            id: 'help-box-entry',
            autoEl: {
                html: '<b>Help tip:</b>Please specify the entry types that are available for this race i.e.  BTF Affiliated Entry or Non BTF Affilated Entry which might be more expensive <br><br>'
            }
        }, FOS.Organiser.Event.entryGridViewConfig, {
            xtype: 'box',
            width: '100%',
            hidden: false,
            cls: 'help-box2',
            id: 'help-box-merchandise',
            autoEl: {
                html: '<b>Help tip:</b> Please specify any merchandise that might be available to purchase example Large T-Shirt, Medium T-Shirt '
            }
        },FOS.Organiser.Event.merchandiseGridViewConfig  /*, FOS.Organiser.Event.rentalGridViewConfig  , {
            xtype: 'box',
             
            hidden: false,
            cls: 'help-box2',
            id: 'help-box-travel',
            autoEl: {
                html: '<b>Help tip:</b> Please specify all products that are available for rent during event regsitration.'
            }
        }, FOS.Organiser.Event.travelGridViewConfig */ ,  {
            xtype: 'box',
        
            hidden: false,
            cls: 'help-box2',
            id: 'help-box-questions',
            autoEl: {
                html: '<b>Help tip:</b> Please specify any questions that you need to ask a participant before the race. i.e. you may need to collect medical information or might want to know how many years an athlete has been racing for? You can see the snwers to these questions via the Answers report from the organiser tools page.'
            }
        }, FOS.Organiser.Event.questionGridViewConfig]
    },{
        xtype: 'box',
     
        cls: 'help-box',
        id: 'help-box-li3',
        autoEl: {
            html: '<b>Help Tip: </b> Once you have completed all the details and are sure they are correct, check the \'publish this event\' box below. The event will remain hidden until this box is checked and you click the save button.  You can edit the event later and keep it hidden until you are satisfied all the information is correct. <br><br> Once you have completed the event details form click the save button below'
        }
    },  {
        xtype: 'checkbox',
        boxLabel: 'Check to publish this event on the Full On Sport event list.',
        
        style: 'font-weight:bold; font-size: 16px;',
        id: 'eventHidden',
        checked: false
    
    },{
    
        xtype: 'box',
        overCls: 'mp',
        id: 'save-event',
        autoEl: {
            style: 'margin: 5px',
            tag: 'img',
            src: 'images/tools/save.gif'
        
        },
        listeners: {
            'render': function(b){
            
                Ext.get('save-event').on('click', function(){
                
                    if (Ext.getCmp('eventDetail').getForm().isValid() == false) {
                        Ext.MessageBox.alert('Full On Sport', 'You have not completed filling out the form. See highlighted fields for details.');
                        return false;
                        
                    }
                    
                    FOS.Organiser.Event.save();
                    
                    
                });
                
            }
            
            
        }
    }, {
    
        xtype: 'box',
        overCls: 'mp',
        hidden: true,
        id: 'destroy-event',
        autoEl: {
            style: 'margin: 5px',
            tag: 'img',
            src: 'images/tools/delete.gif'
        
        },
        listeners: {
            'render': function(b){
            
                Ext.get('destroy-event').on('click', function(){
                    FOS.Organiser.Event.destroy();
                    
                    
                });
                
            }
            
            
        }
    }],
    listeners: {
        beforedestroy: function(f){
        
        
            /*
			 * Ext.Msg.show({
			 * 
			 * title: 'Save Changes?',
			 * 
			 * msg: 'You are closing a tab that has unsaved changes. Would you
			 * like to save your changes?',
			 * 
			 * buttons: Ext.Msg.YESNO,
			 * 
			 * fn: function(btn){
			 * 
			 * if (btn = Ext.Msg.YES)
			 * 
			 * FOS.Organiser.Event.save();
			 *  },
			 * 
			 * animEl: 'elId',
			 * 
			 * icon: Ext.MessageBox.QUESTION
			 * 
			 * });
			 */
            
        }
        
    }

};





FOS.Organiser.Event.ageCategoryStore = new Ext.data.JsonStore({
    url: 'data.php',
    baseParams: {
        set: 'age_category'
    
    },
    root: 'data',
    fields: [{
        name: 'age_category_id'
    }, {
        name: 'age_category_description'
    }]
});

function hasClass(ele,cls) {
	return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}
 
function addClass(ele,cls) {
	if (!this.hasClass(ele,cls)) ele.className += " "+cls;
}
 
function removeClass(ele,cls) {
	if (hasClass(ele,cls)) {
    	var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
		ele.className=ele.className.replace(reg,' ');
	}
}

FOS.Organiser.Event.load = function(eid){

	try {
	     
	    
	        
	        
	       
	    
	    
	    if (eid != null) {
	    	FOS.Organiser.Event.mode = 'read';
	        //Ext.getCmp('acceptOnlineBookings').setVisible( true) ;
	        Ext.getCmp('help-box-online').setVisible( true) ;
	        document.getElementById("acceptOnlineBookings").visible = true;
	       
	        document.getElementById("acceptOnlineBookings").style.cssText = "width: 918px;";
	        
	        removeClass(document.getElementById("acceptOnlineBookings"), "x-hide-display");
	        
	        Ext.getCmp('destroy-event').show();
	        Ext.getCmp('acceptOnlineBookings').show() ; 
	        FOS.Organiser.Event.eventId = eid;
	        
	    }
	    else
	    {
	    	  
	           
	    }
	    
	    Ext.get('eventPanel').mask('Loading profile. Please wait...', 'x-mask-loading');
	    
	    
	    
	    Ext.Ajax.request({
	        url: 'action.php',
	        method: 'POST',
	        
	        params: {
	            module: 'event',
	            action: 'read',
	            eventId: eid
	        },
	        failure: function(response, options){
	            Ext.Msg.alert('Failed', response.status);
	            Ext.get('eventPanel').unmask();
	        },
	        success: function(response, options){
	            var result = Ext.decode(response.responseText);
	            
	            if (result.success == true) {
	            	FOS.Organiser.Event.mode = 'update';
	                FOS.Organiser.Event.isSaved = true;
	                FOS.Organiser.Event.displayFormData(result.data);
	                
	                
	                
	            }
	            
	            else {
	             var result = Ext.decode(response.responseText);
	                Ext.Msg.alert('Failed: ' + result.errorMsg);
	            }
	            Ext.get('eventPanel').unmask();
	        }
	    });
	    
	}
	catch (e) {
		
	}
    
	document.getElementById("acceptOnlineBookings").className.replace('x-hide-display','');
    
};

 


FOS.Organiser.Event.createView = function(){

	try {
		FOS.Organiser.Event.isSaved = false;
		FOS.Organiser.Event.isStandAlone = false;
    
    if (FOS.Organiser.Event.view) {
        FOS.Organiser.Event.view.destroy();
        FOS.Organiser.Event.view = null;
    }
      FOS.Organiser.Event.view = new Ext.FormPanel(FOS.Organiser.Event.viewConfig);
      
      
    
    Ext.getCmp('runDistance').getEl().up('.x-form-item').setDisplayed(false);
    Ext.getCmp('runDistance1').getEl().up('.x-form-item').setDisplayed(false);
    Ext.getCmp('swimDistance').getEl().up('.x-form-item').setDisplayed(false);
    Ext.getCmp('bikeDistance').getEl().up('.x-form-item').setDisplayed(false);
    
	}
	 catch (e) { 
		 Ext.MessageBox.alert('Failed', 'An exception occurred in the script. Error name: ' + e.name + ' Error message: ' + e.message) ;
	 }
};



FOS.Organiser.Event.save = function(){

    if (FOS.Organiser.Event.isSaved == false) 
        FOS.Organiser.Event.create();
    else 
        FOS.Organiser.Event.update();
};

FOS.Organiser.Event.update = function(){

    Ext.get('eventPanel').mask('Saving event data. Please wait...', 'x-mask-loading');
    
    Ext.Ajax.request({
        url: 'action.php',
        method: 'POST',
        waitMsg: 'Saving. Pleas wait...',
        params: {
            module: 'event',
            action: 'update',
            eventId: FOS.Organiser.Event.eventId,
            eventName: Ext.getCmp('eventName').getValue(),
            eventHidden: Ext.getCmp('eventHidden').getValue() == true ? 0 : 1,
            
            typeId: Ext.getCmp('typeId').getValue(),
            subTypeId: Ext.getCmp('subTypeId').getValue(),
            ageCategoryId: Ext.getCmp('ageCategoryId').getValue(),
            runDistance1: Ext.getCmp('runDistance1').getValue(),
            runDistance: Ext.getCmp('runDistance').getValue(),
            swimDistance: Ext.getCmp('swimDistance').getValue(),
            bikeDistance: Ext.getCmp('bikeDistance').getValue(),
            
            
            organiserId: Ext.getCmp('organiserId').getValue(),
            eventDate: Ext.getCmp('eventDate').getValue(),
            profile: Ext.getCmp('profile').getValue(),
            locationInformation: Ext.getCmp('locationInformation').getValue(),
            entryInformation: Ext.getCmp('entryInformation').getValue(),
            registrationInformation:  Ext.getCmp('registrationInformation').getValue(),
            registrationMessage: Ext.getCmp('registrationMessage').getValue(),
            
            /* types of payments */
            acceptOnlineBookings: Ext.getCmp('acceptOnlineBookings').collapsed == false ? 1 : 0,
             
            maxNoParticipants: Ext.getCmp('maxNoParticipants').getValue(),
            requireEstimateSwimTime: Ext.getCmp('requireEstimateSwimTime').getValue() == true ? 1 : 0,
            requireEstimateBikeTime: Ext.getCmp('requireEstimateBikeTime').getValue() == true ? 1 : 0,
            requireEstimateRunTime: Ext.getCmp('requireEstimateRunTime').getValue() == true ? 1 : 0,
            requireEstimateRunTime1: Ext.getCmp('requireEstimateRunTime1').getValue() == true ? 1 : 0
             
         
        
        
        },
        success: function(response, options){
            var result = Ext.decode(response.responseText);
            
            if (result.success == true) {
            	
                Ext.Msg.show({
	            	   title:'Save complete',
	            	   msg: 'Changes saved successfully. Would you like to view the changes now?',
	            	   buttons: Ext.Msg.YESNO,
	            	   fn: function (btn) {
	            			if (btn == 'yes'){
	            				 location.href = '?module=events&action=profile&eventId=' + FOS.Organiser.Event.eventId;
	            	             
	            			}
	            			 
	            		},
	            		animEl: 'elId',
	            	   icon: Ext.MessageBox.QUESTION
	            	});
             
               
                
            }
            
            else 
                Ext.Msg.alert('Failed', response.errorMsg);
            
            Ext.get('eventPanel').unmask();
            
        },
        failure: function(response, options){
            Ext.Msg.alert('Failed', response.status);
            Ext.get('eventPanel').unmask();
        }
        
    });
    
};

FOS.Organiser.Event.create = function(){
   Ext.Ajax.request({
        url: 'action.php',
        method: 'POST',
        waitMsg: 'Saving. Pleas wait...',
        params: {
            module: 'event',
            action: 'createAndSave',
            
            eventName: Ext.getCmp('eventName').getValue(),
            eventHidden: Ext.getCmp('eventHidden').getValue() == true ? 0 : 1,
            
            typeId: Ext.getCmp('typeId').getValue(),
            subTypeId: Ext.getCmp('subTypeId').getValue(),
            ageCategoryId: Ext.getCmp('ageCategoryId').getValue(),
            runDistance1: Ext.getCmp('runDistance1').getValue(),
            runDistance: Ext.getCmp('runDistance').getValue(),
            swimDistance: Ext.getCmp('swimDistance').getValue(),
            bikeDistance: Ext.getCmp('bikeDistance').getValue(),
            
            
            organiserId: Ext.getCmp('organiserId').getValue(),
            eventDate: Ext.getCmp('eventDate').getValue(),
            profile: Ext.getCmp('profile').getValue(),
            locationInformation: Ext.getCmp('locationInformation').getValue(),
            entryInformation: Ext.getCmp('entryInformation').getValue(),
            registrationInformation: Ext.getCmp('registrationInformation').getValue(),
            registrationMessage: Ext.getCmp('registrationMessage').getValue(),
            
            /* types of payments */
            acceptOnlineBookings: Ext.getCmp('acceptOnlineBookings').collapsed == false ? 1 : 0,
            maxNoParticipants: Ext.getCmp('maxNoParticipants').getValue(),
            requireEstimateSwimTime: Ext.getCmp('requireEstimateSwimTime').getValue() == true ? 1 : 0,
            requireEstimateBikeTime: Ext.getCmp('requireEstimateBikeTime').getValue() == true ? 1 : 0,
            requireEstimateRunTime: Ext.getCmp('requireEstimateRunTime').getValue() == true ? 1 : 0,
            requireEstimateRunTime1: Ext.getCmp('requireEstimateRunTime1').getValue() == true ? 1 : 0
        
        
        },
        success: function(response, options){
            var result = Ext.decode(response.responseText);
            
            if (result.success == true) {
            	
            	FOS.Organiser.Event.eventId = result.event_id;
            	
            	if ( FOS.Organiser.Event.isSaved == false ) {
	            	// Show a dialog using config options:
	            	Ext.Msg.show({
	            	   title:'Save complete',
	            	   msg: 'This event has been saved to the database. Would you like to take online entries for this event via the FullOnSport website?',
	            	   buttons: Ext.Msg.YESNO,
	            	   fn: function (btn) {
	            			if (btn == 'yes'){
	            				/* types of payments */
	            	            
	            	            Ext.getCmp('acceptOnlineBookings').show() ; 
	            	             Ext.getCmp('acceptOnlineBookings').expand();
	            	             
	            			}
	            			
	            			else {
	            				if (FOS.Organiser.Event.isPartOfRegistrationProcess == true) 
	                                location.href = 'index.php?module=event&action=complete';
	                            
	                            //FOS.Organiser.Event.toggleMenu();
	                            //FOS.Organiser.refresh();
	            			}
	            		},
	            		animEl: 'elId',
	            	   icon: Ext.MessageBox.QUESTION
	            	});
                
            	}
            	
            	//mark this event as saved
            	FOS.Organiser.Event.isSaved = true;
                
            }
            
            else 
                Ext.Msg.alert('Failed', response.errorMsg);
            
            Ext.get('eventPanel').unmask();
            
        },
        failure: function(response, options){
            Ext.Msg.alert('Failed', response.status);
            Ext.get('eventPanel').unmask();
        }
        
    });
    
};



FOS.Organiser.Event.createx = function(){

    Ext.get('eventPanel').mask('Loading profile. Please wait...', 'x-mask-loading');
    
    Ext.Ajax.request({
        url: 'action.php',
        method: 'POST',
        waitMsg: 'Saving. Pleas wait...',
        params: {
            module: 'event',
            action: 'create'
        
        
        },
        success: function(response, options){
            var result = Ext.decode(response.responseText);
            
            if (result.success == true) {
                   FOS.Organiser.refresh();
            }
            
            else 
                Ext.Msg.alert('Failed', response.errorMsg);
            
            Ext.get('eventPanel').unmask();
            
        },
        failure: function(response, options){
            Ext.Msg.alert('Failed', response.status);
            Ext.get('eventPanel').unmask();
        }
        
    });
};

FOS.Organiser.Event.destroy = function(){

    Ext.Ajax.request({
        url: 'action.php',
        method: 'POST',
        waitMsg: 'Saving. Pleas wait...',
        params: {
            module: 'event',
            action: 'destroy',
            eventId: FOS.Organiser.Event.eventId
        
        },
        success: function(response, options){
            var result = Ext.decode(response.responseText);
            
            Ext.get('eventPanel').unmask();
            
            if (result.success == true) {
                Ext.Msg.alert('Full On Sport', 'Event deleted successfully');
                Ext.getCmp(ORGANISER_MAIN_TAB).removeAll(true);
                FOS.Organiser.Event.view = null;
                FOS.Organiser.refresh(false);
                FOS.Organiser.showDefaultView();
                
            }
            
            else 
                Ext.Msg.alert('Failed', response.errorMsg);
            
            
            
        },
        failure: function(response, options){
            Ext.Msg.alert('Failed', response.status);
            Ext.get('eventPanel').unmask();
        }
        
    });
};



FOS.Organiser.Event.show = function(eid ){
    //FOS.Organiser.Event.ageCategoryStore.load();
    FOS.Organiser.Event.store.load();
    FOS.Organiser.Event.orgnaniserStore.load();
    FOS.Organiser.Event.typeStore.load();
    FOS.Organiser.Event.subTypeStore.load();
    
    FOS.Organiser.Event.createView();
    
    if (eid != null) {
    	
    	
    	FOS.Organiser.Event.entryStore.load({params: {eventId : eid,  uniqueGroupId : 1}});
    	FOS.Organiser.Event.merchandiseStore.load({params: {eventId : eid,  uniqueGroupId : 0}});
    	FOS.Organiser.Event.travelStore.load({params: {eventId : eid,  uniqueGroupId : 2}});
    	FOS.Organiser.Event.rentalStore.load({params: {eventId : eid,  uniqueGroupId : 4}});
    	FOS.Organiser.Event.questionStore.load({params: {eventId : eid}});
    	 FOS.Organiser.Event.load(eid);
    }
     
    
    
   
    
};


FOS.Organiser.Event.displayFormData = function(data){




    // try {
    FOS.Organiser.viewingEventId = data[0].event_id;
    
    Ext.getCmp('eventName').setValue(data[0].name);
    Ext.getCmp('eventHidden').setValue(data[0].hidden == 1 ? false : true);
    
    Ext.getCmp('typeId').setValue(data[0].type_id, true);
    Ext.getCmp('subTypeId').setValue(data[0].sub_type_id, true);
    Ext.getCmp('ageCategoryId').setValue(data[0].age_category_id, true);
    
    
    Ext.getCmp('runDistance1').setValue(data[0].run_distance_1);
    Ext.getCmp('runDistance').setValue(data[0].run_distance);
    Ext.getCmp('swimDistance').setValue(data[0].swim_distance);
    Ext.getCmp('bikeDistance').setValue(data[0].bike_distance);
    
    
    // types of payments
    if (data[0].accept_online_bookings == 1) {
        Ext.getCmp('acceptOnlineBookings').expand();
        //FOS.Organiser.Event./BookingGrids(true);
    }
    
    else {
        Ext.getCmp('acceptOnlineBookings').collapse();
       // FOS.Organiser.Event.showBookingGrids(false);
    }
    
    Ext.getCmp('maxNoParticipants').setValue(data[0].max_no_participants);
    
    
    
    Ext.getCmp('requireEstimateSwimTime').setValue(data[0].require_estimate_swim_time == 1 ? true : false);
    Ext.getCmp('requireEstimateBikeTime').setValue(data[0].require_estimate_bike_time == 1 ? true : false);
    Ext.getCmp('requireEstimateRunTime').setValue(data[0].require_estimate_run_time == 1 ? true : false);
    Ext.getCmp('requireEstimateRunTime1').setValue(data[0].require_estimate_run_time_1 == 1 ? true : false);
   
    
    
    
    
    Ext.getCmp('organiserId').setValue(data[0].organiser_id, true);
    Ext.getCmp('profile').setValue( data[0].profile );
    
    var s = "";
    
    s = data[0].event_date;
    
    Ext.getCmp('eventDate').setValue(s.substring(0,10));
    
    Ext.getCmp('locationInformation').setValue( data[0].location_information );
    Ext.getCmp('entryInformation').setValue( data[0].entry_information );
    Ext.getCmp('registrationInformation').setValue( data[0].registration_information );
    Ext.getCmp('registrationMessage').setValue( data[0].registration_message );
    
    
    
    
    FOS.Organiser.Event.toggleDistances(data[0].type_id);
    
    /*
	 * } catch (e) { Ext.MessageBox.alert('Failed', "An exception occurred in
	 * the script. Error name: " + e.name + ". Error message: " + e.message) }
	 */
};
FOS.Organiser.Event.edit = function(eid){
 FOS.Organiser.Event.show(eid);
    
    
};

FOS.Organiser.Event.toggleDistances = function(typeId){

    switch (typeId) {
        case 'TRI':
            Ext.getCmp('swimDistance').show();
            Ext.getCmp('swimDistance').getEl().up('.x-form-item').setDisplayed(true);
            
            Ext.getCmp('bikeDistance').show();
            Ext.getCmp('bikeDistance').getEl().up('.x-form-item').setDisplayed(true);
            
            Ext.getCmp('runDistance').show();
            Ext.getCmp('runDistance').getEl().up('.x-form-item').setDisplayed(true);
            
            Ext.getCmp('runDistance1').hide();
            Ext.getCmp('runDistance1').getEl().up('.x-form-item').setDisplayed(false);
            break;
            
        case 'DUA':
            Ext.getCmp('swimDistance').hide();
            Ext.getCmp('swimDistance').getEl().up('.x-form-item').setDisplayed(false);
            
            Ext.getCmp('bikeDistance').show();
            Ext.getCmp('bikeDistance').getEl().up('.x-form-item').setDisplayed(true);
            
            Ext.getCmp('runDistance').show();
            Ext.getCmp('runDistance').getEl().up('.x-form-item').setDisplayed(true);
            
            Ext.getCmp('runDistance1').show();
            Ext.getCmp('runDistance1').getEl().up('.x-form-item').setDisplayed(true);
            break;
            
        case 'RUN':
            Ext.getCmp('swimDistance').hide();
            Ext.getCmp('swimDistance').getEl().up('.x-form-item').setDisplayed(false);
            
            Ext.getCmp('bikeDistance').hide();
            Ext.getCmp('bikeDistance').getEl().up('.x-form-item').setDisplayed(false);
            
            Ext.getCmp('runDistance').show();
            Ext.getCmp('runDistance').getEl().up('.x-form-item').setDisplayed(true);
            
            Ext.getCmp('runDistance1').hide();
            Ext.getCmp('runDistance1').getEl().up('.x-form-item').setDisplayed(false);
            break;
            
        case 'CYC':
            Ext.getCmp('swimDistance').hide();
            Ext.getCmp('swimDistance').getEl().up('.x-form-item').setDisplayed(false);
            
            Ext.getCmp('bikeDistance').show();
            Ext.getCmp('bikeDistance').getEl().up('.x-form-item').setDisplayed(true);
            
            Ext.getCmp('runDistance').hide();
            Ext.getCmp('runDistance').getEl().up('.x-form-item').setDisplayed(false);
            
            Ext.getCmp('runDistance1').hide();
            Ext.getCmp('runDistance1').getEl().up('.x-form-item').setDisplayed(false);
            break;
            
    }
    
    
};

