Ext.BLANK_IMAGE_URL = 'extjs/resources/images/default/s.gif';

Ext.namespace('SYST');

Ext.onReady(function() {

  	Ext.QuickTips.init();

	SYST.showErreur = function(text){
		
		Ext.Msg.show({
		   title:'Error during process',
		   msg: text,
		   buttons: Ext.Msg.OK,
		   icon: Ext.MessageBox.ERROR
		});
	};

	/* *********************************************************** 
						FUNCTION SUBMIT
	*********************************************************** */


	function fct_submit(){

		var sb = Ext.getCmp('form-statusbar');    
		sb.showBusy('connexion ...'); 
		login.getEl().mask();   
	
		if(login.getForm().isValid()) { 
			login.getForm().submit({
								   
				url:'ajax/session-connect.php',
				method: 'POST',
				params: { 
					redirect: '<?php echo $urlFinal."index.php" ?>', 
					userType: "user"
				},
				
				success: function(form, action){			
					var objSuc = Ext.util.JSON.decode(action.response.responseText);	
					var messageSuc = objSuc.msgSUC.msg;  
					sb.setStatus({
						text: messageSuc,	
						iconCls:'',
						clear: true	
					});
					window.location="users/epic.php";
				},
				
				failure:function(form, action){
					var obj = Ext.util.JSON.decode(action.response.responseText);
					var message = obj.errors.msg;    	
					sb.setStatus({   
						text:'Error : '+ message,
						iconCls:'',
						clear: true
					});
				}			   						   
			});						  
		}//End if
	
		else{
			sb.setStatus({
				text:'Error : Invalid form.',	
				iconCls:'',
				clear: true
			});
		}

	login.getEl().unmask();
	
	}//End function

	/* *********************************************************** 
						LOGIN FORM
	*********************************************************** */


	var login = new Ext.FormPanel({

		id: 'login',                
		frame: false,                
		width: 275,
		height:100,
		labelWidth: 80,           
		labelAlign: 'left',		
		border:false,

		items: [{        
			xtype: 'textfield',          
			fieldLabel: 'Email',         
			id: 'email',		
			width: 140,
			name: 'email',	
			vtype: 'email',    
			vtypeText: 'The from field should be an email address in the format of user@domain.com',	
			allowBlank: false,                
			blankText:"Please insert your email address."
		},{
			xtype: 'textfield',		
			fieldLabel: 'Password',		
			id: 'pass',
			name: 'pass',
			width: 140,
			allowBlank: false,
			inputType: 'password',
			blankText:"Please insert your password"
		
		},{
			xtype: 'button',
			id: 'buttonLoggin',
			text: 'Login',	
			handler: fct_submit ,
			style:{'position':'relative', 'top':'10px', 'left':'0px'}
		
		},{
			xtype: 'hidden',
			id: 'connexion',	
			name: 'connexion'
		}]
	});
	
	
	var login_message = new Ext.Panel({
    width: 200,
    border:false,
	height:30,
    layout: 'fit',
    items: new Ext.StatusBar({
        id: 'form-statusbar',
		height:30,
		defaultText:"<a href='registration.php'>Create new account</a>",
        plugins: new Ext.ux.ValidationStatus({form:'login'}),
		style:{'background-image':'none', 'background-color':'#FFFFFF', 'color':'#CC0000', 'font-weight':'700', 'border':'none'}
    	}),
	renderTo: 'loginMessage'
	});

	login.render('logWindow');
	
	new Ext.KeyNav("email", {
		"enter" : fct_submit
	});
	
	new Ext.KeyNav("pass", {
		"enter" : fct_submit
	});
		
	/* *********************************************************** 
						USER-PIBLIC TASKS GRID
	*********************************************************** */

	tasksRecordObj = Ext.data.Record.create([
				{name:'taskId', type: 'int'}, 
				{name:'taskName', type:'string'},
				{name:'moduleName', type:'string'},
				{name:'addDate', type: 'date', dateFormat: 'Y-m-d'},
				{name:'status', type:'string'},
				{name:'imposed', type:'bool'},
				{name:'totalVote', type:'int'},
				{name:'description', type:'int'}
	]);
	
	/* *********************************************************** 
						USER-PUBLIC TASKS GRID
	*********************************************************** */
	 
	 
 	var tasksGridStore = new Ext.data.JsonStore({ 
		autoLoad: true,
		url:"ajax/user-public-grid-task.php",
		baseParams:{task: "readTask"},
		root:"rows",
      	id: "id",
      	totalProperty: "count",
      	fields: tasksRecordObj
	});
  
/* tasksGridStore.setDefaultSort("taskId", "ASC"); */

	var tasksGridCM = new Ext.grid.ColumnModel([
		{
           header:"Task #",
		   id:'taskId',
           dataIndex: 'taskId',
		   align:'center',
		   sortable:true,
		   width:50
        },{
			id:'taskName',
			header:"Tasks name",
			dataIndex:'taskName',
			sortable:true,
			width:150	
		},{
           header: "Module Name",
           dataIndex: 'moduleName',
		   sortable:true,
           width: 140
        },{
			header: "Date added",
			sortable:true,
			width: 70,
			renderer: Ext.util.Format.dateRenderer('d/m/Y'),
			dataIndex: 'addDate'
		},{
			header: "Status",
			sortable:true,
			width: 50,
			dataIndex: 'status',
			align:'center'
		},{	
			header: "Imposed",
       		dataIndex: 'imposed',
       		width: 60,
			align:'center'				,
      hidden: true
		},{
			header:	"Votes",
			sortable:true,
			align:'center',
			width: 50,
			dataIndex: 'totalVote',
			renderer: function(data){return '<b>'+data+'</b>';}
        },{
			header:	"Description",
			align:'center',
			width: 70,
			dataIndex: 'description',
			renderer: function(data){return '<a href="#" onclick="SYST.showDescription()"><img src="img-logo/user-public/IconMini-taskInfo.png" /></a>';}
        }]);
	
	
	
	var taskgridView = new Ext.grid.GridView({ 
		getRowClass : function (row, index) { 
		  var cls = ''; 
		  var data = row.data; 
		  switch (data.status) { 
			 case 'closed' : 
				cls = 'closedRow';
				break;
			case 'current' : 
				cls = 'curentRow';
				break; 
		  }
		  if(data.imposed === true){
			cls = 'imposedRow';  
		  }
		  return cls; 
	   } 
	});

	
	var tasksGrid = new Ext.grid.GridPanel({
            autoExpandColumn: 'taskName',        
            store: tasksGridStore,
			colModel: tasksGridCM,
			id: 'tasksGrid',
			autoHeight:true,
			autoWidth:true,
			enableColumnResize: true,
			border:true,
			frame:true,
			loadMask: true,
			stripeRows: true,
			view: taskgridView
        });
	
	
	tasksGrid.getView().scrollOffset = 1;//To get rid of the reserved space for the scroll bar
	
	tasksGrid.render('userPublicGrid');
	
	/* IE6 problem: If the width is no set, it expend twice is normal width */
	
	if(Ext.isIE6 === true) {
    	tasksGrid.setWidth(850);
  	}
	
	
	/* ****************************** POP-UP WINDOW FOR TASK INFORMATION *********************** */
	
	/* ****************************************************************************************** 
		FUNCTIONS
		SYST.showDescription->Give description about a specific task.
			
			
		
	******************************************************************************************** */

	SYST.showDescription = function(){
		 
		var selectedKeys = tasksGrid.selModel.selections.keys; 
		if(selectedKeys.length > 0)
		{
			var selectedRow = tasksGrid.getSelectionModel().getSelected();
			var selectedId = selectedRow.data.taskId;
			
			taskInfoStore.load({
				params: { 
				task: "readDescription", 
				taskId: selectedId
				},
				callback: function(options, success, response){
					var values = Ext.util.JSON.decode(response.responseText);
					InfoWin.show();
				},
				failure: function(response, options){
					var responses = Ext.util.JSON.decode(response.responseText);
					SYST.showERROR(responses.errors.msg);
				}
				
			});
		}
		else
		{
			Ext.MessageBox.alert('Message','Please select one task');
		}//end if/else block
				
	};
		
	var taskInfoStore = new Ext.data.JsonStore({ 
		url:"ajax/user-public-grid-task.php",
		root:"row",
      	id: "description",
      	fields: [{name: 'taskId', type: 'int'},
				 {name: 'taskName', type: 'string'},
				 {name: 'description', type: 'string'},
				 {name: 'objectif', type: 'string'},
				 {name: 'resume', type: 'string'}]
	});
	
	var taskInfoTpl = new Ext.XTemplate(								  
			'<tpl for=".">',
					'<div class="taskIdDesc"><b>Task Id: </b> {taskId}</div><br/>',
					'<div class="taskNameDesc"><b>Task name: </b> {taskName}</div><br/>',
					'<div class="descTitle">Description:<br/><div>{description}</div></div><br/>',
					'<div class="objeTitle">Goal:<br/><div>{objectif}</div></div><br/>',
					'<div class="resuTitle">Summary:<br/><div>{resume}</div></div><br/>',
			'</tpl>');
	
	var taskInfoDataStore = new Ext.DataView({
			id:"informationWindows",
			store: taskInfoStore,
			itemSelector:'div',
			height:325,
			width:600,
			autoWidth:true,
			tpl: taskInfoTpl	
	});

	var InfoWin = new Ext.Window({
		applyTo:'hiddenWin',
		title: 'Task description',
		bodyStyle:{'padding': '10px'},
		width: 650,
		resizable:false,
		iconCls: 'icon-infoWin',
		height: 400,
		closeAction :'hide',
		items: [taskInfoDataStore],
		plain: false,
		buttonAlign: "center",
		buttons: [{
			text: 'OK',
			handler:  function(){InfoWin.hide();}
				}]
	});
	
});
