	//<script>
var OCNMap = function(map_name, data_file) {
	this.map_name = map_name;
	this.data_file = data_file;
	
	var html = ['<div id="',map_name,'_dir-panel" class="dir-panel" style="z-index: 200; display: none; position: absolute; border: 1px dashed #CCCCCC; background: white; width: 300px">',
	'<div style="height: 20px; border-bottom: 1px solid black; text-align: right"><a style="cursor: pointer;" id="', map_name, '_close_button">Close [X]</a></div>',
	'<div id="',map_name,'_contents"></div>',
	'</div>',
	'<div id="',map_name,'_leftmenu" class="leftmenu">',
	'<div id="',map_name,'_pager" class="pager"></div>',
	'<ul id="',map_name,'_marker_list" class="marker_list" style="list-style-position: inside; list-style-type: disc">',
	'</ul>',
	'<div id="',map_name,'_pager2" class="pager"></div>',
	'<ul id="',map_name,'_marker_list2" class="marker_list" style="list-style-position: inside; list-style-type: disc">',
	'</ul>', 
	'<span id="',map_name,'_nearby-communitieslbl">Nearby Communities</span>',
	'</div>',
	'<div class="map" id="', map_name,'_mymap"></div>'];
	html = html.join('');
	
	$jq("#" + map_name + "_map").html(html);
	$jq("#" + map_name + "_close_button").click(function() {$jq("#" + map_name + "_dir-panel").hide(); ShulsMap.directions.clear(); ShulsMap.createMoveHandler();});
	//b = new GDraggableObject(document.getElementById(map_name + "_dir-panel"));

	var ShulsMap = {
	removeMoveHandler : function() {
		GEvent.removeListener(ShulsMap.moveHandler);
		ShulsMap.moveHandler = null;
	},
	createMoveHandler : function() {
		ShulsMap.moveHandler = function() {
			if (ShulsMap.moveHandler) {
				return ShulsMap.moveHandler;
			}
			else {
				ShulsMap.moveHandler = GEvent.addListener(ShulsMap.map, "moveend", handleMapMove);
				return ShulsMap.moveHandler;
			}
		}();
	},
	map : null,
	createMap :
	function(recreate, latitude, longitude, community) {
		ShulsMap.community = community;
		if (recreate) {
			ShulsMap.map = null;
		
		}
		ShulsMap.map = function() {
			if (ShulsMap.map) {
				return ShulsMap.map;
			}
			ShulsMap.moveHandler = null;
			
			ShulsMap.map = new GMap2(document.getElementById(map_name + "_mymap"));
			ShulsMap.map.setCenter(new GLatLng(latitude,longitude), 12);
			ShulsMap.map.addControl(new GSmallMapControl());
			
			ShulsMap.directions = new GDirections(ShulsMap.map, document.getElementById(map_name + "_contents"));
			
			GEvent.addListener(ShulsMap.directions, "load", 
				function() {
					$jq("#" + map_name + "_dir-panel").show();
					if (ShulsMap.moveHandler) {ShulsMap.removeMoveHandler();}
				}
			);
			
			GEvent.addListener(ShulsMap.directions, "error", 
				function() {
					$jq("#" + map_name + "_dir-panel").hide();
					console.log(ShulsMap.directions.getStatus());
				}
			);
			
			ShulsMap.createMoveHandler();
			GEvent.trigger(ShulsMap.map, "moveend", true);
			return ShulsMap.map;
		}();
	}
};
	this.getMap = function() {return ShulsMap;};
		
	highlighted = "http://www.ou.org/036.png";
	green = G_DEFAULT_ICON;
	var def_location;
	var def_lat;
	var def_lng;
	var changecity = false;
	var globalvariable;
	var xhr = {};
	function test() {alert('foo');}
	
	function handleMapMove(init) {
		if (init) {$jq("#marker_list").html("<li>Loading...</li>");}
		
		/*if (xhr.abort) {xhr.abort();}*/
		
		$jq("#loading-div").remove();
		$jq("<div/>").attr("id", "loading-div").attr("style", "position: relative; float: left; background: red; color: white; font-weight: bold; font-size: 14pt; padding: 5px").html('<span>Loading... <img width="16" height="16" style="vertical-align: sub;" src="http://www.ou.org/ncsy/graphics/loader_red.gif"/></span>').appendTo($jq("#" + map_name + "_mymap"));
		
		var bounds = this.getBounds();
		var maxLat = this.getBounds().getNorthEast().lat();
		var maxLng = this.getBounds().getNorthEast().lng();
		var minLat = this.getBounds().getSouthWest().lat();
		var minLng = this.getBounds().getSouthWest().lng();
		//$jq('<script/>').attr('src', 'http://www.ou.org/ncsy_pofs/map_data_json/'+minLat+'/'+minLng+'/'+maxLat+'/'+maxLng).appendTo($jq('head'));
		var map = this;
		
		var params = {	
			minLat : minLat,
			minLng : minLng, 
			maxLat : maxLat, 
			maxLng : maxLng
		};
		
		if (init && ShulsMap.community) {
			params.community = ShulsMap.community;
		}
		xhr = $jq.getJSON('http://www.ou.org/' + data_file, 
		params,	function(json) { handleJson(json, init, map); $jq("#loading-div").remove() });
	}
	var ncsy_cities = [];
	var markers = [];
	var city_markers = [];
	var nearby_communities = [];
	var orig_ncsy_cities = [];
	var city_markers_list = {};
	
	var page = 0;
	
	function handleJson(json, init, map) {
		if (init) {
			city_markers = [];
			nearby_communities = json.nearby_communities;
		}
		
		if (json.shuls.length > 0) {
			ncsy_cities = json.shuls;
			closest_mode = false;
		}
		else {
			closest_mode = true;
			ncsy_cities = json.closest_shuls;
			orig_ncsy_cities = json.closest_shuls
			if (init) {
				populateMenu(ncsy_cities, map, closest_mode, nearby_communities);
			}
			return;
		}
		markers = [];
		for (i = 0; i < ncsy_cities.length; i++) {
			if (!init) {
				//if (!city_markers_list[ncsy_cities[i].entry_id]) {
					markers[i] = createMarker(ncsy_cities[i], ncsy_cities[i].name, ncsy_cities[i].lat, ncsy_cities[i].lng, i);
				//}
			}
			else {
				city_markers[i] = createMarker(ncsy_cities[i], ncsy_cities[i].name, ncsy_cities[i].lat, ncsy_cities[i].lng, i, green);
				city_markers_list[ncsy_cities[i].entry_id] = 1;
				if (json.shuls.length > 0) {
					orig_ncsy_cities = json.shuls;
				}
				else {
					orig_ncsy_cities = json.closest_shuls;
				}
			}
		}
		
		
		if (init) {
			if (ShulsMap.community) {
				var bounds = new GLatLngBounds();
	 			for (var i = 0; i < orig_ncsy_cities.length; i++) {
	    			var point = new GLatLng(orig_ncsy_cities[i].lat, orig_ncsy_cities[i].lng); 
	    			bounds.extend(point);
	  			}
				//If we start getting problems take this out
				/*
				var zoom = map.getBoundsZoomLevel(bounds);
				if (zoom < 12) {map.setZoom(zoom);}
				else
					map.setZoom(12);
				// */
  			}
			
			map.clearOverlays();
			populateMap(city_markers, map, closest_mode);
			populateMenu(ncsy_cities, map, closest_mode, nearby_communities);
		}
		else {
			populateMap(markers, map, closest_mode);
			populateMap(city_markers, map);
			//if (window.version && version == 2.0)
				//populateMenuOtherMarkers(ncsy_cities, map);
		}
	}
	
	function populateMap(nmarkers, map, norefresh, closest_mode) {
		var max = 10;
		var taboo = [];
		for (i = 0; i < city_markers.length; i++) {
			for (j = 0; j < markers.length; j++) {
				if (markers[j] && city_markers[i].getPoint().equals(markers[j].getPoint())) {
					taboo[j] = true;
				}
			}
		}
		if (activeMarker) {
			for (i = 0; i < markers.length; i++) {
				if (!markers[i].getPoint().equals(activeMarker.getPoint())) map.removeOverlay(markers[i]);
			}
			for (i = 0; i < city_markers.length; i++) {
				if (!city_markers[i].getPoint().equals(activeMarker.getPoint())) map.removeOverlay(city_markers[i]);
			}
		}
		else {map.clearOverlays();}
		
		for (i = (0 + page * max); i < Math.min((0 + page * max) + max, city_markers.length); i++) {map.addOverlay(city_markers[i]);}
		
		for (i = 0; i < markers.length; i++) {
			if (!taboo[i]) {map.addOverlay(markers[i]);}
			/*else {//console.log('taboo');}*/
		}
		//myfunc();
	}
	var activeMarker = null;
	
	function isDefined(variable) 	{
		return (typeof(variable) == "undefined")?  false: true;
	}
	
	function createMarker(city, name, lat, lng, id, icon) {
		marker = new GMarker(new GLatLng(lat, lng), icon);
		GEvent.addListener(marker, 'click', 
			function() {
				html = "<div style='width: 300px'><strong>"+name+"</strong><br/>";
				for (i in city) {
					if (isDefined(city[i].value) && city[i].value != '') {
						html += city[i].value + "<br/>";
					}
				}
				if ($jq.fn.jquery >= "1.2.1") {
					html += '<br/><a class="directions" dir_link="'+id+'" href="javascript:void(0)">Get Directions To Here</a>';
				}
				html += "</div>";
				
				this.openInfoWindowHtml(html);
				$jq("a[dir_link='"+id+"']").click(
					function() {
						$jq(this).hide();
						
						$jq(this).parent()
							.append('<input id="q" type="text"/>')
							.append($jq('<input type="button" value="go"/>').click(
								function() {
									//var query = $jq("#q")[0].value + " to " + orig_ncsy_cities[id].lat + ", " + orig_ncsy_cities[id].lng;
									var query = $jq("#q")[0].value + " to " + ncsy_cities[id].address.value + " " + ncsy_cities[id].location.value;
									ShulsMap.directions.load(query);
									ShulsMap.map.closeInfoWindow();
								}
							));
					}
				);
			});
		/*GEvent.addListener(marker, 'remove', 
			function() {
				if (map.getInfoWindow().getPoint().equals(this.getPoint())) {
					activeMarker = this;
				}
			});*/
		GEvent.addListener(marker, 'infowindowopen', 
			function() {
				activeMarker = this;
				//console.log(this);
			});
			
		GEvent.addListener(marker, 'infowindowclose', 
			function() {
				activeMarker = null;
			});
		return marker;
	}
	
	function changePage(newPage, map, norefresh, closest_mode) {
		page = newPage;
		if (!norefresh) GEvent.trigger(map, "moveend", true);
		else {
		populateMap(markers, map);
		populateMenu(orig_ncsy_cities, map);
		}
		return false;
	}
	
	function setupPager(ncsy_cities, map, closest_mode) {
		var max = 10;
		page = page * 1;
		var numPages = Math.ceil(ncsy_cities.length / max);
		var start = (0 + page) * max;
		var end = Math.min((0 + page * max) + 9, ncsy_cities.length - 1);
		
		var resultsHtml = "Results " + (start + 1) + " to " + (end + 1) + " of " + ncsy_cities.length;
		var pagesHtml = '';
		
		$jq('#' + map_name + '_pager').html('');
		$jq('#' + map_name + '_pager').append(resultsHtml + '<br/>Pages&nbsp;');
		
		if (page - 5 >= 0) {
			$jq('<a/>').attr('href', 'javascript:void(0)').html('<<').bind('click',function() {changePage(page - 5, map, true)}).appendTo($jq('#' + map_name + '_pager'));
			$jq('#' + map_name + '_pager').append('&nbsp;');
		}
		
		if (page > 0) {
			$jq('<a/>').attr('href', 'javascript:void(0)').html('<').bind('click',function() {changePage(page - 1, map, true)}).appendTo($jq('#' + map_name + '_pager'));
			$jq('#' + map_name + '_pager').append('&nbsp;');
		}
		for (k = (5 * Math.ceil((page + 1) /5)) - 5; k <= (5 * Math.ceil((page + 1)/5)) && k < numPages; k++) {
			link = $jq('<a/>').attr('href', "javascript:void(0)").html(k + 1).attr('pageid', k);
			if (k == page) link.attr('class', 'currentpage');
			link.bind('click', function() { changePage($jq(this).attr('pageid'), map, true)});
			$jq('#' + map_name + '_pager').append(link).append('&nbsp;');
		}
		
		if (page < numPages - 1) {
			$jq('<a/>').attr('href', 'javascript:void(0)').html('>').bind('click',function() {changePage(page + 1, map, true)}).appendTo($jq('#' + map_name + '_pager'));
			$jq('#' + map_name + '_pager').append('&nbsp;');
		}
		if (page + 5 < numPages - 1) {
			$jq('<a/>').attr('href', 'javascript:void(0)').html('>>').bind('click',function() {changePage(page + 5, map, true)}).appendTo($jq('#' + map_name + '_pager'));
			$jq('#' + map_name + '_pager').append('&nbsp;');
		}
		
		if (ncsy_cities.length > max) {
			$jq('#' + map_name + '_pager').show();
		}
		else {
			$jq('#' + map_name + '_pager').hide();
		}
	}
	var globalVar;
	var page2 = 0;
	function populateMenuOtherMarkers(marker_list, map) {
		$jq('#' + map_name + '_marker_list2').html('');
		var max = 10;
		var setupPager = function() {
			
		};
		for (var i = (0 + page2 * max); i < Math.min((0 + page2 * max) + max, marker_list.length); i++) {
			if (!city_markers_list[marker_list[i].entry_id]) {
				li = $jq('<li/>');
				link = $jq('<a/>')
							.attr('href', 'javascript:void(0)')
							.attr('markerid2', i + 1)
							.html(marker_list[i].name)
							.appendTo(li)
							.bind('click', 
								function() {
									var id = $jq(this).attr('markerid2') - 1;
									globalVar = (markers[id]);
									GEvent.trigger(markers[id], 'click');
							})
							.bind('mouseover',
								function() {
									if (!closest_mode) {
										var id = $jq(this).attr('markerid2') - 1;
										globalVar = (city_markers[id]);
										markers[id].setImage(highlighted);
									}
								})
							.bind('mouseout',
								function() {
									if (!closest_mode) {
										var id = $jq(this).attr('markerid2') - 1;
										globalVar = (city_markers[id]);
										markers[id].setImage(G_DEFAULT_ICON.image);
									}
								});
					
				$jq('#' + map_name + '_marker_list2').append(li);
			}
		}
		$jq('#' + map_name + '_marker_list2').prepend(map_name.substr(0,1).toUpperCase() + map_name.substr(1,map_name.length) + " in surrounding areas");	
	}
	function populateMenu(ncsy_cities, map, closest_mode, nearby_communities) {
		var max = 10;
		setupPager(orig_ncsy_cities, map, closest_mode);
		$jq('#' + map_name + '_marker_list').html('');
		if (closest_mode) {
			$jq('#' + map_name + '_marker_list').prepend("<h4>15 Closest Communities</h4>");
		}
		for (i = (0 + page * max); i < Math.min((0 + page * max) + max, orig_ncsy_cities.length); i++) {
			li = $jq('<li/>');
			link = $jq('<a/>')
						.attr('href', 'javascript:void(0)')
						.attr('markerid', i + 1)
						.html(orig_ncsy_cities[i].name + (orig_ncsy_cities[i].member_shul == "Yes" ? '<img src="http://www.ou.org/images/ou_logo_small.gif"/>': '')  )
						.appendTo(li)
						.bind('click', 
							function() {
								var id = $jq(this).attr('markerid') - 1;
								if (closest_mode) {
									map.setCenter(new GLatLng(ncsy_cities[id].lat, ncsy_cities[id].lng));
									return;
								}
								globalVar = (city_markers[id]);
								GEvent.trigger(city_markers[id], 'click');
						})
						.bind('mouseover',
							function() {
								if (!closest_mode) {
									var id = $jq(this).attr('markerid') - 1;
									globalVar = (city_markers[id]);
									city_markers[id].setImage(highlighted);
								}
							})
						.bind('mouseout',
							function() {
								if (!closest_mode) {
									var id = $jq(this).attr('markerid') - 1;
									globalVar = (city_markers[id]);
									city_markers[id].setImage(G_DEFAULT_ICON.image);
								}
							});
				
			$jq('#' + map_name + '_marker_list').append(li);
		}
		if (!closest_mode) {
			$jq('#' + map_name + '_marker_list').prepend(map_name.substr(0,1).toUpperCase() + map_name.substr(1,map_name.length) + " in " + locData.city);
		}
		if (window.version && version == 2.0 || 1 == 1) {
			$jq('#' + map_name + "_nearby-communities").remove();
			$jq('#' + map_name + '_leftmenu').append("<ul id='" + map_name + "_nearby-communities' class='marker_list'/>");
			if (nearby_communities) {
				$jq('#' + map_name + "_nearby-communiteslbl").show();
				for(var j = 0; j < 5; j++) {
					$jq('#' + map_name + "_nearby-communities").append(
						$jq("<li/>").append(
							$jq("<a id='"+nearby_communities[j].name + "' href='javascript:void(0)'>" + nearby_communities[j].name + "</a>").click(
								function() {doSwitchLocation(this.id)})
						)
					);
				}
			}
			else {
				$jq('#' + map_name + "_nearby-communitieslbl").hide();
			}
		}
			
	};
	
	function askDirections(id) {
		$jq("#dir-query").show();
		$jq("#get-directions").click(function() {
			init.removeMoveHandler();
			var query = $jq("#d_query")[0].value + " to " + orig_ncsy_cities[id].address + " " + orig_ncsy_cities[id].city + ", " + orig_ncsy_cities[id].state;
			init.directions.load(query);
			$jq("#dir-query").hide();
		});
	}
}
