var radMap = function( o){
	o.modin = o.modin || false;
	o.uid = o.uid || false;
	o.mapContainer = o.container || false;
	o.draggable = o.draggable || false;
	o.popUpImg = o.popUpImg || false;
	o.popUpText = o.popUpText || false;
	if( !(o.directions === false) ) {
		o.directions = true;
	}
	
	
	if (typeof(o.mapControl) == "undefined") o.mapControl = true;
	var map;
	var geocoder;
	var data;
	var gdir;
	var rMap= {};
	if ( !o.modin) {
		throw('modin not set');
	} else {
		execute();
	}

	function createMarker(data){
                var success;
    
                // create coordinates
                var coordinates = {};
                var coordinates_exist = false;
                if (data.lat) coordinates.lat = data.lat;
                if (data.long) coordinates.long  = data.long;
                if (data.lat && data.long) coordinates_exist = true;

                // create address
		var address = '';
		if (data.street) address += data.street + ', ';
		if (data.city) address += data.city + ', ';
		if (data.state) address += data.state + ' ';
		if (data.zip) address += data.zip;

                // create popup address
		var popupAddress = '';
		if (data.street) popupAddress += data.street + '<br /> ';
		if (data.city) popupAddress += data.city + ', ';
		if (data.state) popupAddress += data.state + ' ';
		if (data.zip) popupAddress += data.zip;

		// create popup data
		var popUp = { img: '', text: ''};
		if (data.img) {
			popUp.img = '<div class="popUp-img"><img src="'+data.img+'" border="0"/></div>';
		}
		if (data.text){
			popUp.text = '\
			<div class="popUp-text">'+data.text+'</div>\
			<div class="popUp-address">'+popupAddress+'</div>\
			';
		}
		popUp.html = popUp.img+popUp.text;	

                if( coordinates_exist ){ 
                  createMarkerFromPoint( new GLatLng( coordinates.lat, coordinates.long)); 
                } else {
                  success = geocoder.getLatLng(address, createMarkerFromPoint); 
                }

                return success;

                function createMarkerFromPoint( point ){
                        if(!point) {
                          }
                        if (point) {
	                        			var redIcon = new GIcon();
																redIcon.image = "/img/aldf_map_icon1.gif";
																redIcon.shadow = "";
																redIcon.iconSize = new GSize(8, 8);
																redIcon.iconAnchor = new GPoint(6, 20);
																redIcon.infoWindowAnchor = new GPoint(5, 1);

																// Set up our GMarkerOptions object
																markerOptions = { icon:redIcon };

                                var marker = new GMarker(point, markerOptions);
                                map.addOverlay(marker);
                                marker.address = address;
                                marker.popUp = popUp;
                                GEvent.addListener(marker, "mouseover", function(latlng){
                                        var popUpHtml = this.popUp.html;

                                        if( o.directions){
                                                document.directionsForm.to.value = this.address;
                                        }

                                        if (o.popUpType == 'info') {
                                                this.openInfoWindowHtml(popUpHtml);
                                        }
                                        if (o.popUpType == 'overlay') {
                                                $('#map-overlay').slideDown();
                                                $('#popUp-content').fadeOut(200).queue(function (){
                                                        $(this).html(popUpHtml);
                                                        $(this).dequeue();
                                                }).fadeIn(200);
                                        }
                                });

                                GEvent.addListener(marker, "mouseout", function(latlng){
                                //	$('#map-overlay').slideUp();
                                });
                        }
                }
	}
        
        function execute() {
		initialize();

		if (GBrowserIsCompatible()){
			map = new GMap2(document.getElementById(o.mapContainer+"-map"));
			map.setCenter( new GLatLng(44,-110),2);
			if (!o.draggable) map.disableDragging();
			geocoder = new GClientGeocoder();
			
			if( o.mapControl) map.addControl(new GLargeMapControl());
			
			if( o.directions ){
				gdir = new GDirections(map, document.getElementById("directions"));
				$('#directions').hide();
				GEvent.addListener(gdir, "error", handleErrors);
				GEvent.addListener(gdir, "addoverlay", loadDirections);
			}
			
			$.getJSON( o.jsonPath, { modin : o.modin, uid : o.uid, popUpImg: o.popUpImg, popUpText: o.popUpText}, function(data){
				for (var i = 0; i <  data.length; i++){
					createMarker(data[i]);
				}
			});
		}
	}

	function initialize(){
		$('#'+o.mapContainer).empty().css("position","relative");
		
		$('\
			<div class = "map" id="'+o.mapContainer+'-map" style="width: '+o.width+'; height: '+o.height+'">\
			</div>\
			<div id="map-overlay">\
				<div id="popUp-content"></div>\
			</div>\
			').appendTo('#'+o.mapContainer);
			
		if( o.directions ){
			$('\
				<div id="directions-form">\
					<form name="directionsForm"  action="#" onsubmit="'+o.mapName+'.setDirections(this.from.value, this.to.value); return false">\
						<div id="from-box" class="directions-box">\
							<span class="directions-label">From:&nbsp;</span><input type="text" size="25" id="fromAddress" name="from" value="" />\
						</div>\
						<div id="to-box" class="directions-box">\
							<span class="directions-label">To:&nbsp;</span><input type="text" size="25" id="toAddress" name="to" value="" />\
						</div>\
						<div id="submit-box" class="directions-box">\
							<input name="submit" type="submit" value="Get Directions!" />\
						</div>\
					</form>\
				</div>	\
			<div id="directions"></div>\
			').appendTo('#'+o.mapContainer);
		}
	}

	var setDirections = function(fromAddress,toAddress,locale){
		$('#directions').fadeOut('200');
      	gdir.load("from: " + fromAddress + " to: " + toAddress, {"locale": "english" });
		if (!o.mapControl) map.addControl(new GLargeMapControl());
		map.enableDragging();	
//		$('#directions').fadeIn('400');
//		$('#directions').slideDown('800');

    };
	function loadDirections(){
		$('#directions').fadeIn('400');
		$('#directions').slideDown('2600');
	}
	function handleErrors(){
	   if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
	     alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
	   else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
	     alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
	   
	   else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
	     alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);

	//   else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
	//     alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + gdir.getStatus().code);
	     
	   else if (gdir.getStatus().code == G_GEO_BAD_KEY)
	     alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);

	   else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
	     alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
	    
	   else alert("An unknown error occurred.");
	   
	}
	if( o.directions ) rMap.setDirections = setDirections;
	return rMap;
}

