/** Tout droits réservés.
 * @author hti@sirtem.fr
 */

var paiement_cb = false;

/** Derivee de dyntable, liste des adhesions */
function AdhesionsTab ( dom_table  )
{
	this.parent = DynTable;
   	this.parent( dom_table );
	this.doAddRowFromEvent 	= function( event ) {};
	this.TRTextToEdit 		= function( tr ) 	{};
	this.EditToTRText 		= function( tr ) 	{};
	this.MakeEditButtons 	= function( cell ) 	{};	
	this.doClick 			= function( tr )	{};
}
/** Fiche adherent UdPPC
* @var json
*/
function Fiche ( )
{
	this.datas			= null;
	this.prefix			= 'fiche.';
	this.isEditing 		= false;
	
	this.only_part = [];
	this.only_coll = [];
		
	this.last_code_tarif= null; /** Dernier code tarif extrait de adhesiontab*/
	this.adhesionstab 	= $(this.prefix+'Adhesions') ? new AdhesionsTab( $(this.prefix+'Adhesions')) : null;
	this.getAnneeStr	= function ( annee ) { return (this.isColl()) ? AnneeScolaire(annee) : annee ; }
	this.TestIfFiche	= function ( )
	{
		if ( !this.datas || this.datas.Id == -1 ) { alert ( 'Pas de fiche ...'); return false; }	
		return true;
	}	
	this.isColl		= function () { return this.datas.ColPar == COLLECTIVITE; }
	this.newFiche = function ()
	{
		this.isEditing 	= false;
		AjaxHelper.request ( 'Tools/FicheGetNew', this.newFicheDone.bind(this) );
	};
	
	this.newFicheDone= function ( request, json )
	{
		Element.show('fiche');
		this.datas = AjaxHelper.makeresponse( request, json );
		this.datas.Id = -1;
		this.toSpans();
		this.toEdits();
	}

	this.AcheterDone= function ( request, json ) 	{	this.Load( this.datas.Id ); };	
	this.Acheter 	= function ( event )	
	{
		if ( !this.TestIfFiche() ) return;
		if ( !confirm( 'Voulez-vous vraiment enregistrer une nouvelle demande d\'adhésion et/ou abonnement ?' ) ) return;
		AjaxHelper.request ( 'Tools/FicheAchat', this.AcheterDone.bind(this), { fiche: this.datas.Id, tarif:	$F('achat_sel')	} );
	};

	this.AnnulerDone= function ( request, json ) 	{	this.Load( this.datas.Id ); };
	this.Annuler 	= function ( event ) // annuler une fiche => "supprimer" ...
	{
		if ( !this.TestIfFiche() ) return;
		if ( !confirm( 'Voulez-vous vraiment supprimer cette fiche ?' ) ) return;
		AjaxHelper.request ( 'Tools/FicheAnnuler', this.AnnulerDone.bind(this), { fiche: fiche.datas.Id 	} );
	};

	this.RestoreDone= function ( request, json ) 	{	this.Load( this.datas.Id ); };
	this.Restore 	= function ( event ) // restaurer une fiche annulée 
	{
		if ( !this.TestIfFiche() ) return;
		if ( !confirm( 'Voulez-vous vraiment récupérer cette fiche ?' ) ) return;
		AjaxHelper.request ( 'Tools/FicheRestore', this.RestoreDone.bind(this), { fiche: fiche.datas.Id 	} );
	};

	this.ChangePasswordDone= function ( request, json ) 	
	{	
		var res = AjaxHelper.makeresponse( request, json );
		if( res.REC_OK ) alert ('Mot de passe changé.');
		else			alert('Erreur lors de la modification du mot de passe');   
	};
	this.ChangePassword 	= function ( event ) 
	{
		if ( !this.TestIfFiche() ) return;
		if ( !confirm( 'Voulez-vous vraiment changer le mot de passe de cette fiche ?' ) ) return;
		var pw = prompt('Tapez le nouveau mot de passe ( au moins 6 caractères )');
		if ( pw == null ) return;
	
		if ( pw.length < 6 ) 
		{
			alert ('Le mot de passe est trop court et reste inchangé');
			return;
		}
		
		AjaxHelper.request ( 'Tools/ChangePw', this.ChangePasswordDone.bind(this), { id: fiche.datas.Id, pw: pw	} );
	};

	this.doCancel = function ( event )
	{
		if ( !this.isEditing ) return;
		this.endEdit(false);
		if ( this.datas.Id == -1 ) 
		{
			Element.hide('fiche');
			Element.hide(this.prefix+'bt_edit');
			}
		else 	this.Load( this.datas.Id );
	}
	
	this.SaveDone = function ( request, json )
	{
		this.datas = AjaxHelper.makeresponse( request, json );
		this.toSpans();
	}
	this.Save = function ()
	{
		if ( !this.endEdit(true)) return;
		AjaxHelper.request ( 'Tools/FicheSet', this.SaveDone.bind(this), { json: JSON.stringify( this.datas ) } );
	}
	
	this.LoadDone= function ( request, json )
	{
		this.datas = AjaxHelper.makeresponse( request, json );
		this.toSpans();
	}
	this.Load = function ( id )
	{
		if ( this.isEditing ) return false;
		this.last_code_tarif = null;
		AjaxHelper.request ( 'Tools/FicheGet', this.LoadDone.bind(this), { 'id': id } );
	}
	
	this.ShowHideSpecials = function( )
	{
		if ( this.isEditing )
		{
			if ( $(this.prefix+'Profession_edit') )		this.datas.Profession 	= $F(this.prefix+'Profession_edit');
			if ( $(this.prefix+'ColPar_edit') ) 		this.datas.ColPar 		= $F(this.prefix+'ColPar_edit');
			this.datas.HasBupAdr 	= $(this.prefix+'HasBupAdr_edit_cb').checked ? OUI : NON;
		}
		
		for ( var i=0; i < this.only_part.length; i++ )	ShowElement( this.only_part[i], 	!this.isColl() );
		for ( var i=0; i < this.only_coll.length; i++ )	ShowElement( this.only_coll[i], 	this.isColl() );
		
		if ( ! this.isColl() )
		{
			var enseignant = this.datas.Profession == 1;
			ShowElement( this.prefix+'ProfessionAutre', 	this.datas.Profession == 5 );
			ShowElement( this.prefix+'AcademieExerciceId', 	enseignant );
			ShowElement( this.prefix+'TypesEnseignementId', 	enseignant );
		}
		
		ShowElement( this.prefix+'adrbup', 		this.datas.HasBupAdr  == OUI );
		ShowElement( this.prefix+'Canceled', 	this.datas.Canceled == OUI );
		ShowElement( 'fichetable', 				this.datas.Canceled != OUI );
//		this.TestFields(false);
	};
	/** Change la visibilité des bouttons selon l'état de la fiche */
	this.updateButtons = function ( )
	{
		var credok = true;
		if ( window.HasCredential )
		{
			credok = HasCredential('admin_gestion') || HasCredential('admin_su')
		}
		ShowElement( this.prefix+'bt_password', !this.isEditing && credok );
		ShowElement( this.prefix+'bt_cancel', 	this.isEditing && credok );
		ShowElement( this.prefix+'bt_save',		this.isEditing && credok);
		ShowElement( this.prefix+'bt_edit', 	!this.isEditing && credok);
		ShowElement( this.prefix+'Adhesion', 	!this.isEditing );
		if ( $(this.prefix+'bt_delete') && credok ) ShowElement( this.prefix+'bt_delete', !this.isEditing );
	};

	this.selectArrayToStr = function ( obj, datas )
	{
		var str ='' ;
		var lookupstr = obj.getAttribute('lookup');
		if ( !lookups.datas[lookupstr] ) return str;
		for ( var j = 0; j < datas.length; j++ )
			if ( datas[j] != 0 ) str += lookups.datas[lookupstr][datas[j]] + ", ";
		str = str.substring(0, str.length - 2 );
		return str;
	}
	
	this.selectToStr = function ( obj, datas )
	{
		var str ='' ;
		var lookupstr = obj.getAttribute('lookup');
		if ( !lookups.datas[lookupstr] ) return str;;
		str = lookups.datas[lookupstr][datas];
		return str;
	}
	
	/** Création des champs texte et edition */
	this.createFields = function ()
	{
		// prechargement
		this.only_part = $A( $$('.only_part'));
		this.only_coll = $A( $$('.only_coll'));
		
		var list = $$('.iedit');
		
		for ( var i = 0; i < list.length; i++ )
		{
			var obj		= list[i];
			var editType= obj.getAttribute('editType');
			if ( editType == 'special' ) { continue;}
			var display = Builder.node( 'text', { id: obj.id + '_display' }, ' ' )
			var edit 	= null;
			var editId	= obj.id + '_edit';
			
			if ( !obj.getAttribute('dontEdit') )
				switch ( editType ) 
				{	
					//case 'static': edit = Builder.node( 'text', {id:editId }, ' ' );break;
					case 'select':
						var lookupstr = obj.getAttribute('lookup');
						if ( lookups.datas[lookupstr] ) edit = MakeSelect( null, editId,  lookups.datas[lookupstr] , null, 0);
						break;
					case 'textarea':
						var cols = obj.getAttribute('cols');
						var rows = obj.getAttribute('rows');
						var opts = { id: editId };
						if ( cols ) opts.cols = cols ;
						if ( rows ) opts.rows = rows ;
						edit =  Builder.node('textarea', opts  );
						break;
					case 'text':
						var size= obj.getAttribute('size');
						var opts = { id:editId, type:'text' };
						if ( size ) opts.size = size;
						edit = Builder.node('input', opts );
						break;
					case 'selectarray':
						var lookupstr= obj.getAttribute('lookup');
						if ( !lookups.datas[lookupstr] ) break;
						edit = Builder.node( 'text', {id:editId } );
						var count = obj.getAttribute('count');
						for ( var j = 0; j < count ; j++ )
						{
							edit.appendChild( MakeSelect( null, editId + '_' + j,  lookups.datas[lookupstr] ));
							if ( j < (count-1)) edit.appendChild( Builder.node('br'));
						}
						break;
					case 'checkbox': 
//						edit = Builder.node('input', { id: editId, type:'checkbox' }  );
						var label= obj.getAttribute('label');
						
						edit = Builder.node( 'span', { id: editId }, [ 
							Builder.node('input', { id:  editId + '_cb', type:'checkbox' }  ),
							Builder.node('label', { htmlFor: editId + '_cb' }, label  )
							]);	
							break;
				}
			obj.appendChild( display );
			if ( edit ) 
			{
				obj.appendChild( edit );
				Element.hide( edit );
			}
		}		
		var fpe = $(this.prefix+'Profession_edit');
		if ( fpe ) 
		{	
			Event.observe( fpe, 'click', 	this.ShowHideSpecials.bind(this) );
			Event.observe( fpe, 'change', 	this.ShowHideSpecials.bind(this) );
			Event.observe( fpe, 'keyup', 	this.ShowHideSpecials.bind(this) );
		}
		var fcpe = $(this.prefix+'ColPar');
		if ( fcpe ) 
		{	
			Event.observe( fcpe, 'click', 	this.ShowHideSpecials.bind(this) );
			Event.observe( fcpe, 'change', 	this.ShowHideSpecials.bind(this) );
			Event.observe( fcpe, 'keyup', 	this.ShowHideSpecials.bind(this) );
		}
		
		var hba = $(this.prefix+'HasBupAdr_edit_cb');
		if ( hba )
		{
			Event.observe( hba, 'click', 	this.ShowHideSpecials.bind(this) );
			Event.observe( hba, 'keyup', 	this.ShowHideSpecials.bind(this) );
		}
		
	}
	this.createFields();
	
	this.toSpans = function ( )
	{
		Element.show('fiche');
		this.last_code_tarif = null;
		this.isEditing	= false;
		this.updateButtons();
		if ( !( this.datas instanceof Object ) ) return;
		for( var i = 0; i < this.datas.Adhesions.length; i++ )
			if ( this.datas.Adhesions[i].Status == 2 ) // validée
				this.last_code_tarif = this.datas.Adhesions[i].TarifCode;
		//var dbg = '';
		for ( var i in this.datas )
		{
			
			//dbg += i+'=>'+this.datas[i]+'\n';
			var str 		= '';
			var obj			= $( this.prefix + i  );
			if ( !obj ) continue;
			var editType	= obj.getAttribute('editType');
			if ( editType == 'special' )
			{
				switch ( i )
				{
					case 'Adhesions': 	 
						this.adhesionstab.LoadFromArray( this.datas[i] ); 
						// on en profite pour informer en cas de demande effectuee
						
						if ( $(this.prefix+'tr_demande_non_payee') )
						{
							ShowElement( this.prefix+'tr_demande_non_payee', 	this.datas.AdhesionNonPayee );
							if ( this.datas.AdhesionNonPayee )
							{
								var array = $A( this.datas.AdhesionNonPayee );
								var strimp = '';
								array.each( function ( t ) 
								{
									strimp += 'Pour la période : '	+ t.AnneeText+
											'  Montant : '	+ t.TarifPrixTotal +' Euros&nbsp;&nbsp; ';
									// if ( paiement_cb ) strimp += '<a href="/Paiement/Adhesion?adh_id='+ t.Id +" >Payer par carte bancaire</a><br/>';
									if ( paiement_cb ) strimp += '<button onclick="LoadWorkspace(\'Paiement/Adhesion?adh_id='+ t.Id +'\' )" >Payer par carte bancaire</button><br/>';
								});
								Element.update( this.prefix+'tr_demande_non_payee_detail', strimp );
							}
						}
						break;
					case 'TarifsDispo':
						RemoveChilds( obj );
	
						var array = $A( this.datas[i] );
						var liste = new Hash;
						var default_code = this.last_code_tarif;
						var default_id_for_current_year	= null; /* pour l'annee courante */
						var default_id_else			 	= null;	/* si pas dispo pour annee courante */
						var current_year = lookups.datas.current_year[this.datas.ColPar];
						array.each( function ( t ) 
							{ 
								liste[t.Id] = ' Code: ' + t.Code +'- '+'Année: '+ t.AnneeText + ' ' + t.Nom +'  '+ t.PrixTotal+ ' Euros ' ;
								if ( t.Code == default_code && t.Annee == current_year ) default_id_for_current_year = t.Id;
								if ( t.Code == default_code ) default_id_else = t.Id;
							});
						if ( default_id_for_current_year ) default_id_else = default_id_for_current_year;
						MakeSelect( obj,'achat_sel', liste, default_id_else );
						ShowElement( this.prefix+'tr_tarifs_nondispos', 	array.length == 0 );
						ShowElement( this.prefix+'tr_tarifs_dispos', 		array.length != 0 );
						break;
				}
				continue;			
			}
			//dbg+= "editType:"+editType;
			var display		= $( this.prefix + i + '_display' );
			
			if ( !display  ) continue;
			
			switch ( editType )
			{
				case 'selectarray':	str = this.selectArrayToStr	( obj, this.datas[i] );	break;
				case 'select':		str = this.selectToStr		( obj, this.datas[i] );	break;
				case 'checkbox':	break;
				case 'text':
				case 'textarea':
				case 'static':
					var s= ''+this.datas[i];
					str = s.gsub( /\n/, '<br />' );
					break;
			}
			switch ( obj.getAttribute('format') )
			{
				case 'date': str = GetHumanDate( str, true ); break;
			}
			display.update( str );
		}
		//alert (dbg);
		this.ShowHideSpecials();
	};
	
	/** Cree les champs editions */
	this.toEdits = function ( )
	{
		if ( this.isEditing ) return;
		this.isEditing	= true;
		this.updateButtons();
		
		if ( !( this.datas instanceof Object ) ) return;		
		for ( var i in this.datas )
		{
			var obj 	= $( this.prefix + i );
			var display	= $( this.prefix + i + '_display' );
			var edit 	= $( this.prefix + i + '_edit' );
			if ( !obj ||  obj.getAttribute('dontEdit') || !edit )		continue;
			if ( display ) 	display.hide();
			edit.show();

			var editType= obj.getAttribute('editType');
			
			switch ( editType ) 
			{
				case 'static': break;
				case 'select':
				case 'textarea':
				case 'text':
					if ( !edit ) break;
					edit.value = this.datas[i];
					break;
				case 'selectarray':
					for ( var j = 0; j < this.datas[i].length; j++ )
						$( this.prefix + i + '_edit' + '_' + j ).value = this.datas[i][j];
					break;
				case 'checkbox':
					var edit 	= $( this.prefix + i + '_edit_cb' );
					edit.checked = this.datas[i] == OUI;
					break;
			}
		}
	};
	
	/** dontHide = true => ne pas cacher les edits */
	this.formToDatas = function ( dontHide ) 
	{
		if ( !( this.datas instanceof Object ) ) return;
		for ( var i in this.datas )
		{
			var obj 	= $( this.prefix + i );
			var display	= $( this.prefix + i + '_display' );
			var edit 	= $( this.prefix + i + '_edit' );
			if ( !obj )		continue;
			if ( !edit )	continue;
			if ( !dontHide )
			{
				if ( display ) 	display.show();
				edit.hide();
			}

			var editType= obj.getAttribute('editType');
			var value	= null;	
			switch ( editType )
			{
				case 'static': break;
				case 'select':
				case 'textarea':
				case 'text':		if ( edit ) this.datas[i] = edit.value;	break;
				case 'selectarray':
					for ( var j = 0; j < this.datas[i].length; j++ ) 
					{
						var edit = $( this.prefix + i + '_edit' + '_' + j );
						this.datas[i][j] = edit.value;
					}
					break;
				case 'checkbox':
					var edit 	= $( this.prefix + i + '_edit_cb' );
					if ( edit ) this.datas[i] = edit.checked ? OUI : NON;
					break;
			}
		}
	};
	
	/** Fin du mode edition */
	this.endEdit = function ( doalert )
	{
		if ( !this.isEditing ) return;
		if (!this.TestFields()) 
		{
			if (doalert)
			{
				alert ('Il y a des erreurs dans votre saisie\n Les champs contenant des erreurs sont en rouge' );
				return false;
			}
		}
		this.formToDatas();
		this.isEditing	= false;
		this.updateButtons();
		this.toSpans();
		return true;
	};
	
	this.ObserveTestFields = function ( event )
	{
	//	Event.observe( 'fiche.Rne',			'keyup', 	this.TestFields.bind(this) );
		Event.observe( this.prefix+'Etablissement',	'keyup', 	this.TestFields.bind(this) );
		Event.observe( this.prefix+'Service',		'keyup', 	this.TestFields.bind(this) );
		Event.observe( this.prefix+'Nom',	 		'keyup', 	this.TestFields.bind(this) );
		Event.observe( this.prefix+'Prenom', 		'keyup', 	this.TestFields.bind(this) );
		Event.observe( this.prefix+'Adresse', 		'keyup', 	this.TestFields.bind(this) );
		Event.observe( this.prefix+'CodePostal', 	'keyup', 	this.TestFields.bind(this) );
		Event.observe( this.prefix+'Ville', 		'keyup', 	this.TestFields.bind(this) );
		Event.observe( this.prefix+'Email', 		'keyup', 	this.TestFields.bind(this) );
		Event.observe( this.prefix+'BupAdresse', 	'keyup', 	this.TestFields.bind(this) );
		Event.observe( this.prefix+'BupCodePostal',	'keyup', 	this.TestFields.bind(this) );
		Event.observe( this.prefix+'BupVille',		'keyup', 	this.TestFields.bind(this) );

		Event.observe( this.prefix+'Profession', 	'change', 	this.TestFields.bind(this) );
		Event.observe( this.prefix+'Profession', 	'keyup', 	this.TestFields.bind(this) );
		Event.observe( this.prefix+'ProfessionAutre','keyup', 	this.TestFields.bind(this) );
	};
	
	/* Tester les champs de saisie	
		tout tester
		si event = 5, ne pas tester étape 5...
	*/
	this.TestFields = function ( event )
	{
		this.formToDatas( true );
		if( $('rappel_pays')) $('rappel_pays').update( lookups.datas['pays'][this.datas.PaysId]);
		var testcol = this.isColl() ? 0 : 1;
		var	tests = {
				'Etablissement':[{ minsize: 5 },{} ],
				'Nom': 			[{},			{ minsize: 3 }],
				'Prenom': 		[{},			{ minsize: 3 }],
				'Adresse': 		[{ minsize: 3 },{ minsize: 3 }],
				'CodePostal':	[{ minsize: 3 },{ minsize: 3 }],
				'Ville':		[{ minsize: 3 },{ minsize: 3 }],
				'PaysId':		[{ isnot: 0  },	{ isnot: 0  }],
				'Email':		[{ minsize: 3 },{ minsize: 3 }],
				//'Rne':		[{ minsize: 1 },{ minsize: 1 }],
				'Profession':	[{},			{ valdiffer: 0 }]
				};
		if ( this.datas.HasBupAdr == OUI )
		{
			tests['BupAdresse'] 	= [{ minsize: 3 },{ minsize: 3 }];
			tests['BupCodePostal'] 	= [{ minsize: 3 },{ minsize: 3 }];
			tests['BupVille'] 		= [{ minsize: 3 },{ minsize: 3 }];	
		}
		if ( this.datas.Profession == 5 )
		{
			tests['ProfessionAutre'] 	= [{},{ minsize: 3 }];
		}
		
		// bidouille pour test partiel depuis l'inscription
		if ( event != 5 )
		{
			tests['AcademieRattachementId'] = [{ valdiffer: 0 },	{ valdiffer: 0 }];
			if ( this.datas.Profession == 1 ) // enseignant
				tests['AcademieExerciceId'] = [{},			{ valdiffer: 0 }];
		}
			
		if ( window.HasCredential )
		{
			var credok = HasCredential('admin_gestion') || HasCredential('admin_su')
			if ( credok ) tests['Email'] 	= [{},{}];
		}
		
		
		var errs = false;		
		for ( var field_name in tests )
		{
			var err = false;
			for ( var test_name in tests[field_name][testcol] )
			{
				if 		( test_name == 'minsize' )	 err = this.datas[field_name].length <  tests[field_name][testcol][test_name];
				else if ( test_name == 'valdiffer' ) err = this.datas[field_name]		==  tests[field_name][testcol][test_name]; 
				else if ( test_name == 'isnot' ) 	err = this.datas[field_name]		==  tests[field_name][testcol][test_name]; 
			}

			if 	( err )	Element.addClassName	( this.prefix + field_name + '_edit', 'error'); 
			else 		Element.removeClassName	( this.prefix + field_name + '_edit', 'error');
			errs = errs || err;
		}
		return !errs;	
	}
	if ( $(this.prefix+'bt_new') )		Event.observe( this.prefix+'bt_new',	 	'click', this.newFiche.bind(this));
	if ( $(this.prefix+'bt_edit') )		Event.observe( this.prefix+'bt_edit',	 	'click', this.toEdits.bind(this));
	if ( $(this.prefix+'bt_save') )		Event.observe( this.prefix+'bt_save',	 	'click', this.Save.bind(this));
	if ( $(this.prefix+'bt_delete') )	Event.observe( this.prefix+'bt_delete', 	'click', this.Annuler.bind(this));
	if ( $(this.prefix+'bt_cancel') )	Event.observe( this.prefix+'bt_cancel', 	'click', this.doCancel.bind(this));
	if ( $(this.prefix+'bt_acheter'))	Event.observe( this.prefix+'bt_acheter', 	'click', this.Acheter.bind(this));
	
	if ( $(this.prefix+'bt_restore'))	Event.observe( this.prefix+'bt_restore', 	'click', this.Restore.bind(this));
	if ( $(this.prefix+'bt_password'))	Event.observe( this.prefix+'bt_password', 	'click', this.ChangePassword.bind(this));
	this.ObserveTestFields();
}

