	 if (typeof SPLCENTER == "undefined" || !SPLCENTER) {
		 /**
		  * The SPLCENTER global namespace object.  If SPLCENTER is already defined, the
		  * existing SPLCENTER object will not be overwritten so that defined
		  * namespaces are preserved.
		  */
		 var SPLCENTER = {};
		 }
 
 SPLCENTER.namespace = function(s) {
		 
	 var a, o, i, j, d;
		// Determine if s is string or array and
		// force it to an array
		if (typeof s === 'string') {
			a = [s];
		}
		else if (s.length !== undefined) {
			a = s;
		}
		else {
			// Neither a string or an array was passed in, so exit
			return {};
		}
		for (i = 0; i < a.length; i++) {
			d = a[i].split(".");
			o = SPLCENTER;
			// FOTI is implied, so it is ignored if it is included
			for (j = (d[0] == "SPLCENTER") ? 1 : 0; j < d.length; j++) {
				o[d[j]] = o[d[j]] || {};
				o = o[d[j]];
			}
		}
		return o;
	};

 

SPLCENTER.namespace(["standstrong2.map",
                     "standstrong2.map.currentlocation",
                     "standstrong2.incidents.unitedstates",
                     "standstrong2.states",
                     "standstrong2.randommembers"]);	

//************Begin edit *****************
//Where do we want to center the map
SPLCENTER.standstrong2.map.centreLat=37.609066626725074;
SPLCENTER.standstrong2.map.centreLon=-97.42397784847942;

//When we load the map, or what to reset, what is the default zoom level
SPLCENTER.standstrong2.map.defaultzoom=4

//do we want to decide the proper pan and zoom when data is shown, or the map is clicked.
SPLCENTER.standstrong2.map.AUTOSTATEPANANDZOOM=true

//milliseconds between each marker
SPLCENTER.standstrong2.map.MEMBERSTOMEMBERTIMER=1500;

//milliseconds between each marker
SPLCENTER.standstrong2.map.MEMBERSSTAYTIMER=1500;

//Should we run the map like we're in production? This enables and disables certain controls they may be useful for testing.
SPLCENTER.standstrong2.map.RUNINT = true;

//how many member records do we want to cycle thru when the random members is loaded.
SPLCENTER.standstrong2.map.RANDOMRECORDSATATIME = 3; 

//what year do we load when the national level is shown
SPLCENTER.standstrong2.incidents.NATIONALLEVELDEFAULTYEAR = "2009";

//what level of debugging do we want to see. Ranges are 0-5. Zero is off. 1=errors only, 4=every step shows feedback. includes loops.
SPLCENTER.standstrong2.DEBUGLEVEL = 0;

//which debug window do we want, 1=glog or 2=jquery. only use jquery with firebug
SPLCENTER.standstrong2.DEBUGMETHOD = 2;

//The Google maps background color
SPLCENTER.standstrong2.map.MAPBACKGROUNDCOLOR = "#bdcbd0";



//*************end edit******************//





//some other global variables being setup for later
SPLCENTER.standstrong2.map.MAP;
SPLCENTER.standstrong2.map.MARKERMANAGER;
SPLCENTER.standstrong2.map.HATEMAP;
SPLCENTER.standstrong2.map.STANDSTRONG;
SPLCENTER.standstrong2.map.GTYPECONTROL;
SPLCENTER.standstrong2.map.GLARGECONTROL;
SPLCENTER.standstrong2.map.currentzoom = SPLCENTER.standstrong2.map.defaultzoom;
SPLCENTER.standstrong2.CANCELACTIONS = false;



//setup google maps
google.load("maps", "2");

//when ready, kick off the initialization process
google.setOnLoadCallback(initialize);





// This function is used for triggering the debug window in google maps.
// Use various levels within our code to trigger more verbose output
SPLCENTER.writedebug = function (level,text) {
	if (level <= SPLCENTER.standstrong2.DEBUGLEVEL){
		switch(SPLCENTER.standstrong2.DEBUGMETHOD) {
		case 1:
			GLog.write(text);
			break; 
		case 2:
			console.debug(text);
			break; 
		}

	}

}


function initialize() {  
	if (GBrowserIsCompatible()) {

		var allowedBounds = new GLatLngBounds(new GLatLng(-180,90), new GLatLng(180,-90));
		SPLCENTER.writedebug(4,allowedBounds.getSouthWest() + "" + allowedBounds.getNorthEast());

		var copyright = new GCopyright(1, allowedBounds, 0, "<a href=\"http://www.splcenter.org\">Southern Poverty Law Center</a>");
		var copyrightCollection = new GCopyrightCollection("Map Data: ");
		var currentZoom;
		copyrightCollection.addCopyright(copyright);

		//create an array of tilelayers. We only need one right now.
		var hatemaptiles  =  [new GTileLayer(copyrightCollection, 4, 10, {
			tileUrlTemplate: GEOSERVERADDRESS + '?layers=hategroupsmap&zoom={Z}&x={X}&y={Y}', 
			isPng:true
			//opacity:0.5 
		})];

		//This is the standstrong members layer
		var standstrongtiles =  [new GTileLayer(copyrightCollection, 4, 10, {
			tileUrlTemplate: GEOSERVERADDRESS + '?layers=standstrong2&zoom={Z}&x={X}&y={Y}', 
			isPng:true
			//opacity:0.5 
		})]; 


		//Create a new map with the wms layer we just created.
		SPLCENTER.standstrong2.map.STANDSTRONG = new GMapType(standstrongtiles, new GMercatorProjection(11), "StnStrong", {maxResolution:10, minResolution:4, errorMessage:"Data not available"});
		SPLCENTER.standstrong2.map.HATEMAP = new GMapType(hatemaptiles, new GMercatorProjection(11), "HateMap", {maxResolution:10, minResolution:4, errorMessage:"Data not available"});


		//build map controls
		var mapControl = new GMapTypeControl();
		SPLCENTER.standstrong2.map.GLARGECONTROL = new GLargeMapControl();

		//var map = new GMap2(document.getElementById("map"));
		//MAP = new GMap2(document.getElementById("map"),{mapTypes:[standStrongMap,G_DEFAULT_MAP_TYPES],draggableCursor: 'crosshair'});
		SPLCENTER.standstrong2.map.MAP = new GMap2(document.getElementById("map"),{mapTypes:[SPLCENTER.standstrong2.map.HATEMAP,SPLCENTER.standstrong2.map.STANDSTRONG],draggableCursor: 'crosshair',backgroundColor:SPLCENTER.standstrong2.map.MAPBACKGROUNDCOLOR});


		SPLCENTER.standstrong2.map.MAP.setMapType(SPLCENTER.standstrong2.map.HATEMAP);




		SPLCENTER.standstrong2.map.MAP.disableDoubleClickZoom();
		SPLCENTER.standstrong2.map.MAP.disableDragging();







		//SPLCENTER.standstrong2.map.MAP.addOverlay(standstrongcountieslayer);


		//Center map, and go to default zoom
		SPLCENTER.standstrong2.map.MAP.setCenter(new GLatLng( SPLCENTER.standstrong2.map.centreLat, SPLCENTER.standstrong2.map.centreLon), SPLCENTER.standstrong2.map.defaultzoom);


		//Create a new marker manager
		SPLCENTER.standstrong2.map.MARKERMANAGER = new MarkerManager(SPLCENTER.standstrong2.map.MAP,{trackMarkers:true});



		//Trigger event when their zoom in/out ends. We may want to kill the timer used to cycle thru the markers. 
		GEvent.addListener(SPLCENTER.standstrong2.map.MAP,"zoomend",
				function(oldLevel,newLevel){ 
			SPLCENTER.writedebug(4,"Zoom new:" + newLevel + " old:" + oldLevel);
			SPLCENTER.standstrong2.map.currentzoom = newLevel;
			removeMapOverlays();
			removeAllMarkers();
			stopMembersHeadsUp();	
			hideLoadingStatus();
		}
		);

		// Add a move listener to restrict the bounds range
		GEvent.addListener(SPLCENTER.standstrong2.map.MAP, "dragstart", function() {
			SPLCENTER.writedebug(4,"dragging...");
			removeMapOverlays();
			removeAllMarkers();
			stopMembersHeadsUp();	
			hideLoadingStatus();

		});


		//add loading container
		$("#map").append('<div id="loading" style="display: none;opacity: 1.0; position: absolute; left:50%; top:360px; line-height:.8em;"><img src="images/ajax-loader.gif" height="16" width="16" border="0"></div>');

		//add thank you container
		$("#map").append('<div  id="thankyou" style="display: none;opacity: 1.0; position: absolute; left:145px; top:150px; line-height:.8em;">' +
				'<table cellpadding="0" cellspacing="0" border="0"><tr><td style="width:11px;height:11px;padding:0px;margin:0px;"><img src="images/markers/tl.png" width="11" height="11" alt="tl" style="padding:0px;margin:0px;"></td><td style="background-color:white;padding:0px;margin:0px;"></td><td style="width:11px;height:11px;padding:0px;margin:0px;"><img src="images/markers/tr.png" width="11" height="11" alt="tr" style="padding:0px;margin:0px;"></td></tr><tr><td style="background-color:white;"></td><td style="background-color:white;font-size:1em; line-height:1.5em;">'+
				'<span id="thankyoumessage">Sending your incident report..</span>' +	 
				'</td><td style="background-color:white;"></td></tr><tr><td style="width:11px; height:11px;"><img src="images/markers/bl.png" width="11" height="11" alt="bl"></td><td style="background-color:white;"></td><td style="width:11px; height:11px;"><img src="images/markers/br.png" height="11" width="11" alt="br"></td></tr></table>'+
		'</div>');


		if (SPLCENTER.standstrong2.map.RUNINT) {
			getMembersByRandom(SPLCENTER.standstrong2.map.RANDOMRECORDSATATIME);

		} else {
			addClickEventToMap();
			addMapControls();
		}
		loadUnitedStatesIncidents(SPLCENTER.standstrong2.incidents.NATIONALLEVELDEFAULTYEAR);
		showContainer('#nationaltext');
		hideContainer('#statetext');
		hideContainer('#hatecount');



		//setup default zoom levels
		var zoomlevels = '{"SC":["SC","South Carolina","6","33.8521697,-80.44189453"],"VA":["VA","Virginia","6","37.21283151,-78.81591797"],"LA":["LA","Louisiana ","6","31.6533814,-92.50488281"],"GA":["GA","Georgia","6","32.56533316,-83.34228516"],"DC":["DC","District of Columbia","10","38.88996393,-77.0375061"],"OH":["OH","Ohio","6","40.2459915,-82.66113281"],"MN":["MN","Minnesota","5","46.04273565,-94.35058594"],"KY":["KY","Kentucky ","6","37.40507375,-84.74853516"],"WA":["WA","Washington","6","47.279229,-120.27832"],"IL":["IL","Illinois","5","40.21244072,-89.12109375"],"OR":["OR","Oregon","5","43.73935208,-120.3881836"],"NM":["NM","New Mexico","5","33.94335995,-105.8862305"],"MA":["MA","Massachusetts","7","42.4639928,-71.94946289"],"MS":["MS","Mississippi","5","33.35806161,-89.34082031"],"DE":["DE","Delaware","7","38.7969083,-75.42114258"],"WV":["WV","West Virginia","6","38.41916639,-80.9362793"],"HI":["HI","Hawaii","7","19.70465758,-155.5444336"],"FL":["FL","Florida","5","29.68805275,-82.22167969"],"KS":["KS","Kansas","6","38.46219172,-98.10791016"],"SD":["SD","South Dakota","6","44.51217617,-100.0634766"],"AK":["AK","Alaska","5","64.9979392,-150.9960938"],"TN":["TN","Tennessee","6","35.81781316,-86.00097656"],"ID":["ID","Idaho","4","43.48481213,-113.8183594"],"RI":["RI","Rhode Island","7","41.80407814,-71.4440918"],"NC":["NC","North Carolina","6","35.59478567,-79.47509766"],"NY":["NY","New York","5","42.77927536,-75.67382813"],"NH":["NH","New Hampshire","6","43.31718492,-71.61987305"],"MT":["MT","Montana","5","46.8752134,-109.3139648"],"CO":["CO","Colorado","6","39.25777815,-105.5566406"],"WI":["WI","Wisconsin","5","44.37098696,-89.12109375"],"OK":["OK","Oklahoma ","6","35.81781316,-96.89941406"],"NE":["NE","Nebraska","6","41.4756602,-99.27246094"],"NV":["NV","Nevada","5","39.80853604,-116.6748047"],"MI":["MI","Michigan","5","43.50075244,-84.77050781"],"MD":["MD","Maryland","7","39.41922074,-76.75048828"],"TX":["TX","Texas","4","31.42866312,-98.70117188"],"VT":["VT","Vermont","6","44.29240109,-72.86132813"],"AZ":["AZ","Arizona","5","34.1981731,-111.8847656"],"IN":["IN","Indiana","6","40.2459915,-85.95703125"],"AL":["AL","Alabama","6","32.91648535,-86.59423828"],"CA":["CA","California","4","37.14280344,-119.3994141"],"UT":["UT","Utah","5","38.99357206,-111.6870117"],"WY":["WY","Wyoming","6","42.90816007,-107.2265625"],"ND":["ND","North Dakota","6","47.31648293,-100.4040527"],"PA":["PA","Pennsylvania","6","40.74725696,-77.60742188"],"AR":["AR","Arkansas","6","34.97600151,-92.15332031"],"CT":["CT","Connecticut","7","41.59901305,-72.4987793"],"NJ":["NJ","New Jersey","6","39.53793975,-74.49829102"],"ME":["ME","Maine","6","44.98811303,-69.21386719"],"IA":["IA","Iowa","6","41.86956083,-92.98828125"],"MO":["MO","Missouri","6","38.27268854,-92.15332031"]}';
		SPLCENTER.standstrong2.map["zoomlevels"] = eval('(' + zoomlevels + ')');


		SPLCENTER.standstrong2.counts = eval('(' + standstrongcounts + ')');
		SPLCENTER["intel"] = eval('(' + hategroupcounts + ')');



	}


}

function addClickEventToMap(){
	//clear and readd
	GEvent.clearListeners(SPLCENTER.standstrong2.map.MAP,"click");
	//Trigger event when map is clicked
	GEvent.addListener(SPLCENTER.standstrong2.map.MAP, "click",function(overlay,point) {

		mapClickController(point);

	} );

}

function mapClickController(point) {

	var lat;
	var lng;
	lat = point.lat();
	lng = point.lng();
	SPLCENTER.writedebug(4,"Map clicked");

	removeMapOverlays();
	removeAllMarkers();
	showLoadingStatus();
	stopMembersHeadsUp();
	getStateByLocation(lat, lng);
	//$("#introtext").hide();



}

function isDefined(variable) {

	return eval('(typeof('+variable+') != "undefined");');
}

function loadStateDataFromServer(data) {

	//save their current location for next time

	SPLCENTER.standstrong2.map.currentlocation = data;

	SPLCENTER.writedebug(4,"Got state location: " + data.state);

	var state = data.state;

	if (!isDefined("SPLCENTER.standstrong2.states." + state)) {
		SPLCENTER.namespace(["SPLCENTER.standstrong2.states." +state]); 
		SPLCENTER.writedebug(4,"State was not defined: " + state);
	}

	//do we already have the information loaded for members of this state?
	if (!isStateMembersManaged(state)) {
		SPLCENTER.writedebug(4,"Did not find members for that state. Get data: " + state);
		loadMembers(state,true); 	
	} else {
		SPLCENTER.writedebug(4,"State already loaded: " + data.state);	
		loadMembers(state,false);

	}

	if (!isStateIncidentManaged(state)) {
		SPLCENTER.writedebug(4,"Did not find incidents for that state. Get data: " + state);
		loadStateIncidents("",state,true);
	} else {
		SPLCENTER.writedebug(4,"State incidents already loaded: " + state);	
		loadStateIncidents("",state,false);

	}


	if (!isStateCountiesManaged(state)) {

		SPLCENTER.writedebug(4,"Did not find counties for that state. Get data: " + state);
		loadCounties(state,true);
	} else {
		SPLCENTER.writedebug(4,"State counties already loaded: " + state);	
		loadCounties(state,false);

	}

	$("#statetext").show();
	$("#statemembers").show();
	$("#statecounties").show();
	$("#hatecount").show();
	$("#nationaltext").hide();


}

function isStateManaged(state) {
	try {  
		if (isDefined("SPLCENTER.standstrong2.states." + state)) {
			SPLCENTER.writedebug(4,"We found the state.");
			return true;
		} else {
			SPLCENTER.namespace(["SPLCENTER.standstrong2.states." + state]);
			return false;
			SPLCENTER.writedebug(4,"No members were found for this state");
		}
	} catch (e) {
		SPLCENTER.namespace(["SPLCENTER.standstrong2.states." + state]);
		SPLCENTER.writedebug(2,"No members were found for this state with Exception: " + e);
		return false;
	}
}

function isStateMembersManaged(state) {
	try { 
		if (SPLCENTER.standstrong2.states[state].members.length > 0) {

			SPLCENTER.writedebug(4,"We found members for this state. bypass server call");
			return true;
		} else {

			return false;
			SPLCENTER.writedebug(4,"No members were found for this state");
		}
	} catch (e) {
		SPLCENTER.writedebug(2,"No members were found for this state with Exception: " + e);
		return false;
	}
}

function isStateIncidentManaged(state) {
	try {  
		if (SPLCENTER.standstrong2.states[state].incidents.length > 0) {

			SPLCENTER.writedebug(4,"We found incidents for this state. bypass server call");
			return true;
		} else {

			return false;

			SPLCENTER.writedebug(4,"No incidents were found for this state");
		}
	} catch (e) {
		SPLCENTER.writedebug(2,"No incidents were found for this state with Exception: " + e);
		return false;
	}
}

function isStateCountiesManaged(state) {
	try {  
		if (SPLCENTER.standstrong2.states[state].counties.length > 0) {
			SPLCENTER.standstrong2.states[state].counties;
			SPLCENTER.writedebug(4,"We found counties for this state. bypass server call");
			return true;
		} else {
			return false;
			SPLCENTER.writedebug(4,"No counties were found for this state");
		}
	} catch (e) {
		SPLCENTER.writedebug(2,"No counties were found for this state with Exception: " + e);
		return false;
	}
}

function getStateByLocation(lat, lng) {

	var state = null;

	$.getJSON("location_json.jsp?lat=" +lat +"&lng=" + lng,
			function(data){
		//we have the city,state location. Let's show the data.

		if (data.state != "NA") {
			SPLCENTER.writedebug(4,"Got a state location back");
			loadStateDataFromServer(data);	
		} else {
			SPLCENTER.writedebug(4,"Did not get a state back");
			hideLoadingStatus(); 
		}

	});

}

function getMembersByRandom(limit) {
	showLoadingStatus();
	//grab json state data and load into the dom
	$(document).ready(function(){
		$.getJSON("members_json.jsp?random=" +limit,
				function(data){
			//Center map, and go to default zoom
			SPLCENTER.standstrong2.map.MAP.setCenter(new GLatLng( SPLCENTER.standstrong2.map.centreLat, SPLCENTER.standstrong2.map.centreLon), SPLCENTER.standstrong2.map.defaultzoom);


			SPLCENTER.standstrong2.randommembers = data;
			loopMembers(0,data);
			removeMapOverlays();
			removeMapControls();
			removeAllMarkers();

		});
	});


}

function createMarkerIcon(){
	var randomnumber = Math.floor(Math.random()*2000);
	// Create a lettered icon for this point using our icon class
	var micon = new GIcon(G_DEFAULT_ICON);
	micon.image = "images/markers/epicenter2.gif?" + randomnumber;
	micon.shadow = "";
	micon.iconSize = new GSize(35, 35);
	// micon.shadowSize = new GSize(37, 34);
	micon.iconAnchor = new GPoint(17, 17);
	micon.infoWindowAnchor = new GPoint(9, 2);
	SPLCENTER.namespace(["SPLCENTER.standstrong2.map.markericon"]);
	SPLCENTER.standstrong2.map["markericon"] = micon;
	return micon;
}

function createMarker2(point, content) {

	// var micon = SPLCENTER.standstrong2.map["markericon"]; // use a constant marker icon object when we're not using rotating gifs
	//we need to call this over and over to get the gif to rotate correctly. This function can be loaded one time if we don't use rotating gifs, then the same object can be used over and over.
	var micon = createMarkerIcon();
	markerOptions = { icon:micon };

	var marker = new GMarker(point,markerOptions);

	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(content);
		whereAreYouMarker(marker);
	});
	SPLCENTER.writedebug(4,"Marker added");

	return marker;
}

function membersCallback(page_index, jq){
	// Get number of elements per pagionation page from form
	SPLCENTER.writedebug(4,"Members callback called");
	var items_per_page = 5;
	var members = SPLCENTER.standstrong2.states[SPLCENTER.standstrong2.map.currentlocation.state].members;
	var max_elem = Math.min((page_index+1) * items_per_page, members.length);
	var newcontent = '';

	// Iterate through a selection of the content and build an HTML string

	for(var i=page_index*items_per_page;i<max_elem;i++)
	{
		newcontent += "<p><strong>" + members[i].firstname + " " + members[i].lastname + ".</strong> "  + members[i].county + "<p/>";
		SPLCENTER.writedebug(4,"Building the members list: " + members[i].firstname + " " + members[i].lastname + " - " + members[i].city + ", " + members[i].state);
	}

	// Replace old content with new content
	$("#members_list").html(newcontent);


	// Prevent click eventpropagation
	return false;
}

function stateIncidentsCallback(page_index, jq){
	// Get number of elements per pagionation page from form
	var items_per_page = 5;

	var incidents = SPLCENTER.standstrong2.states[SPLCENTER.standstrong2.map.currentlocation.state].incidents;
	var max_elem = Math.min((page_index+1) * items_per_page, incidents.length);
	var newcontent = '';

	// Iterate through a selection of the content and build an HTML string
	for(var i=page_index*items_per_page;i<max_elem;i++)
	{
		newcontent += '<p><strong>' + incidents[i].city + ', ' + incidents[i].state + '</strong><br />' +
		incidents[i].description + '<br />' +
		'<em>Reported:' + incidents[i].display_date + '</em></p>';

	}


	// Replace old content with new content
	$("#incident_list").html(newcontent);


	// Prevent click eventpropagation
	return false;
}

function loadStateIncidents(year,state,isnew) {


	// Create pagination element with options
	var optInit = {
			callback: stateIncidentsCallback,
			items_per_page:5,
			num_display_entries:0,
			num_edge_entries:0,
			prev_text:"<",
			next_text:">",
			ellipse_text:"...",
			prev_show_always:true,
			next_show_always:true
	};

	//grab json state data and load into the dom if it's a new state
	if (isnew) {
		var url ="";

		if (state.length > 0) {
			url += "state=" + state;
		}
		if (year.length > 0) {
			if (state.length > 0) {
				url += "&";
			}
			url += "year=" + year;
		}
		$.getJSON("incidents_json.jsp?" + url,
				function(data){



			SPLCENTER.standstrong2.states[state].incidents = data;
			var incidents = data;


			// change the elements data with the new incidents
			$("#incidentspagination").pagination(incidents.length, optInit);

		});

	} else {
		// change the elements data with the new incidents
		incidents = SPLCENTER.standstrong2.states[state].incidents;
		$("#incidentspagination").pagination(incidents.length, optInit);
	}

}

function unitedStatesIncidentsCallback(page_index, jq){
	// Get number of elements per pagionation page from form
	var items_per_page = 5;

	var incidents = SPLCENTER.standstrong2.incidents.unitedstates;
	var max_elem = Math.min((page_index+1) * items_per_page, incidents.length);
	var newcontent = '';

	// Iterate through a selection of the content and build an HTML string
	for(var i=page_index*items_per_page;i<max_elem;i++)
	{
		newcontent += '<p><strong>' + incidents[i].city + ', ' + incidents[i].state + '</strong><br />' +
		incidents[i].description + '<br />' +
		'<em>Reported:' + incidents[i].display_date + '</em></p>';

	}


	// Replace old content with new content
	$("#incident_list").html(newcontent);


	// Prevent click eventpropagation
	return false;
}

function loadUnitedStatesIncidents(year) {


	// Create pagination element with options
	var optInit = {
			callback: unitedStatesIncidentsCallback,
			items_per_page:5,
			num_display_entries:0,
			num_edge_entries:0,
			prev_text:"<",
			next_text:">",
			ellipse_text:"...",
			prev_show_always:true,
			next_show_always:true
	};

	//grab json state data and load into the dom if it's a new state
	var url ="";


	if (year.length > 0) {

		url += "year=" + year;
	}
	$.getJSON("incidents_json.jsp?" + url,
			function(data){



		SPLCENTER.standstrong2.incidents.unitedstates = data;
		var incidents = data;


		// change the elements data with the new incidents
		$("#incidentspagination").pagination(incidents.length, optInit);

	});


}

function loadMembers(state,isnew) {
	var members;

	// Create pagination element with options
	var optInit = {
			callback: membersCallback,
			items_per_page:5,
			num_display_entries:0,
			num_edge_entries:0,
			prev_text:"< previous",
			next_text:"next >",
			ellipse_text:"...",
			prev_show_always:true,
			next_show_always:true
	};

	if (isnew) {
		//grab json state data and load into the dom
		$(document).ready(function(){
			$.getJSON("members_json.jsp?state=" + state + "&random=50",
					function(data){



				SPLCENTER.standstrong2.states[state].members = data;
				members =  SPLCENTER.standstrong2.states[state].members;
				//change the elements data with the new incidents
				$("#memberspagination").pagination(members.length, optInit);
				SPLCENTER.writedebug(4,"State members were pulled from server:"  + members.length);
				hideLoadingStatus();


			});
		}); 
	} else {

		members =  SPLCENTER.standstrong2.states[state].members;
		SPLCENTER.writedebug(4,"State members were already loaded: " + members.length);
		$("#memberspagination").pagination(members.length, optInit);
		SPLCENTER.writedebug(4,SPLCENTER.standstrong2.map.zoomlevels[state][2]);
		hideLoadingStatus();
	}


	if (SPLCENTER.standstrong2.map.AUTOSTATEPANANDZOOM) {
		//split latlon
		var latlnga = new Array();
		try { 
			latlnga = SPLCENTER.standstrong2.counts.states[state][4].split(',');
			var lat = latlnga[0];
			var lng = latlnga[1];
		}catch(e) {
			SPLCENTER.writedebug(2,"Failed to split the states lat/lng location: " + latlnga);
		}


		if (SPLCENTER.standstrong2.map.currentzoom < SPLCENTER.standstrong2.counts.states[state][3]) {
			SPLCENTER.standstrong2.map.MAP.setCenter(new GLatLng(lat,lng))
			SPLCENTER.standstrong2.map.MAP.setZoom(parseFloat(SPLCENTER.standstrong2.counts.states[state][3]));
			SPLCENTER.writedebug(2,"Changing zoom: " + lat + "/" + lng + " and pan: " + SPLCENTER.standstrong2.counts.states[state][3]);
		}


	}

	//$("#statelistheader").html('Recent Hate Incidents in the ' + SPLCENTER.standstrong2.map.zoomlevels[state][1]);

	$("#memberstatename").html(SPLCENTER.standstrong2.counts.states[state][2]);
	$("#memberstatecount").html(SPLCENTER.standstrong2.counts.states[state][0]);
	$("#countystatename").html(SPLCENTER.standstrong2.counts.states[state][2]);
	$("#incidentstatename").html(SPLCENTER.standstrong2.counts.states[state][2]);
	$("#hategroupstatename").html(SPLCENTER.standstrong2.counts.states[state][2]);
	$("#hategroupstatecount").html(SPLCENTER.intel.map[state][0]);

}

function whereAreYouMarker(point) {
	//var point = marker.getLatLng();
	var pixelpoint = SPLCENTER.standstrong2.map.MAP.fromLatLngToContainerPixel(point); //this is what figures out where the heck the markers going to me later
	SPLCENTER.writedebug(4,"This marker is here:" + pixelpoint.x + "," + pixelpoint.y);

	return pixelpoint;
}

function addMapControls() {



	//Setup user controls

	SPLCENTER.standstrong2.map.MAP.enableContinuousZoom();
	SPLCENTER.standstrong2.map.MAP.enableScrollWheelZoom();
	SPLCENTER.standstrong2.map.MAP.enableDragging();
	SPLCENTER.standstrong2.map.MAP.enableDoubleClickZoom();

	//build map controls
	//GTYPECONTROL = new GMapTypeControl();
	//MAP.addControl(GTYPECONTROL);

	SPLCENTER.standstrong2.map.MAP.removeControl(SPLCENTER.standstrong2.map.GLARGECONTROL);
	SPLCENTER.standstrong2.map.MAP.addControl(SPLCENTER.standstrong2.map.GLARGECONTROL);


}

function addTakeActionLayer() {

	//if this container doesnt exists add it
	if (!$("#whatdoyouwanttodo").length > 0) {

		var content = '<a href="javascript:showAddForm()">Add yourself</a> to the map and stand strong against hate';
		if ($("#whatdoyouwanttodo").length < 1) {
			$("#map").append('<div  id="whatdoyouwanttodo" style="opacity: 1.0; position: absolute; left:145px; top:150px; line-height:.8em;">' +
					'<table cellpadding="0" cellspacing="0" border="0"><tr><td style="width:11px;height:11px;padding:0px;margin:0px;"><img src="images/markers/tl.png" width="11" height="11" alt="tl" style="padding:0px;margin:0px;"></td><td style="background-color:white;padding:0px;margin:0px;"></td><td style="width:11px;height:11px;padding:0px;margin:0px;"><img src="images/markers/tr.png" width="11" height="11" alt="tr" style="padding:0px;margin:0px;"></td></tr><tr><td style="background-color:white;"></td><td style="background-color:white;font-size:1em; line-height:1.5em;">'+
					content +		 
					'</td><td style="background-color:white;"></td></tr><tr><td style="width:11px; height:11px;"><img src="images/markers/bl.png" width="11" height="11" alt="bl"></td><td style="background-color:white;"></td><td style="width:11px; height:11px;"><img src="images/markers/br.png" height="11" width="11" alt="br"></td></tr></table>'+
			'</div>');
		}
	}

}

function removeMapControls() {

	SPLCENTER.standstrong2.map.MAP.disableContinuousZoom();
	SPLCENTER.standstrong2.map.MAP.disableScrollWheelZoom();

	SPLCENTER.standstrong2.map.MAP.removeControl(SPLCENTER.standstrong2.map.GTYPECONTROL);
	SPLCENTER.standstrong2.map.MAP.removeControl(SPLCENTER.standstrong2.map.GLARGECONTROL);
	SPLCENTER.standstrong2.map.MAP.disableDoubleClickZoom();
	SPLCENTER.standstrong2.map.MAP.disableDragging();

}

function removeMapOverlays() {
	if ($("#whatdoyouwanttodo").length > 0) {
		$("#whatdoyouwanttodo").remove();
	}

}

function removeAllMarkers() {
	try {
		if(isDefined("SPLCENTER.standstrong2.map.MARKERMANAGER")) {

			SPLCENTER.standstrong2.map.MARKERMANAGER.clearMarkers();
		}
	} catch (e) {
		SPLCENTER.writedebug(2,"Could not remove markers Exception: " + e);

	}


}

function loadCounties(state,isnew) {

	var newcontent = '';
	var counties;

	//grab json state data and load into the dom
	$(document).ready(function(){
		if (isnew) {
			$.getJSON("county_json.jsp?state=" + state,
					function(data){
				SPLCENTER.standstrong2.states[state].counties = data;
				// change the elements data with the new incidents

				counties =  SPLCENTER.standstrong2.states[state].counties;
				SPLCENTER.writedebug(4,"State counties were pulled from server:"  + counties.length);	

				var capacity = 300; // The first number is the highest, so it's the maximum width
				var highestcounty;
				jQuery.each(counties, function(i, record) {

					if (i == 0) {
						highestcounty = record.count;
					} else {
						capacity = Math.round((record.count / highestcounty) * 300); // Divide by 2 to scale to desired widths.

					}

					SPLCENTER.writedebug(4,"my id: " + record.county + " - " +record.count + "- capacity" + capacity);
					newcontent += '<div><label>' + record.county + '</label><br><em style="width:' + capacity + 'px; background-color:#067115; display: block;">' + record.count + '</em></div>';
					$("#counties_list").html(newcontent);

					if (i == 4) {
						return false; 
					}


				});
			});
		} else {
			counties =  SPLCENTER.standstrong2.states[state].counties;
			var capacity = 300; // The first number is the highest, so it's the maximum width
			var highestcounty;
			jQuery.each(counties, function(i, record) {

				if (i == 0) {
					highestcounty = record.count;
				} else {
					capacity = Math.round((record.count / highestcounty) * 300); // Divide by 2 to scale to desired widths.

				}

				SPLCENTER.writedebug(4,"my id: " + record.county + " - " +record.count + "- capacity" + capacity);
				newcontent += '<div><label>' + record.county + '</label><br><em style="width:' + capacity + 'px; background-color:#067115; display: block;">' + record.count + '</em></div>';
				$("#counties_list").html(newcontent);

				if (i == 4) {
					return false; 
				}


			});


		}
	});



}

function countiesCallback(page_index, jq){
	// Get number of elements per pagionation page from form
	var items_per_page = 5;
	var counties = SPLCENTER.standstrong2.states[SPLCENTER.standstrong2.map.currentlocation.state].counties;
	var max_elem = Math.min((page_index+1) * items_per_page, counties.length);
	var newcontent = '';


	// Iterate through a selection of the content and build an HTML string
	for(var i=page_index*items_per_page;i<max_elem;i++)
	{

		//newcontent += '<p><strong>' + counties[i].county + '</strong> <em>' + counties[i].count + '</em></p>';
		newcontent += '<div><label>' + counties[i].county + '</label><em>' + counties[i].count + '</em></div>';
	}

	// Replace old content with new content

	$("#member_count").html(counties[0].statesum);


	// Prevent click eventpropagation
	return false;
}

function loopMembers(i,members) {
	if (members != null) {
		if (members.length > 0) {
			var content = "<b>" + members[i].firstname + " " + members[i].lastname + ".</b><br /><span>"  + members[i].city + ", " + members[i].state + "</span>";
			var point = new GLatLng(members[i].lat,members[i].lng);
			var pixelpoint = whereAreYouMarker(point);
			var marker = createMarker2(point,content);
			var id = members[i].recordid;
			var show = SPLCENTER.standstrong2.map.RANDOMRECORDSATATIME;
			//append a new layer for each member after the map container is ready.

			$("#map").append('<div id="membersheadsup' + id + '" style="opacity: 1.0; position: absolute; left:205px; top:65px; line-height:.8em;">' +
					'<table cellpadding="0" cellspacing="0" border="0"><tr><td style="width:11px;height:11px;padding:0px;margin:0px;"><img src="images/markers/tl.png" width="11" height="11" alt="tl" style="padding:0px;margin:0px;"></td><td style="background-color:white;padding:0px;margin:0px;"></td><td style="width:11px;height:11px;padding:0px;margin:0px;"><img src="images/markers/tr.png" width="11" height="11" alt="tr" style="padding:0px;margin:0px;"></td></tr><tr><td style="background-color:white;"></td><td style="background-color:white;font-size:2.5em; line-height:1.5em;">'+
					content +
					'</td><td style="background-color:white;"></td></tr><tr><td style="width:11px; height:11px;"><img src="images/markers/bl.png" width="11" height="11" alt="bl"></td><td style="background-color:white;"></td><td style="width:11px; height:11px;"><img src="images/markers/br.png" height="11" width="11" alt="br"></td></tr></table>'+
			'</div>');

			//now lets show this member and shrink it to the marker				
			$("#membersheadsup" + id)
			//Stay here for a little while so we can see you	
			.animate({
				opacity: 0.7
			}, SPLCENTER.standstrong2.map.MEMBERSSTAYTIMER )
			//go to the location of the point
			.animate({ 
				left: pixelpoint.x,
				top: pixelpoint.y,
				opacity: '0.0',
				height: '0px',
				width: '0px'
			}, 250,

			//when we get to the location, fadeout and show the marker
			function() {
				$("#membersheadsup" + id).fadeOut("fast");
				SPLCENTER.standstrong2.map.MARKERMANAGER.addMarker(marker,4,10); //add the marker at the proper zoom level 
			}
			)
			.delay(SPLCENTER.standstrong2.map.MEMBERSTOMEMBERTIMER, //delay between members
					function(){
				//remove this container before we add another
				$("#membersheadsup" + id).remove();
				if (i < members.length - 1) {


					i++; //add one for the next member
					loopMembers(i,members); //call the next member
					SPLCENTER.writedebug(4,"Added another member to the list");

				} else {
					//show controls or something
					SPLCENTER.writedebug(4,"Adding controls and click events. That was the last one " + i + " of " + show);

					if (members.length > 1) {
						addTakeActionLayer();
						removeAllMarkers();
						SPLCENTER.standstrong2.map.MAP.setMapType(SPLCENTER.standstrong2.map.STANDSTRONG);
						SPLCENTER.standstrong2.map.MAP.removeMapType(SPLCENTER.standstrong2.map.HATEMAP);
					}
					addMapControls();
					addClickEventToMap();
					hideLoadingStatus();
				}

			}
			);
			SPLCENTER.writedebug(4,"This is member " + i + " of " + members.length + ". Only showing " + show);

		} else {
			SPLCENTER.writedebug(4,"No members found");
		}
	} else {
		SPLCENTER.writedebug(4,"No members found. null");
	}				
}

function showLoadingStatus(){
	if ($("#loading").length <= 1) {
		//remove events first then add them the way we want them
		$("#loading").unbind();
		$("#loading").show().click(function () {
			SPLCENTER.writedebug(4,"User wants to cancel actions");
			stopMembersHeadsUp();

		});
	}
}

function hideLoadingStatus() {
	$("#loading").hide();

}

function showAddForm() {
	$("#addformstatus").text("");
	$("#formadd").show();
	$("#logo").scrollTo(1000); //this is a simple jquery plugin included by us
	$("#formreport").hide();
	removeMapOverlays();
	//removeMapControls();

}

function showReportForm() {

	$("#formreport").show();
	$("#logo").scrollTo(1000); //this is a simple jquery plugin included by us
	$("#formadd").hide();
	removeMapOverlays();
	//removeMapControls();
	$("#reportincidentreply").text('');

}

function stopMembersHeadsUp() {
	$("div:contains('membersheadsup')").unbind();
	$("div:contains('membersheadsup')").queue("fx",[]);
}

function hideContainer(container) {
	$(container).hide();	
}

function showContainer(container) {
	$(container).show();	
}

function toggleContainer(container) {
	$(container).toggle();	
}

function getHateGroupCountsByStateInitial(state) {

	$(this).ajaxForm( { 
		target: '#hategroupstatecount',
		url: 'hategroups_json.jsp',
		success: function() {
		$('#hategroupstatecount').fadeIn('slow');
	}

	} );

}

function validateReportIncidentCallback(formData, jqForm, options) { 

	var fieldsvalues = "";
	var form = jqForm[0]; 
	for (var i=0; i < formData.length; i++) {
		fieldsvalues = fieldsvalues + formData[i].name + ": " + formData[i].value + "\n";

	}
	$("#formreport").hide();
	SPLCENTER.writedebug(4,"This is the beforeSubmit callback.\n" + fieldsvalues);
	$("#thankyou").show();

}

function validateAddMemberCallback(formData, jqForm, options) { 
	$("#addformstatus").html("Sending your form...");
	var fieldsvalues = "";
	var form = jqForm[0]; 
	for (var i=0; i < formData.length; i++) {
		fieldsvalues = fieldsvalues + formData[i].name + ": " + formData[i].value + "\n";

	}

	SPLCENTER.writedebug(4,"This is the beforeSubmit callback.\n" + fieldsvalues); 

}

function  memberAddedCallback(data) {


	if (data.id > 0) {

		SPLCENTER.writedebug(4,"This is the afterSubmit callback. We got an id back: " + data.id);
		//$("#addformstatus").html("Member id add: " + data.id);
		$("#addformstatus").html("Saved.");

		$("#formadd").delay(500);
		var onememberarray = jQuery.makeArray(data);
		SPLCENTER.writedebug(4,"Adding: " + onememberarray.length + " for looping");
		$("#formadd").fadeOut(

				function(){

					SPLCENTER.writedebug(4,"Calling members headsup display");
					loopMembers(0,onememberarray);
					$("#addformstatus").html("");

				}
		);
		loadStateDataFromServer(data);
	} else {
		$("#addformstatus").html(data.status);
		SPLCENTER.writedebug(4,"Status: " + data.status);
	}

}

function drawCountyBarGraph() {

	$("#counties_list div em").each(function (i) {
		var capacity = Math.round($(this).text().replace(/\,/,"") / 2); // Divide by 350 to scale to desired widths.
		$(this).width(capacity).css("background-color", "#c00000");
		SPLCENTER.writedebug(4,"Looping county" + i);
	}).show(700);


}



$(document).ready(function(){
	$('#addyourself').submit(function() { 

		$(this).ajaxSubmit( { 
			beforeSubmit: validateAddMemberCallback,
			type: 'POST',
			dataType: 'json',
			url: 'signup_json.jsp',
			success: memberAddedCallback

		} );
		return false;
	}); 
});


$(document).ready(function(){
	$('#reportincident').submit(function() { 

		$(this).ajaxSubmit( { 
			beforeSubmit: validateReportIncidentCallback,
			type: 'POST',
			dataType: 'json',
			url: 'report_json.jsp',
			success: function(data) {

			if (data.status == '1') {
				$("#thankyou").delay(1000);
				$("#thankyoumessage").text('Thank You. We will contact you if we have any questions.');

			} else { //end if good form submit
				showReportForm();
				$("#reportincidentreply").text('We had trouble getting your incident report. Try again.');


			}
			$("#thankyou").delay(1000).fadeOut(
					function() {
						//reset for next time
						$("#thankyoumessage").text("Sending your incident report..");
					}
			);
		}


		} );
		return false;
	}); 
});
