/*
#################################
[QA] [POUR MISE EN PROD] WEBSITE-1585 : validate phone number on form using 3rd party validation service
[QA] [POUR MISE EN PROD] WEBSITE-1510 : Integration SR LIFE CYCLE- Thank you page-PP matches
#################################
*/

(function($) {

	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() {};
		}
	}

	createCORSRequest = function (method, url){
		var xhr = new XMLHttpRequest();
		if ("withCredentials" in xhr){
			xhr.open(method, url, true);
		} else if (typeof XDomainRequest != "undefined"){
			xhr = new XDomainRequest();
			xhr.open(method, url);
		} else {
			xhr = null;
		}
		return xhr;
	};
	Eu = {};
	Eu.sm = {};
	Eu.sm.formSpec = [];
	Eu.sm.mainSiteUrl = '';

	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;
	};

	Eu.sm.switchText = function () {
		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'));
		}
	};


	Eu.sm.setIndications = function (){
		return $('.indications').each(function() {
			if ($(this).val() == '') $(this).val($(this).attr('title'));
			if ($(this).val() == $(this).attr('title')) $(this).addClass('style_indications');

		});
	};

	Eu.sm.alertError = function (title,msg){
		var msgInner = msg.replace(/\n/g,'<br />');
		$('<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');
				}
			}
		});
		try{
			if (typeof(Eu.sm.validationFailed) == 'function' ){
				Eu.sm.validationFailed(msg);
			}
		} catch (e){}
	};

	Eu.sm.createTooltip = function(field, message){
		field.qtip({
			content : message,
			show : {
//				when :	false,
//				ready :	false,
				event : 'unfocus'
			},
			hide : {
				event : 'focus change'
			},
			position : {
				at : 'right center',
				my : 'left center'
			}
		}).qtip('show');
	};

	Eu.sm.checkContainer = {

		check_txtPostcode : function (field,form,test){
			if (test.errorEmpty){
				if (Eu.sm.checkContainer.check_txtFieldNotNull(field,form,test)){
					return test.errorEmpty;
				}
			}
			if (test.countryField) {
				var country = ''+$('select[name=form_data__'+test.countryField+'], input[name=form_data__'+test.countryField+'][type=hidden]',form).val();
			}

			var lang = test['lang'];
			var postCode = field.val();
			postCode = (postCode+'').replace(/ /g,'');//suppr espaces
			field.val(postCode);//reinjecte le cp sans espace
			switch (lang){
				case 'TRL_DE':
					if ( !/^[0-9]{4,5}$/.test(postCode)){
						return test.errorMessage;
					}
				break;
				case 'TRL_FR':
					if (test.errorMessage != 'ajax') {
						if ( /^[0-9]{4}$/.test(postCode)){
							postCode = '0'+postCode;
							field.val(postCode);//on rajoute le 0 si 4 chiffres
						}
					}//pour ne pas ajouter le 0 alors qu'on est en train de taper
					if (test.countryField) {
						if (country.toUpperCase()=='FRANCE' && !/^[0-9]{4,5}$/.test(postCode)){
							return test.errorMessage;
						}
					}else{
						if ( !/^[0-9]{4,5}$/.test(postCode)){
							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 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+'], input[name=form_data__'+test.countryField+'][type=hidden]',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-new.js');
					break;
			}
			return false;
		},

		check_txtPhone : function (field,form,test){
			if ( !trim(field.val()) && (test['mandatory'] == false) ){
				return false;
			}
			else if (test.errorEmpty){
				if (Eu.sm.checkContainer.check_txtFieldNotNull(field,form,test)){
					return test.errorEmpty;
				}
			}
			if (test.countryField) {
				var country = ''+$('select[name=form_data__'+test.countryField+']',form).val();
			}
			var val = (trim(field.val())+'').replace(/\./g,'').replace(/\-/g,'').replace(/ /g,'');
			if (val!=field.val() && !test.noalterfield){
				field.val(val);
			}
			var lang = test['lang'];
			switch (lang){
				case 'TRL_FR':
					if (test.countryField) {
						if (!(/^(0[0-9])[0-9]{8}$/).test(trim(val)) && (country.toUpperCase()=='FRANCE')){
							return test.errorMessage;
						}
					}else{
						if ( !/^(0[0-9])[0-9]{8}$/.test(val)){
							return test.errorMessage;
						}
					}
					break;
				case 'TRL_DE':
					if (test.countryField) {
						if (!(/^0[0-9]{10,}$/).test(trim(val)) && (country.toUpperCase()=='DEUTSCHLAND')){
							return test.errorMessage;
						}
					}else{
						if ( !/^0[0-9]{10,}$/.test(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(val) && !(/^07[0-9]{9}$/).test(val))){
							return test.errorMessage;
						}
					}else{
						if (!(/^0[12358][0-9]{8,9}$/).test(val) && !(/^07[0-9]{9}$/).test(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-new.js');
					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){
			console.log(field);
			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?test.errorMessage:'bad email';
			}
			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?test.errorMessageSyntax:'bad email syntax';
			}
			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_txtWebsiteValidSyntax : function (field,form,test){
			if (field.val()==''){
				return false;
			}
			if (!/^(http:\/\/)?[_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 (test.txtFieldNotNullIfZero){
				if (field.val()==0 && (''+$('input[name="form_data__'+test.txtFieldNotNullIfZero+'"]').val())==''){
					return test.errorMessage;
				}
			}

			if (!field.val() || field.val()=='Choose'){
				return test.errorMessage;
			}
			return false;
		}
	};

	trim  = function (myString) {
		//return (myString+'').replace(/^\s+/g,'').replace(/\s+$/g,'');
		return (myString+'').replace(/(\s*)/g,"");
	};



	initMapSr = function (MapId,arrSR,frontDataUrl,defaultZoom,withDetail,globalObject){
		if (!defaultZoom){
			defaultZoom=13;
		}
		if (!$("#"+MapId)){
			return;
		}
		if (arrSR.length == 0){
			$("#"+MapId).hide();
			return;
		}


		if (withDetail==undefined) withDetail=true;

		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 = [];


		if (withDetail){
			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);
			if (withDetail){
				google.maps.event.addListener(marker[k], 'click', function(){srInfoWindow(k);});
			}
		});
		if (nb>1){
			map.fitBounds(bounds);
		}
		if (globalObject!=undefined){
			globalObject= map;
		}
	};

	$(document).ready(function(){

		//WEBSITE-1709
		if ($('#dialogBlockNewsletterOk').length && $('#dialogBlockNewsletterOk').length==1){
			$("#dialogBlockNewsletter").dialog({autoOpen	: true,
												height		: 200,
												width		: 380,
												modal		: true,
												draggable	: true,
												resizable	: false,
												buttons		: {"Close" : function(){$(this).dialog("close");}}});
		}
		if ($('#formNumDevis').length && $('#formNumDevis').length==1){
			getListProMatching($('#formNumDevis').html(),0);
			$('p.loader').removeClass('hidden');
		}

		$('input[name=js_enabled]').val('1');
		Eu.sm.lang = $('html').attr('lang');

		// @Jira : WEBSITE-1770
		// Sous Wordpress la fonction language_attributes() retourne la locale
		// On la convertit pour être compatible avec les sites SM
		if (Eu.sm.lang == 'fr-FR')  {
			Eu.sm.lang = 'fr';
		}

		Eu.sm.mainSiteUrl = 'http://';
		if (/^dev-/.test(document.domain)){
			Eu.sm.mainSiteUrl=Eu.sm.mainSiteUrl+'dev-';
		}
		if (/^local-/.test(document.domain)){
			Eu.sm.mainSiteUrl=Eu.sm.mainSiteUrl+'local-';
		}
		if (Eu.sm.lang=='en'){
			Eu.sm.mainSiteUrl=Eu.sm.mainSiteUrl+'www.servicemagic.co.uk';
		}
		if (Eu.sm.lang=='fr'){
			Eu.sm.mainSiteUrl=Eu.sm.mainSiteUrl+'www.123devis.com';
		}
		if (Eu.sm.lang=='de'){
			Eu.sm.mainSiteUrl=Eu.sm.mainSiteUrl+'www.servicemagic.de';
		}

		Eu.sm.divAutreVilleDisplay = 0;
		Eu.sm.abtestversion = $('input[name=jsAbTestVersion]').val();
		if (typeof(Eu_sm_formSpec_init) !== 'undefined'){
			Eu_sm_formSpec_init();
		}

		if ((Eu.sm.abtestversion == 'B68' || Eu.sm.abtestversion == 'C68') && Eu.sm.lang == 'en') {
			$('.required:visible:not(.preFilled):not([type=hidden])',$('.main_forms_step2')).addClass('notPreFilled').bind('focus.blurPrefilled',function(e){
				$(this).removeClass('notPreFilled').unbind('focus.blurPrefilled');
			});
		}

		if (
			((Eu.sm.abtestversion == 'B54' || Eu.sm.abtestversion == 'C54') && Eu.sm.lang == 'fr') ||
			((Eu.sm.abtestversion == 'B70' || Eu.sm.abtestversion == 'C70') && Eu.sm.lang == 'en')
			)
		{
			if ($('input[name=con_id]').val() != '') {
				$('#fieldsetCp').hide();

				if (Eu.sm.lang == 'fr') {
					$('input[name=submitForm]').val('Valider');
				}
				else {
					$('input[name=submitForm]').val('Get Quotes for '+$('.mini_header h1').text());
				}
			}
			$('.coordonnees').show();
			$('input[name=byPassStep2]').val('1');
			$('.idUpdateCoordinate').bind('click',function(e){
				$('input[name=byPassStep2]').val('0');
				$('.coordonnees').hide('fast');
				$('#fieldsetCp').show('fast');
				if (Eu.sm.lang == 'fr') {
					$('input[name=submitForm]').val('Étape suivante');
				}
				else {
					$('input[name=submitForm]').val('Next step');
				}
	/*
				var frm = $(this).closest('form');
				frm.attr('action',frm.attr('action') +'?submitForm=true');
				frm.submit();
	*/
			});
		}

		$('#containerCountry').hide();
		$('#id_international').click(function(){
			if ($('#id_international').val() == 0) {
				$('#containerCountry').show('fast');
				$('#id_international').val('1');
			}
			else {
				$('#containerCountry').hide('fast');
				$('#id_international').val('0');
			}
		});

		$('#divAutreVille').hide();
		$('#linkAutreVille').show();//c'est le js qu'il affiche erreur lieu car inutile si on a pas de js
		$('#linkAutreVille').click(function(){
			if (Eu.sm.divAutreVilleDisplay == 0) {
				$('#divAutreVille').show('fast');
				Eu.sm.divAutreVilleDisplay = 1;
			}
			else {
				$('#divAutreVille').hide('fast');
				Eu.sm.divAutreVilleDisplay = 0;
			}
		});//WEBSITE-1239

	//WEBSITE-1214
		if  ( ($("[name=form_data__cas_cp]").val() == 3) || ($("[name=form_data__cas_cp]").val() == 2)) {
			delete (Eu.sm.formSpec[0].fields.ville_absente);
			delete (Eu.sm.formSpec[0].fields.id_ville);
		}
		if ($("[name=form_data__cas_cp]").val() == 1) {
			delete (Eu.sm.formSpec[0].fields.id_ville);
		}

		if ((Eu.sm.lang == 'fr')||(Eu.sm.lang == 'de')) {
			$('.divAjaxOnCp').hide();
			var form_data__cp_suggestions=[];

			$("[name=form_data__ville_absente]").hide();
			$('#linkAutreVilleAjax').click(function(){
				if (Eu.sm.divAutreVilleDisplay == 0) {
					$("[name=form_data__ville_absente]").show('fast');
					Eu.sm.divAutreVilleDisplay = 1;
				}
				else {
					$("[name=form_data__ville_absente]").hide('fast');
					$("[name=form_data__ville_absente]").val('');
					Eu.sm.divAutreVilleDisplay = 0;
				}
			});//WEBSITE-1356

			$("[name=form_data__cp]").bind('keydown.antiPost',function(){
				console.log('1)'+$("[name=form_data__cp]").val());/////////////////////////////////////////
				console.log('antiPost active');
				$("[name=form_data__cp]").addClass('antiPost');
			}).bind('change.antiPost',function(){
				console.log('antiPost desactive3');
				$("[name=form_data__cp]").removeClass('antiPost');
			}).autocomplete({
				delay : 300,
				source: function(req, add){
					console.log('source');
					this.close();
					var that=this.element[0];
					that.addMethod = null;
					that.suggestions = [];
					if (Eu.sm.checkContainer.check_txtPostcode($("[name=form_data__cp]"),$('form.main_forms_step1'),{'errorEmpty':'ajax','errorMessage':'ajax','lang':'TRL_FR'})){
						$("[name=form_data__cp]").removeClass('ui-autocomplete-loading');
						$('.divAjaxOnCp').hide();
						return false;
					}//evite de poster pour rien

					//Eu.sm.formSpec[0].fields.ville_absente= {"test_function":"txtFieldNotNull","errorMessage":"TRL_SRFORM_VILLE_ERROR","dbField":"ville_absente"};
					Eu.sm.formSpec[0].fields.id_ville= {"test_function":"alwaysOk","errorMessage":"TRL_SRFORM_VILLE_ERROR","dbField":"id_ville"};
					console.log('antiPost desactive');
					$("[name=form_data__cp]").removeClass('antiPost');

					// @Jira : WEBSITE-1770
					// Modification de l'appel AJAX pour utilisation dans Wordpress
					var inWPcalled = (typeof(SMWP_SR_Forms_Params) != 'undefined');

					$.getJSON(
						!inWPcalled?'/formulaires/ajax_on_cp/'+req.term:SMWP_SR_Forms_Params.ajax_url,
						!inWPcalled?{
						}:{
							action: SMWP_SR_Forms_Params.actions.ajax_on_cp,
							ajax_cp: req.term
						},
						function(data) {
							//Eu.sm.success_ajaxOnCp(data, that, req, add);
							success_ajaxOnCp(data);
						}
					);

					var success_ajaxOnCp = function(data) {

						switch(data.cas_cp){
							case 1: // zero match
								$("#ajax_cas_cp").val('1');

								//$('.divAjaxOnCp').show();
								$('.divAjaxOnCp').hide();

								if (Eu.sm.lang == 'de') {
									$('#ajax_id_cp').val(data.id_cp);
								}

								//$('#ajax_div_ville_absente').show('fast');
								$('#ajax_div_ville_absente').hide();

								$('#ajax_commune_libelle').html(data.villes[0].libelle);

								$('#ajax_input_ville_absente').val('Code postal introuvable');
								$('#idLinkAutreVille').hide();
								delete (Eu.sm.formSpec[0].fields.id_ville);
							break;
							case 2 ://1 match
								if (Eu.sm.lang == 'de') {
									$('#ajax_id_cp').val(data.id_cp);
								}
								$('#ajax_input_ville_absente').val('');//pour écraser
								$("#ajax_cas_cp").val('2');
								$('.divAjaxOnCp').show();
								$('#ajax_div_ville_absente').show('fast');
								$('#idLinkAutreVille').show();
								$('#ajax_commune_libelle').html(data.villes[0].libelle);
								$('#ajax_hidden_id_ville').val(0);
								// renseigné en hidden dessus
								//Eu.sm.formSpec[0].fields.id_ville= {"test_function":"txtFieldNotNull","errorMessage":"TRL_SRFORM_VILLE_ERROR","dbField":"id_ville"};
								delete (Eu.sm.formSpec[0].fields.ville_absente);
							break;
							case 3 ://n match
								if (Eu.sm.lang == 'de') {
									$('#ajax_id_cp').val(data.id_cp);
								}
								$('#ajax_input_ville_absente').val('');//pour écraser
								$("#ajax_cas_cp").val('3');
								$('.divAjaxOnCp').hide();//cache dans le cas de précédentes recherches
								$('#idLinkAutreVille').show();
								$('#ajax_hidden_id_ville').show();
								$('#ajax_hidden_id_ville').val(0);
								$('#ajax_commune_libelle').html('');
								//si on ne choisit pas la ville dans le select
								delete (Eu.sm.formSpec[0].fields.ville_absente);//lève 2 erreur sinon
								jQuery.each(data.villes,function(k,v){
									that.suggestions.push({'label':v.libelle,'idVille':v.id,'value':req.term,'cp':req.term,'cas_cp':data.cas_cp});
								});
								that.addMethod = add;
							break;
						}
						add(that.suggestions);
						console.log(this.menu);
					};
				},
				select: function(e, ui) {

					console.log('antiPost desactive2');
					$("[name=form_data__cp]").removeClass('antiPost');
					$('.divAjaxOnCp').show();
					$('#ajax_div_ville_absente').show('fast');
					$('#ajax_commune_libelle').show();
					$('#ajax_hidden_id_ville').val(ui.item['idVille']);

					$('.divAjaxOnCp').show();

					//$('#ajax_input_ville_absente').val($('#ajax_input_ville_absente').attr('title'));//reinit le ville absente

					if (ui.item['idVille']==0){
						$('#ajax_input_ville_absente').val('Autre ville'); // dans le champ texte caché
						$('#ajax_commune_libelle').html('Autre'); // libelle
					}else{
						$('#ajax_commune_libelle').html(ui.item['label']);//on affiche pas autre
						delete (Eu.sm.formSpec[0].fields.ville_absente);
						$('#ajax_input_ville_absente').val('');//sinon bug lorsqu'on clique sur erreur lieu
					}
					return false; // ne pas supprimer, sert a detourner le comprotement par defaut de l'autocomplete
				}
			}).click (function(e){
				if ($(this)[0].addMethod){
					$(this)[0].addMethod($(this)[0].suggestions);
				}
			});
		}
	//FIN WEBSITE-1214

		$('.div_main_cat').hide();//ferme tout la 1ere fois
		$('.dt_main_cat').click(function() {

			if ($(this).find('a[id=a_main_cat]').hasClass('close')){
				$(this).find('a[id=a_main_cat]').removeClass('close');
			}
			else {
				$(this).find('a[id=a_main_cat]').addClass('close');
			}
			$(this).find('div').toggle();//ouvre/ferme
		});//DSGN-69

		function initFormStep1(){
			$("[name=form_data__cp]").focus();//met le focus sur le code postal
		}
		initFormStep1();
		//footer flottant always on bottom
		/*$(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);
		});*/

		// gestion du bt_howitwork
		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() {
				});
			});
		}

		/* alert remplacement */
		if (!$('form[name=formAffiliateChoice]').length) {
			Eu.sm.setIndications()
					.unbind('focus.setIndications')
					.unbind('blur.setIndications')
					.bind('focus.setIndications',Eu.sm.switchText)
					.bind('blur.setIndications',Eu.sm.switchText);
		}//AFF-749
		/* 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 ){
				var multiFormMode = ($('#form_splitter_part2').hide().length)==1;
				if (multiFormMode){
					var multiFormMode_step	= 1;
					var multiFormMode_split = 'crit_'+$('input[name=form_splitter_value]').val();
				}

				// Messages d'erreur
				//####################################################################################################################################################################################################
				Eu.sm.setIndications().unbind('focus.setIndications').unbind('blur.setIndications').bind('focus.setIndications', Eu.sm.switchText).bind('blur.setIndications', Eu.sm.switchText);

				if (Eu.sm.abtestversion == 'C65' && Eu.sm.lang == 'fr'){
					Eu.sm.TestOnFlyError = function(event){
						htmlForm.useByPassable = ($('input[name=useByPassable]').val() == "1");
						$('#Eu_sm_formSpec_error_block').hide();
						$('[id^=result_error_]', htmlForm).hide();
						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;
						}

						var thisChamp = this.name;
						var message = '';
						fieldName = thisChamp.replace('form_data__', '');
						if (formDef_fields_limited[fieldName]){
							var test = formDef_fields_limited[fieldName];
							var field = $('[name=form_data__' + fieldName + ']', htmlForm);
							var labelError = $('[id=data_' + fieldName + ']', htmlForm);
							var isError = false;
							if (test.test_function && Eu.sm.checkContainer["check_" + test.test_function]){
								if (field && (messageIn = Eu.sm.checkContainer['check_' + test['test_function']](field, htmlForm, test))){
									isError = true;
								}else if (test.js_function && field && (messageIn = Eu.sm.checkContainer['check_' + test['js_function']](field, htmlForm, test))){
									isError = true;
								}
								if (field.hasClass('antiPost')){
									isError = true;
								}
							}
							if (isError == true){
								var fieldNameErrorId = fieldName.replace(/crit_/, '').replace(/_saisie/, '');
								labelError.addClass('isOnFlyError');
								Eu.sm.createTooltip(labelError, messageIn);
//								field.addClass('isOnFlyError');
//								Eu.sm.createTooltip(field, messageIn);
							}else{
								labelError.removeClass('isOnFlyError');
								$(labelError).qtip('destroy');
//								field.removeClass('isOnFlyError');
//								$(field).qtip('destroy');
							}
						};
					};
				}
				$('.requiredField').bind('blur.onFlyError',Eu.sm.TestOnFlyError);
				Eu.sm.setIndications().unbind('focus.setIndications').unbind('blur.setIndications').bind('focus.setIndications', Eu.sm.switchText).bind('blur.setIndications', Eu.sm.switchText);
				//####################################################################################################################################################################################################


				htmlForm.submit(function(event) {
					htmlForm.useByPassable = ($('input[name=useByPassable]').val() == "1");//AFF-622
					$('#Eu_sm_formSpec_error_block').hide();
					var messageIn 		= '';
					var tabError		= '?';
					var separateur		= '';
					if (verifMode == 'autre'){
						if(Eu.sm.lang=='fr'){
							var message 					= 'Veuillez remplir :\n';
							var messageWeNeedYourAttention	= 'Merci de corriger les erreurs ci-dessous';
						}
						if(Eu.sm.lang=='de'){
							var message 					= '';
							var messageWeNeedYourAttention	= 'Bitte die unten genannten Fehler korrigieren';
						}
						else {
							var message 					= 'Please :\n';
							var messageWeNeedYourAttention	= 'We need your attention';
						}
					}
					if (verifMode == 'sr'){
						if(Eu.sm.lang=='fr'){
							message 						= 'Veuillez remplir :\n';
							messageWeNeedYourAttention		= 'Nous avons besoin de vous sur les points suivants';
						}
						if(Eu.sm.lang=='de'){
							message 						= 'Bitte :\n';
							messageWeNeedYourAttention		= 'Bitte die unten genannten Fehler korrigieren';
						}else{
							message 						= 'Please :\n';
							messageWeNeedYourAttention		= 'We need your attention';
						}
					}
					var 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){
						var labelError = $('[id=data_' + fieldName + ']', htmlForm);
						if (test.selector){
							var field = $(test.selector,htmlForm);
						}else{
							var field = $('[name=form_data__'+fieldName+']',htmlForm);
						}
						if ($(field).val() == $(field).attr('title')) {
							$(field).val('');
							//$(field).removeClass('style_indications');
						}
						if (htmlForm.useByPassable){
							if (!(typeof(test.notByPassable)!='undefined' && (test.notByPassable!='' || (test.notByPassable!='' && /^check_(.*)/.test(test.notByPassable))))) {
								return true;
							}else{
								if (typeof(test.notByPassable)!='undefined' && (test.notByPassable!='' && /^check_(.*)/.test(test.notByPassable))) {
									test.test_function = test.notByPassable.replace(/^check_/,'');
								}
							}
						}

						if (test.test_function && Eu.sm.checkContainer["check_" + test.test_function]){
							var isError = false;
							if (field && (messageIn = Eu.sm.checkContainer['check_'+test['test_function']](field,htmlForm,test))){
								isError=true;
							}else if (test.js_function && field && (messageIn = Eu.sm.checkContainer['check_'+test['js_function']](field,htmlForm,test))){
								isError=true;
							}
							if (field.hasClass('antiPost')){
								//messageIn ='too fast';//affiché avec le WEBSITE-1455 donc pas bon
								isError=true;
							}//WEBSITE-1214
							if (isError == true){
								var fieldNameErrorId = fieldName.replace(/crit_/,'') .replace(/_saisie/,'');
								message +='- ' +messageIn+'\n';
								if (verifMode == 'sr'){
									if ((Eu.sm.abtestversion == 'B65' || Eu.sm.abtestversion == 'C65') && Eu.sm.lang == 'fr'){
										Eu.sm.createTooltip(labelError, messageIn);
//										Eu.sm.createTooltip(field, messageIn);
									}else{
										$('#result_error_'+fieldNameErrorId+'',htmlForm).show();//log des erreurs
									}
								}
								errorTab['_'+fieldNameErrorId] = messageIn;//erreurs renvoyees
								valueTab['_'+fieldNameErrorId] = field.val();//valeurs entrees
								tabError += separateur+fieldNameErrorId+'='+messageIn;
								separateur 	= '&';
								//fieldNameErrorId - messageIn
								Eu.sm.setIndications().unbind('focus.setIndications').unbind('blur.setIndications').bind('focus.setIndications', Eu.sm.switchText).bind('blur.setIndications', Eu.sm.switchText);
							}
						}
					});

					//$('#Eu_sm_formSpec_error_block').hide();
					if(message!=messageToTest){
						if (verifMode == 'sr'){
							//envoi du msg de log d'erreurs
							var data	= {
								ajax_error_log	: errorTab,
								ajax_value_log	: valueTab,
								page			: formDef.className,
								id_activite		: $('input[name=id_activite]').val()
							};
							//"http://dev-"+(Eu.sm.lang=='fr'?'www.123devis.com':'www.servicemagic.co.uk')
							var request = createCORSRequest("post", Eu.sm.mainSiteUrl+"/log_error/?"+jQuery.param( data ));
							if (request){
								request.send();
							}
							$('#Eu_sm_formSpec_error_block').show();
							$('html').animate({scrollTop : 0},'slow');
						}else{
							Eu.sm.alertError(messageWeNeedYourAttention,message);
						}
						Eu.sm.setIndications();
						return false;
					}else{
						if (multiFormMode && multiFormMode_step==1){
							$('#form_splitter_part1').hide();
							$('#form_splitter_part2').show();
							multiFormMode_step = 2;
							Eu.sm.setIndications().unbind('focus.setIndications').unbind('blur.setIndications').bind('focus.setIndications', Eu.sm.switchText).bind('blur.setIndications', Eu.sm.switchText);
							$('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{
							//console.log(event,event.currentTarget,event.currentTarget.data.value,prm01,prm02,prm03);return false;
							if(formDef.antiDoublePost != undefined){
								$(formDef.antiDoublePost.toHide).hide();
								$(formDef.antiDoublePost.toShow).show();
							}
							if (formDef.ajaxPost && event.originalEvent && event.originalEvent.explicitOriginalTarget && event.originalEvent.explicitOriginalTarget.name == 'submitForm' && !formDef.ajaxPostOnClick ){
								return true;
							}
							if (verifMode == 'sr' && formDef.ajaxPost){
								var queryToPost = htmlForm.serialize();
								$.ajax({
									url		: htmlForm.attr('action')+'?'+queryToPost+'&submitForm=true&ajaxPost=1',
									context	: document.body,
									success	: function(){
										$.prettyPhoto.open('#janrain_engage','Title','');
										//var cbUrl = $('#cbUrl').text();
										//$.prettyPhoto.open('/social_network_signin.php?cbUrl='+cbUrl+'&iframe=true','','');
									}
								});
								return false;
							}else{
								return true;
							}
							return true;
						}
					}
				});
			}
		});

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

		$('#form_search').submit(function() {
			if (typeof($('#keyword').val())=='undefined' ||$('#keyword').val() == '' ){
				return false;
			}
			return true;
		});

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

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



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

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

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

		/******************** 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 if (/^Ja/.test(text)){
					rtn = true;
				}else if (/^Andere/.test(text)){
					rtn = true;
				}else{
					rtn = false;
				}
				return rtn;
			};

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

			if (match = $(this)[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 if (/^Ja/.test(text)){
					rtn = true;
				}else if (/^Andere/.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 *********************************/
		if ($(".register_activity").length >0){
			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){
				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 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');
				});
			});
		}
		/********************************** END SP **************************************/

	});




	/* --- DSGN-63 --- */
	$(document).ready(function(){

		var prefixUrl = '';
		if (/^dev-/.test(document.domain)){
			prefixUrl = 'dev-';
		}
		else if (/^local-/.test(document.domain)){
			prefixUrl = 'local-';
		}

		if ($('div.plan').hasClass("ok")){
			if (Eu.sm.globalMapPros==undefined){
				Eu.sm.globalMapPros={};
				initMapSr('mapSrCanvas',arrDisplayedSR,'http://'+prefixUrl+'front.data.servicemagic.eu/',8,false,Eu.sm.globalMapPros);
			}
		}
		$('a#plan').click(function(event){
			if ($('div.plan.hidden')){
				$('a#plan').addClass('actif');
				$('a#photos').removeClass('actif');
				$('div.plan').removeClass('hidden');
				$('div.photo').addClass('hidden');
				if (Eu.sm.globalMapPros==undefined){
					Eu.sm.globalMapPros={};
					initMapSr('mapSrCanvas',arrDisplayedSR,'http://'+prefixUrl+'front.data.servicemagic.eu/',8,false,Eu.sm.globalMapPros);
				}
			}
		});
		$('a#photos').click(function(event){
			if ($('div.photo.hidden')){
				$('a#photos').addClass('actif');
				$('a#plan').removeClass('actif');
				$('div.photo').removeClass('hidden');
				$('div.plan').addClass('hidden');
				if (Eu.sm.globalMapPros==undefined){
					Eu.sm.globalMapPros={};
					initMapSr('mapSrCanvas',arrDisplayedSR,'http://'+prefixUrl+'front.data.servicemagic.eu/',8,false,Eu.sm.globalMapPros);
				}
			}
		});
	});

	/* --- fin DSGN-63 --- */

	/* --- CYRCLI-1211 --- */

	getListProMatching = function(sre_id,nb){
		$.getJSON('getListProMatching/' + sre_id + '/'+nb,
			function(data) {
				if (data.notAvailable == 1){
					if(nb<=4){
						var str = "getListProMatching("+sre_id+","+(nb+1)+")";
						console.log(str);
						setTimeout(str,1000);
					}else{
						$("p.loader").addClass('hidden');
					}
				}else{
					$("div#dynamic_validation_header").html(data.dynamic_validation_header.value);
					$("div#dynamic_validation_listPro").html(data.dynamic_validation_listPro.value);

					var time=0;
					var nbChild = $("div#dynamic_validation_listPro").children('div.hidden').length;
					$("div#dynamic_validation_listPro").children('.proMatching_show').children('div.hidden').each(function(k,v){
						$(this).delay(time).fadeIn(1000);
						time=time+2000;
					});
					$("div#dynamic_validation_additional_text").delay(time).queue(function(n) {
						//if(nbChild==k+1){ //sur le dernier
							$('#dynamic_validation_additional_text').html(data.dynamic_validation_additional_text.value).slideDown('slow');
						//}
						n();
					}).fadeIn(1000);

					$("a[rel=showProfileSP]").unbind("click").click(function(){
						iframeJqueryUi($(this).attr('href'),$(this).attr('title'),780,600);

						return false;
					});

//						$("a[rel^='prettyPhoto']").prettyPhoto({
//							animationSpeed: 'fast', /* fast/slow/normal */
//							opacity: 0.80, /* Value between 0 and 1 */
//							showTitle: false, /* true/false */
//							allowresize: false, /* true/false */
//							default_width: 740,
//							default_height: 600,
//							theme: 'facebook' /* light_rounded / dark_rounded / light_square / dark_square / facebook */
//						});

					$("a.requestCall").click(function(e,u){
						showDialogThankYouPage('Call', $(this));
						return false;
					});
					$("a.requestMail").click(function(e,u){
						showDialogThankYouPage('Email', $(this));
						return false;
					});

					/* --- WEBSITE-1202 / WEBSITE-1207 --- */
					$('p.pro_matching_show_info a, p.sm_pro_matching_show_info a').click(function(){
						if ($(this).next().attr('class')=='sm_pro_show_info hidden'){
							$(this).addClass('actif');
							$(this).next().removeClass('hidden');

							var email = $('.requestCall_Email',$(this).closest('div')).html();
							if(email!=''){
								var aAction = $(this).attr('id').split('_');
								var action=aAction[0];
								var srid = $('.requestCall_SR',$(this).closest('div')).html();
								var idClient = $('.requestCall_IdClient',$(this).closest('div')).html();
								var idDemandeur = $('#id_demandeur').html();
								$.ajax({
									type	: 'POST',
									url		: 'contactRequestProMatching/'+idClient+'/'+email+'/'+srid+'/'+action+'/'+idDemandeur,
									success	: function(data) {
									}
								});
							}
						}
						return false;
					});
					/* --- fin WEBSITE-1202 / WEBSITE-1207 --- */
				}
			}
		);
	};

	showDialogThankYouPage = function (action, obj){
		var email = $('.requestCall_Email',obj.closest('div')).html();
		if(email!=''){
			var rs = $('.requestCall_RS',obj.closest('div')).html();
			var srid = $('.requestCall_SR',obj.closest('div')).html();
			var idClient = $('.requestCall_IdClient',obj.closest('div')).html();
			$('.pro_name', "#dialog_request"+action ).html(rs);
			$( "#dialog_request"+action ).dialog({
				autoOpen	: false,
				height		: 320,
				width		: 655,
				modal		: true,
				draggable	: true,
				resizable	: false,
				open : function (e,u){

					Eu.sm.setIndications()
						.unbind('focus.setIndications')
						.unbind('blur.setIndications')
						.bind('focus.setIndications',Eu.sm.switchText)
						.bind('blur.setIndications',Eu.sm.switchText);

					$("#submitForm_progress"+action).click(function(){
						var msg = $('#dialog_request'+action+' #sendMailMsg').val();
						$.getJSON('sendMailProMatching/'+idClient+'/'+email+'/'+srid+'/'+action+'/?sendMailMsg='+encodeURIComponent(msg),
							function(data) {
								if(typeof(data) != 'undefined' && data != '') {
									if(data.resultatSendTitle!=null){
										$("p.titreDansJqueryUI").html(data.resultatSendTitle);
									}
									$("#dialog_request"+action+" div.sendMail").html(data.resultatSendText);
								}
							}
						);
					});
				},
				close: function() {
				}
			}).dialog( "open" );
		}
	};
	/* --- fin WEBSITE-1202 / WEBSITE-1207 --- */

	/* --- fonction pour ouverture iframe avec paramètre dans boite dialog par jquery ui --- */
	iframeJqueryUi = function (src,title,width,height){
		var iFramePP = 'iFramePP'+Math.round((Math.random()*1000));
		$('<iframe id="'+iFramePP+'"></iframe>').dialog({
			autoOpen	: false,
			height		: height,
			width		: width,
			modal		: true,
			draggable	: true,
			resizable	: false,
			title		: title,
			open: function() {
				$('#'+iFramePP).attr('src',src);
				$('#'+iFramePP).height(height-20);
				$('#'+iFramePP).width(width-20);
			},
			close: function() {
			}
		}).dialog( "open" );
	};

	/*
	* this jquery function takes inputs and on blur will autocap the first line of each word
	* call like $(selector that matches text inputs).autoCap();
	* autocalled via input.autoCap
	* WEBSITE-1653
	*/
	$.fn.autoCap = function() {
		var ac = function(itm){
			var $this = $(itm);
			var contents = $this.val();

			if (contents == '') return;
			var contentsa = contents.split(/[ ]+/);

			if ($this.attr("type") != 'text') return this;
			if ($this.attr("title") == contents) return this;

			for (var word_i in contentsa){
				var word = contentsa[word_i];
				if (word.length > 1){
					contentsa[word_i] = word.substr(0,1).toUpperCase() + word.substr(1).toLowerCase();
				}
			}
			$this.val(contentsa.join(' '));
		};
		var listoforms = [];

		this.each(function() {
			//asssign blur event
			$(this).blur(function(){
				ac(this);
			});
			//track parent forms in array
			var parentform = $(this).closest("form")[0];
			var notfound = 1;
			for (var f_i in listoforms){
				if (listoforms[f_i] === parentform) notfound = 0;
			}
			if (notfound) listoforms.push(parentform);
		});
		//assign submit event to act on all input.autoCap
		for (var f_i in listoforms) {
			$(listoforms[f_i]).submit(function(){
				$("input.autoCap", this).each(function(i, itm){
					ac(itm);
				});
			});
		}
	};

	/*
	* this jquery function takes inputs and on blur will autocap the first line of each word
	* call like $(selector that matches text inputs).autoCap();
	* autocalled via input.autoCap
	* WEBSITE-1653
	*/
	$.fn.phoneFormCheck = function() {
		this.each(function() {
			$(this).blur(function(){
				var $phone_input = $(this);
				var $parent_form_of_phone_input = $phone_input.closest("form");
				var $warning_ref = $("#" + $phone_input.attr("id") + '_phone_warning');
				var phone_num = $(this).val();
				if ($phone_input.attr("id") == 'tel_fixe2' && $("#id_international:checked").length){
					$warning_ref.hide();
					return;
				}
				//reeuse validation to deterimine if should send ajax
				for (thisform_i in Eu.sm.formSpec){
					var thisform = Eu.sm.formSpec[thisform_i];
					if ($parent_form_of_phone_input.is(thisform.className ? "." + thisform.className : "#" + thisform.id)){
						var keyname = $phone_input.attr("name").replace("form_data__", "");
						if (typeof(thisform.fields[keyname]) == 'object'){
							var testObj = thisform.fields[keyname];
							testObj.noalterfield = 1;
							if (Eu.sm.checkContainer.check_txtPhone(
									$phone_input,
									$parent_form_of_phone_input,
									testObj
								)  !== false
							){
								return;
							}
						}
					}
				}
				//ok validated send the ajax request
				$.post('/validate_phone/', {'phone': phone_num}, function(res){
					if (res == 'bad'){
						$warning_ref.show();
					} else {
						$warning_ref.hide();
						if ($phone_input.attr("id") == 'tel_fixe2') {
							$("#result_error_tel_fixe").hide();
						}
					}
				});
			});
		});
	}

	$(document).ready(function() {
		$("a[rel=IframeMyAccountPP]").click(function(){
			iframeJqueryUi($(this).attr('href'),$(this).attr('title'),760,600);
			return false;
		});
		$("a[rel=IframeMyAccountProjectProgress]").click(function(){
			iframeJqueryUi($(this).attr('href'),$(this).attr('title'),760,600);
			return false;
		});
		$("a[rel=IframeMyAccountRating]").click(function(){
			iframeJqueryUi($(this).attr('href'),$(this).attr('title'),540,500);
			return false;
		});
		$("a[rel=sendMailPpToConsumer]").click(function(){
			iframeJqueryUi($(this).attr('href'),$(this).attr('title'),390,430);
			return false;
		});

		$("a[rel=showProfileSP]").click(function(){
			iframeJqueryUi($(this).attr('href'),$(this).attr('title'),720,600);
			return false;
		});

		// fermeture de l'iframe quand ouverte dans la boite de dialog de jquery ui
		$('a.pp_mail_preformat_close').click(function(){
			parent.window.location.href=parent.window.location;
			return false;
		});

		// pour la sidebar mod_sb_last_leads.tpl permet la rotation des dernier leads
		if (jQuery().cycle){
			$(".sidebar_design1_content .sidebar_last_leads_rotate").cycle({
				timeout:6000,
				pause:1,
				fx:"scrollRight",
				cleartypeNoBg:true,
				after:function(currSlideElement, nextSlideElement, options, forwardFlag){
					console.log();
				}
			});
		}

		$("#submitCoordinate").click(function(){
			$(this).addClass('hidden');
			$('.forms-registration_veuillez_patienter').removeClass('hidden');
		});
		// pour tester si on est en local ou dev
		var reg_local = new RegExp("\/\/local\-","g");
		var reg_dev = new RegExp("\/\/dev\-","g");

		if (reg_local.test(document.location) || reg_dev.test(document.location)){
			// mise en place dans ce fichier pour être utilisé partout et en particulier dans la pp interface
			// pour le UI-247

			//QTip Create the tooltips (info bulles) only on document load
			// pensez à inclure common/common/js/jquery/plugins/jquery-ui/jquery.qtip-1.0.0-rc3.min.js dans la page
			// Notice the use of the each() method to acquire access to each elements attributes
			$('div[tooltip],p[tooltip],span[tooltip]').each(function()
			{
				$(this).qtip({
					content: $(this).attr('tooltip'), // Use the tooltip attribute of the element for the content
					position: {
						corner: {
							target: 'topRight',
							tooltip: 'bottomLeft'
						}
					},
					style: {
						width: 155,
						padding: 5,
						background: '#ffffff',
						color: '#4F9FEF',
						fontSize: '10px',
						lineHeight: '12px',
						textAlign: 'center',
						border: {
							width: 3,
							radius: 3,
							color: '#C2DFFD'
						},
						tip: 'bottomLeft',
						name: 'dark' // Inherit the rest of the attributes from the preset dark style
					}
				});
			});
		}

		$("input.autoCap").autoCap();	// WEBSITE-1653

		$("input.phone-check").phoneFormCheck(); //WEBSITE-1585

		// permet de d'ouvrir/fermer dans sm.co.uk sur le module de sidebar sur la HP d'inscription à la newsletter
		$("#sidebar_bloc_hp_subnews_learn").click(function(){
			if($(this).hasClass('close')){
				$(this).removeClass('close').addClass('open');
				$(".sidebar_bloc_hp_subnews_example").removeClass('hidden');
				$(".sidebar_bloc_find_tradesmen").addClass('hidden');
			}else{
				$(this).removeClass('open').addClass('close');
				$(".sidebar_bloc_hp_subnews_example").addClass('hidden');
				$(".sidebar_bloc_find_tradesmen").removeClass('hidden');
			}
		});
		// permet de d'ouvrir/fermer dans sm.co.uk sur le module de sidebar sur les pages intérieures d'inscription à la newsletter
		$("#sidebar_bloc_subnews_learn").click(function(){
			if($(this).hasClass('close')){
				$(this).removeClass('close').addClass('open');
				$(".sidebar_bloc_subnews_example").removeClass('hidden');
			}else{
				$(this).removeClass('open').addClass('close');
				$(".sidebar_bloc_subnews_example").addClass('hidden');
			}
		});

		// FancyBox pour la vignette du module d'inscription à la newsletter
		// Set custom style, close if clicked, change title type and overlay color
		if (jQuery().fancybox){
			$(".sidebar_subnews_fancybox").fancybox({
				wrapCSS    : 'fancybox-custom',
				closeClick : true,

				helpers : {
					title : {
						type : 'inside'
					},
					overlay : {
						css : {
							'background-color' : '#EEEEEE'
						}
					}
				}
			});
		}

	});
})(jQuery);

