// copyright 2008-2009 maps4me.com

m4m = {
	
	map : null,
	axis : {lat:0,lng:0},
	currentCat : '',
	catUrls : ['empty','yard_sales','performances','meetings','community'],
	
	prepareAddress : function(){
		// first validate the fields
		var goFlag = true;
		if(!$('#mapevent_address').val().length) goFlag = false;
		if(!$('#mapevent_city').val().length) goFlag = false;
		if(!$('#mapevent_state').val().length) goFlag = false;
		// if(!$('#mapevent_zip').val().length) goFlag = false;
		
		// build the full address string
		var tmpFields = $('#mapevent_address').val();
		tmpFields += " " + $('#mapevent_city').val();
		tmpFields += " "  + $('#mapevent_state').val();
		tmpFields += " " + $('#mapevent_zip').val();
		tmpFields += " US";
		
		this.address = tmpFields;
		
		if(goFlag){
			// init the google map
			initialize();
			// send the entered address to be geocoded
			showLocation(tmpFields);	
		} 
	},
	
	setCat : function(catId){
		$('#mapevent_category_id').attr('value',catId);
	},
	
	getSubcats : function(theId){
		$('#subCats').load('/subcategories/' + theId);
	},
	
	/**
	 * Sets the map up, loops through the event listing in the DOM, and creates the map markers
	 */
	mapInit : function(){
		
		var startCoords = {};
		
		if (GBrowserIsCompatible()) {
		
			m4m.map = new google.maps.Map2(document.getElementById("eventMap"));
			m4m.map.addControl(new GSmallMapControl());
			m4m.map.setCenter(new GLatLng(m4m.axis.lat, m4m.axis.lng), 9);
			
			GEvent.addListener(m4m.map, 'moveend', function() {
				m4m.checkForReset();
			});
			
			$(".mapevent").each(function(){
				var infHead = $(this).find("h3").text();
                var infAddr = $(this).find("p:first").text();
                var infDates = $(this).find("p:eq(1)").html();
				var tmpMeta = $(this).attr('meta').split(',');
				var eventType = tmpMeta[0];
				var point = new GLatLng(tmpMeta[1], tmpMeta[2]);
				var theMark = new GMarker(point);
				GEvent.addListener(theMark, 'click', function(){
					theMark.openInfoWindow('<div class="infDiv"><h3>' + infHead + '</h3><p>' + infAddr  + '</p><p>' + infDates + '</p></div>');
				});
				m4m.map.addOverlay(theMark);
				eventMarkers[eventType].push(theMark);
				$('#' + eventType).next().text('(' + eventMarkers[eventType].length + ')')
			});
			 
		}
	},

	/**
	 * 
	 * @param {Object} eventType : subcategory_id
	 * Loops through the proper eventMarker array and toggles visibility
	 */
	updateMarkers : function(eventType) {
      for (var i = 0; i < eventMarkers[eventType].length; i++) {
        var marker = eventMarkers[eventType][i];
        if (marker.isHidden()) {
          marker.show();
        } else {
          marker.hide();
        }
      }
      m4m.updateList(eventType);
    },
	
	/**
	 * 
	 * @param {Object} eventType : subcategory_id
	 * Loops through the mapevent collection and toggles visibility
	 */
	updateList : function(eventType){
		$('.mapevent').each(function(itm){
			if ($(this).hasClass(eventType)){
				($(this).css('display') == 'none') ? $(this).blindDown() : $(this).blindUp();
    		}
    	});
    },
	
	/**
	* if the map has been scrolled more than 40Km from the last search
	* turn on the 'load more' button
	*/
	checkForReset : function(){
		var currCenter = m4m.map.getCenter();
		var point = new GLatLng(m4m.axis.lat, m4m.axis.lng);
		var movedBy = currCenter.distanceFrom(point);
		movedBy > 40000 ? m4m.setReset(1): m4m.setReset(0);
	},
	
	/**
	*	iterates thru the filters
	*/
	filterReset : function(){
		$$('.filterGroup').each(function(itm){
			itm.setStyle('height',0);
		});
		$$('#filterBar input').each(function(itm){
			itm.getNext().addClass('empty')
		});
	},
	
	setReset : function(state){
		if(state == 1){
			$('#resetSearch')
				.removeClass('disabled')
				.attr('href','javascript:m4m.resetCenter()');
		}else{
			$('#resetSearch')
				.addClass('disabled')
				.removeAttr('href');
		}
	},
	
	resetCenter : function(){
		var newCenter = m4m.map.getCenter();
		var newLat = newCenter.lat();
		var newLng = newCenter.lng();

		// load a new page with the new coordinates - better for bookmarking
		document.location = "/" + m4m.catUrls[m4m.currentCat] + "/" + m4m.safeCoord(newLat) + "/" + m4m.safeCoord(newLng);
		
	},
	
	// for some reason Rails routes do not like a decimal point in them...
	safeCoord : function(decimalVar){
		decimalVar = decimalVar.toString();
		var safeVar = decimalVar.replace(/\./gi,'_');
		return safeVar;
	}
}


	var map;
	var geocoder;
  
	function initialize() {
		map = new google.maps.Map2(document.getElementById("geoPreview"));
		map.setCenter(new GLatLng(34, -117), 10);
		geocoder = new GClientGeocoder();
	}

    function addAddressToMap(response) {
    	map.clearOverlays();
			
		if (!response || response.Status.code != 200) {
			$('#msgCenter').text('Sorry, we are unable to find that address');	
			// $('#section2').slideUp();
			
      	} else {
        	$('#msgCenter').text('Address found: Please continue!');
			// $('#section2').slideDown();
				
			place = response.Placemark[0];
        	point = new GLatLng(place.Point.coordinates[1],
                            	place.Point.coordinates[0]);

			map.setCenter(point, 15);

			marker = new GMarker(point);
			map.addOverlay(marker);
        
			$('#mapevent_lat').val(place.Point.coordinates[1]);
			$('#mapevent_lng').val(place.Point.coordinates[0]);
      	}
    }
    
	function showLocation(address) {
    	geocoder.getLocations(address, addAddressToMap);
    }


