// Global variables if they enter an address and radius
var startAddress;
var selectedRadius;
var startPoint;
// GOT IP LOCATION
// Use this as our default starting point
var gotIPLocation = function(o) {
    if( (typeof(o) != "undefined" && typeof(o.match) != "undefined") && (o.match.city.indexOf(", CA") >= 0) ){
	// We think we know where person came from based on their IP
	var iplat = o.match.latitude;
	var iplng = o.match.longitude;
	var citystate = o.match.city;
// 	// Let's center and zoom the map around the lat/lng of the ip address
	    startAddress = citystate;
	    startPoint = new GLatLng(iplat, iplng);
	    map.setCenter(startPoint, 10);
	// If the city/state is not California, then default to San Francisco, CA
    } else {
	var citystate = "San Francisco, CA";
	if (typeof(gmaps_default_loc) != "undefined" && gmaps_default_loc.length > 0)
	    citystate = gmaps_default_loc;
	startAddress = citystate;
	updateAddress();
//	startPoint = new GLatLng(37.7742, -122.417068);
//	map.setCenter(startPoint, 10);
    }
    $j("input[name=address]", "#addressForm").val(citystate);
    updateMap();
    $j("input[name=address]", "#addressForm").val(startAddress);
};

// CHECK IP
// Uses a php file to get the location from the IP address
function checkIP(data){

    // Store the full schools xml file in a global variable so we can re-use it
    fullXMLFile = data;

    // Call the ip helper file to determine the users's approximate location
    // Try for 30 seconds before failing gracefully

    gotIPLocation();
/*
    var url = pluginurl + "/lib/map/ip.php";
    $j.post(url,
	{},
  	gotIPLocation,
	"json");
*/
}

// ON MAP MOVE
// Called when the user drags the map
function onMapMove(){
    updateMap();
}

// ON MAP ZOOM
// Called when the user changes the zoom level
function onMapZoom(oldLevel,newLevel){
    if(newLevel < 8){ alert("You have reached the maximum level of zooming for this map."); }
    updateMap();
}

// ON PAGE LOAD
// Initializes some variables, downloads the full school xml file, adds event listeners to map
function mapLoad() {

    // Show progress bar
$j("#loadingmessage").show();

    // Set the subjects dropdown to "all"
    //document.getElementById("subject").selectedIndex = 0;

    if (GBrowserIsCompatible()) {

	// Set some global variable values
    map = new GMap2(document.getElementById("map"));
	geocoder = new GClientGeocoder();
	//debug = document.getElementById("debug");

	// Restricting the range of Zoom Levels
        // Get the list of map types
            var mt = map.getMapTypes();
			 // Overwrite the getMinimumResolution() and getMaximumResolution() methods
		for (var i=0; i<mt.length; i++) {
		    mt[i].getMinimumResolution = function() { return 8;};
		}

	// Add the zoom/pan control
		    map.addControl(new GSmallMapControl());

	// Add listeners to the map for moving and zooming
	GEvent.addListener(map,'dragend',onMapMove);
            GEvent.addListener(map,'zoomend',onMapZoom);
    }

}


// CREATE MARKER
// Creates a marker on the map
function createMarker(p,content1,content2,icontype,num){
    // Create a marker
    if(icontype == "school"){
	var icon = new GIcon(schoolIcon);
  	icon.image = pluginurl + "/lib/map/images/markers/marker" + num + ".png";
	var marker = new GMarker(p, icon);

	// Add it to our array so we can have the sidebar click
	gmarkers[num] = marker;
	GEvent.addListener(marker, "click", function() {
        		       marker.openInfoWindowHtml(content1);
			   });
    } else {
	var marker = new GMarker(p, startIcon);
	gmarkers[0] = marker;

	// Add address information to marker
        GEvent.addListener(marker, "click", function() {
        		       marker.openInfoWindowHtml(content1);
			   });
    }
    return marker;
}

function clearResults(){
    map.clearOverlays();
    $j("#list").html("");
    $j("#navigation").html("");
    $j("#results").html("");
    gmarkers = [];
}

// PROCESS BOXED POINTS
// The function that actually places the points on the map based on the XML file provided
function updateMap()
{
    // Show progress bar
$j("#loadingmessage").show();

    // Clear existing markers/list from the page
    clearResults();

    var page = 0;

    if (typeof startPoint != "undefined") {
    $j.post(pluginurl + "/lib/schools-site-ajax.php",
	{
	    cmd: "nearby_campuses",
	    distance: $j("select#radius").val() || 25,
	    latitude: startPoint.y,
	    longitude: startPoint.x,
	    subject:  selectedSubject || '',
	    level:    selectedLevel || ''
	},
	gotMatches,
	"json"
	);
     }
} // function updateMap

function addStartMarkerAndRadius(p,addr,radius){
    var content = "<div class='addresstab'><span class='schoolname'>Your Address</span><br/>";
    content += "<span class='address'>" + addr + "</span><br/>";
    // Add the marker
    map.addOverlay(createMarker(p,content,"","start",0));
    // Draw the radius circle
    drawCircle(p,radius);
}

function generateMarkerContent(school, count, p){
    // Extract all the information from the xml file
    var schoolname = school["SchoolName"];
    var street = school["CampusAddress"];
    var city = school["CampusCity"];
    var state = school["CampusStateID"];
    var zip = school["CampusPostalCode"];
    var phone = school["CampusPhone"];
    var website =  school["CampusWebsite"];
    var address = street + ", " + city + ", " + state + "  " + zip;
    var num_programs = school["num_programs"] || "";
    var list_programs = school["list_programs"] || "";
    var ppl = school["ppl"] || "";
    // Create Address Tab Content
    var content1 = "<div class='addresstab'><span class='schoolname'>" + schoolname + "</span><br/>";
    content1 += "<span class='address'>" + street + "<br/>" + city + ", " + state + "  " + zip + "</span><br/>";
    content1 += "<span class='phone'>" + phone + "</span><br/>";
    if (ppl.length > 0)
	content1 += "<a href='" + ppl + "' target='_blank' class='link'>More Information</a>";
    content1 += "</div>";

    // Create Programs Tab Content
    var content2 = "<div class='programstab'><ul>";

    var programs = list_programs.split("|");

    for (var k=0; k < programs.length; k++)
    {
  	var prog = programs[k];
  	content2 += "<li>" + prog +  "</li>";
    }
    content2 += "</ul></div>";

    // Add the marker to the map
	map.addOverlay(createMarker(p,content1,"","school",count));
	// Add an entry to the list
	addToList(content1,content2,count, programs.length);
}

// GO TO PAGE
function goToPage(page){

    // Show progress bar
$j("#loadingmessage").show();

    displayMatches(page);

    // Hide Progress Bar
$j("#loadingmessage").hide();

}

// GOT MATCHES
var gotMatches = function(o){
    if (o.nearby_campuses !== undefined ) {
	if (!o.nearby_campuses.campuses)
	    didNotGetMatches(o);
	else {
	    // Place matches into global variable
	    matches = o.nearby_campuses;
	    displayMatches(0);
	}
	// Hide Progress Bar
	$j("#loadingmessage").hide();
    }
};

// DID NOT GET MATCHES
// Called if the PHP helper file does not sucessfully return any content
var didNotGetMatches = function(o){
    if(o.responseText !== undefined){
	$j("#errors").html("Sorry, we were unable to return matching schools.");
	// Hide Progress Bar
$j("#loadingmessage").hide();
	}
};

// DISPLAY MATCHES
// When needed, this will handle paging as well
function displayMatches(page){
    clearResults();

    var itemsPerPage = 99;
    var startIndex = page * itemsPerPage; // 0*99 = 0, 1*99 = 99
    var endIndex = startIndex + itemsPerPage; // 0+99 = 99, 99+99 = 198

    if(matches.campuses && matches.campuses.length < endIndex){
	endIndex = matches.campuses.length;
    }

    var count = 1;

    for (var i = startIndex; i < endIndex; i++)
    {

	var school = matches.campuses[i];

  	var lat = school["Latitude"];
  	var lon = school["Longitude"];

    	generateMarkerContent(school, count, new GLatLng(lat,lon));

	count++;

    }
/*
// NOW add the markers
    var markmgr = new GMarkerManager(map);
    markmgr.addMarkers(gmarkers[1]);
    markmgr.refresh();
*/
    // Result Stats
    if(matches.campuses.length == 0){
	$j("#results").html("Showing <strong>0 - 0</strong> of <strong>0</strong> Results<br/><br/>Sorry, we could not find any matching schools.");
	    }
    else {
	$j("#results").html("Showing <strong>" + (startIndex+1) + " - " + endIndex + "</strong> of <strong>" + matches.campuses.length + "</strong> Results");
	    }

    // Paging (if applicable)

    var navg = $j("#navigation");
    if(page > 0){
	var prev = page-1;
	navg.html(navg.html() + "<a href='javascript: goToPage(" + prev + ")'>Previous</a> &nbsp; ");
    }
    if(matches.campuses.length > endIndex){
	var next = page+1;
	navg.html(navg.html() + "<a href='javascript: goToPage(" + next + ")'>Next</a>");
    }


    // Is there a user-entered starting point?
    // If so, create a special marker for it
    if(startAddress != ""){
	addStartMarkerAndRadius(startPoint, startAddress, selectedRadius);
    }
} // function displayMatches

// ADD FACET
function addFilter(which,val){
    // Show progress bar
    $j("#loadingmessage").show();
    var items = "";
    // If there's a previousy selected subject, clear it
    if(which == "s"){
	// Return the previous link to an active state
	toggleFacetLink("s",selectedSubject);
	selectedSubject = val;
	items = document.getElementById("subjectsList").getElementsByTagName("li");
    } else {
	// Return the previous link to an active state
	toggleFacetLink("l",selectedLevel);
	selectedLevel = val;
	items = document.getElementById("levelsList").getElementsByTagName("li");
    }

    // Make the clicked link inactive with an [x]
    toggleFacetLink(which,val);

    // Hide all other items
    for (var i=0;i<items.length;i++){
	if(val!="all"){
    	    if(items[i].id.indexOf(val)==-1 && items[i].id.indexOf("all")==-1){
    		toggleFacetItem(items[i],"hide");
    	    }
  	}
	// Clicked on all so remove all filters
	else{
	    toggleFacetItem(items[i],"show");
	}
    }
    updateMap();
}

// They clicked on the [x]
function removeFilter(which,val){

    // Show progress bar
$j("#loadingmessage").show();

    var items = "";

    // If there's a previousy selected subject, clear it

    if(which == "s"){
	// Return the link to an active state
	toggleFacetLink("s",val);
	selectedSubject = "all";
	items = document.getElementById("subjectsList").getElementsByTagName("li");
    }
    else{
	// Return the previous link to an active state
	toggleFacetLink("l",val);
	selectedLevel = "all";
	items = document.getElementById("levelsList").getElementsByTagName("li");
    }

    // Make "All" active again
    toggleFacetLink(which,"all");

    // Show all other items
    for (var i=0;i<items.length;i++){
	toggleFacetItem(items[i],"show");
    }

    updateMap();

}

function toggleFacetItem(li,how){

    if(how=="show"){
	li.style.display = "";
    }

    else{
	li.style.display = "none";
    }

}

// TOGGLE FACET LINK
function toggleFacetLink(which,val){

    var lnk = "";
    var spn = "";

    if(which=="s"){
	lnk = document.getElementById("subjLink_" + val);
	spn = document.getElementById("subjSpan_" + val);
    }
    else {
	lnk = document.getElementById("levLink_" + val);
	spn = document.getElementById("levSpan_" + val);
    }

    // Link is already hidden so show it and hide the static text and [x]
    if(lnk.style.display == "none"){
	lnk.style.display = "";
	    spn.style.display = "none";
    }
    // Link is currently shown so hide it and show the static text and [x]
    else{
	lnk.style.display = "none";
	    spn.style.display = "";
    }

}

// UPDATE ADDRESS
// Called when the address form is submitted
function updateAddress(f){
    // Show progress bar
    $j("#loadingmessage").show();

    // Get the form values
    startAddress = $j("input[name=address]", "#addressForm").val();
    selectedRadius = parseInt($j("select[name=radius]", "#addressForm").val());
    // If there's an address...
    if(!isBlank(startAddress)){
  	geocoder.getLatLng(
  	    startAddress,
  	    function(p) {
        if (!p) {
	    var errs = $j("#errors");
	    errs.html(errs.html() + "<br/>Sorry, we can't seem to find the address you entered.  Could you double-check it?");
            return null;
        }
  		else {

		    // Set the global variable for start lat/lng
		    startPoint = p;
		    var prevZoom = map.getZoom();
		    var idealZoom = 10;

		    switch(selectedRadius)
		    {
		    case 5:
			idealZoom = 12;
			break;
		    case 10:
			idealZoom = 11;
			break;
		    case 25:
			idealZoom = 10;
			break;
		    case 50:
			idealZoom = 9;
			break;
		    }

		    // Center and zoom the map in on the address entered
		    map.setCenter(p,idealZoom);

		    // If the zoom is the same, the zoom event listener won't be called so we will need to udpate the map from within this function
		    if(map.getZoom() == prevZoom) {
			updateMap();
		    }
  		}
  	    }
  	);

    }

    else {

	$j("#errors").html("Please enter an address.");

    }
    mapLoad();
}

// ADD TO LIST
// Adds the school information to a list that will be displayed alongside the map
function addToList(content1,content2,num,numprogs){
    var listhtml = $j("#list").html();
    listhtml += "<table><tr><td valign='top' width='25'><a href='javascript: sidebarClick(" + num + ")'><img src='" + pluginurl + "/lib/map/images/markers/marker" + num + ".png' alt='' border='0'/></a></td><td>" + content1 + "<br/><a href='javascript:toggleProgPanel(" + num + ")' id='progToggle_" + num + "'>Show Programs</a> (" + numprogs + ")</td></tr></table>";
    listhtml += "<div id='progPanel_" + num + "' style='display: none; margin-left: 35px;'>" + content2 + "</div>";
    listhtml += "<div class='sep'></div>";
    $j("#list").html(listhtml);
}

function toggleProgPanel(num){

    var panel = document.getElementById("progPanel_" + num);
    var lnk = document.getElementById("progToggle_" + num);

    if(panel.style.display == "none"){
	panel.style.display = "";
	lnk.innerHTML = "Hide Programs";
    }
    else {
	panel.style.display = "none";
	lnk.innerHTML = "Show Programs";
    }

}

// SIDEBAR CLICK
// Opens the marker's information window when the corresponding marker on the sidebar is clicked
function sidebarClick(num){
    GEvent.trigger(gmarkers[num], "click");
}

// IS BLANK
// A function that determines if a value is composed of all spaces
function isBlank(val){
    if(val==null){return true;}

    for(var i=0;i<val.length;i++) {
	if ((val.charAt(i)!=' ')&&(val.charAt(i)!="\t")&&(val.charAt(i)!="\n")&&(val.charAt(i)!="\r")){return false;}
    }
    return true;
}

// RETURN INNER TEXT
// IE and FF treat this differently; this function makes sure it will work for both browsers
function getInnerText(obj) {
    return (obj.text) ? obj.text
	: (obj.textContent) ? obj.textContent
	: "";
}

// DRAW CIRCLE
// If the user enters an address, this will draw a circle indicating the selected radius from the address
// This function is courtesy of http://esa.ilmari.googlepages.com/circle.htm
function drawCircle(center, miles){
    var nodes = 40;

    // Convert miles to KM
    var radius = miles * 1.609344;

    //calculating km/degree
    var latConv = center.distanceFrom(new GLatLng(center.lat()+0.1, center.lng()))/100;
    var lngConv = center.distanceFrom(new GLatLng(center.lat(), center.lng()+0.1))/100;

    //Loop
    var points = [];
    var step = parseInt(360/nodes)||10;
    for(var i=0; i<=360; i+=step){
    var pint = new GLatLng(center.lat() + (radius/latConv * Math.cos(i * Math.PI/180)), center.lng() +
    (radius/lngConv * Math.sin(i * Math.PI/180)));
    points.push(pint);
    }

    var poly = new GPolyline(points);
    map.addOverlay(poly);
}

