// JavaScript Document

function isDate(d) {
	
	if (d == "") // si la variable est vide on retourne faux
		return false;

	e = new RegExp("^[0-9]{1,2}\/[0-9]{1,2}\/([0-9]{2}|[0-9]{4})$");

 	if (!e.test(d)) // On teste l'expression régulière pour valider la forme de la date
 		return false; // Si pas bon, retourne faux

	 // On sépare la date en 3 variables pour vérification, parseInt() converti du texte en entier
	 j = parseInt(d.split("/")[0], 10); // jour
	 m = parseInt(d.split("/")[1], 10); // mois
	 a = parseInt(d.split("/")[2], 10); // année

	 // Si l'année n'est composée que de 2 chiffres on complète automatiquement
	 if (a < 1000) {
	 	if (a < 89) 
			a+=2000; // Si a < 89 alors on ajoute 2000 sinon on ajoute 1900
	 	else
			a+=1900;
	 }

	 // Définition du dernier jour de février
	 // Année bissextile si annnée divisible par 4 et que ce n'est pas un siècle, ou bien si divisible par 400
	 if (a%4 == 0 && a%100 !=0 || a%400 == 0) 
	 	fev = 29;
	 else
	 	fev = 28;

	 // Nombre de jours pour chaque mois
	 nbJours = new Array(31,fev,31,30,31,30,31,31,30,31,30,31);

	 // Enfin, retourne vrai si le jour est bien entre 1 et le bon nombre de jours, idem pour les mois, sinon retourn faux
	 return ( m >= 1 && m <=12 && j >= 1 && j <= nbJours[m-1] );
 } 


function insertClient(){

	Element.update('resultat', '');
	$('resultat').hide();
	
	var vNaiss = $F('idJour')+"/"+$F('idMois')+"/"+$F('idAnnee');
	
	if( isDate(vNaiss) ){
		
		
		var newsletter = false;
		
		if( $("id_newsletter").checked )
			newsletter = true;
		else
			newsletter = false;		
	
		new Ajax.Request('ajax/_client-register.php', {
			method: 'post',
			postBody: $H({
				'txtNom' : $F('idNom'),
				'txtPrenom' : $F('idPrenom'),
				'txtDept' : $F('idDept'),
				'txtMail' : $F('idEmail'),
				'txtTel' : $F('idTel'),
				'txtNaissance' : vNaiss,
				'txtDocs' : $F('iddoc'),
				'txtNewsletter' : newsletter
			}).toQueryString(),
			
			
			onLoading: function(){
				Element.show('chargement');
			},
			
			on500 : function(){
				insertClient();	
			},
			
			
			onComplete: function(eRequester) {
				vResultat = eval('(' + eRequester.responseText + ')');
				
				if(vResultat.etat == 1) {
					Element.update('text','<div id="resultat" style="font-size:14px;"></div>');
					Element.update('resultat', vResultat.message);					
					$('resultat').show();
					//updateListe(true);
				} else {
					Element.update('resultat', vResultat.message);
					$('resultat').show();
				}
			}
		});
	
	}  else {
		
		Element.update('resultat', '<p class="errorbox">Le champ "Date de naissance" doit respecté le format jj/mm/aaaa.<br /><i style="font-size:10px;">Exemple : 14/03/1975 pour le 14 mars 1975.</i></p>');
		$('resultat').show();
		
	}
	
}


function identifieClient(){


	new Ajax.Request('ajax/_client-ident.php', {
		method: 'post',
		postBody: $H({
			'txtIdent' : $F('idLogin'),
			'txtPassword' : $F('idPassword')
		}).toQueryString(),
		
		
		onLoading: function(){
			Element.show('chargement');
		},
		
		on500 : function(){
			identifieClient();	
		},
		
		onComplete: function(eRequester) {
			vResultat = eval('(' + eRequester.responseText + ')');
			if(vResultat.etat == 1) {
				alert(vResultat.txtAlert);				
				Element.update('client', vResultat.message);
			} else if(vResultat.etat == 0) {
				alert(vResultat.txtAlert);
				var url = "http://www.bardahlfrance.fr/produits/auto/identifiants-perdus.php";
				document.location.href=url;
				
				//Element.update('resultat', vResultat.message);
			} else {
				
				alert(vResultat.txtAlert);
				Element.update('resultat', vResultat.message);
			}
		}
	});
}


function checkLogin(qs){

	new Ajax.Request('ajax/_client-ident.php', {
		method: 'post',
		postBody: $H({
			'txtIdent' : $F('idIdentifiant'),
			'txtPassword' : $F('idPass')
		}).toQueryString(),
		
		
		onComplete: function(eRequester) {
			vResultat = eval('(' + eRequester.responseText + ')');
			
			if(vResultat.etat == 1) {
				alert(vResultat.txtAlert);				
				Element.update('client', vResultat.message);				
				if(qs != ""){
					var url = "http://www.bardahlfrance.fr/produits/auto/telecharger-fiche.php?"+qs;
					document.location.href=url;
				} else {
					var url = "http://www.bardahlfrance.fr/produits/auto/espace-visiteur.php";
					document.location.href=url;
				}
				
			} else {
				alert(vResultat.txtAlert);
				Element.update('resultat', vResultat.message);
			}
		}
		
	});
}




function forgotPass(){
	
	
	new Ajax.Request('ajax/_client-newPass.php', {
		method: 'post',
		postBody: $H({
			'txtIdent' : $F('idMail')
		}).toQueryString(),
		
		
		onLoading: function(){
			Element.show('chargement');
		},
		
		on500 : function(){
			forgotPass();	
		},
		
		
		onComplete: function(eRequester) {
			Element.hide('chargement');
			vResultat = eval('(' + eRequester.responseText + ')');
			if(vResultat.etat == 1) {
				alert(vResultat.txtAlert);				
				//Element.update('client', vResultat.message);
			} else {
				alert(vResultat.txtAlert);
				Element.update('resultat', vResultat.message);
			}
		}
	});
	
	
}



//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////

MultipleSelectCheck_Controller = {
	current : null,
	_s_openLock :false,
	
	init	: function()
	{
		Event.observe(document, 'mousedown', function() {
			if (MultipleSelectCheck_Controller.current != null && !MultipleSelectCheck_Controller._s_openLock)
			{
				window.setTimeout("MultipleSelectCheck_Controller.documentClick()", 100);
			}
			MultipleSelectCheck_Controller._s_openLock = false;
		});
	},
	
	documentClick : function()
	{
		if (this.current != null)
		{
			this.current.documentClick();
		}
	},
	
	openStart : function()
	{
		this._s_openLock = true;

		if (this.current != null)
		{
			this.current.close();
		}
	},

	globalSwitch : function(objMSC)
	{
		objMSC = eval(objMSC);
		
		var state = $(objMSC.htmlMSCId + '_globalSwitch').checked;
		objMSC.globalSwitchChecked = state;
		
		var optionsCollection = $(objMSC.htmlMSCId + '_optionsContainer').getElementsByTagName('input');

		for (i=0; i<optionsCollection.length; i++)
		{
			currentInput	= optionsCollection.item(i);
			if (currentInput.getAttribute('value') )
			{
				currentInput.checked = state;
			}
		}
		objMSC.updateMSCinput();
	}
}

	
	
function MultipleSelectCheckbox(objName)
{
	this.objName			= objName;
	this.htmlSelectName		= null;
	this.htmlSelectId		= null;
	
	this.htmlMSCName		= null;
	this.htmlMSCId			= null;

	this.MSCoptionsKeys		=  Array();
	this.MSCoptions			=  Array();

	this.globalSwitch		= null;
	this.globalSwitchValue	= null;
	this.URLSeparator		= ',';
	this.visualSeparator	= ',';

	this._s_opened			= false;
	this._s_clicked			= false;



	this.updateMSCinput		= function()
	{
		tmp = Array();
		tmp2 = Array();

		var optionsCollection = $(this.htmlMSCId + '_optionsContainer').getElementsByTagName('input');

		var allChecked = true;
		var noneChecked = true;

		for (i=0; i<optionsCollection.length; i++)
		{
			currentInput	= optionsCollection.item(i);
			if (currentInput.checked)
			{
				noneChecked = false;
				if (currentInput.getAttribute('value') )
				{
					tmpValue = currentInput.getAttribute('value');
					tmp.push( tmpValue );
					if (tmpValue != this.globalSwitchValue) tmp2.push( this.MSCoptions[tmpValue] );
				}
			}
			else
			{
				if (currentInput.getAttribute('value') && currentInput.getAttribute('value') != this.globalSwitchValue) allChecked = false;
			}
		}
		
		this.globalSwitchChecked = allChecked;
		$(this.htmlMSCId + '_globalSwitch').checked = this.globalSwitchChecked;
		
		
		$(this.htmlMSCId).value	= tmp.join(this.URLSeparator);

		if (this.globalSwitch != null && this.globalSwitchChecked)
		{
			tmpHTML = this.globalSwitch;
		}
		else
		{
			tmpHTML = tmp2.join(this.visualSeparator);
		}
		 
		
		$(this.htmlMSCId + '_selectedView').innerHTML = tmpHTML; 
	}



	this.addGlobalSwitch = function(label, value, checked)
	{
		this.globalSwitch = label;
		this.globalSwitchValue = value;
		this.globalSwitchChecked = checked;
	}



	this.create = function (htmlSelectName, htmlSelectId, htmlMSCName, htmlMSCId)
	{
		this.htmlSelectName		= htmlSelectName;
		this.htmlSelectId		= htmlSelectId;		
		this.htmlMSCName		= htmlMSCName;
		this.htmlMSCId			= htmlMSCId;
	
		var html = '';
		var htmlOptions = '';
		
		var width = $(htmlSelectId).getWidth() + 15;
		var optionsCollection = $(htmlSelectId).getElementsByTagName('option');

		var ie6_hover = document.all ? 'onmouseover="Element.addClassName(this,\'hover\');" onmouseout="Element.removeClassName(this,\'hover\')" ' : '';

		for (i=0; i<optionsCollection.length; i++)
		{
			currentOption	= optionsCollection.item(i);
			currentValue	= currentOption.getAttribute('value');
			currentChecked	= currentOption.getAttribute('checked') != null;
			currentId		= htmlMSCId + '_' + i;

			this.MSCoptionsKeys[currentValue] = currentValue;
			this.MSCoptions[currentValue] = currentOption.firstChild.data;

			htmlOptions +=	'<div class="MCP_option" ' + ie6_hover + '>'
							+ '<input type="checkbox" id="' + currentId + '" value="' + currentValue + '" '
									+  (currentChecked ? ' checked="checked" ' : '')
							+ ' />'
							+ '<label style="width:' + (width - 20) + 'px" '
									+ 'onclick="$(\'' + currentId + '\').checked =!$(\'' + currentId + '\').checked; '
									+ this.objName + '.updateMSCinput();">' + currentOption.firstChild.data + '</label>'
							+ '<div style="clear:both;"></div>'
							+ '</div>';
		}

		if (this.globalSwitch !== null)
		{
			var tmpOnclick = 'MultipleSelectCheck_Controller.globalSwitch(\'' + this.objName + '\');';
			htmlOptions =	'<div class="MCP_option global" ' + ie6_hover + '>'
							+ '<input type="checkbox" id="' + htmlMSCId + '_globalSwitch"'
									+ ' onclick="' + tmpOnclick + '" '
									+  (this.globalSwitchChecked ? ' checked="checked" ' : '')
									+  (this.globalSwitchValue ? ' value="' + this.globalSwitchValue + '" ' : '')
							+ ' />'
							+ '<label style="width:' + (width - 20) + 'px" '
								+ 'onclick="$(\'' + htmlMSCId + '_globalSwitch\').checked = !$(\'' + htmlMSCId + '_globalSwitch\').checked;' + tmpOnclick + '">' + this.globalSwitch + '</label>'
							+ '<div style="clear:both;"></div>'
							+ '</div>'
						+ htmlOptions;
		}


		html += '<div class="MCP_control" style="width:' + width +  'px" id="' + htmlMSCId + '_select"  onmousedown="' + this.objName + '.toggle()">'
					+ '<div class="toggle"></div>'
					+ '<div style="padding:1px 3px;"><label>Choisissez</label></div>'
				+ '<div style="clear:both"></div>'
				+ '</div>';
		
		html += '<div class="MCP_optionsContainer" id="' + htmlMSCId + '_optionsContainer" style="width:' + (width + 2) + 'px" onmousedown="' + this.objName + '._s_clicked=true;">';
		html += htmlOptions;
		html += '</div>';

		html += '<div style="clear:both"></div>';
		html += '<div class="MCP_selectedView" id="' + htmlMSCId + '_selectedView"></div>';		
		html += '<input type="hidden" id="' + htmlMSCId + '" name="' + htmlMSCName + '" value="" />';
		
		
		Insertion.After( $(htmlSelectId), html);
		Element.remove( $(htmlSelectId) );

		// si globalSwitch à la création, on coche tout
		if (this.globalSwitchChecked)
		{
			MultipleSelectCheck_Controller.globalSwitch(this.objName);
		}

		this.updateMSCinput();
	}



	this.toggle = function()
	{
		if (this._s_opened) this.close();
		else this.open();
	}



	this.open = function()
	{
		MultipleSelectCheck_Controller.openStart();
		$(this.htmlMSCId + '_optionsContainer').style.display = 'block';
		MultipleSelectCheck_Controller.current = this;
		this._s_opened = true;
	}



	this.close = function()
	{
		$(this.htmlMSCId + '_optionsContainer').style.display = 'none';
		MultipleSelectCheck_Controller.current = null;
		this._s_opened = false;
		this.updateMSCinput();
	}



	this.documentClick = function()
	{
		if (!this._s_clicked)
		{
			this.close();
		}
		this._s_clicked = false;
	}

}