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() {};
}
function initMapSr(MapId,arrSR,frontDataUrl,defaultZoom){
	if (!defaultZoom){
		defaultZoom=13
	}
	if (!$("#"+MapId)){
		return;
	}
	if (arrSR.length > 0){
		$("#"+MapId).show();
	}else{
		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]);
		},

	jQuery.each(arrSR,function(k,v){
		marker[k] = new google.maps.Marker({
			position	: new google.maps.LatLng(v.lat,v.long),
			map			: map,
			title		: v.lib_activite
		});
		google.maps.event.addListener(marker[k], 'click', function(){srInfoWindow(k)});
	});
}

$(document).ready(function() {

	/* slide homepage & page 3 */
	$(".zone_retour").click(function(event){
		$("#bloc_all_category_inside").animate({left:0},'slow','linear',function(){
			$("#subLink_"+id).hide();
		});
	});
	$(".maintitle_link").click(function(event){
		id = event.target.id.replace('mainLink_','');
		$(".bloc_subcategory").hide();
		$("#subLink_"+id).show();
		$("#bloc_all_category_inside").animate({
			left:-605,
			"duration": "slow",
			"easing": "easeout"
		});
		return false;
	});

	/* alert remplacement */
	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');
		});
	}
	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 �gal au titre lors du submit


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


	$('.contact_form').submit(function() {
		var var_return = true;
		var returnStr = 'We need you to fill these fields :';
		$('.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('We need your attention',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').submit(function() {
		if( ($('#select_activite').val() != '' ) && ($('#select_activite').val() != 0 ) && ($('#select_activite').val() != undefined) ) {
			$(location).attr('href',$('#select_activite').val());
			return false;
		}
	});

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


	/* form SR submit test */
	function formSRSubmit(){
		var isGood = true;
		var missingStr = 'Please: \n';
		var missingStrSepa = '';
		var tabCheckbox = Array();
		var tabRadio = Array();
		$('.requiredField').each(function(k,v){
			// var currObj = $('[name="'+v.nom+'"]');

			idCheckbox = $(/^critere\[(.*)\]\[valeur\]\[(.*)\]/.exec(v.name))[1];//on recupere l'id_critere
			idRadio = $(/^critere\[(.*)\]\[valeur\]$/.exec(v.name))[1];//on recupere l'id_critere
			if(idCheckbox != undefined) {
				if (!tabCheckbox[idCheckbox])
					tabCheckbox[idCheckbox] = v.checked;
			}
			if(idRadio != undefined) {
				if (!tabRadio[idRadio])
					tabRadio[idRadio] = v.checked;
			}
			if (v.name=='cp' && v.value!=''){
				if (!checkPostCode(v.value)){
					missingStr = missingStr + missingStrSepa + "- Incorrect Post code" ;
					missingStrSepa = '\n';
					isGood = false;
				}
			}
			if ((v.type=='select-one' && v.selectedIndex==0) ||
				(v.type=='text' && v.value == '') ||
				(v.type=='textarea' && v.value == '')
			){
				isGood = false;
				if (v.name == 'cp'){
					missingStr = missingStr + missingStrSepa + "- " + tab_element[v.name];
				}else{
					missingStr = missingStr + missingStrSepa + "- Select a choice for '" + tab_element[v.name] + "'";
				}
				missingStrSepa = '\n';
			}
		});
		// parser tabRadioCheckbox pour voir s'il y a des false dans les entr�es
		$(tabCheckbox).each(function(k,v){
			if ( (v != undefined) && (v == false) ) {
				key = "critere["+k+"][saisie]";
				field = tab_element[key];
				missingStr = missingStr + missingStrSepa + "- Select a choice for '" + field + "'";
				isGood = false;
				missingStrSepa = '\n';
			}
		});
		$(tabRadio).each(function(k,v){
			if ( (v != undefined) && (v == false) ) {
				key = "critere["+k+"][valeur]";
				field = tab_element[key];
				missingStr = missingStr + missingStrSepa + "- Select a choice for '" + field + "'";
				isGood = false;
				missingStrSepa = '\n';
			}
		});

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

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


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

	function checkPostCode(toCheck) {
		// 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);
		// Load up the string to check
		var postCode = toCheck;
		// Assume we're not going to find a valid postcode
		var valid = false;
		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');
		}
	});

	function personnalInfoSubmit()
	{
		var message="Please :\n";
		var txtFieldNotNull = function(k,v){
			if ($("#"+k).val()==''){
				return v.errorMessage;
			}
			if (v.defaultValue && $("#"+k).val()==v.defaultValue){
				return v.errorMessage;
			}
			return false;
		}
		var comboFieldNotNull = function(k,v){
			if ($("#"+k).selectedIndex==0){
				return v.errorMessage;
			}
			return false;
		}
		var required={
			'IdVille' : {
				isError: function(k,v){
					if ($("#cp_pasville2").val() != "" && $("#cp_pasville2").val() != undefined) {
						//cas ou on a pas trouv� de ville
						if (($('#ville_absente').val()+'').trim()==''){
							return "Choose a work location. If you don't find your location, please select Other and state your location below.\n";
						}
					}
					else if ($("#cp").val() != "" && $("#cp").val() != undefined) {
						//on a trouv� plusieurs ville
						if ($("#IdVille")[0].selectedIndex==0){
							return "Choose a work location. If you don't find your location, please select Other and state your location below.\n";
						}
						if ( $("#IdVille").val()=='0' && ($('#ville_absente').val()+'').trim()==''){
							return "Fill in the work place.\n";
						}
					}
					else if ($("#cp3").val() != "" && $("#cp3").val() != undefined) {
						//on a trouv� une ville, donc pas de controle
					}
/*
					if ($("#IdVille").val() != undefined){
						if ($("#IdVille")[0].selectedIndex==0){
							return "Choose a work location. If you don't find your location, please select Other and state your location below.\n";
						}
						if ($("#IdVille").val()=='0' && ($('#ville_absente').val()+'').trim()==''){
							return "Fill in the work place.\n";
						}
					}else{
						if ($("#cp_pasville").val()!='' && ($('#ville_absente').val()+'').trim()==''){
							return "Choose a work location. If you don't find your location, please select Other and state your location below.\n";
						}
					}
*/
					return false;
				},
				errorMessage : ''
			},
			'civilite' :{
				isError : txtFieldNotNull,
				errorMessage : 'Choose your title'
			},
			'prenom' :{
				isError : txtFieldNotNull,
				defaultValue : 'first name',
				errorMessage : 'Fill in your First name'
			},
			'nom' :{
				isError : txtFieldNotNull,
				defaultValue : 'surname',
				errorMessage : 'Fill in your Surname'
			},
			'adresse' :{
				isError : txtFieldNotNull,
				defaultValue : 'e.g. 182-194 Union Street',
				errorMessage : 'Fill in your Address'
			},
			'ville' :{
				isError : txtFieldNotNull,
				defaultValue : 'e.g. London',
				errorMessage : 'Fill in your Town/City'
			},
			'IdOptionCountry' :{
				isError : comboFieldNotNull,
				errorMessage : 'Select your country'
			},
			'postal2' :{
				isError : function (k,v){
					var val = $('#postal2').val();
					if ($('#IdOptionCountry').val()!='United Kingdom') return false;
					if (val==''){
						return v.errorMessage;
					}
					if (!checkPostCode(val)){
						return v.errorMessage;
					}
					return false;
				},
				errorMessage : 'Postcode error: the postcode you filled in does not exist, please enter a valid postcode'
			},
			'tel_fixe2' :{
				isError : function (k,v){
					var val = $('#tel_fixe2').val().replace(' ','');
					if ($('#IdOptionCountry').val()!='United Kingdom' && val!='') return false;
					if (val == ''){
						return v.errorMessage;
					}
					if (!/^0[123578][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]$/.test(val)){
						return v.errorMessage;
					}
					return  false;
				},
				errorMessage : 'Phone error : please a valid phone number'
			},
			'email2' :{
				isError : function (k,v){
					var val = $('#email2').val();
					if (!/^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,4})+$/.test(val)){
						return v.errorMessage;
					}
					return false;
				},
				errorMessage : 'E-mail error: please enter a valid e-mail'
			},
			'horaire' :{
				isError : txtFieldNotNull,
				errorMessage : 'Enter a time you are available by'
			}

		}

		var message="Please :\n";
		jQuery.each(required,function(k,v){
			var messageIn = v.isError(k,v);
			if (messageIn){
				message +='- ' +messageIn+'\n';
			}
		});

		if(message!="Please :\n"){
			alertError('We need your attention',message);
			setIndications();
			return false;
		}else{
			if ($("#tel_portable2").val()=="other number (optional)") {
				$("#tel_portable2").val("");
			}//to avoid insertion in the db
			return true;
		}
	}//personnalInfoSubmit

	$('.main_forms_step2').submit(personnalInfoSubmit);

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


/******************** ancien /js/SR/UK-ActivityForm.js *********************/

	$(':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{
				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();
			}
		}
	});
/************************************************************************/

/*********************************** 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');

	$(".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){
		//console.log($(this).parent().parent());
		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");
			}
		}
	);
	$(".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])
	});


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

		$(this).find('input[type=checkbox]').each(function(k,v){
			//console.log(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 **************************************/

});
