var fundedProjects = null;
var mapProjectsUrl = null;

var mapIntervalId = -1;
var mapCloseIntervalId = -1;

var mapIntervalCount = 0;
var mapCloseIntervalCount = 0;

// cache the national and state level projects:
var nationalProjects = null;
var stateProjects = [];

var mapStart = 0;
var openingMap = false;

var lastState = null;
var lastCity = null;

function toggleSWF()
{
	var flash = document.getElementById("flashID");

	if( mapClosed ){
		flash.height = 550;

		//this function is available via external interface
		flash.loadApplication();
		loadFundedProjects(null,null,true);
	}
	else{
		flash.closeApplication();
	}
}

function startMapInterval()
{
	if(mapIntervalId == -1) {
		logItem("flash map not fully loaded. waiting 500ms");
		mapIntervalCount=0;
		mapIntervalId = window.setInterval(openMap, 500);
	}
	else
	{
		mapIntervalCount < 10 ? mapIntervalCount++ : window.clearInterval(mapIntervalId);
	}
}

function startMapCloseInterval()
{
	// only attempt to close the map if currently on the fundedProjects page (map showing):
	if(navAction == "#/fundedProjects")
	{
		if(mapCloseIntervalId == -1) {
			logItem("flash map hasn't fully opened. wait 500ms to close");
			mapCloseIntervalCount=0;
			mapCloseIntervalId = window.setInterval(closeMap, 500);
		}
		else
		{
			mapCloseIntervalCount < 10 ? mapCloseIntervalCount++ : window.clearInterval(mapCloseIntervalId);
		}
	}
}

function openMap()
{
	if(hasFlash == false)
		alert("Sorry! You need Flash to view the funded map.");
	else 
	{
		var flash = document.getElementById("flashID");
		if(flash != null)
		{
			if(mapIntervalId != -1) {
				window.clearInterval(mapIntervalId);
				mapIntervalId = -1;
			}
			
			if(openingMap == false){
				flash.height = 550;
		
				$("#navAccordion").accordion('activate',false);
		    	resetSearch();
				   
				//this function is available via external interface
				try
				{
					flash.loadApplication();
					loadFundedProjects(null,null,true);
					openingMap = true;
				}
				catch(err){
					//timer for openMap();
					startMapInterval();
				}
			}
		}
		else
		{
			//timer for openMap();
			startMapInterval();
		}
		
		setNavAction("#/fundedProjects");
	}
}

function closeMap()
{
	var flash = document.getElementById("flashID");
	if(mapClosed == false && flash != null && openingMap == false)
	{
		if(mapCloseIntervalId != -1) {
			window.clearInterval(mapCloseIntervalId);
			mapCloseIntervalId = -1;
		}
		flash.closeApplication();
	}
	else
	{
		startMapCloseInterval();
	}
}

function animateOpenComplete()
{
	logItem( "Animate open complete" );
	mapClosed = false;
	openingMap = false;
}

function animateCloseComplete()
{
	logItem( "Animate close complete" );
	var flash = document.getElementById("flashID");
	flash.height = 100;
	mapClosed = true;
	openingMap = false;
	
	//TODO: check to see if we were on the funded projects page, and if so navigate to howItWorks
	if(navAction.indexOf("#/fundedProjects") == 0)
	{
		setNavAction("#/howItWorks");
        $("#centerContent").load("./bodycontent/howItWorks.html",null);
	}
}

function openToolbox() {
		setNavAction("#/toolbox");
		$("centerContent").load(".bodyContent/tools.html", null);
}

//this function in being called from flash when the animation is finished
function minimizeComplete()
{
	logItem( "Minimize complete" );
	var flash = document.getElementById("flashID");
	flash.height = 80;
}

function loadFundedProjects( state, city, initialLoad )
{
	if(state == null) state = "";
	if(city == null) city = "";
	if(initialLoad == null) initialLoad = false;
	
	var stateKey = "";
	if(city == "" && state != "")
		stateKey = state;
		
	var msg = "Google analytics called with state=" + state + " and city=" + city;
	logItem( msg );
	trackView("#/map/"+state+"/"+city);
	
	mapProjectsUrl = actionPrefix + "mapProjects.do";
	if(initialLoad == false)
		mapProjectsUrl += "?state=" + state + "&city=" + city;
		
	fundedProjects = null;
	
	// loadFunded ajax call to fill body content (state, city);
	mapStart = null;
	$("#centerContent").load("./bodycontent/search.html", null, function() {
	
	lastState = state;
	lastCity = city;
	
		if(state == "" && city == "" && nationalProjects != null)
		{
			fundedProjects = nationalProjects;
			getMapProjects(false);
		}
		else if(state != "" && city == "" && stateProjects[state] != null)
		{
			fundedProjects = stateProjects[state];
			getMapProjects(false);
		}
		else
		{
			getMapProjects(true, initialLoad, stateKey); 
		}
	});
}

function getMapProjects(makeAjaxCall, initialLoad, stateKey)
{
	if (makeAjaxCall == null) { makeAjaxCall = true; }
	if (initialLoad == null) { initialLoad = false; }
		
	// if mapStart is null, get the first set of results:
	if ( mapStart == null ) { mapStart = 0; }
	   
	//if(mapProjectsUrl.indexOf("state") == -1)
	//	openAjaxLoader();
	
	if(makeAjaxCall == true)
	{
		$.ajax({
		        type: "GET",
		        url: mapProjectsUrl,
		        dataType: "json",
		        success : function(result) { 
		 	   				fundedProjects = result.projects;
		 	   				
							if(initialLoad)
							{
								nationalProjects = result.projects;
							}
							
							if(stateKey != "")
							{
								stateProjects[stateKey] = result.projects;
							}
							
		 	   			    getMapProjectsCallback();
		 	   			},
		        error : function(xOption, status) { 
		        		//closeAjaxLoader();
		        		logErrorMessage("loadFundedProjects","Error returned from json ajax call. mapProjectsUrl: " + mapProjectsUrl);
		        		alert("We're sorry. The system is having issues. Please try again later."); 
		        },
		        async: true
		});	
	}
	else
	{
		getMapProjectsCallback();
	}
}

function getMapProjectsCallback()
{
	var ids = "";
		 	   			    
	for (var i=0; i < 10; i++)
	{
		if(fundedProjects.length > (mapStart+i))
		{
			ids += fundedProjects[mapStart+i].id;
			if ( (mapStart+i+1) < fundedProjects.length) { ids  += " OR "; }
		}
	}
	searchUrl = baseSearchUrl + "&historical=true&keywords=(" + escape(ids) + ")";
	
	searchOptions = new Array();
	addSearchOption("historical","true");
	addSearchOption("keywords","("+escape(ids)+")");
	
	getSearchResults(searchUrl, false, showMapSearchResults, sortProjectsByCreated, null, mapPageHeader, false);
}

 function mapPageHeader()
 {
  $("<tr/>").attr("id","pagerRow").appendTo("#pagerTop");
     
     $("<td/>").append("SONIC&reg; Funded Projects").appendTo("#pagerRow");  
     
     $("<td/>").attr("class","pagesList").appendTo("#pagerRow");      
     if (mapStart > 0) 
     {
		$("<a/>").append("&lt; Previous 10").click(function(event){ mapStart -= 10; getMapProjects(false); event.preventDefault(); }).appendTo(".pagesList");
		if ( fundedProjects.length > (mapStart + 10) ) { $(".pagesList").append("&nbsp; . . . &nbsp;"); }
     }
     if (fundedProjects.length > (mapStart + 10))
     {
		var aPg = document.createElement("a");
		$(aPg).click(function(event){ mapStart += 10; getMapProjects(false); event.preventDefault(); });
		$(aPg).append("Next 10 &gt;");
		$(".pagesList").append("&nbsp;").append($(aPg));
     }
     
     // Set bottom pager content to the same as top.
     $("#pagerRow").clone(true).appendTo($("#pagerBottom"));	   
 }
   
   
   function showMapSearchResults(dcResult)
   {
       // Clear previous results
	   $("#searchCriteriaList").empty();
       $("#pagerTop").empty();
       $("#searchResults").empty();
       $("#pagerBottom").empty();
       
       buildSearchResults(dcResult.proposals);
       
       $(".votesCast").each( function() { $(this).css("display","none"); } );
   }
   
function sortProjectsByCreated(dcResult)
{
	   if ( dcResult.proposals != null && fundedProjects != null && dcResult.proposals.length > 0)
	   {
		   var sortedProposals = new Array();
		   var idx = 0; // needs its own index in case a funded project has
		   for (var i=0; i < fundedProjects.length; i++)
		   {
			   for(var j=0; j < dcResult.proposals.length; j++)
			   {
				   if ( fundedProjects[i].id == dcResult.proposals[j].id )
				   {
					   sortedProposals[idx] = dcResult.proposals[j];
					   idx++;
				   }
			   }
		   }
		   dcResult.proposals = sortedProposals;
	   }
	   else
	   {
  		   //closeAjaxLoader();
		   return true;
	   }
	   return false;
}

function logItem(msg)
{
	if ( window.console )
	{
		try
		{
			console.log(msg);
		}
		catch(cErr) {}
	}
}