var dist = 10;

var map = null;
//var geocoder = null;
var bounds = null;
// var latLng = null;
// var center = null;
var markers = null;
var searchLocation = null;

var GeoCodeCalc = {};
GeoCodeCalc.EarthRadiusInMiles = 3956.0;
GeoCodeCalc.EarthRadiusInKilometers = 6367.0;
GeoCodeCalc.ToRadian = function(v) { return v * (Math.PI / 180);};
GeoCodeCalc.DiffRadian = function(v1, v2) { 
return GeoCodeCalc.ToRadian(v2) - GeoCodeCalc.ToRadian(v1);
};
GeoCodeCalc.CalcDistance = function(lat1, lng1, lat2, lng2, radius) { 
return radius * 2 * Math.asin( Math.min(1, Math.sqrt( ( Math.pow(Math.sin((GeoCodeCalc.DiffRadian(lat1, lat2)) / 2.0), 2.0) + Math.cos(GeoCodeCalc.ToRadian(lat1)) * Math.cos(GeoCodeCalc.ToRadian(lat2)) * Math.pow(Math.sin((GeoCodeCalc.DiffRadian(lng1, lng2)) / 2.0), 2.0) ) ) ) );
};

function searchPartner() {
	$.ajax({
		url: "../partners/resultSearch?search="+$("#searchText").val(),
		cache: false,
		success: function(response) {
			if (response == "None Found.") {
				getGeocode($("#searchText").val());
			}
			else {
				window.location = "../partners/resultList?id="+response;
			}
		},
		error: function() {}
	})
}

function loadPartner(id) {
	$.ajax({
		url: "../partners/generateResultsFromName?id="+id,
		cache: false,
		success: function(html){
			$('#results').html(html);
			if (GBrowserIsCompatible()) {
			    map = new GMap2(document.getElementById("map_canvas"));
			    map.setCenter(new GLatLng(37.4419, -122.1419), 7);
				map.addControl(new GLargeMapControl3D());
				bounds = new GLatLngBounds();
			
				points = ($('.results td.geoCode').text()).split(',');
				map.clearOverlays();
				var blueIcon = new GIcon(G_DEFAULT_ICON);
				blueIcon.image = "images/location_pointer_blue.png";
				//blueIcon.iconSize = (new GSize(32,32));
				markerOptions = {icon:blueIcon};
				center = new GLatLng(points[0],points[1]);
		        marker = new GMarker(center,markerOptions);
		        map.addOverlay(marker);
				map.setCenter(center);
				
				GEvent.addListener(marker,"click",function() {
					marker.openInfoWindowHtml($(".moreDetails").first().html());
				});
				GEvent.trigger(marker,'click');
		  	}							
		},
		error: function(e,f,g) {
			//alert('error' + e+f+g);
		}
	});
}

function getGeocode(searchLocation) {
	if (GBrowserIsCompatible()) {
		geocoder = new GClientGeocoder();
	}
	if (geocoder) {
		geocoder.getLatLng(searchLocation, function(e) {
			if (!e) {
				$("#searchHint").fadeTo(1000,0.8);
			}
			else {
				window.location = "../partners/resultList?latLng="+e.lat()+','+e.lng()+"&location="+searchLocation;
			}
		})
	}		
}

function loadPartnerList(location, latLng) {
	$.ajax({
		url: "../partners/generateResults?centerPt="+latLng+"&location="+location,
		cache: false,
		success: function(html){
			$('#results').html(html);
			searchLocation = location;
			initialize();
		},
		error: function(e,f,g) {
			//alert('error' + e+f+g);
		}	
	})
}

function showMoreResults() {
	$('.selected').removeClass('selected');
	showRows();
	
	map.closeInfoWindow();
}

function showRows() {
	var firstMarker = null;
	var results = 0;
	var test = [];
	
	$('.results.hidden:lt(5)').each(function(index) {
		var baseIcon = new GIcon(G_DEFAULT_ICON);
	    baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
	    baseIcon.iconSize = new GSize(20, 36);
	    baseIcon.shadowSize = new GSize(37, 34);
	    baseIcon.iconAnchor = new GPoint(9, 34);
	    baseIcon.infoWindowAnchor = new GPoint(9, 2);
	
			if ($('.results:not(.hidden)').size() > 5)
				$(this).effect('pulsate',{times:1},700);
			points = $(this).find('td.geoCode').text().split(',');
			var point = new GLatLng(points[0],points[1]);
		
			var customIcon = new GIcon(baseIcon);
			customIcon.image = "images/location_pointer_orange.png";
			markerOptions = {icon:customIcon};
			var marker = new GMarker(point,markerOptions);
			
			var e = $(this);
			bounds.extend(point);
			marker.bindInfoWindowHtml($(this).find('td.moreDetails').html());
			GEvent.addListener(marker, "click", function() {
				if (e.hasClass('selected')) {
					return;
				}
				map.panTo(point);
				$('.selected').removeClass('selected');
				e.addClass('selected');
	        });

			GEvent.addDomListener(e[0], 'click', function(){
				GEvent.trigger(marker, 'click');
			})

			map.addOverlay(marker);	
			mapResize();

			$(this).removeClass('hidden');
	});
}

function initTable() {
	$('.results').addClass('hidden');
	showRows();
	
	$('#partnersTable th:gt(0)').each(function(col) {
		$(this).click(function() {
			var rows = $('#partnersTable tbody tr').get();
			
			rows.sort(function(a,b) {
				keyA = $(a).children().eq(col+1).children().size() < 1;
				keyB = $(b).children().eq(col+1).children().size() < 1;
				
				if ((keyA == false) && (keyB == true)) return -1;
				if ((keyA == true) && (keyB == false)) return 1;
				return 0;
			});
			$.each(rows, function(index, row) {
				$('#partnersTable').children('tbody').append(row);
			});
			return false;
		}).mouseover(function() {
			$(this).css('color','rgb(255, 114, 0)');
		}).mouseout(function() {
			$(this).css('color','#767676');
		});
	});
}

function initialize() {
  	//if (navigator.appName == "Netscape")
	

	if (GBrowserIsCompatible()) {
		geocoder = new GClientGeocoder();
    	map = new GMap2(document.getElementById("map_canvas"));
    	map.setCenter(new GLatLng(37.4419, -122.1419), 13);
		map.addControl(new GLargeMapControl3D());
		//map.enableScrollWheelZoom();
		bounds = new GLatLngBounds();
		geocoder.getLocations(searchLocation, addAddressToMap);
  	}
}

function findLocation() {
	if (geocoder) {
		geocoder.getLocations(boo, addAddressToMap);
	}
}

function addAddressToMap(response) {
	map.clearOverlays();
	var blueIcon = new GIcon(G_DEFAULT_ICON);
	blueIcon.image = "images/location_pointer_blue.png";
	blueIcon.iconSize = (new GSize(20,36));
	markerOptions = {icon:blueIcon}
	if (!response || response.Status.code != 200) {
		alert("Sorry, we were unable to geocode that address");
	}
	else {
		place = response.Placemark[0];
        center = new GLatLng(place.Point.coordinates[1],
                            place.Point.coordinates[0]);
        marker = new GMarker(center,markerOptions);
        map.addOverlay(marker);
		bounds.extend(center);
		
		GEvent.addListener(marker,"click",function() {
			marker.openInfoWindowHtml("You searched: <i>" + searchLocation + "</i>");
			map.panTo(center);
		});
		
		initTable();
	}
}

function mapResize()
{
	newZoom = map.getBoundsZoomLevel(bounds);
	newCenter = bounds.getCenter();
	map.setCenter(newCenter, newZoom);
}
