if (!window.console || !console.firebug){
	var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml","group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];
	window.console = {};
	for (var i = 0; i < names.length; ++i)
		window.console[names[i]] = function() {};
}
Eu = {};
Eu.sm = {};
Eu.sm.formSpec = [];
Eu.sm.arrayValuesInArray = function (a,b){
	if (!jQuery.isArray(a)){
		a = [a];
	}
	var tmpval = false;
	jQuery.each(a,function(k,v){
		if (jQuery.inArray(v,b)!=-1){
			tmpval=true;
			return true;
		}
	});
	return tmpval;
}

checkContainer = {

	check_txtPostcode : function (field,form,test){

		if (test.errorEmpty){
			if (checkContainer.check_txtFieldNotNull(field,form,test)){
				return test.errorEmpty;
			}
		}
		var lang = test['lang'];
		switch (lang){
			case 'TRL_FR':
				// Pour le step 2
				if (typeof(test.countryField) !='undefined' && test.countryField){
					var country = ''+$('select[name=form_data__'+test.countryField+']',form).val();

					if (country.toUpperCase()=='FRANCE' && !/^[0-9]{4,5}$/.test(field.val())){
						return test.errorMessage;
					}
				}
				// Nécessaire pour le step 1
				else{
					if ( !/^[0-9]{4,5}$/.test(field.val())){
						return test.errorMessage;
					}
				}
			break;
			case 'TRL_EN':

				var alpha1 = "[abcdefghijklmnoprstuwyz]"; 	// Character 1
				var alpha2 = "[abcdefghklmnopqrstuvwxy]"; 	// Character 2
				var alpha3 = "[abcdefghjkstuw]"; 			// Character 3
				var alpha4 = "[abehmnprvwxy]"; 				// Character 4
				var alpha5 = "[abdefghjlnpqrstuwxyz]"; 		// Character 5
				var postCode = field.val();
				postCode = (postCode+'').replace(/ /g,'');
				var valid = false;
				var i=0;
				var pcexp = new Array ();
				pcexp.push (new RegExp ("^([a-z][a-z]?[0-9]{1,2})(\\s*)([0-9][a-z][a-z])$",	"i"));
				pcexp.push (new RegExp ("^([a-z][0-9][a-z])(\\s*)([0-9][a-z][a-z])$",		"i"));
				pcexp.push (new RegExp ("^([a-z][a-z]?[0-9][a-z])(\\s*)([0-9][a-z][a-z])$",	"i"));
				pcexp.push (/^(GIR)(\s*)(0AA)$/i);
				pcexp.push (/^(bfpo)(\s*)([0-9]{1,4})$/i);
				pcexp.push (/^(bfpo)(\s*)(c\/o\s*[0-9]{1,3})$/i);

				// Pour le step 2
				if (typeof(test.countryField) !='undefined' && test.countryField){
					var country = ''+$('select[name=form_data__'+test.countryField+']',form).val();

					if(country.toUpperCase()=='FRANCE') {
						if(!/^[0-9]{4,5}$/.test(field.val())){
							return test.errorMessage;
						}
					}

					if ( country.toUpperCase()=='UNITED KINGDOM (THE)' || country.toUpperCase()=='UNITED KINGDOM' || country.toUpperCase()=='UNITED-KINGDOM'){
						for (i=0; i<pcexp.length; i++) {
							if (pcexp[i].test(postCode)) {
								pcexp[i].exec(postCode);
								postCode = RegExp.$1.toUpperCase() + " " + RegExp.$3.toUpperCase();
								postCode = postCode.replace (/C\/O\s*/,"c/o ");
								valid = true;
								break;
							}
						}
						if (valid==false){
							return test.errorMessage;
						}
					}
				}
				// Nécessaire pour le step 1
				else{
					for (i=0; i<pcexp.length; i++) {
						if (pcexp[i].test(postCode)) {
							pcexp[i].exec(postCode);
							postCode = RegExp.$1.toUpperCase() + " " + RegExp.$3.toUpperCase();
							postCode = postCode.replace (/C\/O\s*/,"c/o ");
							valid = true;
							break;
						}
					}
					if (valid==false){
						return test.errorMessage;
					}
				}
			break;
			// @jira PRODEV-412
			default	:
				Eu.sm.alertError('Erreur de langue', 'lang n\'est pas défini pour ce pays : ' + lang + 'Emplacement : servicemagic.js');
				break;
		}
		return false;
	},

	check_txtPhone : function (field,form,test){
		if (test.errorEmpty){
			if (checkContainer.check_txtFieldNotNull(field,form,test)){
				return test.errorEmpty;
			}
		}
		var lang = test['lang'];
		switch (lang){
			case 'TRL_FR':
				if (typeof(test.countryField) !='undefined' && test.countryField){
					var country = ''+$('select[name=form_data__'+test.countryField+']',form).val();

					if ((country.toUpperCase()=='FRANCE') && (!(/^(0[0-9])[0-9]{8}$/).test(trim(field.val())))){
						return test.errorMessage;
					}
				}
			break;
			case 'TRL_EN':
				if (typeof(test.countryField) !='undefined' && test.countryField){
					var country = ''+$('select[name=form_data__'+test.countryField+']',form).val();

					if ((country.toUpperCase()=='UNITED KINGDOM (THE)' || country.toUpperCase()=='UNITED KINGDOM' || country.toUpperCase()=='UNITED-KINGDOM')
						&& (!(/^0[12358][0-9]{8,9}$/).test(trim(field.val())) && !(/^07[0-9]{9}$/).test(trim(field.val())))){
						return test.errorMessage;
					}
				}
			break;
			// @jira PRODEV-412
			default	:
				Eu.sm.alertError('Erreur de langue', 'lang n\'est pas défini pour ce pays : ' + lang + 'Emplacement : servicemagic.j');
				break;
		}
		return false;
	},

	check_atLeastOneCheckboxChecked : function (field,form,test){
		var arrcheck = $(test.js_pattern+':checked',form);
		if (form.useByPassable){
			if (!/^check_/.test(test.notByPassable)){
				var arrVals = [];
				jQuery.each(arrcheck,function(idx,fld){
					arrVals.push($(fld).val());
				});
				var arrAcceptable = (test.notByPassable+'').split(',');
				if (!jQuery.isArray(arrAcceptable)){
					arrAcceptable=[];
				}
				if(!Eu.sm.arrayValuesInArray(arrVals,arrAcceptable)){
					return test.errorMessage;
				}else{
					return false;
				}
			}else{
				return false;
			}
		}
		console.log(field,form,test);
		//
		if (test.other_field){
			var oth = $('input[name=form_data__'+test.other_field+']');
			if (oth.defaultValue){
				if (oth.defaultValue && oth.val()!=field.defaultValue && oth.val()!=''){
					return false;
				}
			}
			if (oth.val()!=''){
				return false;
			}
		}
		return ((arrcheck.length && arrcheck.length>0)?false:test.errorMessage);
	},

	check_alwaysOK				: function (field,form,test){
		return false;
	},

	check_atLeastOneRadioChecked : function (field,form,test){
		var arrcheck = $(test.js_pattern+':checked',form);
		return ((arrcheck.length && arrcheck.length>0)?false:test.errorMessage);
	},

	check_txtFieldNotNull		: function (field,form,test){
		if (trim(field.val())==''){
			return test.errorMessage;
		}
		if (field.defaultValue && field.val()==field.defaultValue){
			return test.errorMessage;
		}
		return false;
	},

	check_txtAreaNotNull : function (field,form,test){
		if (trim(field.val())==''){
			return test.errorMessage;
		}
		if (field.defaultValue && field.val()==field.defaultValue){
			return test.errorMessage;
		}
		return false;
	},

	check_txtFieldValidConfirmation : function (field,form,test){
		var f1 = field.val();
		var f2 = $('[name='+field[0].name.replace('_confirmation','')+']',form).val();
		if (f1 != f2){
			return test.errorMessage;
		}
		return false;

	},

	check_txtEmailValid : function (field,form,test){
		if (field.val()==''){
			return test.errorMessage;
		}
		if (!/^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,4})+$/.test(field.val())){
			return test.errorMessageSyntax;
		}
		return false;
	},

	check_txtWebsiteValid : function (field,form,test){
		if (field.val()==''){
			return test.errorMessage;
		}
		if (!/^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,4})+$/.test(field.val())){
			return test.errorMessageSyntax;
		}
		return false;
	},

	check_comboFieldNotNull		: function (field,form,test){
		if (!field.val() || field.val()=='Choose'){
			return test.errorMessage;
		}
		return false;
	}
};
	function trim (myString) {
		//return (myString+'').replace(/^\s+/g,'').replace(/\s+$/g,'');
		return (myString+'').replace(/(\s*)/g,"");
	}

	function alertError(title,msg){
		var msgInner = msg.replace(/\n/g,'<br />');
		var dialog = $('<div></div>')
			.html(msgInner)
			.dialog({
				autoOpen		: true,
				modal			: true,
				title			: title,
				closeOnEscape	: true,
				resizable 		: false,
				autoHeight		: true,
				autoWidth		: true,
				buttons 		: {
					Ok 				: function() {
						$(this).dialog('close');
					}
				}
			});
	}

	function switchText() {
		if ($(this).val() == $(this).attr('title')) {
			$(this).val('').removeClass('style_indications');
			if (this.id == 'keyword') {$('#select_activite').val(0);}
		}
		else if ($(this).val() == '')
			$(this).addClass('style_indications').val($(this).attr('title'));
	}

	function setIndications(){
		return $('.indications').each(function() {
			if ($(this).val() == '') $(this).val($(this).attr('title'));
			if ($(this).val() == $(this).attr('title')) $(this).addClass('style_indications');
		});
	}
function initMapSr(MapId,arrSR,frontDataUrl,defaultZoom){
	if (!defaultZoom){
		defaultZoom=13;
	}
	if (!$("#"+MapId)){
		return;
	}
	if (arrSR.length == 0){
		$("#"+MapId).hide();
		return;
	}

	var infoWindow = new google.maps.InfoWindow();

	var selected = null;
	var map;
	var marker = [];
	var idx=0;

	var infowindow = new google.maps.InfoWindow({
		'size': new google.maps.Size(300, 180)
	} );

	var coordInfoWindow;
	var mapOptions = {
		zoom			: defaultZoom,
		center			: new google.maps.LatLng(arrSR[0].lat,arrSR[0].long),
		mapTypeId		: google.maps.MapTypeId.ROADMAP,
		scaleControl	: true,
		mapTypeControl	: false,
		scrollwheel		: false
	};
	map = new google.maps.Map(document.getElementById(MapId), mapOptions);
	var marker = [];


	srInfoWindow = function(idx) {
		infoWindow.setContent([
				'<a href="',
				arrSR[idx].formUrl,
				'"><img src="',
				frontDataUrl,
				'www2.servicemagic.co.uk/common/images/bt_request_gm.gif" style="margin-right:10px;float: right;" /></a>',
				'<div style="font-family: Trebuchet MS, Geneva, Arial, Helvetica, SunSans-Regular, sans-serif; font-size: 21px; font-weight: bold; color: #000;">',
				arrSR[idx].lib_activite
				,'</div>',
				'<div style="font-family: Trebuchet MS, Geneva, Arial, Helvetica, SunSans-Regular, sans-serif; font-size: 19px; font-style: italic; color: #828282;">Job Description</div>',
				'<div style="font-family: Trebuchet MS, Geneva, Arial, Helvetica, SunSans-Regular, sans-serif; font-size: 13px; color: #828282;">',
				arrSR[idx].small_texte
				,'</div>'
			].join(''));
		infoWindow.open(map, marker[idx]);
	};
	var bounds = new google.maps.LatLngBounds();

	var nb = 0;
	jQuery.each(arrSR,function(k,v){
		nb++;
		var myLatLng = new google.maps.LatLng(v.lat,v.long);
		marker[k] = new google.maps.Marker({
			position	: myLatLng,
			map			: map,
			title		: v.lib_activite
		});
		bounds.extend(myLatLng);
		google.maps.event.addListener(marker[k], 'click', function(){srInfoWindow(k)});
	});
	if (nb>1){
		map.fitBounds(bounds);
	}


}

$(document).ready(function(){

	if (typeof(Eu_sm_formSpec_init) !== 'undefined'){
		Eu_sm_formSpec_init();
	}

	function initFormStep1(){
		$("[name=form_data__cp]").focus();//met le focus sur le code postal
	}
	initFormStep1();

	/* slide homepage & page 3 */
	/*
	if ($(".maintitle_link") && $(".maintitle_link").length>0){ // test if we are on ssactivite or on dynamic duv
		$(".zone_retour").click(function(event){
			$("#bloc_all_category_inside").animate({left:0},'slow','linear',function(){
				$("#subLink_"+id).hide();
			});
			return false;
		});
	}
	$(".maintitle_link").click(function(event){
		id = event.target.id.replace('mainLink_','');
		$(".bloc_subcategory").hide();
		$("#subLink_"+id).show();

		$.ajax({
			method: "get", url: "track_main_category.php",dataType: 'json', data: "id_main_cat="+id, complete: function(){ }, success: function(data){ }
		});//WEBSITE-521

		$("#bloc_all_category_inside").animate({
			left:-605,
			"duration": "slow",
			"easing": "easeout"
		});
		return false;
	});
	* /

	/* alert remplacement */
	setIndications().focus(switchText).blur(switchText);

	/* reinitialisation field tooltips */
	$('form').submit(function() {
		$(this).find('input[type=text][title!=""]').each(function() {
			if ($(this).val() == $(this).attr('title')) $(this).val('');
		});
		$(this).find('textarea[title!=""]').each(function() {
			if ($(this).val() == $(this).attr('title')) $(this).val('');
		});
	});//suppression du texte s'il est egal au titre lors du submit



	jQuery.each(Eu.sm.formSpec,function(key,formDef){

		var htmlForm = (formDef.id )?$('#'+formDef.id):$('.'+formDef.className);

		var verifMode = (formDef.verificationMode)?(formDef.verificationMode):'autre';

		if (htmlForm && verifMode == 'autre'){
			htmlForm.submit(function() {
				var message = 'Please :\n';
				var messageIn = '';
				jQuery.each(formDef.fields,function(fieldName,test){
					if (test.selector){
						var field = $(test.selector,htmlForm);
					}else{
						var field = $('[name=form_data__'+fieldName+']',htmlForm);
					}
					if (field && (messageIn = checkContainer['check_'+test['test_function']](field,htmlForm,test))){
						message +='- ' +messageIn+'\n';
					}else{
						if (test.js_function && field && (messageIn = checkContainer['check_'+test['js_function']](field,htmlForm,test))){
							message +='- ' +messageIn+'\n';
						}
					}
				});
				if(message!="Please :\n"){
					alertError('We need your attention',message);
					setIndications();
					return false;
				}else{
					return true;
				}
			});
		}

		if (htmlForm && verifMode == 'sr'){
			var multiFormMode = ($('#form_splitter_part2').hide().length)==1;
			if (multiFormMode){
				var multiFormMode_step=1;
				var multiFormMode_split = 'crit_'+$('input[name=form_splitter_value]').val();

			}
			htmlForm.submit(function() {
				htmlForm.useByPassable = ($('input[name=useByPassable]').val() == "1");//AFF-622
				$('#Eu_sm_formSpec_error_block').hide();
				var lang 			= $('html').attr('lang');
				var messageIn 		= '';
				var message 		= '';
				var messageToTest	= '';
				var errorMessage	= '';
				var tabError		= '?';
				var separateur		= '';
				if(lang=='fr'){
					message 		= 'Veuillez :\n';
					errorMessage	= 'Nous avons besoin de vous sur les points suivants';
				}
				else{

					message 		= 'Please :\n';
					errorMessage	= 'We need your attention';
				}
				messageToTest		= message;

				$('[id^=result_error_]',htmlForm).hide();
				var errorTab = {};
				var valueTab = {};
				var formDef_fields_limited = {};
				if (multiFormMode){
					if( multiFormMode_step==1){
						var doIconcat = true;
						jQuery.each(formDef.fields,function(fieldName,test){
							if (doIconcat || (!doIconcat && fieldName.replace('_saisie','')==multiFormMode_split)){
								formDef_fields_limited[fieldName]=test;
							}
							if (fieldName.replace('_saisie','')==multiFormMode_split){
								doIconcat=false;
							}
						});
					}
					if( multiFormMode_step==2){
						var doIconcat = false;
						jQuery.each(formDef.fields,function(fieldName,test){
							if (!(fieldName.replace('_saisie','')==multiFormMode_split) && doIconcat){
								formDef_fields_limited[fieldName]=test;
							}
							if (fieldName.replace('_saisie','')==multiFormMode_split){
								doIconcat=true;
							}
						});
					}
				}else{
					formDef_fields_limited= formDef.fields;
				}

				jQuery.each(formDef_fields_limited,function(fieldName,test){
					if (test.selector){
						var field = $(test.selector,htmlForm);
					}else{
						var field = $('[name=form_data__'+fieldName+']',htmlForm);
					}
					if (htmlForm.useByPassable){
						if (!(typeof(test.notByPassable)!='undefined' && (test.notByPassable!='' || (test.notByPassable!='' && /^check_(.*)/.test(test.notByPassable))))) {
							return true;
						}else{
							if (htmlForm.useByPassable && typeof(test.notByPassable)!='undefined' && (test.notByPassable!='' && /^check_(.*)/.test(test.notByPassable))) {
								test.test_function = test.notByPassable.replace(/^check_/,'');
							}
						}
					}



					var fieldNameErrorId = fieldName.replace(/crit_/,'') .replace(/_saisie/,'');
					if (test.test_function && checkContainer["check_" + test.test_function])
					{
						if (field && (messageIn = checkContainer['check_'+test['test_function']](field,htmlForm,test))){
							message +='- ' +messageIn+'\n';
							$('#result_error_'+fieldNameErrorId+'',htmlForm).show();
							//log des erreurs
							errorTab['_'+fieldNameErrorId] = messageIn;//erreurs renvoyees
							tabError += separateur+fieldNameErrorId+'='+messageIn;
							valueTab['_'+fieldNameErrorId] = field.val();//valeurs entrees
							separateur 	= '&';
							//fieldNameErrorId - messageIn
						}else{
							if (test.js_function && field && (messageIn = checkContainer['check_'+test['js_function']](field,htmlForm,test))){
								message +='- ' +messageIn+'\n';
								$('#result_error_'+fieldNameErrorId+'',htmlForm).show();
							}
						}
					}
				});
				if(message!=messageToTest){
					//envoi du msg de log d'erreurs
					$.ajax({
						method	: "post", url: "/log_error/",
						data	: {
							ajax_error_log	: errorTab,
							ajax_value_log	: valueTab,
							page			: formDef.className,
							id_activite		: $('input[name=id_activite]').val()
						}

					});//WEBSITE-993
				}

				//$('#Eu_sm_formSpec_error_block').hide();
				if(message!=messageToTest){
					$('#Eu_sm_formSpec_error_block').show();
					$('html').animate({scrollTop : 0},'slow');
					//alertError(errorMessage,message);//nouvel affichage
					setIndications();
					return false;
				}else{
					if (multiFormMode && multiFormMode_step==1){
						$('#form_splitter_part1').hide();
						$('#form_splitter_part2').show();
						multiFormMode_step = 2;
						$('input[name=submitPreviousJS]').show().unbind('click').click(function(){
							$('#form_splitter_part1').show();
							$('#form_splitter_part2').hide();
							$('input[name=submitPreviousJS]').hide();
							multiFormMode_step = 1;
							return false;
						});
						return false;
					}else{
						return true;
					}
				}
			});
		}
	});

	$('.contact_form2').submit(function() {
		var lang 			= $('html').attr('lang');
		var returnStr		= '';
		var errorMessage	= '';
		var var_return 		= true;
		if(lang=='fr'){
			returnStr		= 'Nous avons besoin de vous sur les points suivants :';
			errorMessage	= 'Nous avons besoin de vous sur les points suivants';
		}
		else{
			returnStr		= 'We need you to fill these fields :';
			errorMessage	= 'We need your attention';
		}
		$('.field_obligatoire').each(function(field) {
			if ($(this).val()==''){
				var_return = false;
				returnStr += '\n- '+this.id;
			}
		});
		if (!var_return){
			setIndications();//on remet les exemples si necessaire
			alertError(errorMessage,returnStr);
		}
		return var_return;
	});


	if (jQuery.browser.msie) {
		$('.bt_howitwork').click(function() {
			//$('.cadre_full select').addClass('selectHidden').hide();
			$('.howitwork').show();
		});

		$('.bt_howitwork').mouseout(function() {
			//$('.selectHidden').removeClass('selectHidden').show();
			$('.howitwork').hide();
		});

	}
	else{
		$('.bt_howitwork').click(function() {
			$('.howitwork').fadeIn('slow', function() {
			});
		});

		$('.bt_howitwork').mouseout(function() {
			//$('.selectHidden').removeClass('selectHidden').show();
			$('.howitwork').fadeOut('slow', function() {
			});
		});
	}

	$(function(){
		positionFooter();
		function positionFooter(){
			if($(document.body).height() < $(window).height()){
				$("#footer").css({
					position: "absolute",
					top: ($(window).scrollTop()+$(window).height()-$("#footer").height())+"px"
				});
			}
		}
		$(window).scroll(positionFooter).resize(positionFooter);
	});

	/*moteur de recherche*/
	$('#form_search>#select_activite').change(function(){
		window.location = $(this).val();
	}).select(function(){
		window.location = $(this).val();
	});

	$('#form_search').submit(function() {
		if ($('#keywords').val() == '' || $('#keywords').hasClass('style_indications')){
			return false;
		}
		return true;
	});

	/*id_demandeur reset onchange form2*/
	$('.main_forms_step2').each(function(){
		$(this).change(function(){
			$('#id_demandeur2').val('');
		});
	});


	//$('#form1').submit(formSRSubmit);


/*************************** Form 2 - info perso ***************************/


	// Masquage de toutes les erreurs
	function hideErrorFormStep2(){
		$('.main_forms_step2 [id^=error_]').hide();
	}

// pas utilisé en nt uk SR
	function checkPostCode(toCheck) {
		var lang 		= $('html').attr('lang');
		var postCode 	= toCheck;
		var valid 		= false;

		// Si le code postal est vide
		if(postCode == '') {
			return false;
		}
		else{
			if(lang=='fr'){
				// Si le code postal a 5 chiffres
				if (/^[0-9]{4,5}$/.test(postCode)){
					valid	= true;
				}

			}
			else{
				// Permitted letters depend upon their position in the postcode.
				var alpha1 = "[abcdefghijklmnoprstuwyz]";                       // Character 1
				var alpha2 = "[abcdefghklmnopqrstuvwxy]";                       // Character 2
				var alpha3 = "[abcdefghjkstuw]";                                // Character 3
				var alpha4 = "[abehmnprvwxy]";                                  // Character 4
				var alpha5 = "[abdefghjlnpqrstuwxyz]";                          // Character 5

				// Array holds the regular expressions for the valid postcodes
				var pcexp = new Array ();
				// Expression for postcodes: AN NAA, ANN NAA, AAN NAA, and AANN NAA
				pcexp.push (new RegExp ("^([a-z][a-z]?[0-9]{1,2})(\\s*)([0-9][a-z][a-z])$","i"));
				// Expression for postcodes: ANA NAA
				pcexp.push (new RegExp ("^([a-z][0-9][a-z])(\\s*)([0-9][a-z][a-z])$","i"));
				// Expression for postcodes: AANA  NAA
				pcexp.push (new RegExp ("^([a-z][a-z]?[0-9][a-z])(\\s*)([0-9][a-z][a-z])$","i"));
				// Exception for the special postcode GIR 0AA
				pcexp.push (/^(GIR)(\s*)(0AA)$/i);
				// Standard BFPO numbers
				pcexp.push (/^(bfpo)(\s*)([0-9]{1,4})$/i);
				// c/o BFPO numbers
				pcexp.push (/^(bfpo)(\s*)(c\/o\s*[0-9]{1,3})$/i);

				var i=0;
				// Check the string against the types of post codes
				for (i=0; i<pcexp.length; i++) {
					if (pcexp[i].test(postCode)) {
						// The post code is valid - split the post code into component parts
						pcexp[i].exec(postCode);

						// Copy it back into the original string, converting it to uppercase and
						// inserting a space between the inward and outward codes
						postCode = RegExp.$1.toUpperCase() + " " + RegExp.$3.toUpperCase();

						// If it is a BFPO c/o type postcode, tidy up the "c/o" part
						postCode = postCode.replace (/C\/O\s*/,"c/o ");

						// Load new postcode back into the form element
						valid = true;

						// Remember that we have found that the code is valid and break from loop
						break;
					}
				}
			}
		}
		// Return with either the reformatted valid postcode or the original invalid
		// postcode
		if (valid){
			return postCode;
		}
		else{
			return false;
		}
	}//checkPostCode

	/*
	function Remplace(expr,a,b) {
		var i=0
		while (i!=-1) {
			i=expr.indexOf(a,i);
			if (i>=0) {
				expr=expr.substring(0,i)+b+expr.substring(i+a.length);
				i+=b.length;
			}
		}
		return expr
	}//Remplace
	*/

	if($('#IdVille')){
		$('.DivVilleAbsente').hide();
	}
	$('#IdVille').change(function(){
		if ($(this).val()=='0'){
			$('.DivVilleAbsente').show('slow');
		}else{
			$('.DivVilleAbsente').hide('fast');
		}
	});

/****************************************************************************/


/******************** hide other text field **********************/

	$(':text[name^=critere]').each(function(){
		var that = $(this);

		var parentShowHide = function (visible){
			//console.log(that,visible,that.parent());
			if (visible){
				//a laisser en fast, ne pas mettre en normal car plante sur les forms de passage de SR
				that.parent().show('fast');
				//a laisser en fast, ne pas mettre en normal car plante sur les forms de passage de SR
			}else{
				that.parent().hide();
			}
		};
		var testIfToDisplay=function(text){
			var rtn;
			if (/^If yes/.test(text)){
				rtn = true;
			}else if (/^Other/.test(text)){
				rtn = true;
			}else if (/^Yes/.test(text)){
				rtn = true;
			}else if (/^Autre/.test(text)){
				rtn = true;
			}else if (/^Oui/.test(text)){
				rtn = true;
			}else if (/^Si oui/.test(text)){
				rtn = true;
			}else{
				rtn = false;
			}
			return rtn;
		};

		var rgx1 = new RegExp('critere\\\[(.*)\\\]\\\[saisie\\\]');

		if (match = that[0].name.match(rgx1)){
			//bloc select
			var slc = $('select[name=critere\\\['+match[1]+'\\\]\\\[valeur\\\]]');
			if (slc.length){
				slc.change(function(){
					var maCombo = $(this)[0];
					var DisplayOrNot;
					//console.log(that,maCombo);
					if (testIfToDisplay(maCombo.options[maCombo.selectedIndex].text)){
						DisplayOrNot = true;
					//}else{
						//DisplayOrNot = maCombo.selectedIndex==maCombo.options.length-1;
					}
					parentShowHide(DisplayOrNot);
				});
				that.parent().hide();
			}

			//bloc checkbox
			var checks = $(':checkbox[name^=critere['+match[1]+'][valeur]]');
			if (checks.length){
				/*var libelle = $('#label_'+(/radio_id_(.*)__/.exec(this.className))[1])[0].innerHTML;
				DisplayOrNot = false;
				if (testIfToDisplay(libelle)){
					DisplayOrNot = true;
				}*/
				$(checks[checks.length-1]).click(function(){
					parentShowHide($(this).is(':checked'));
				});
				that.parent().hide();
			}

			//bloc radio
			var radios = $('input[type="radio"][name^=critere['+match[1]+'][valeur]]');
			if (radios.length){
				$(radios).click(function(){
					var libelle = $('#label_id_'+(/radio_id_(.*)__/.exec(this.id))[1]+'__')[0].innerHTML;
					DisplayOrNot = false;
					if (testIfToDisplay(libelle)){
						DisplayOrNot = true;
						//}else{ DisplayOrNot = $(this).val()==radios.length-1;
					}
					//= testIfToDisplay(maCombo.options[maCombo.selectedIndex].text)
					parentShowHide(DisplayOrNot);
				});
				that.parent().hide();
			}
		}
	});

	$(':text[name^=form_data__]').each(function(){
		var that = $(this) ;

		var parentShowHide = function (visible){
			//console.log(that,visible,that.parent());
			if (visible){
				//a laisser en fast, ne pas mettre en normal car plante sur les forms de passage de SR
				that.parent().show('fast');
				//a laisser en fast, ne pas mettre en normal car plante sur les forms de passage de SR
			}else{
				that.parent().hide();
			}
		};
		var testIfToDisplay=function(text){
			var rtn;
			if (/^If yes/.test(text)){
				rtn = true;
			}else if (/^Other/.test(text)){
				rtn = true;
			}else if (/^Yes/.test(text)){
				rtn = true;
			}else if (/^Autre/.test(text)){
				rtn = true;
			}else if (/^Oui/.test(text)){
				rtn = true;
			}else if (/^Si oui/.test(text)){
				rtn = true;
			}else{
				rtn = false;
			}
			return rtn;
		};

		if (match = that[0].name.match(new RegExp('form_data__(.*)_saisie'))){
			//bloc select
			var slc = $('select[name=form_data__'+match[1]+']');
			if (slc.length){
				slc.change(function(){
					var maCombo = $(this)[0];
					var DisplayOrNot;
					if (testIfToDisplay(maCombo.options[maCombo.selectedIndex].text)){
						DisplayOrNot = true;
					}
					parentShowHide(DisplayOrNot);
				});
				//that.parent().hide();
				slc.change();
			}

			//bloc checkbox
			var checks = $(':checkbox[name^="form_data__'+match[1]+'__check__"]');
			if (checks.length){
				var labelLast = $('label[for^='+checks[checks.length-1].id+'].lastCheckboxInSrFormField').html();
				console.log(labelLast );
				if (testIfToDisplay(labelLast)){
					$(checks[checks.length-1]).click(function(){
						parentShowHide($(this).is(':checked'));
					});
				}
				that.parent().hide();
				parentShowHide( testIfToDisplay(labelLast) && $(checks[checks.length-1]).is(':checked'));
			}

			//bloc radio
			var radios = $(':radio[name=form_data__'+match[1]+']');
			if (radios.length){
				$(radios).click(function(){
					parentShowHide( testIfToDisplay($('label[for='+this.id+']').html()));
				});

				that.parent().hide();
				$(radios).each(function(){
					if (testIfToDisplay($('label[for='+this.id+']').html()) && $(this).is(':checked')){
						parentShowHide( true);
					}
				});
			}
		}
	});

/************************************************************************/

/*********************************** SP *********************************/

	var IE6 = false;
	var strChUserAgent = navigator.userAgent;
	var intSplitStart = strChUserAgent.indexOf("(",0);
	var intSplitEnd = strChUserAgent.indexOf(")",0);
	var strChStart = strChUserAgent.substring(0,intSplitStart);
	var strChMid = strChUserAgent.substring(intSplitStart, intSplitEnd);
	var strChEnd = strChUserAgent.substring(strChEnd);
	if(strChMid.indexOf("MSIE 6") != -1) {
		return false;
	}//on desactive le jquery pour ie6

	$(".register_activity input[type=checkbox]").css('visibility','hidden');
	//$(".register_activity").addClass('closed');
	if (($(".selectorCheckboxOtherActivity:checkbox:not(:checked)",".register_activity")).length>0){
		$('#register_activity_other_input').hide();	/* ---- WEBSITE-610 ---- */
	}


	$(".register_activity .select_all").click(function(e){
		console.log($(this).parent().parent());
		var li = $('li',$(this).parent().parent());
		jQuery.each(li,function(k,v){
			$(v).addClass('selected');
			$(v).find(":checkbox").attr("checked","checked");
		});
		return false;

	});
	$(".register_activity .unselect_all").click(function(e){
		var li = $('li',$(this).parent().parent());
		jQuery.each(li,function(k,v){
			$(v).removeClass('selected');
			$(v).find(":checkbox").attr("checked","");
		});
		return false;

	});


	$(".register_activity li").click(
		function(event) {
			event.preventDefault();
			if ($(this).find(":checkbox").attr('checked')){
				$(this).removeClass('selected');
				$(this).find(":checkbox").attr("checked","");
			}else{
				$(this).addClass('selected');
				$(this).find(":checkbox").attr("checked","checked");
			}
		}
	);

	/* ---- WEBSITE-610 ---- */
	$(".register_activity td.tick").click(
		function(event) {
			event.preventDefault();
			if ($(this).find(":checkbox").attr('checked')){
				$(this).removeClass('tickticked');
				$(this).find(":checkbox").attr("checked","");
				/*if ($(this).find(":checkbox").hasClass('selectorCheckboxOtherActivity')){
					$('#register_activity_other_input').hide();
				}*/
			}else{
				$(this).addClass('tickticked');
				$(this).find(":checkbox").attr("checked","checked");
				/*if ($(this).find(":checkbox").hasClass('selectorCheckboxOtherActivity')){
					$('#register_activity_other_input').show('fast');
				}*/
			}
		}
	);

	$(".register_activity td.libele").click(
		function(event) {
			var tdTick = $(this).closest('tr').find('.tick');

			event.preventDefault();
			if (tdTick.find(":checkbox").attr('checked')){
				tdTick.removeClass('tickticked');
				tdTick.find(":checkbox").attr("checked","");
				/*if ($(this).find(":checkbox").hasClass('selectorCheckboxOtherActivity')){
					$('#register_activity_other_input').hide();
				}*/
			}else{
				tdTick.addClass('tickticked');
				tdTick.find(":checkbox").attr("checked","checked");
				/*if ($(this).find(":checkbox").hasClass('selectorCheckboxOtherActivity')){
					$('#register_activity_other_input').show('fast');
				}*/
			}
		}
	);
	/* ---- fin WEBSITE-610 ---- */

	$(".register_activity .category_name").click(function(e){
		var par = $(this).parent();
		if (par.hasClass('closed')){
			$('.contenu',par).slideDown('fast',function(){
				par.removeClass('closed');
			});
		}else{
			$('.contenu',par).slideUp('fast',function(){
				par.addClass('closed');
			});
		}
	});


	$(".register_activity li").click(function (e,a,b,c){
		var checkbox = $(this)[0].children[0];

		//console.log(checkbox);
		//if ($(this)[0].children[0])
	});

	$(".register_activity td").each(function (k,v){
		$(v).find(":checkbox:checked").each(function (kk,vv){
			$(v).addClass('tickticked');
		});
	});

	$(".register_activity li").each(function (k,v){
		$(v).find(":checkbox:checked").each(function (kk,vv){
			$(v).addClass('selected');
		});
	});

	$("input[name=submitPrevious]").show().click(function(){
		$("#postPrevious").submit();
	});


	/* formSP1Submit test */
	function formSP1Submit(){
		var isGood = false;
		var missingStr = 'Please select a least one trade';

		$(this).find('input[type=checkbox]').each(function(k,v){
			if (v.checked == true) {
				isGood = true;
			}
		});

		if (!isGood){
			alertError('We need your attention',missingStr);
			setIndications();
			return false;
		}
	}//formSP1Submit

	$('#formSP1').submit(formSP1Submit);

	/* formSP2Submit test */
	function formSP2Submit(){
		var isChecked 		= false;
		var isGood 			= false;
		var missingStr 		= '';

		$(this).find('input[type=checkbox]').each(function(k,v){
			if (v.checked == true) {
				isChecked = true;
			}
		});

		if(!isChecked) {
			if (checkPostCode($('#postcode').val())) {
				isGood = true;
			}//pas de cochage mais le code postal est bon
			else {
				missingStr = 'The Post code you entered is incorrect';
			}

			if ($('#postcode').val() == '') {
				missingStr = 'Please select a least one area';
			}
		}
		else {
			isGood = true;
		}

		if (!isGood){
			alertError('We need your attention',missingStr);
			setIndications();
			return false;
		}
	}//formSP2Submit

	$('#formSP2').submit(formSP2Submit);


	/* formSP3Submit test */
	function formSP3Submit(){
		var isGood = true;
		var missingStr = 'Please: \n';
		var missingStrSepa = '';
		$('.requiredField').each(function(k,v){

			if (v.name=='code_postal' && v.value!='' && $('#pays')[0].value == 'United Kingdom'){
				if (!checkPostCode(v.value)){
					missingStr = missingStr + missingStrSepa + "- Incorrect Post code" ;
					missingStrSepa = '\n';
					isGood = false;
				}
			}

			if (v.name=='telephone' && v.value!='' && $('#pays')[0].value == 'United Kingdom')
			{
				if (!/^0[123578][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]$/.test(v.value))
				{
					missingStr = missingStr + missingStrSepa + "- Incorrect main phone number" ;
					missingStrSepa = '\n';
					isGood = false;
				}
			}

			if ((v.type=='select-one' && v.selectedIndex==0) ||
				(v.type=='text' && v.value == '') ||
				(v.type=='textarea' && v.value == '')
			){
				isGood = false;
				missingStr = missingStr + missingStrSepa + "- " + tab_element[v.name];
				missingStrSepa = '\n';
			}
		});

		if (!isGood){
			alertError('We need your attention',missingStr);
			setIndications();
			return false;
		}
	}//formSP3Submit

	$('#formSP3').submit(formSP3Submit);



/********************************** END SP **************************************/

});
