function geocodePosition(pos) {
	  geocoder.geocode({
	    latLng: pos
	  }, function(responses) {
	    if (responses && responses.length > 0) {
	    	$('user_ville').setProperty('value',responses[6].formatted_address);
	    } else {
	    }
	  });
	}
var map;
var geocoder;
var markersArray = [];
 markersArray['seeu'] = [];
 markersArray['general'] = [];

function UnirgyStoreLocator(config) {

    function searchLocationsNear(center, params) {
        var searchUrl = config.searchUrl+'?lat='+center.lat()+'&lng='+center.lng()+'&'+Object.toQueryString(params);

        jQuery.ajax({
            type: "GET",
            url: searchUrl,
            dataType: "xml",
            success: function(xml) {        

        	deleteOverlays();
        	jQuery('#'+config.sidebarEl).empty();
	        if (jQuery(xml).find("marker").length==0) {
	        	 jQuery('#'+config.sidebarEl).append('No results found.');
	             return;
	        }
	        var bounds = new google.maps.LatLngBounds();
	        i = 0;
	        jQuery(xml).find("marker").each(function() {
	        	var entry = jQuery(this);
	            var point = new google.maps.LatLng(parseFloat(entry.attr('latitude')), parseFloat(entry.attr('longitude')));
	            bounds.extend(point);
	            var marker = createMarker(entry, point);
	            var sidebarEntry = createSidebarEntry(entry, marker);
	            i++;
	        });
	        map.setCenter(bounds.getCenter(), map.fitBounds(bounds));
            
            }
        });

    }

    function escapeUserText(text) {
        if (text === undefined) {
            return null;
        }
        text = text.replace(/@/, "@@");
        text = text.replace(/\\/, "@\\");
        text = text.replace(/'/, "@'");
        text = text.replace(/\[/, "@[");
        text = text.replace(/\]/, "@]");
        return encodeURIComponent(text);
    };

    function createLabeledMarkerIcon(m) {
        var opts = config.iconOpts || {};

        var primaryColor = opts.primaryColor || "#DA7187";
        var strokeColor = opts.strokeColor || "#000000";
        var starPrimaryColor = opts.starPrimaryColor || "#FFFF00";
        var starStrokeColor = opts.starStrokeColor || "#0000FF";
        var label = escapeUserText(opts.label) || "";
        var labelColor = opts.labelColor || "#000000";
        var addStar = m.attr('star') || false;

        var pinProgram = (addStar) ? "pin_star" : "pin";
        var baseUrl = "http://chart.apis.google.com/chart?cht=d&chdp=mapsapi&chl=";
        var iconUrl = baseUrl + pinProgram + "'i\\"
            + "'[" + m.attr('marker_label') +  "'-4'f\\"  + "hv'a\\]" + "h\\]o\\"
            + primaryColor.replace("#", "")  + "'fC\\"
            + labelColor.replace("#", "")  + "'tC\\"
            + strokeColor.replace("#", "")  + "'eC\\";
        if (addStar) {
            iconUrl += starPrimaryColor.replace("#", "") + "'1C\\"
                + starStrokeColor.replace("#", "") + "'0C\\";
        }
        iconUrl += "Lauto'f\\";

        var icon = new GIcon(G_DEFAULT_ICON);
        icon.image = iconUrl + "&ext=.png";
        icon.iconSize = (addStar) ? new GSize(23, 39) : new GSize(21, 34);
        return icon;
    }
    function createMarker(m, point) {
    	  var clickedLocation = new google.maps.LatLng(point);

    	  //Content
          var url = m.attr('website_url').replace(/\s/,'');
          img='';
          for(i=1;i<4;i++){
              if(m.attr('img'+i+'_thumb')!=''){
              	img+='<a href="/media/'+m.attr('img'+i+'_url')+'" rel="slider'+m.attr('location_id')+'"><img class="img'+i+'" src="/media/'+m.attr('img'+i+'_thumb')+'" alt="" /></a>';
              }
          }
//          alert("a[rel='slider"+m.attr('location_id')+"']");}
          content = '<b>' + img + m.attr('title') + '</b> <br/>'
              + m.attr('address_display').replace(/\n/, '<br/>') + '<br/>'
              + (m.attr('phone').length>5 ? m.attr('phone') + '<br/>' : '')
              + '<div class="spacer"></div><br />'
              + (url.length>5 ? '<a class="rose" href="' + (url.match(/@/) ? 'mailto:' : '') + url + '"><strong>' + url + '</strong></a><br/>' : '')
              + '<p>' + m.attr('notes')+ '</p>';
          
    	  var infowindow = new google.maps.InfoWindow({
    	      content: content
    	  });

      	  
    	 var marker = new google.maps.Marker({
    	      position: point, 
    	      map: map
    	  });
		markersArray[config.own].push(marker);
    	    	  
        google.maps.event.addListener(marker, 'click', function() {
        	infowindow.open(map,marker);
        	jQuery("a[rel='slider"+m.attr('location_id')+"']").colorbox();
        });
        return marker;
    }

 // Removes the overlays from the map, but keeps them in the array
    function clearOverlays() {
      if (markersArray[config.own]) {
        for (i in markersArray[config.own]) {
          markersArray[config.own][i].setMap(null);
        }
      }
    }

    // Shows any overlays currently in the array
    function showOverlays() {
      if (markersArray[config.own]) {
        for (i in markersArray[config.own]) {
          markersArray[config.own][i].setMap(map);
        }
      }
    }

    // Deletes all markers in the array by removing references to them
    function deleteOverlays() {
      if (markersArray[config.own]) {
    	  for( var i = 0; i < markersArray[config.own].length; i++ ) {
          markersArray[config.own][i].setMap(null);
        }
        markersArray[config.own].length = 0;
      }
    }
    function createSidebarEntry(m, marker) {
       el = jQuery('#'+config.sidebarEl).append(config.generateSidebarHtml(m));
       jQuery('#'+config.sidebarEl+' div').last().click(   function() {
        	google.maps.event.trigger(marker, 'click');
        });
        return el;
    }

    return {
        load: function () {
            var clientLocation	=	google.loader.ClientLocation;
    	 	geocoder = new google.maps.Geocoder();
			centerZoom	=	4;
            if (clientLocation != undefined)
			{
				centerLat	= 	clientLocation.latitude;
				centerLong	=	clientLocation.longitude;
				city		=	clientLocation.address.city;
				region		=	clientLocation.address.region;
				country		=	clientLocation.address.country;

           	 	jQuery('.clientInfo').append(city+', '+region+', '+country);
          	 	jQuery('#address').val(city+', '+region+', '+country);
			var latlng = new google.maps.LatLng(centerLat, centerLong);

			}
			else{
			//	centerLat	= 	clientLocation.latitude;
			//	centerLong	=	clientLocation.longitude;
				city		=	defaultLocation;
				region		=	'';
				country	= 	'';           	 	
			jQuery('.clientInfo').append(city);           	 	
			jQuery('#address').val(city);
 			geocoder.geocode( { 'address': city}, function(results, status) {
        	      		if (status == google.maps.GeocoderStatus.OK) {
                    			var latlng =  results[0].geometry.location;
        	      		} else {
           	 			jQuery('.clientInfo').append('Not avalaible');
        	        		//alert("Geocode was not successful for the following reason: " + status);
        	      		}
        	    	});
        	  	}





    	    
    	    var myOptions = {
    	      zoom: centerZoom,
    	      center: latlng,
    	      mapTypeId: google.maps.MapTypeId.ROADMAP,

    	      mapTypeControl: true,
    	      mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
    	  	      
    	      navigationControl: true,
    	      navigationControlOptions: {
    	        style: google.maps.NavigationControlStyle.ZOOM_PAN
    	      }
    	    	      
    	    };
    	    map = new google.maps.Map(document.getElementById(config.mapEl), myOptions);
        },
        search: function(address, params) {
        	if (geocoder) {
        	    geocoder.geocode( { 'address': address}, function(results, status) {
        	      if (status == google.maps.GeocoderStatus.OK) {
                    searchLocationsNear(results[0].geometry.location, params);
//        	        map.setCenter(results[0].geometry.location);
        	      } else {
        	        alert("Geocode was not successful for the following reason: " + status);
        	      }
        	    });
        	  }
        }
    };
}
