function include_dom(script_filename) {
    var html_doc = document.getElementsByTagName('head').item(0);
    var js = document.createElement('script');
    js.setAttribute('language', 'javascript');
    js.setAttribute('type', 'text/javascript');
    js.setAttribute('src', script_filename);
    html_doc.appendChild(js);
    return false;
}

function include(script_filename) {
    document.write('<' + 'script');
    document.write(' language="javascript"');
    document.write(' type="text/javascript"');
    document.write(' src="' + script_filename + '">');
    document.write('</' + 'script' + '>');
}

include("http://maps.google.com/maps/api/js?sensor=false");

String.prototype.toProperCase = function() {
  return this.toLowerCase().replace(/^(.)|\s(.)/g, 
      function($1) { return $1.toUpperCase(); });
}

function LMICAgentFinder(MapDiv, AgtListDiv, Options) {
	this.defaultzoom = 8;
	this.zoomarray = [[5,11],[10,10],[15,9]];
	this.mapmarkers = null;
	this.infowin = null;
	this.geocoder = new google.maps.Geocoder(); 
	this.mapdiv = dojo.byId(MapDiv);
	this.agtdiv = dojo.byId(AgtListDiv);
	this.compcolors = ['','',['6060FF','FFFFFF'],['80FF80','000000'],['F0F04C','000000'],['AD0064','FFFFFF']];
	this.comp = 0;
	
	if (typeof(this.mapdiv) == "undefined") {
		alert('Map Div ' + MapDiv + ' not Found');
		return;
	}
	if (typeof(this.agtdiv) == "undefined") {
		alert('Agent List Div ' + AgtListDiv + ' not Found');
		return;
	}
	if (Options && dojo.isArray(Options.ZoomArray)) this.zoomarray = Options.ZoomArray; 
	if (Options && dojo.isString(Options.Company)) this.comp = Options.Company; 
		
	this.ShowAgentMap = function(City, State, Zip, Miles) {	
		var addr = "";
		if (Zip != "")
			addr = Zip;
		else if(State == "") {
			alert("Please enter Zip Code or City and State");
			return;
		} else {
			addr = City + " " + State;
		}
		this.miles = parseInt(Miles);
	
		this.geocoder.geocode( {'address': addr},  this.geocoderCallback); 
	}
	
	this.geocoderCallback = dojo.hitch(this, function(results, status) {
		if (status == google.maps.GeocoderStatus.OK) { 
			this.ShowAgentMapLocs(results[0].geometry.location);
    	} else { 
      		alert("Geocode was not successful for the following reason: " + status); 
    	} 
	})
		
	this.ShowAgentMapLocs = function (GeoLoc) {

		dojo.xhrGet( {url: dburl + "/getLocAgtLocs?openagent",
						handleAs: "json",
						content: { 'lat':GeoLoc.lat(), 'lng':GeoLoc.lng(), 'miles':this.miles, 'comp':this.comp},
						load: dojo.hitch(this, function(response, ioArgs) {
								var latlng;
						
								if (typeof(response.centerlat) != "undefined") {
								
							 		latlng = new google.maps.LatLng(response.centerlat, response.centerlng);
							 	} else {
							 			
							 		latlng = new google.maps.LatLng(GeoLoc.lat(), GeoLoc.lng());
							 	}	
							 		 
						    	var myOptions = { 
							      	zoom: this.defaultzoom,
							      	center: latlng, 
					 		     	mapTypeId: google.maps.MapTypeId.ROADMAP, 
					 		     	scaleControl:true,
					 		     	mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU} 
    								}; 	
    								
					    		this.map = new google.maps.Map(this.mapdiv, myOptions); 
					   
								this.mapmarkers = new Array();
								this.infowin = new Array();
								var info = "";
								var agtMiles = 0;
								var agtrecs = response.mapagents;
								var html = "<table align='center' style='width:97%' cellpadding='2' cellspacing='0'>";
								if (agtrecs.length > 0) {
									html += "<tr><th/><th>Agency</th><th>Miles</th></tr>"
									for (var i=0; i < agtrecs.length; i++) {
									 	var agt = agtrecs[i];
									 	html += "<tr>"+
													"<td class='agtidx'>" + String.fromCharCode(65+i) + "</td>"+
													"<td class='agtinfo' id='agtrec"+i+"'>"+
													"<span class='agtNm'>" + agt.agtname + "</span><br>" + agt.agtaddr + "<br>" + 
													agt.agtcity + ", " + agt.agtstate + "&nbsp;&nbsp;" + agt.agtzip + "<br>" +													"Phone: " + agt.agtphone + "&nbsp;";
													if (agt.agtemail != "") {			
														html += " / <a href='mailto:" +  agt.agtemail + "'>Email</a>";	
													}			 
													if (agt.agturl != "") {
														html += " / <a href='" + agt.agturl + "' target='_blank'>Web Site</a>";
													}
													html += "</td>";
										html += "<td class='agtmiles'>" + agt.miles + "</td></tr>";
										agtMiles = parseFloat(agt.miles);
									 	var agtlatlng = new google.maps.LatLng(agt.lat, agt.lng); 	
										this.mapmarkers[i] = new google.maps.Marker({ 
	    									  position: agtlatlng,
	    									  map: this.map,  
	    									  icon: "//chart.apis.google.com/chart?chst=d_map_pin_letter&chld="+
	    									  			String.fromCharCode(65+i)+
	    									  			"|"+this.compcolors[agt.agtcomp][0]+"|"+this.compcolors[agt.agtcomp][1],
	    									  title: String.fromCharCode(65+i)+") " + agt.agtname.toProperCase()
										  }); 
										  
										var info = "<div class='agtinfo'>" + agt.agtname + "<br/>" + agt.agtaddr + "<br/>" +
													agt.agtcity + ", " + agt.agtstate + "&nbsp;&nbsp;" + agt.agtzip + "<br>" +
													"phone: " + agt.agtphone + "<br>";
													
										if (agt.agtemail != "") {			
											info += "<a href='mailto:" +  agt.agtemail + "'>Email</a>";
											info += (agt.agturl != "") ? " / " : "";				
										}			 
										if (agt.agturl != "") {
											info += "<a href='" + agt.agturl + "' target='_blank'>Web Site</a>";
										}
										this.mapmarkers[i].parent = this;
										this.mapmarkers[i].infowin = new google.maps.InfoWindow({content:info});  
										google.maps.event.addListener(this.mapmarkers[i], 'click', dojo.hitch(this.mapmarkers[i], function() { 
													this.parent.closeInfoWin();
	  												this.infowin.open(this.map, this);
												})
											);
									  
									 }
								} else {
									html += "<tr><td class='NoAgtMsg'>No Agents Found for your Search Criteria."+
											"<br/><a onClick=\"hideMe('map');showMe('myPage')\">Try Again</a></td></tr>";
								}	 
								html += "</table>"
								 
								this.agtdiv.innerHTML = html;
								
								var zoom = this.defaultzoom;
								for(var i=0; i<this.zoomarray.length; i++) {
									if (agtMiles <= this.zoomarray[i][0]) {
										zoom = this.zoomarray[i][1];
										break;
									}	
								}
								this.map.setZoom(zoom);
								
								for (var i=0; i < agtrecs.length; i++) {
									var rec = dojo.byId('agtrec'+i);
									dojo.connect(rec, "click", this.mapmarkers[i], function() { 
												this.parent.closeInfoWin();
  												this.infowin.open(this.map, this);
											});
								}
								
							}),
						error : function(response, ioArgs) {
									alert("Agents Lookup Error: " + response.message);
							}
			})
		}	
		
		this.openinfo = function(arg1, arg2) {
		debugger;
			alert(arg1.id);
		
		}
		
		this.closeInfoWin = function() {
			for (var i=0; i < this.mapmarkers.length; i++) {
				this.mapmarkers[i].infowin.close()
			}
		}
}

