/****************************************************************************************************************
	main behaviour
****************************************************************************************************************/

function initForms()
{
	$('form input:text, form textarea').each(function()
	{
		// stocking the value in the 'defaultValue' attribute
		$(this).attr('defaultValue', $(this).val());
		
		$(this).focus(function()
		{
			// clearing the field on focus
			if ($(this).val() == $(this).attr('defaultValue')) $(this).val('');
		});
		
		
		$(this).blur(function()
		{
			// if not changed, replacing by the default value											  
			if (($(this).val() == '') && ($(this).attr('defaultValue'))) $(this).val($(this).attr('defaultValue'));
		});
	});
}

/****************************************************************************************************************
	Check
****************************************************************************************************************/

function setError(elt)
{
	elt.addClass('errorWarning');
	$("label[for="+elt.attr("id")+"]").addClass('errorWarning');
	elt.focus();
	return true;
}

function setErrorRadio(elt)
{
	elt.parent().children('.legend').addClass('errorWarning');
	return true;
}

function setErrorCheckBox(elt)
{
	elt.addClass('errorWarning');
	elt.parent().children('label').addClass('errorWarning');
	return true;
}

function eraseErrorCheckBox(elt)
{
	elt.removeClass('errorWarning');
	$("label[for="+elt.attr("id")+"]").removeClass('errorWarning');
}

function eraseError(elt)
{
	elt.removeClass('errorWarning');
	$("label[for="+elt.attr("id")+"]").removeClass('errorWarning');
}

function initCheck()
{
	$('form').submit(function()
	{
		// reInit
		$('#errorSummary').hide();
		$('#'+$(this).attr('id')+' input[type=text], #'+$(this).attr('id')+' input[type=password]').removeClass('errorWarning');
		$('.legend').removeClass('errorWarning');
		
		var error = false;
		
		// mandatory fields
		
		// input text
        var lastEmail = ' ';
        var numEmail = 0;
		$('#'+$(this).attr('id')+' input[type=text].mandatory').each(function()
		{
			// Exception ! If the field containers are "display : none" - inscription_newsletter.html
			if( $(this).parent().parent().parent().parent().is(':visible') && ($(this).parent().parent().is(':visible')) ) 
			{
				// is empty ?
				if($(this).val() == '')
					error = setError($(this));	
				
				// is valid ? (for emails)
				else if ($(this).attr('class').indexOf('mandatoryEmail') != -1){

					var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
					
					if (!(emailPattern.test($(this).val()))) error = setError($(this));
					else eraseError($(this));
					
					if(numEmail == 1)
					{
					    if(lastEmail != $(this).val())
					        error = setError($(this));
					    else eraseError($(this));
					}
					
					numEmail = (numEmail + 1) % 2;
				    lastEmail = $(this).val();
				}
				// EXPERTIME / AMO : Check Captcha
				// is valid ? (for captcha)
				else if ($(this).attr('class').indexOf('mandatoryCaptcha') != -1)
				{
					var errorCaptcha = CheckCaptcha($(this).attr('id'))
					if(errorCaptcha != false)
					    error = errorCaptcha;				
				}
				
				else eraseError($(this));
			}		
		});

		// Password
		var lastPwd = ' ';
		var numPwd = 0;
		$('#'+$(this).attr('id')+' input[type=password].mandatory').each(function()
		{
		    // is empty ?
			if($(this).val() == '')
			{	
			    error = setError($(this));
			}
		    else if($(this).val().length < 6)
			{
			    error = setError($(this));
			}
            else if(numPwd == 1)
		    {
		        if(lastPwd != $(this).val())
		            error = setError($(this));
		        else eraseError($(this));
		    }
		    else eraseError($(this));
			
			numPwd = (numPwd + 1) % 2;		
			lastPwd = $(this).val();
		
		});

		// CheckBoxes
		$('#'+$(this).attr('id')+' input[type=checkbox].mandatory').each(function()
		{
		    var checked = $(this).attr("checked");
			if (typeof(checked) == 'undefined')
			{ 
				error = setErrorCheckBox($(this));
			}
			else
			{
				eraseErrorCheckBox($(this));
			}
		});

		
		// radio buttons
		
		// array containing all names of mandatory radio buttons
		var radioNamesArray =  new Array;
		
		// filling it
		// for each radio button
		$('#'+$(this).attr('id')+' input[type=radio].mandatory').each(function()
		{
			
			var trouve = false;
			
			for (i=0; i<radioNamesArray.length; i++){
				if (radioNamesArray[i] == $(this).attr('name')) trouve = true;
			}

			if (!trouve) radioNamesArray.push($(this).attr('name'));
			
		});

		// checking if button is checked for each "name"
		for (i=0; i<radioNamesArray.length; i++) 
		{
			
			var isCheck = false;
			
			$('#'+$(this).attr('id')+" [@name='"+radioNamesArray[i]+"']").each(function(){
				
				if ($(this).attr("checked") == true) isCheck = true;
				
			});
			
			if (!isCheck) setErrorRadio($('#'+$(this).attr('id')+" [@name='"+radioNamesArray[i]+"']"));
			
		}

		// form submit ?
		if (error) 
		{
			$('#errorSummary').show();
			return false;
		}
		else
		{
			$('#errorSummary').hide();
		}
	});
}

/****************************************************************************************************************
	collapse on click
****************************************************************************************************************/

function initRadioCollapse(){

	$('.toCollapseIfYesContent').hide();
	/* EXPERTIME / AB 23/06/2008 : Mise en commentaire de la ligne suivant, qui empechait les radiobuttons d'etre checkes au chargement de la page.
	 */
	/*$('input[type=radio], input[type=checkbox]').attr("checked", false);*/
		
	
	$('.toCollapseIfYesInput[type=radio]').click(function(){
		
		if ($(this).attr('id').indexOf('oui') != -1) $(this).parent().next('.toCollapseIfYesContent').show();
		else $(this).parent().next('.toCollapseIfYesContent').hide();
		
	});
	
	$('.toCollapseIfYesInput[type=checkbox]').click(function(){
		
		if ($(this).attr('checked')) $(this).parent().next('.toCollapseIfYesContent').show();
		else $(this).parent().next('.toCollapseIfYesContent').hide();
		
	});
	
	/* EXPERTIME / AB 23/06/2008 : Permet d afficher les div lorsque qu un radiobutton est checke au chargement de la page (via le cookie)*/
	if ($('.toCollapseIfYesInput[type=radio]:checked') != null && $('.toCollapseIfYesInput[type=radio]:checked').attr('id') != null)
	{
	    var rdb = $('.toCollapseIfYesInput[type=radio]:checked');
	    var index = $(rdb).attr('id').indexOf('oui');

        if (index > 0)
        {
            $(rdb).parent().next('.toCollapseIfYesContent').show();
        }
	}
}

/****************************************************************************************************************
	collapse on select
****************************************************************************************************************/

function initSelectCollapse(){

	$('.toCollapseOnNumberContent').children().hide();
	$('.collapseCount-1').show();
	
	$('.toCollapseOnNumber').change(function(){
		
		if(($(this).val() > 0) && ($(this).val() < 11)){
			
			$(this).parent().next('.toCollapseOnNumberContent').children('div').hide();
			
			for (i=1; i<(parseInt($(this).val())+1); i++) {
				
				$(this).parent().next('.toCollapseOnNumberContent').children('.collapseCount-'+i).show();
				
			}
			
		}
		
	});
	
	
	/* EXPERTIME /  AB 23/06/2008 : Permet d afficher les enfants a partir du cookie*/
	if ($('.toCollapseOnNumber') != null && $('.toCollapseOnNumber').attr('id') != null)
	{
	    var ddl = $('.toCollapseOnNumber');
	    var ddlChild = $(ddl).attr('id').indexOf('nbEnfants');
	    var val = $(ddl).val();
	    if (ddlChild > 0)
	    {
	        if ((val > 0) && (val < 11))
	        {
                for (i=1; i<=val; i++) 
                {				
			        $(ddl).parent().next('.toCollapseOnNumberContent').children('.collapseCount-'+i).show();
		        }
		    }
	    }
	}
}


/****************************************************************************************************************
	onLoad
****************************************************************************************************************/

$(document).ready(function(){
	//initForms();
	initCheck();
	initRadioCollapse();
	initSelectCollapse();
});