$(document).ready(function() {
    nb_car = $('#conteneur_autopromotion').children().length;
    $('#conteneur_autopromotion').width(nb_car * 200)
    car_en_cours = 0;
    function animateCar(){
        car_en_cours++;
        if(car_en_cours == nb_car){
            car_en_cours = 0;
        }
        $('#conteneur_autopromotion').animate({
            left:-car_en_cours * 200
        },500,function(){
            setTimeout(animateCar,3000);
        })
    }
    setTimeout(animateCar,3000)
    
	$('#geolocalisation').click(function() {
		loadPopupmaps();
	});
    function loadPopupmaps(){
        $('#latitude').attr('value', '');
		$('#longitude').attr('value', '');
		$('#proximite').attr('value', '');
		$('#localisation_libel').attr('value', '');
		$('#localisation_sel').attr('value', '');



		var windowWidth = document.documentElement.clientWidth;
		var windowHeight = document.documentElement.clientHeight;
		var popupHeight = $("#content_geo").height();
		var popupWidth = $("#content_geo").width();

		// centering
		$("#content_geo").css( {
			"position" : "absolute",
			"top" : windowHeight / 2 - popupHeight / 2,
			"left" : windowWidth / 2 - popupWidth / 2
		});

		$("#backgroundPopup").css( {
			"height" : windowHeight
		});

		$("#backgroundPopup").css( {
			"opacity" : "0.6"
		});
		$("#backgroundPopup").fadeIn("slow");
		$('#content_geo').fadeIn("slow");
		popupStatus = 1;

		if( $('#address_search').val() != '' && $('#address_search').val() != 'Saisir une adresse' ) {
			$('#address').val($('#address_search').val());
		}
		initialize();
    }
	
	$("#backgroundPopup").click(function(){
		disablePopup();
	});
		
	$("#popupClose").click(function() {
		disablePopup();
	});
	
	$("#recherche_annonces").click(function() {
		disablePopup();
	});
	
	$("#valid_coord").click(function() {
            if( $("input[name='type_localisation']:checked").val() == 1 ){
                if( $('#address').val() == 'Lieu actuel' ){
                    valid_form();
                    
                }else{
                    codeAddress(false);
                    
                }
            }else{
              if( $("#Localisation_sel option:selected").attr('value') != 0 ){
                        $("#Localisation").attr('value', $("#Localisation_sel option:selected").attr('value'));
                        $("#Localisation_libel").attr('value', $("#Localisation_sel option:selected").text());
                }
                    disablePopup();
            }
	});


        $('#reset_coord').click(function() {
		disablePopup();
	});
	
	function disablePopup(){
		//disables popup only if it is enabled
		if(popupStatus==1){
			$("#backgroundPopup").fadeOut("slow");
			$("#content_geo").fadeOut("slow");
			$("#fiche_commerciale").fadeOut("slow");
			popupStatus = 0;
		}
		if(popupStatus==5){
			document.getElementById("content_geo").style.display = "none";
		}
	}
	
	
	document.onkeyup = function(e){ 	
		if (e == null) { // ie
			keycode = event.keyCode;
		} else { // mozilla
			keycode = e.which;
		}
		if(keycode == 27){ // close
			disablePopup();
		}	
	};
	
	$('.lbOn').click(function() {
		var windowWidth = document.documentElement.clientWidth;
		var windowHeight = document.documentElement.clientHeight;
		var popupHeight = $("#fiche_commerciale").height();
		var popupWidth = $("#fiche_commerciale").width();

		// centering
		$("#fiche_commerciale").css( {
			"position" : "absolute",
			"top" : windowHeight / 2 - popupHeight / 2,
			"left" : windowWidth / 2 - popupWidth / 2
		});

		$("#backgroundPopup").css( {
			"height" : windowHeight
		});

		$("#backgroundPopup").css( {
			"opacity" : "0.6"
		});
		$("#backgroundPopup").fadeIn("slow");
		$('#fiche_commerciale').fadeIn("slow");
		popupStatus = 1;
		
		$('#fiche_commerciale').load($(this).attr('href'));
		return false;
	});



        $("input[name='type_localisation']").click(function(){
            if( $(this).val() == 1 ) {
                $('#Localisation_sel').attr('disabled', 'disabled');
                loadPopupmaps();
            }else{
                $('#Localisation_sel').removeAttr('disabled');
                $('#address_search').val('Saisir une adresse');
                $('#address_search_hidden').val('');

            }
        });


        
        function valid_form(){
         $("#latitude").attr('value', $("#latitude_sel").attr('value'));
                $("#longitude").attr('value', $("#longitude_sel").attr('value'));
                if( $("#perimetre").attr('value') != 0 ){
                        $("#proximite").attr('value', $("#perimetre").attr('value'));
                }
                $("#address_search").attr('value', $("#address").attr('value'));
                $("#address_search_hidden").attr('value', $("#address").attr('value'));
                disablePopup();
                document.recherche.submit();
        }

        var initialLocation;
        var paris = new google.maps.LatLng(48.8566667, 2.3509871);
        var marker;
        var browserSupportFlag = new Boolean();
        var map;
        var infowindow = new google.maps.InfoWindow();
        var geocoder;
        var infowindow;

        function initialize() {
                geocoder = new google.maps.Geocoder();
                $('#message').text('');
                var myOptions = {
                        zoom : 13,
                        center : paris,
                        mapTypeId : google.maps.MapTypeId.ROADMAP
                };
                map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

                if( $('#address_search').val() == '' || $('#address_search').val() == 'Saisir une adresse' || $('#address_search').val() == 'Lieu actuel') {
                    localizeMe();
                }else{
                    codeAddress(true);
                    $('#localize_me').css('display', 'inline');
                }

                google.maps.event.addListener(map, 'click', function(event) {
                    placeMarker(event.latLng);
                });
                // Try W3C Geolocation method (Preferred)

        }

        function placeMarker(location) {
             if (marker) {
                        marker.setMap(null);
                }
                        
          marker = new google.maps.Marker({
              position: location,
              map: map
          });

         map.setCenter(location);


         geocoder.geocode({'latLng': location}, function(results, status) {
          if (status == google.maps.GeocoderStatus.OK) {
            if (results[1]) {

              /*document.getElementById('latitude_sel').value = location.lat();
                 document.getElementById('longitude_sel').value = location.lng();
                 document.getElementById('message').innerHTML = '';*/
                 document.getElementById('address').value = results[0].formatted_address;
              //alert(results[0].formatted_address);
              //infowindow.open(map, marker);
            }
          } else {
            alert("problème de géolocalisation : " + status);
          }
        });




        }

        


        function localizeMe() {
                $('#message').text('Localisation en cours...');
                if (marker) {
                        marker.setMap(null);
                }

                if (navigator.geolocation) {

                        browserSupportFlag = true;
                        navigator.geolocation.getCurrentPosition(function(position) {
                                latitude = position.coords.latitude;
                                longitude = position.coords.longitude;
                                initialLocation = new google.maps.LatLng(latitude, longitude);

                                map.setCenter(initialLocation);
                                infowindow.setPosition(initialLocation);
                                infowindow.open(map);

                                marker = new google.maps.Marker( {
                                        map : map,
                                        animation : google.maps.Animation.DROP,
                                        position : initialLocation
                                });
                                document.getElementById('latitude_sel').value = latitude;
                                document.getElementById('longitude_sel').value = longitude;
                                document.getElementById('message').innerHTML = '';
                                document.getElementById('address').value = 'Lieu actuel';

                        }, function() {
                                handleNoGeolocation(browserSupportFlag);
                        });
                } else if (google.gears) {
                        // Try Google Gears Geolocation
                        browserSupportFlag = true;
                        var geo = google.gears.factory.create('beta.geolocation');
                        geo.getCurrentPosition(function(position) {
                                latitude = position.latitude;
                                longitude = position.longitude;
                                initialLocation = new google.maps.LatLng(latitude, longitude);
                                contentString = "Location found using Google Gears";
                                map.setCenter(initialLocation);
                                infowindow.setContent(contentString);
                                infowindow.setPosition(initialLocation);
                                infowindow.open(map);
                                marker = new google.maps.Marker( {
                                        map : map,
                                        animation : google.maps.Animation.DROP,
                                        position : initialLocation
                                });
                                document.getElementById('latitude').value = latitude;
                                document.getElementById('longitude').value = longitude;
                                document.getElementById('message').innerHTML = '';
                                document.getElementById('address').value = 'Lieu actuel';

                        }, function() {
                                handleNoGeolocation(browserSupportFlag);
                        });
                } else {
                        // Browser doesn't support Geolocation
                        browserSupportFlag = false;
                        handleNoGeolocation(browserSupportFlag);
                }

                
        }

        /**
         *
         */
        function handleNoGeolocation(errorFlag) {
                if (errorFlag == true) {
                        initialLocation = newyork;
                        contentString = "Error: The Geolocation service failed.";
                } else {
                        initialLocation = siberia;
                        contentString = "Error: Your browser doesn't support geolocation. Are you in Siberia?";
                }
                map.setCenter(initialLocation);
                infowindow.setContent(contentString);
                infowindow.setPosition(initialLocation);
                infowindow.open(map);
        }

        /**
         *
         */
        function codeAddress(refresh) {
                if (marker) {
                        marker.setMap(null);
                }
                var address = document.getElementById("address").value;
                geocoder.geocode({'address' : address},
                function(results, status) {

                        if (status == google.maps.GeocoderStatus.OK) {
                                map.setCenter(results[0].geometry.location);
                                if( refresh == true ){
                                    marker = new google.maps.Marker( {
                                            map : map,
                                            animation : google.maps.Animation.DROP,
                                            position : results[0].geometry.location
                                    });
                                }
                                document.getElementById('latitude_sel').value = results[0].geometry.location.lat();
                                document.getElementById('longitude_sel').value = results[0].geometry.location.lng();
                                if( refresh == false ){
                                 valid_form();
                                }

                        } else {
                                alert("Une erreur est survenue lors de la recuperation des informations");
                                return false;
                        }
                });
        }


        



        $('#actualize_position').click(function(){
            codeAddress(true);
        })

        $('#label_textfield').click(function(){
            $('#manuel_loc_radio').attr('checked', true);
            loadPopupmaps();
        })


        $('#localize_me').click(function(){
            localizeMe()
        })


        $('#Localisation_sel').click(function(){
            $('#Localisation_sel').removeAttr('disabled');
            $('#address_search').val('Saisir une adresse');
            $('#manuel_loc_radio').removeAttr('checked');
            $('#macro_loc_radio').attr('checked', true);
        })


        $('#address').focus(function (){
            temp_text = $(this).val();
            $(this).val("");
        })

        $('#address').blur(function (){
            if( $(this).val() == '' ){
                $(this).val(temp_text);
            }
            temp_text = '';
            
        })

});
