var locationNewInputSettings;
var locationEditSettings;

var newLocationTrigger ;
var locationModifyTrigger;
var addresseTooltipTrigger;
var newInputContent;
var modifyInputContent;

var geocoder = new google.maps.Geocoder();

$('document').ready(function(){

	locationNewInputSettings = {
		'id':'pop-window',
		'width':'392',
		'header_image':(isIE6)?'images/ie6/bg_precisez_votre_adresse.gif':'images/lb_precisez_ad_header.png',
		content:function(){
			return $(this).locationInputContent();
		},
		'parent':$('#current-location'),
		'top':'20',
		'left':'16',
		'sourceName': 'newlocation',
		callBack:function(){
			$(this).addEventsToInputLocationWindow();
            $(this).addAddressBackgroundFix();
		}
	};
	locationEditSettings = {
		'id':'pop-window',
		'width':'392',
		'header_image':(isIE6)?'images/ie6/lb_modifier_add_header.gif':'images/lb_modifier_header.png',
		'header_height':'35',
		content:function() {
			return $(this).modifyLocationInputContent();
		},
		'parent':$('#current-location'),
		'top':'22',
		'left':'180',
		'callBack':function(){
			$(this).addEventsToInputLocationWindow();
            $(this).addAddressBackgroundFix();
		}
	};
    locationNewInputSettings.content();
	newLocationTrigger = '<span id="specify-current-location"></span>';
	locationModifyTrigger = '<div id="modify-current-location"></div>';
	addresseTooltipTrigger = '<img src="/images/blue_question_mark.png" id="trigger-location-tooltip" alt="">';	

	currentLocation = $(this).cookie('current_location');
	currentLocationLatLng = $(this).cookie('current_location_latlng');
	if(null == currentLocation || null == currentLocationLatLng){
		$(this).askForLocation();
	}else{
		$(this).populateLocation(currentLocation, currentLocationLatLng);
		$('#shortcuts div#active').css({'display':'block'});
		$('#shortcuts div#inactive').css({'display':'none'});
	}
	
	$('#trigger-location-tooltip').live('mouseover mouseout', function(event) {
		if (event.type == 'mouseover') {
			$(this).attr('src', $(this).attr('src').replace('blue_question_mark.png', 'blue_question_mark_over.png'));
		}else if(!$('#pop-address-description:visible').length) {
			$(this).attr('src', $(this).attr('src').replace('blue_question_mark_over.png', 'blue_question_mark.png'));
		}
	});
	
	if((null == currentLocation || null == currentLocationLatLng)){
		if(navigator.geolocation){
			navigator.geolocation.getCurrentPosition(function(position){
				var latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
				geocoder.geocode(
					{'latLng':latLng},
					function(results,status){
						if (status == google.maps.GeocoderStatus.OK && results[1]) {
	//						$(this).cookie('current_location',results[1].formatted_address);
	//						$(this).cookie('current_location_latlng',position.coords.latitude+','+position.coords.longitude);
							$(this).populateLocation(results[1].formatted_address, (position.coords.latitude+','+position.coords.longitude));
							$('#popup-help-opt-indispo').hide();							
						}else{
							alert('Désolé, nous ne pouvons pas vous localiser.'+"\n"+'['+status+']'); 
						}
					}
				);
			});
		}
	}

    $('#modify-current-location').live('click', function(){
		if($('#pop-window:visible').length) {
			$('#pop-window').hide();
			$(this).removeClass('modify-current-location-hover');
			
			if(isIE6) {
				$(this).css({'background-position':'left top'});
			}
		}else {
			$(this).popWindow(locationEditSettings);
			$(this).addClass('modify-current-location-hover');
			$('#trigger-location-tooltip').attr('src', $('#trigger-location-tooltip').attr('src').replace('blue_question_mark_over.png', 'blue_question_mark.png'));
			
			if(isIE6) {
				$(this).css({'background-position':'left bottom'});
			}
		}
	});
	/*
    $('#find-professional').click(function(){
        if($(this).val() == 'ex: hôpital, mairie, plombier, durand,...') $(this).val('');
		$(this).addClass('input-black');
    });
    $('#find-professional').blur(function(){
        if($(this).val() == '') $(this).val('ex: hôpital, mairie, plombier, durand,...');
		$(this).removeClass('input-black');
    });
	*/
	
    $('#go-find-professional').live('click',function(){
        $(this).parents('form').submit();
    });
});

jQuery.fn.askForLocation = function(){
	$('#location-address').append($(newLocationTrigger));
	$('#specify-current-location').click(function() {
		if($('#pop-window:visible').length) {
			$('#pop-window').hide();
			$(this).removeClass('hover');
			if(isIE6) {
				$(this).css({'background-image':'url(/images/precisez_votre_adresse.png)'});
			}
		}else {
			$(this).popWindow(locationNewInputSettings);
			$(this).addClass('hover');
			if(isIE6) {
				$(this).css({'background-image':'url(/images/precisez_votre_adresse_over.png)'});
			}
		}
	});
};

jQuery.fn.populateLocation = function(currentLocation, currentLocationLatLng){
	if(undefined == currentLocation || undefined == currentLocationLatLng){
		$('#specify-current-location').remove();
		$(this).removeClass('hover');
		$('#location-address').text($('#new-location-field').val() + ' ');
		$(this).storeUserLocation($('#new-location-field').val());
	}else{
		$('#location-address').text(currentLocation + ' ');
		$(this).storeUserLocation(currentLocation);
	}
	
	if(isIE6) {
		$('#specify-current-location').css({'background-image':'url(/images/precisez_votre_adresse.png)'});
	}	
	
	if(!$('#modify-current-location').length){
        $('#current-location').append($(locationModifyTrigger));
    }
	$('#location-address').addAddresseToolTipTrigger();
	$('#shortcuts div#active').css({'display':'block'});
	$('#shortcuts div#inactive').css({'display':'none'});
};

jQuery.fn.locationInputContent = function() {
   var popupContent = $('#new-location-pop-html').html();   
   return popupContent;
};

jQuery.fn.modifyLocationInputContent = function() {
   var popupContentClone = $('#new-location-pop-html').clone();
   popupContentClone.find('#new-location-description').html('Les recherches « Autour de vous », par les icônes ou le champ libre « trouvez un autre professionnel », sont effectuées autour de l’adresse saisie dans le champ ci-dessus.<br /><br />Vos informations de localisation sont utilisées uniquement pour ces recherches.');
   var popupContent = popupContentClone.html();    
   return popupContent;
};


jQuery.fn.addEventsToInputLocationWindow = function(){
	$('#get-location').hover(
		function(){
			$(this).toggleValider();
			if(isIE6) {
				$(this).css({'background-position':'left bottom'});
			}
		},
		function(){
			$(this).toggleValider();
			if(isIE6) {
				$(this).css({'background-position':'left top'});
			}
		}
	);

	$('#get-location').click(function(){
		if($('#new-location-field').val().length>0){
			$(this).populateLocation();
		}
		$('#pop-window').remove();
	});
};

jQuery.fn.toggleValider = function(){
	var state = $('#tip-location-valider').css('display');
	if('none' == state){
		$('#tip-location-valider').css({'display':'block'});
	}else{
		$('#tip-location-valider').css({'display':'none'});
	}
};

jQuery.fn.toggleShortCuts = function(mark){
	if(true == mark){
		$('#inactive').css({'display':'none'});
		$('#active').css({'display':'block'});
	}else{
		$('#active').css({'display':'none'});
		$('#inactive').css({'display':'block'});
	}
};

jQuery.fn.addAddresseToolTipTrigger = function(){
	$(this).append($(addresseTooltipTrigger));

    /*
     *
     *<div id="tt_aide">
    <div class="header clearfix">
        &nbsp;
        <a href="">&nbsp;</a>
    </div>
    <div class="content"></div>
    <div class="footer">&nbsp;</div>
</div>
     *
     *
     **/
	$('#trigger-location-tooltip').click(function() {
		if($('#pop-address-description:visible').length) {
			$('#trigger-location-tooltip').attr('src', $('#trigger-location-tooltip').attr('src').replace('blue_question_mark_over.png', 'blue_question_mark.png'));
			$('#pop-address-description:visible').hide();
		}else {
			$(this).toggleClass('opened');
			$(this).popWindow({
				'id':'pop-address-description',
				'width':'235',
				'header_height':'35',
				'header_image':'images/aide_tip_top_left.png',
				content:function(){
					var content = $(
						'<div id="aid-tip">La recherche « Autour de vous », par icônes ou par le champ libre « trouver un autre professionnel », est effectuée autour de l\'adresse indiquée. Vous pouvez modifier l\'adresse en utilisant le bouton « Modifier l\'adresse ».<br /><br />Ces informations de localisation sont utilisées uniquement pour ces recherches.</div>'+
						'<div id="aid-tip-bottom"></div>'
					);

					return content;
				},
				'parent':$('#location-address'),
				'top':15,
				'left':$('#location-address').width() - 9,
				callBack:function(){
					$('#aid-tip').parent().css({'background':'transparent url("/images/' + ((isIE6)?'ie6/aide_tip_middle.gif':'aide_tip_middle.png') + '") top left repeat-y','position':'relative'});
				}
			});
			
			if($('#pop-address-description:visible').length) {
				$(this).attr('src', $(this).attr('src').replace('blue_question_mark.png', 'blue_question_mark_over.png'));
			}else {
				$(this).attr('src', $(this).attr('src').replace('blue_question_mark_over.png', 'blue_question_mark.png'));
			}
			$('#modify-current-location').removeClass('modify-current-location-hover');
			if(isIE6) {
				$(this).css({'background-position':'left top'});
			}
		}
	});
};

jQuery.fn.storeUserLocation = function(locationAddress){
	geocoder.geocode(
		{'address':locationAddress},
		function(results,status){
			if (status == google.maps.GeocoderStatus.OK) {
				$(this).cookie('current_location',locationAddress);
				$(this).cookie('current_location_latlng',results[0].geometry.location.lat()+','+results[0].geometry.location.lng());
			}else{
				alert('Désolé, nous ne pouvons pas vous localiser.'+"\n"+'['+status+']'); 
			}
		}
	);
}

jQuery.fn.addAddressBackgroundFix = function(){
    $('#new-location-field-container').parent().css({'background':'transparent url("/images/' + ((isIE6)?'ie6/lb_precisez_ad_mid.gif':'lb_precisez_ad_mid.png') + '") top left repeat-y','position':'relative'});
}

