/* config */
var mapSelector = '.map';

/* script */
$(function() {
   if($(mapSelector).length>0){  
      var s = document.createElement("script");
      s.type = "text/javascript";
      s.src  = "http://maps.google.com/maps/api/js?v=3&sensor=false&callback=gmap_draw";
      window.gmap_draw = function(){
          buildMaps(mapSelector);
      };
      $("head").append(s);
   }
});
function buildMaps(selector){
	$(selector).each(function(){
          
		var mapProperties = getMapProperties($(this));
		var myLatLng = new google.maps.LatLng(mapProperties.centerLat, mapProperties.centerLon);

		var myOptions = {
			   zoom: mapProperties.zoom,
			   center: myLatLng,
			   mapTypeId: mapProperties.mapType,
			   streetViewControl: false
			 };
          var geocoder;
		var map = new google.maps.Map($(this).get(0), myOptions);			 



		for(var i = 0;i<mapProperties.markers.length;i++){
			var markerProperties = mapProperties.markers[i];
               if(markerProperties.geolocation){
                  addressToCoords(mapProperties.geolocationmapcenter,'marker',map,markerProperties);
               }else{
                  var markerLatLng = new google.maps.LatLng(markerProperties.markerLat, markerProperties.markerLon);
                  var marker = new google.maps.Marker({
                         position: markerLatLng,
                         map: map,
                         icon: markerProperties.image
                    });
                    var infowindow = new google.maps.InfoWindow({
                            content: markerProperties.infoWindow
                       });

                  google.maps.event.addListener(marker, 'click', function() {
                    infowindow.open(map,marker);
                  });
                  if(markerProperties.showInfoWindow){
                       infowindow.open(map,marker);
                  }
               }

		}

          if(mapProperties.geolocationmapcenter){
             addressToCoords(mapProperties.geolocationmapcenter,'center',map);
          }
		
		
	});
}

function getMapProperties(map){
	var markers = new Array();
	map.find('.marker').each(function(){
		markers.push({
			markerLat : parseFloat($(this).find('.location').html().split(',')[0]),
			markerLon : parseFloat($(this).find('.location').html().split(',')[1]),
			infoWindow : ($(this).find('.infowindow')?$(this).find('.infowindow').html():null),
			showInfoWindow : ($(this).find('.infowindow').hasClass('show')?true:false),
			image : ($(this).find('.image')?$(this).find('.image').html():null),
               geolocation: map.find('.geolocation').html()
		});
	});

     
     var centerLat = parseFloat(map.find('.mapcenter').html().split(',')[0]);
     var centerLon = parseFloat(map.find('.mapcenter').html().split(',')[1]);
     

	properties = {
		zoom: parseInt(map.find('.zoomlevel').html(),10)>0?parseInt(map.find('.zoomlevel').html(),10):10,
		mapType: map.find('.maptype').html()!=""?map.find('.maptype').html():"roadmap",
		centerLat: centerLat,
		centerLon: centerLon,
		markers: markers,
          geolocationmapcenter: map.find('.geolocationmapcenter').html()
	};
	return properties;
}

function showInfoWindow(html){
	//console.log(html);
}

 function addressToCoords(address,action,map,markerProperties) {
    var geocoder = new google.maps.Geocoder();
    return geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
         if(action=='center'){
            //console.log(action);
            map.setCenter(results[0].geometry.location);
         } else if(action=='marker'){
            var marker = new google.maps.Marker({
                   position: results[0].geometry.location,
                   map: map,
                   icon: markerProperties.image
              });
              var infowindow = new google.maps.InfoWindow({
                      content: markerProperties.infoWindow
                 });

            google.maps.event.addListener(marker, 'click', function() {
              infowindow.open(map,marker);
            });
            if(markerProperties.showInfoWindow){
                 infowindow.open(map,marker);
            }
         }
        return results[0].geometry.location;
      } else {
        //alert("Geocode was not successful for the following reason: " + status);
      }
    });
  }
