$(document).ready(function(){


	
	$('#slider2').anythingSlider({
  // Appearance
  width               : null,      // Override the default CSS width
  height              : null,      // Override the default CSS height
  resizeContents      : true,      // If true, solitary images/objects in the panel will expand to fit the viewport

  // Navigation
  startPanel          : 1,         // This sets the initial panel
  hashTags            : true,      // Should links change the hashtag in the URL?
  buildArrows         : true,      // If true, builds the forwards and backwards buttons
  buildNavigation     : true,      // If true, buildsa list of anchor links to link to each panel
  navigationFormatter : null,      // Details at the top of the file on this use (advanced use)
  forwardText         : "&raquo;", // Link text used to move the slider forward (hidden by CSS, replaced with arrow image)
  backText            : "&laquo;", // Link text used to move the slider back (hidden by CSS, replace with arrow image)

  // Slideshow options
  autoPlay            : true,      // This turns off the entire slideshow FUNCTIONALY, not just if it starts running or not
  startStopped        : false,     // If autoPlay is on, this can force it to start stopped
  pauseOnHover        : true,      // If true & the slideshow is active, the slideshow will pause on hover
  resumeOnVideoEnd    : true,      // If true & the slideshow is active & a youtube video is playing, it will pause the autoplay until the video has completed
  stopAtEnd           : false,     // If true & the slideshow is active, the slideshow will stop on the last page
  playRtl             : false,     // If true, the slideshow will move right-to-left
  startText           : "Start",   // Start button text
  stopText            : "Stop",    // Stop button text
  delay               : 3000,      // How long between slideshow transitions in AutoPlay mode (in milliseconds)
  animationTime       : 600,       // How long the slideshow transition takes (in milliseconds)
  easing              : "swing"    // Anything other than "linear" or "swing" requires the easing plugin
});

    /* Inscription déploiement */
    $('.btn_inscription').live('click', function(){
        $('#conteneur_inscription').empty();
        showFiltreLoading();

        $.ajax({
            type: 'POST',
            url : fw_uri+'/'+$('html').attr('lang')+'/index/preinscription/',
            success : function(msg){
				
                $("#inscription").animate({
                    height:"284px"
                }, 500,function(){
					  
                    hideFiltreLoading();
                    $('#conteneur_inscription').append(msg);
                    $('#slider').nivoSlider();
							
							  
                } );
				
            }
        });
        return false;
    });


    $('#btn_minimize').live('click', function(){
		
        $('#conteneur_inscription').empty();
        showFiltreLoading();
        $.ajax({
            type: 'POST',
            url : fw_uri+'/'+$('html').attr('lang')+'/index/preinscription_minimize/',
            success : function(msg){
				
                $("#inscription").animate({
                    height:"59px"
                }, 500,function(){
                    hideFiltreLoading();
                    $('#conteneur_inscription').append(msg);
                } );
				
            }
        });
        return false;
    });
	
    $('#form_search_barre').submit(function(){
	
        if( $('#parcs_ville').val() == "Ville" && $('#departements_id').val() == 0 && $('#categories_id').val() == 0)
        {
            alert('Veuillez spécifier au moins un champs');
        }
        else
        {
            //$.getScript(fw_uri+'/fr/search/bybarre/');
            $("#map").animate({
                height:"430px"
            }, 500,function(){
                load();
               
            });
            
             $("#actions_map").show();
	
            return false;
        }
	
    });


    $('#submit_search_barre').live('click', function(){
	
        if( $('#parcs_ville').val() == "Ville" && $('#departements_id').val() == 0 && $('#categories_id').val() == 0)
        {
            alert('Veuillez spécifier au moins un champs');
        }
        else
        {
            //$.getScript(fw_uri+'/fr/search/bybarre/');
            $("#map").animate({
                height:"430px"
            }, 500,function(){
                load();
            });
			
			 $("#actions_map").show();
			 
            return false;
        }
	
    });


    function InfoBox(opts) {
        google.maps.OverlayView.call(this);
        this.latlng_ = opts.latlng;
        this.html = opts.html;
  
        this.map_ = opts.map;
        this.offsetVertical_ = -130;
        this.offsetHorizontal_ = -105;
        this.height_ = 120;
        this.width_ = 200;
  

        var me = this;
        this.boundsChangedListener_ =
        google.maps.event.addListener(this.map_, "bounds_changed", function() {
            return me.panMap.apply(me);
        });

        // Once the properties of this OverlayView are initialized, set its map so
        // that we can display it.  This will trigger calls to panes_changed and
        // draw.
        this.setMap(this.map_);
    }

    /* InfoBox extends GOverlay class from the Google Maps API
 */
    InfoBox.prototype = new google.maps.OverlayView();

    /* Creates the DIV representing this InfoBox
 */
    InfoBox.prototype.remove = function() {
        if (this.div_) {
            this.div_.parentNode.removeChild(this.div_);
            this.div_ = null;
        }
    };

    /* Redraw the Bar based on the current projection and zoom level
 */
    InfoBox.prototype.draw = function() {
        // Creates the element if it doesn't exist already.
        this.createElement();
        if (!this.div_) return;

        // Calculate the DIV coordinates of two opposite corners of our bounds to
        // get the size and position of our Bar
        var pixPosition = this.getProjection().fromLatLngToDivPixel(this.latlng_);
        if (!pixPosition) return;

        // Now position our DIV based on the DIV coordinates of our bounds
        this.div_.style.width = this.width_ + "px";
        this.div_.style.left = (pixPosition.x + this.offsetHorizontal_) + "px";
        this.div_.style.height = this.height_ + "px";
        this.div_.style.top = (pixPosition.y + this.offsetVertical_) + "px";
        this.div_.style.display = 'block';
    };

    /* Creates the DIV representing this InfoBox in the floatPane.  If the panes
 * object, retrieved by calling getPanes, is null, remove the element from the
 * DOM.  If the div exists, but its parent is not the floatPane, move the div
 * to the new pane.
 * Called from within draw.  Alternatively, this can be called specifically on
 * a panes_changed event.
 */
    InfoBox.prototype.createElement = function() {
        var panes = this.getPanes();
        var div = this.div_;
        if (!div) {
            // This does not handle changing panes.  You can set the map to be null and
            // then reset the map to move the div.
            div = this.div_ = document.createElement("div");
  
            div.className = "infoWinContainer";
            div.style.width = this.width_ + "px";
            div.style.height = this.height_ + "px";
   
            var contentDiv = document.createElement("div");
            contentDiv.style.position = "absolute";
            contentDiv.style.top = "20px";
            contentDiv.style.left = "20px";
            contentDiv.innerHTML = this.html;

            var topDiv = document.createElement("div");
            topDiv.style.position = "absolute";
            topDiv.style.bottom = "0";
            topDiv.style.left = "20px";
	
            var closeImg = document.createElement("img");
            closeImg.style.position = "absolute";
            closeImg.style.right = "-186px";
            closeImg.style.top = "-117px";
            closeImg.src = "http://gmaps-samples.googlecode.com/svn/trunk/images/closebigger.gif";
            topDiv.appendChild(closeImg);

            function removeInfoBox(ib) {
                return function() {
                    ib.setMap(null);
                };
            }

            google.maps.event.addDomListener(closeImg, 'click', removeInfoBox(this));

            div.appendChild(topDiv);
            div.appendChild(contentDiv);
            div.style.display = 'none';
            panes.floatPane.appendChild(div);
            this.panMap();
        } else if (div.parentNode != panes.floatPane) {
            // The panes have changed.  Move the div.
            div.parentNode.removeChild(div);
            panes.floatPane.appendChild(div);
        } else {
    // The panes have not changed, so no need to create or move the div.
    }
    }

    /* Pan the map to fit the InfoBox.
 */
    InfoBox.prototype.panMap = function() {
        // if we go beyond map, pan map
        var map = this.map_;
        var bounds = map.getBounds();
        if (!bounds) return;

        // The position of the infowindow
        var position = this.latlng_;

        // The dimension of the infowindow
        var iwWidth = this.width_;
        var iwHeight = this.height_;

        // The offset position of the infowindow
        var iwOffsetX = this.offsetHorizontal_;
        var iwOffsetY = this.offsetVertical_;

        // Padding on the infowindow
        var padX = 0;
        var padY = 0;

        // The degrees per pixel
        var mapDiv = map.getDiv();
        var mapWidth = mapDiv.offsetWidth;
        var mapHeight = mapDiv.offsetHeight;
        var boundsSpan = bounds.toSpan();
        var longSpan = boundsSpan.lng();
        var latSpan = boundsSpan.lat();
        var degPixelX = longSpan / mapWidth;
        var degPixelY = latSpan / mapHeight;

        // The bounds of the map
        var mapWestLng = bounds.getSouthWest().lng();
        var mapEastLng = bounds.getNorthEast().lng();
        var mapNorthLat = bounds.getNorthEast().lat();
        var mapSouthLat = bounds.getSouthWest().lat();

        // The bounds of the infowindow
        var iwWestLng = position.lng() + (iwOffsetX - padX) * degPixelX;
        var iwEastLng = position.lng() + (iwOffsetX + iwWidth + padX) * degPixelX;
        var iwNorthLat = position.lat() - (iwOffsetY - padY) * degPixelY;
        var iwSouthLat = position.lat() - (iwOffsetY + iwHeight + padY) * degPixelY;

        // calculate center shift
        var shiftLng =
        (iwWestLng < mapWestLng ? mapWestLng - iwWestLng : 0) +
        (iwEastLng > mapEastLng ? mapEastLng - iwEastLng : 0);
        var shiftLat =
        (iwNorthLat > mapNorthLat ? mapNorthLat - iwNorthLat : 0) +
        (iwSouthLat < mapSouthLat ? mapSouthLat - iwSouthLat : 0);

        // The center of the map
        var center = map.getCenter();

        // The new map center
        var centerX = center.lng() - shiftLng;
        var centerY = center.lat() - shiftLat;

        // center the map to the new shifted center
        map.setCenter(new google.maps.LatLng(centerY, centerX));

        // Remove the listener after panning is complete.
        google.maps.event.removeListener(this.boundsChangedListener_);
        this.boundsChangedListener_ = null;
    };


    var customIcons = {
        2: {
            icon: fw_uri+'/templates/defaut/front/images/marker_2.png',
            shadow: fw_uri+'/templates/defaut/front/images/marker_shadow.png'
        },
        3: {
            icon: fw_uri+'/templates/defaut/front/images/marker_3.png',
            shadow: fw_uri+'/templates/defaut/front/images/marker_shadow.png'
        },
        4: {
            icon: fw_uri+'/templates/defaut/front/images/marker_4.png',
            shadow: fw_uri+'/templates/defaut/front/images/marker_shadow.png'
        },
        5: {
            icon: fw_uri+'/templates/defaut/front/images/marker_5.png',
            shadow: fw_uri+'/templates/defaut/front/images/marker_shadow.png'
        },
        6: {
            icon: fw_uri+'/templates/defaut/front/images/marker_6.png',
            shadow: fw_uri+'/templates/defaut/front/images/marker_shadow.png'
        }
	 
    
    };

     function load() {
		
		
        var map = new google.maps.Map(document.getElementById("map"), {
            center: new google.maps.LatLng(46.4576, 2.55968),
            zoom: 6,
            mapTypeId: google.maps.MapTypeId.TERRAIN
        });
	  
	  
        // Verifier si la div #map a changer de taille
	
        var infoWindow = new google.maps.InfoWindow;
        var marker_array = new Array();
        // Récupération des données du formulaire
        var ville = $('#parcs_ville').val();
        var categories_id = $('#categories_id').val();
        var departements_id = $('#departements_id').val();
	
        // Change this depending on the name of your PHP file
        downloadUrl(fw_uri+"/index.php?lang=fr&p=search&a=bybarre&parcs_ville="+ville+"&categories_id="+categories_id+"&departements_id="+departements_id, function(data) {
            var xml = data.responseXML;
            var markers = xml.documentElement.getElementsByTagName("marker");
       //     var bounds = map.getBounds();
		
		
		
			var bounds = new google.maps.LatLngBounds();
	
		
            for (var i = 0; i < markers.length; i++) {
				
				// Centrer la map sur les markers
				var ll = new google.maps.LatLng(markers[i].getAttribute("lat"), 
				markers[i].getAttribute("lng"));
				bounds.extend(ll);
				
                var name = markers[i].getAttribute("name");
                var id = markers[i].getAttribute("id");
                var address = markers[i].getAttribute("address");
                var type = markers[i].getAttribute("type");
                var point = new google.maps.LatLng(
                    parseFloat(markers[i].getAttribute("lat")),
                    parseFloat(markers[i].getAttribute("lng")));
                var html = "<strong> " + name + "</strong><br /> " + address + '<br /><a href="'+ fw_uri+'/'+$('html').attr('lang')+'/parcs/redirect/index.html?parcs_id='+id+'"><img src="'+fw_uri+'/templates/defaut/front/images/acceder_fiche.png" alt="" style="position:absolute;bottom:-36px;left:0px;"></a>';
                var icon = customIcons[type] || {};
                var marker = new google.maps.Marker({
                    map: map,
                    position: point,
                    icon: icon.icon,
                    shadow: icon.shadow
                });
		  
		  		map.fitBounds(bounds);
				
                marker_array.push(marker);
		  
                bindInfoWindow(marker, map, infoWindow, html);
		 
            }
		



		

        });
    /*var bounds = new google.maps.LatLngBounds();
		for (var index in marker_array) {
   	     var lat = marker_array[index].lat;
         var lng = marker_array[index].lng;
         var latlng = new google.maps.LatLng(lat, lng);
         bounds.extend(latlng);
   	 }
	 map.fitBounds(bounds);*/
	  
    }

	
	

    function bindInfoWindow(marker, map, infoWindow, html) {
		
        google.maps.event.addListener(marker, "click", function(e) {
            //removeInfoBox();
			
            var infoBox = new InfoBox({
                latlng: marker.getPosition(),
                map: map,
                html : html
            });
        });
    }
	 
    function downloadUrl(url, callback) {
        var request = window.ActiveXObject ?
        new ActiveXObject('Microsoft.XMLHTTP') :
        new XMLHttpRequest;

        request.onreadystatechange = function() {
            if (request.readyState == 4) {
                request.onreadystatechange = doNothing;
                callback(request, request.status);
            }
        };

        request.open('GET', url, true);
        request.send(null);
    }

    function doNothing() {}
	
	
});



    

