/*
* CHARITECH.COM
* 08/02/2009
* 
* Google Map Rendering script
* jquery.js and mapdata.js required
*/
var a;
var map;
var clusterer;
var iconMap;
var geocoder = new GClientGeocoder();	
var pointTo = '';
var systemBusy = false;

function renderMap () {
	var i, ts, markers = [], cluster_opts = {
		gridSize: 40,
		maxZoom: 9,
		minClusterSize: 5,
		styles: [ {
			height: 32,
			width: 28,
			opt_anchor: [ 3 ],
			url: baseURL + '/images/shield_medium.png'
		} ]
	};

	if (document.getElementById('map')) {
		if (GBrowserIsCompatible()) {
			//geocoder = new GMercatorProjection();
			
			if ( map ) {
				map.clearOverlays();
			} else {
				map = new GMap2(document.getElementById("map"));
				map.setCenter(new GLatLng(39.90973623453719,-97.20703125),4);
				map.addControl(new GLargeMapControl() );
				map.addControl(new GMapTypeControl());
			}
			
			//update status
			try {
			$('#status').html(entries.length+" Entries found." );
			} catch (e) {
				//initData()
			}
			
			// find map location (if specifed in the serch result)
			if (pointTo.length > 2 ){
				geocoder.getLocations(pointTo, function (response) {
					if (response && response.Status.code == 200) {	
						place = response.Placemark[0];
        				newpoint = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
						map.setCenter(newpoint);
						pointTo = '';
					}
				});		
			}
			
			// disply info window
			if (firsttime) {
			map.openInfoWindowHtml(new GLatLng(37.3002752813443,-101.25), '<div class="waiting"><b>Loading data...</b><p>This may take few seconds. Please be patient!</p></div>');
				firsttime = false;
			}
			
			for ( i = 0; entries && i < entries.length; i += 1 ) {
				// create icons
				cIcon = getIcon(entries[i].t, entries[i].m);				
				// add marker
				var latlng = new GLatLng(entries[i].l,entries[i].o);
				marker = new GMarker(latlng,{icon:cIcon});
				//map.addOverlay(marker);			
				//add event listener
				marker.value = { id:String(entries[i].i), pos:latlng};
				GEvent.addListener(marker,"click", displayPopUp);
				markers.push( marker );
		  }

			if ( clusterer ) {
				clusterer.clearMarkers();
			}
			clusterer = new MarkerClusterer( map, markers, cluster_opts );
			
			entries = null;
			
		}
	} //map result
	else if (document.getElementById('map2')) {
			if (GBrowserIsCompatible()) {
			geocoder = new GClientGeocoder();	
			//check for existing latlng values, if found, add marker
			ext_long = $('#EntryLong').val();
			ext_lat = $('#EntryLat').val();
			//create map
			map = new GMap2(document.getElementById("map2"));
			
			if (ext_long.length > 0 && ext_lat.length > 0) {
				map.setCenter(new GLatLng(ext_lat,ext_long),5);
				map.addControl(new GLargeMapControl() );
				map.addControl(new GMapTypeControl());				
				//add marker
				addMarker (new GLatLng(ext_lat,ext_long));	
				
			}
			else {
				map.setCenter(new GLatLng(48.69096039092549,-102.919921875),3);
				map.addControl(new GLargeMapControl() );
				map.addControl(new GMapTypeControl());
				
				// Add event listener to insert marker
				var insertListener =  GEvent.addListener(map,"click", function(overlay,latlng) {
					// create icons									  
					addMarker (latlng)	
					GEvent.removeListener(insertListener);
					geocoder.getLocations(latlng, reverseLookup);
				});
			}
		}
	}   	
}


// add new icon to give location
function addMarker (latlng){
	// wait untill load the map
	if (!map)
		return;
	//clear existing icons
	map.clearOverlays();
	// add new icon
	var baseIcon = new GIcon(G_DEFAULT_ICON);
	baseIcon.shadow = baseURL+"/images/shadow.png";
	baseIcon.iconSize = new GSize(15, 26);
	baseIcon.shadowSize = new GSize(34, 26);
	baseIcon.iconAnchor = new GPoint(7, 26);
	baseIcon.infoWindowAnchor = new GPoint(8, 2);

	var cIcon = new GIcon(baseIcon);
	cIcon.image = baseURL+"/images/blue.png";
	// add marker and make it dragable
	marker = new GMarker(latlng,{icon:cIcon, draggable: true});
	//update fields
	updateLatLng( latlng);
	
	map.addOverlay(marker);
	// remove insert listener
	
	// add a listenr to take the position
	GEvent.addListener(marker, "dragend", function(marker) {
		//marker.y , marker.x
		updateLatLng(marker);
		geocoder.getLocations(marker, reverseLookup);
	});	
}

// Update long/lat fields on the form
function updateLatLng( latlng){
	
	if (latlng){
		$('#EntryLat').val(latlng.y);
		$('#EntryLong').val(latlng.x);
	}
}

// query latlang
function findLatlng (){
	q = $('#queryAddress').val();
	
	if (q.length > 2 ){
		geocoder.getLocations(q, addAddressToMap);		
	}
	else {
		alert('Address is too short.\nPlease try with city,zip,state etc...');
	}
	
	// always prevent submitting
	return false;
}

function findLocation (){
	address = $('#EntryStreet').val()+" "+$('#EntryCity').val()+" "+$('#EntryState').val()+" "+$('#EntryZip').val()+" "+$('#EntryCountry').val();
	address = $.trim(address);
	if (address.length > 1)
		geocoder.getLocations(address, addAddressToMap2);
}

// once the query is succseeded, fire this function 
function addAddressToMap(response) {
	if (!response || response.Status.code != 200) {
        alert("Sorry, we were unable to geocode that address");
      } else { 	
		// add new mark
        place = response.Placemark[0];
        point = new GLatLng(place.Point.coordinates[1],
                            place.Point.coordinates[0]);
		addMarker(point);
		// move map 
		map.setCenter(point,5);
		// update country
		opts = $('#EntryCountry option');
		country = place.AddressDetails.Country.CountryName.toLowerCase();
		try { 
			updateForm (place.address);
		} catch (e) {}

      }
}

function addAddressToMap2(response) {
	if (!response || response.Status.code != 200) {
        //alert("Sorry, we were unable to geocode that address");
      } else { 	
		// add new mark
        place = response.Placemark[0];
        point = new GLatLng(place.Point.coordinates[1],
                            place.Point.coordinates[0]);
		addMarker(point);
		// move map 
		map.setCenter(point,5);
		// update country
		opts = $('#EntryCountry option');
		country = place.AddressDetails.Country.CountryName.toLowerCase();
		try { 
			//updateForm (place.address);
		} catch (e) {}

      }
}

function reverseLookup (response) {
	if (response || response.Status.code == 200) {
		try {
        	updateForm (response.Placemark[0].address);
		} catch (e) {}
      } 
}

function updateForm (address){
	
	if (!address)
		return;
	//clear entries
	$('#EntryZip').val('');
	$('#EntryCity').val('');
	$('#EntryState option').attr('selected',false);
	opts2 = $('#EntryState option');
	$(opts2[0]).attr('selected',true);
		
	// split address lines
	lines = address.split(',');
	
	// update country
	opts = $('#EntryCountry option');
	country = $.trim(lines[lines.length - 1]).toLowerCase();

	if (country == 'United States')
		country = 'USA';
	$.each (opts, function (){
		$(this).attr('selected',false);
		
		if ($(this).val().toLowerCase() == country ){	
			$(this).attr('selected',true);
			return;
		}
	})
	
	// update state/zip (us) or city
	if (!lines[lines.length - 2])
		return;
		
	line2 = $.trim(lines[lines.length - 2]).split(' ');
	if (line2.length > 1){
		//first line would be state
		state = findState($.trim(line2[0].toLowerCase()));

		if (!state){
			v = $.trim(line2[0])+' '+$.trim(line2[1]);
			state = findState(v.toLowerCase());
			
			if (state)
				line2.shift();
		}
		opts2 = $('#EntryState option');
		$.each (opts2, function (){
		$(this).attr('selected',false);
		
			if ($(this).html() == state ){	
				$(this).attr('selected',true);
				line2.shift();
				return;
			}
		});
		
		//second line would be zip code
		if (line2[line2.length-1]*1) {
			$('#EntryZip').val(line2[line2.length-1]);
			// there might be city name at the leadeing elemnts	
			line2.pop();
		}
		line2 = $.trim(line2.join(' '));
		if (line2.length > 0)
			$('#EntryCity').val(line2);
		else {
			if (lines[lines.length - 3]){
				$('#EntryCity').val($.trim(lines[lines.length - 3]));
			}
		}
			
	}
	else {
		if (lines[lines.length - 3]){
				$('#EntryCity').val($.trim(lines[lines.length - 3]));
		}
		// this line would contains city
		
		state = findState($.trim(line2[0]).toLowerCase());
		opts2 = $('#EntryState option');
		$.each (opts2, function (){
		$(this).attr('selected',false);			
			if ($(this).html() == state ){	
				$(this).attr('selected',true);
				line2[0].pop();
				return;
			}
		});	

		$('#EntryCity').val(line2[0]);
	}	
}

var stateNames = ['alaska','alabama','arkansas','arizona','california','colorado','connecticut','d. columbia','delaware','florida','georgia','hawaii','iowa','idaho','illinois','indiana','kansas','kentucky','louisiana','massachusetts','maryland','maine','michigan','minnesota','missouri','mississippi','montana','north carolina','north dakota','nebraska','new hampshire','new jersey','new mexico','nevada','new york','ohio','oklahoma','oregon','pennsylvania','puerto rico','rhode island','south carolina','south dakota','tennessee','texas','utah','virginia','vermont','washington','wisconsin','west virginia','wyoming'];

var stateCodes = ['AK','AL','AR','AZ','CA','CO','CT','DC','DE','FL','GA','HI','IA','ID','IL','IN','KS','KY','LA','MA','MD','ME','MI','MN','MO','MS','MT','NC','ND','NE','NH','NJ','NM','NV','NY','OH','OK','OR','PA','PR','RI','SC','SD','TN','TX','UT','VA','VT','WA','WI','WV','WY'];

function findState (name){
	sindex =  $.inArray(name,stateNames);
	if (sindex >= 0){
		return stateCodes[sindex];	
	}
	else {
		name = name.toUpperCase();
		if ($.inArray(name,stateCodes) >= 0)
			return name;
		else
			return false;
	}
}

function getIcon (icontype, military){
	var baseIcon;

	icontype = parseInt(icontype);
	
	if ( ! iconMap ) {
		iconMap = [];
		baseIcon = new GIcon(G_DEFAULT_ICON);
		baseIcon.iconSize = new GSize(15, 26);
		baseIcon.shadow = baseURL+"/images/shadow.png";
		baseIcon.shadowSize = new GSize(34, 26);
		baseIcon.iconAnchor = new GPoint(8, 10);
		baseIcon.infoWindowAnchor = new GPoint(8, 2);

		iconMap[0] = new GIcon( baseIcon );
		iconMap[0].image = baseURL+"/images/chapters.png";
		iconMap[1] = new GIcon( baseIcon );
		iconMap[1].image = baseURL+"/images/orange.png";
		iconMap[2] = new GIcon( baseIcon );
		iconMap[2].image = baseURL+"/images/green.png";
		iconMap[3] = new GIcon( baseIcon );
		iconMap[3].image = baseURL+"/images/red.png";
		iconMap[4] = new GIcon( baseIcon );
		iconMap[4].image = baseURL+"/images/blue.png";
		iconMap[5] = new GIcon( baseIcon );
		iconMap[5].image = baseURL+"/images/yellow.png";

		baseIcon.shadow = baseURL+"/images/shadow2.png";
		iconMap[6] = new GIcon( baseIcon );
		iconMap[6].image = baseURL+"/images/flag_orange.png";
		iconMap[7] = new GIcon( baseIcon );
		iconMap[7].image = baseURL+"/images/flag_green.png";
		iconMap[8] = new GIcon( baseIcon );
		iconMap[8].image = baseURL+"/images/flag_red.png";
		iconMap[9] = new GIcon( baseIcon );
		iconMap[9].image = baseURL+"/images/flag_blue.png";
		iconMap[10] = new GIcon( baseIcon );
		iconMap[10].image = baseURL+"/images/flag_yellow.png";
	}
	if (military == 1){
		icontype += 5;
	}
	
	return iconMap[ icontype ];
}


function displayPopUp (marker) {
					var latlng = this.value.pos;
					var record = this.value.id;
					map.openInfoWindow(latlng, '<div class="waiting">Please wait...</div>');
					systemBusy = true;
					
					//load data from serevr
					$.ajax({
					  url:  baseURL+"/info/"+ record,
					  cache: false,
					  success: function(data){
							// display pop up window aith new contents
							map.closeInfoWindow();
							map.openInfoWindowHtml(latlng,data);
							
					  },
					  error : function (data){
							systemBusy = false;
							map.closeInfoWindow();
							alert("Sorry! Cannot load information.\nPlease try again later.");
					  }
					});
				
}
