var side_bar_html = "";
var gmarkers = [];
var htmls = [];
var i = 0;
var map;
var selectedServices = new Array();
var tooltip = document.createElement("div");
var tryagain = true;
var catid = 18;
var MarkerIDs;
var abcount=0;

var iconDefault = new GIcon;
iconDefault.image = "/map/imagens/seta1.png";
iconDefault.shadow = "/map/imagens/shadow-seta1.png";

iconDefault.iconSize = new GSize(24.0, 24.0);
iconDefault.shadowSize = new GSize(37.0, 24.0);
iconDefault.iconAnchor = new GPoint(24.0, 24.0);
iconDefault.infoWindowAnchor = new GPoint(24.0, 24.0);

//       iconDefault.iconSize = new GSize(28.0, 28.0);
//       iconDefault.shadowSize = new GSize(43.0, 28.0);
//       iconDefault.iconAnchor = new GPoint(14.0, 14.0);
//       iconDefault.infoWindowAnchor = new GPoint(14.0, 14.0);

function GetMarkers(cid, category) 
{
    // Set the global value for every other function to use
    catid = cid;
    if (catid == 18) 
	{
      $("#subtitle").css('display', 'block');
      $("#serviceList").css('display', 'block');
      $("#printButton").css('display', 'block');
      $("#filterInput").css('display', 'block');
      $("#filterResults").css('display', 'block');
      $("#SearchClear").css('display', 'block');
    } 
	else 
	{
      $("#subtitle").css('display', 'none');
      $("#serviceList").css('display', 'none');
      $("#printButton").css('display', 'none');
      $("#filterInput").css('display', 'none');
      $("#filterResults").css('display', 'none');
      $("#SearchClear").css('display', 'none');
    }
    $("#filterInput").value = "";
    $("#mapTitle").html("Map of " + category);
    $("#noResults").css('visibility', 'hidden');
    $("#serviceHeader").css('visibility', 'hidden');
    selectedServices = new Array();
    $("#categoryID").value = catid;
    //$("#teste").load(SGL_JS_WEBROOT + "/usermap/action/generate/catid/" + catid + "/category/" + category + "/");
    
    //        teste2 = "/map/" + catid + ".xml";
    readMap();
    return (false);
}

function gera(catid, category) 
{
      if(catid == 18) 
	  {
          document.getElementById("subtitle").style.display = 'block';
      } 
	  else 
	  {
          document.getElementById("subtitle").style.display = 'none';
      }
      document.getElementById("filterInput").value = "";
      document.getElementById("mapTitle").innerHTML = "Map of " + category;
      document.getElementById("noResults").style.visibility = 'hidden';
      document.getElementById("serviceHeader").style.visibility = 'hidden';
      document.getElementById("printButton").style.visibility   = 'hidden';
      //document.getElementById("serviceList").innerHTML = "";
      selectedServices = new Array();
      document.getElementById("categoryID").value = catid;
      var teste2;
      teste2 = "/map/" + catid + ".xml";
		//             ajaxGet("/map/gera_xml.php?role="+role+"&rolename="+rolename,document.getElementById("teste"),true);
		//alert(category);
      ajaxGet(SGL_JS_WEBROOT + "/usermap/action/generate/catid/"+catid+"/category/"+category+"/", document.getElementById("teste"),true);
      readMap();
}

// A function to create the marker and set up the event window
function createMarker(point,name,html) 
{
	if (!html) 
 	{
  	// Some markers have no data, so ignore them
  		return;
 	}
	var marker = new GMarker(point, iconDefault);
	GEvent.addListener(marker, "click", function() {
  	//marker.openInfoWindowHtml(html);
  	marker.openInfoWindowHtml('<div class="nome">'+html+'</div>', {maxWidth:300});
	'<div class="tooltip">'+name+'</div>'
	});
	//  ======  The new marker "mouseover" and "mouseout" listeners  ======
	GEvent.addListener(marker,"mouseover", function() {
  	showTooltip(marker);
	});
	GEvent.addListener(marker,"mouseout", function() {
      tooltip.style.display="none"
	});
	gmarkers[i] = marker;
	marker.tooltip = '<div class="tooltip">'+name+'</div>';
//htmls[i] = html;
//side_bar_html += '<a href="javascript:myclick(' + i + ')">' + name + '</a><br>';
//i++;
	return marker;
}

function mymouseout() 
{
     tooltip.style.visibility="hidden";
}
// ====== This function displays the tooltip ======
// it can be called from an icon mousover or a side_bar mouseover
function showTooltip(marker) 
{
	tooltip.innerHTML = marker.tooltip;
  	var point=map.getCurrentMapType().getProjection().fromLatLngToPixel(map.getBounds().getSouthWest(),map.getZoom());
  	var offset=map.getCurrentMapType().getProjection().fromLatLngToPixel(marker.getPoint(),map.getZoom());
  	var anchor=marker.getIcon().iconAnchor;
  	var width=marker.getIcon().iconSize.width;
  	var pos = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(offset.x - point.x - anchor.x + width,- offset.y + point.y +anchor.y));
  	//var pos = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(10,10));
	pos.apply(tooltip);
  	tooltip.style.visibility="visible"; 
}

// ===== This function is invoked when the mouse goes over an entry in the side_bar =====
// It launches the tooltip on the icon
function mymouseover(i) 
{
	showTooltip(gmarkers[i])
}

// This function picks up the click and opens the corresponding info window
function myclick(i) 
{
	gmarkers[i].openInfoWindowHtml('<div class="tooltip">'+htmls[i]+'</div>');
}

function criaLocal() 
{
	map.setCenter(new GLatLng(43.669914  	,-79.388390), 4);
	// var point = new GLatLng(latid  	,longi);
	// var marker = createMarker(point,'The Pantages','210 Victoria Street','default');
	// map.addOverlay(marker);
}

/* Use this to append a random string to a URL so that it is never cached */
function RandomURLEnding() 
{
	return '?a=' + Math.random(); 
}

function HandleLoadedMarkers(responseText, textStatus, Req) 
{
	PutMarkersOnMap();
}

function PutMarkersOnMap() 
{
    if (typeof(SetMarkerIDs) == "undefined") 
	{
        // The data hasn't been loaded yet
        return;
    }
    map.clearOverlays();
    MarkerIDs = SetMarkerIDs();
    var Filters = new Array();

   	if ($("#AllFiltersCheck").attr('checked')) 
	{
        // Clear all the checkboxes
        $("input[@name='ServiceFilters[]']").each(function() {
            this.checked = false;
        });
    } 
	else 
	{
		$("input[@name='ServiceFilters[]']").each(function() {
         if ($(this).attr('checked')) 
		 {
            Filters.push($(this).val());
         }
        });
    }
	
	for (MIndex in MarkerIDs) 
	{
		var MarkerData = MarkerIDs[MIndex];
      	var Allowed = false;
      	if (Filters.length > 0 && MarkerData.length > 4) 
		{
        	// There are some filters selected, so see if we should use this point
        	for (var i = 0; i < Filters.length; i++) 
			{
            	if (MarkerData[4].indexOf(',' + Filters[i]) != -1) 
				{
                	Allowed = true;
                	break;
            	}
        	}
      	} 
		else 
		{
        	Allowed = true;
      	}
      
      	if (Allowed) 
		{
         	MID = MarkerData[0];
          	HTMLControl = document.getElementById("marker_" + MID);
          	HTMLData    = HTMLControl.innerHTML;
          	//HTMLData    = $("#marker_" + MID).html();
          	var HTMLDataNew       = HTMLData.toLowerCase();
          	var SearchTerms = $("#filterInput").attr('value');
          	if (typeof(SearchTerms) != 'undefined') 
			{
            	SearchTerms  = SearchTerms.toLowerCase();
            	if (SearchTerms) 
				{
                	Allowed =(HTMLDataNew.indexOf(SearchTerms) != -1);
            	}
          	}
          
          	if (Allowed) 
			{
            	point = new GLatLng(MarkerData[1],MarkerData[2]);
            	var marker = createMarker(point, MarkerData[3], HTMLData);
            	// create the marker
            	if (marker) 
				{
                	map.addOverlay(marker);
            	}
          	}
      	}	
    }
	return;
}

function stateChanged() 
{	
	if (request.readyState == 4)/* || request.readyState=="complete") */
	{
    	var xmlDoc = request.responseXML;
    	// obtain the array of markers and loop through it
    	//alert(url);
    	var markers = xmlDoc.getElementsByTagName("marker");
  		//  var markers = xmlDoc.documentElement.getElementsByTagName("marker");
		// hide the info window, otherwise it still stays open where the removed marker used to be
    	map.getInfoWindow().hide();
		//map.clearOverlays();
		// empty the array
    	gmarkers = [];
		// reset the side_bar
    	//side_bar_html="";
		//Verifica Fronteiras
    	var bounds = map.getBounds();
    	var southWest = bounds.getSouthWest();
    	var northEast = bounds.getNorthEast();
    	var lngSpan = northEast.lng() - southWest.lng();
    	var latSpan = northEast.lat() - southWest.lat();
    	map.clearOverlays();
    	var markerCount = 0;
		for (var i = 0; i < markers.length; i++) 
		{
			/*var markerCountField = document.getElementById("markerCount");
			markerCountField.innerHTML=123;*/
      		// obtain the attribues of each marker
      		var lat = parseFloat(markers[i].getAttribute("lat"));
      		var lng = parseFloat(markers[i].getAttribute("lng"));
   			//if ((lng > southWest.lng() && lng < northEast.lng()) &&  (lat > southWest.lat() && lat < northEast.lat())) {
        	point = new GLatLng(lat,lng);
          	var label = markers[i].getAttribute("city");
          	var count = markers[i].getAttribute("count");
          	var region = markers[i].getAttribute("region");
          	var country = markers[i].getAttribute("country");
			if (count > 1) 
			{
              	plural = 's';
          	} 
			else 
			{
              	plural = '';
          	}
          	var html = '<div style="max-width:400px; font-size:10px; font-family: Verdana;">'+label+',</br> '+region+'</br> '+country+'<br>';
          	var info   = label + ' ' + region + ' ' + country + ' ' + count + ' registration' + plural + ' ';
         	var showMarker = true;
          	/* Code for service provider information!!!! */
          	var organization  = markers[i].getAttribute("organization");
         	var address       = markers[i].getAttribute("address");
          	var phone         = markers[i].getAttribute("phone");
          	var postalcode    = markers[i].getAttribute("postalcode");
          	var website       = markers[i].getAttribute("website");
          	var services      = markers[i].getAttribute("services");
          	var otherServices = markers[i].getAttribute("otherServices");
          	var email =         markers[i].getAttribute("email");
          	var agegroups     = markers[i].getAttribute("agegroups");
          	var languages     = markers[i].getAttribute("languages");
          	var description   = markers[i].getAttribute("description");
          	var otherlanguage = markers[i].getAttribute("otherlanguage");
			if(services != null && services != "") 
			{
            	var serviceArray = services.split('+');
                document.getElementById("serviceHeader").style.visibility = 'visible';
                document.getElementById("printButton").style.visibility   = 'visible';
                info += '|' + services;
            }
          	if(organization != null && organization != "") 
			{
              	html +='<br>';
              	info += '|' + organization;
              	var orgArray = organization.split('|');
				if(otherServices != null && otherServices != "") 
				{
                  	var otherArray = otherServices.split('|');
                  	info += '|' + otherServices;
                  	info += '|Other';
                  	generateService('Other');
             	} 
              	if(postalcode != null && postalcode != "") 
				{
                  	var postArray = postalcode.split('|');
                  	info += '|' + postalcode;
              	}  
              	if(email != null && email != "") 
				{
                 	var emailArray = email.split('|');
                 	info += '|' + email;  
               	}                    
              	if(phone != null && phone != "") 
				{
                  	var phoneArray = phone.split('|');
                  	info += '|' + phone;
              	}                         
              	if(address != null && address != "") 
				{
                  	var addressArray = address.split('|');
                  	info += '|' + address;
              	}                      
              	if(website != null && website != "") 
				{
                  	var siteArray = website.split('|');
                  	info += '|' + website;
              	}
              	if(agegroups != null && agegroups !="")
				{
                  	var agegroupArray = agegroups.split('|');
                   	info += '|' + agegroups;
              	} 
              	if(languages != null && languages !="")
				{
                  	var languageArray = languages.split('|');
                   	info += '|' + languages;
              	} 
              	if(otherlanguage != null && otherlanguage !="")
				{
                  	var otherlanguageArray = otherlanguage.split('|');
                   	info += '|' + otherlanguage;
              	} 
              	if(description != null && description != "") 
				{
                 	var descriptionArray = description.split('|');
                 	info += '|' + description;  
               	} 
                 
              	var separator = '';
              	for (org in orgArray) 
				{
                  	if(orgArray[org] != "") 
					{
                      	html += separator + '<i>Organization:</i> ' + orgArray[org];
                      	separator = '<br>';
                      	if(phone && phoneArray[org] && phoneArray[org] != "") 
						{
                          	html += separator + '<i>Telephone:</i> ' + phoneArray[org];
                      	}
                        if(address && addressArray[org] && addressArray[org] != "") 
						{
                          	html += separator + '<i>Address:</i> ' + addressArray[org] + ', ' + label;
                      	}
                       	if(postalcode && postArray[org] && postArray[org] != "") 
						{
                          	html += ', ' + postArray[org];
                      	}
                      	if(email && emailArray [org] && emailArray[org] != "")
						{
                       		html += separator + '<i>Email:</i> <a  href="mailto:'+emailArray[org]+'"/>'+ emailArray[org] + '</a>';
                      	}
                      	if(website && siteArray[org] && siteArray[org] != "") 
						{
                          	html += separator + '<i>Website:</i> <a target="_blank" href="'+siteArray[org]+'"/>'+ siteArray[org] + '</a>';
                      	}
                      	if(services && serviceArray[org]) 
						{
                          	html += separator + '<i>Services:</i> ';
                          	var orgServices = serviceArray[org].split('+');
                         	var sComma = '';
							for (entry in orgServices) 
							{
                          	  	generateService(orgServices[entry]);
                          	  	if(orgServices[entry] == "Other") 
								{
                                  	if(otherServices && otherArray[org] != null && otherArray[org] != "") 
									{
                                     	// if we know of other services, carry on!
                                  	} 
									else 
									{
                                      	html += sComma + "Unknown";
                                      	info += '|Unknown';
                                  	}
                              	} 
								else 
								{
								  	html += sComma + orgServices[entry];
								  	sComma = ', ';
                              	}
                          	}
                      	}
                      	if(otherServices && otherArray[org] != null && otherArray[org] != "") 
						{
                          	html += sComma + otherArray[org];
                      	}
                      	if(agegroups && agegroupArray[org] != null && agegroupArray[org] != "") 
						{
                          	html += separator +'<i>Age group(s) serviced:</i> ' ;
                          	var orgageGroups = agegroupArray[org]. split('+');
                          	var sComma ='';
                          	for(entry in orgageGroups)
							{
                           		/* generateService(orgageGroups[entry]);*/
                             	html+=sComma + orgageGroups[entry];
                             	sComma =', ';
                          	}
                       	}
                     	if(languages && languageArray[org] != null && languageArray[org] != "") 
						{
                          	html += separator +'<i>Language(s) serviced:</i> ' ;
                          	var orglanguages = languageArray[org]. split('+');
                          	var sComma ='';
                          	for(entry in orglanguages)
							{
                             	html+=sComma + orglanguages[entry];
                             	sComma =', ';
                          	}
                       	}
                      	if(otherlanguage && otherlanguageArray[org] != null && otherlanguageArray[org] != "") 
						{
                          	html += sComma + otherlanguageArray[org];
                      	}
                    	if(description && descriptionArray[org] && descriptionArray[org] != "")
						{
                       		html += separator + '<i>Description:</i> ' + descriptionArray[org];
                      	}
                   	}
              	}
          	} 
			else 
			{
              	html +='<br> '+count+' registration'+plural;
          	}
          	/*var allDetails = markers[i].getAttribute("details");
          	if (allDetails != null) 
			{
              	var details = allDetails.split('|');
              	// get details for each individual at this point
              	for ( individual in details ) 
				{
                  	if(details[individual] != "") 
					{
                     	html += '<br> '+ details[individual];
                     	info += details[individual] + ' ';        This is all commented out.
                  	}
              	}
          	} 
			else 
			{
              	html +='<br> '+count+' registration'+plural;
          	}

          	var website = markers[i].getAttribute("website");
          	if(website != null && website != "") 
			{
              	html +='<br>Website: ';
              	info += '|' + website;
              	var siteArray = website.split('|');
              	var separator = '';
              	for (site in siteArray) 
				{
                  	if(siteArray[site] != "") 
					{
                      	html += separator + siteArray[site];
                      	separator = ', ';
                  	}
              	}
          	}
          
          	var contact = markers[i].getAttribute("contact");
          	if(contact != null && contact != "") 
			{
              	html +='<br>Contact: ';
              	info += '|' + contact;
             	var conArray = contact.split('|');
              	var separator = '';
              	for (con in conArray) 
				{
                  	if(conArray[con] != "") 
					{
                      	html += separator + conArray[con];
                      	separator = ', ';
                  	}
              	}
          	}
          
          	var services = markers[i].getAttribute("services");
          	if(services != null && services != "") 
			{
              	document.getElementById("serviceHeader").style.visibility = 'visible';
              	document.getElementById("printButton").style.visibility   = 'visible';
              	html +='<br>Services: ';
              	info += services;
              	var serviceArray = services.split('|');
              	var separator = '';
              	for (service in serviceArray) 
				{
                  	if(serviceArray[service] != "") 
					{
                      	html += separator + serviceArray[service];
                      	separator = ', ';
                      	generateService(serviceArray[service]);
                  	}
              	}
          	}*/                  
          
          	/* End code for service provider service information */
          
          	html += '</div>';
          	//var html = 'Teste';
			if (document.getElementById("filterInput")) 
			{
             	var filter = document.getElementById("filterInput").value;
             	//alert("f=" + filter);
          	}
          	var filtering = false;
          	if ((getServices() != "") || (filter != null && filter != '' && filter != ' ' && filter != '0')) 
			{
              	filtering = true;
              	info   = info.toUpperCase();
              	info   = info.replace(/|/," "); // replace separators with spaces
              	info   = info.replace(/\,/,""); // remove commas
              
              	if(filter != null && filter != '' && filter != ' ' && filter != '0') 
				{
                 	filter = ',' + filter;
              	}
              	filter = getServices() + filter;
              	filter = filter.toUpperCase();
              	filter = filter.split(',');
              	showMarker = true;
              	for ( clause in filter ) 
				{
                  	disjunction = trimSpaces(filter[clause]);
                  	foundMatch  = (disjunction == null || disjunction == '');
                  	disjunction = disjunction.split('.');
                  	for( term in disjunction) 
					{
                     	searchTerm = trimSpaces(disjunction[term]);
                     	if (searchTerm != '' && info.match(searchTerm) != null) 
						{
                         	foundMatch = true;
                     	}
                  	}
                  	showMarker = showMarker && foundMatch;
              	}
          	}
			if (showMarker) 
			{
             	markerCount = markerCount + parseInt(count);
             	var marker = createMarker(point,label,html);
             	// create the marker
             	map.addOverlay(marker);
          	}
    	}
    }
    criaLocal();
    // shows "no results found!" message and/or the #shown of #total number
    var markerCountField = document.getElementById("markerCount");
    if(markerCountField) 
    { 
    	if(filtering) 
		{
	    	if (markerCount > 0) 
			{
				markerCountField.innerHTML = markerCount+" of";
			} 
			else 
			{
				markerCountField.innerHTML = "0 of";
			    document.getElementById("noResults").style.visibility="visible";
			}
	    } 
		else 
		{
			markerCountField.innerHTML = "";
		}
	}
	  
	if(!filtering && markerCount == 0 && tryagain) 
	{
	    tryagain = false;
	    readMap();
	}
	// put the assembled side_bar_html contents into the side_bar div
    //document.getElementById("side_bar").innerHTML = side_bar_html;
}

function createRequestObject() 
{
    var ro;
    var browser = navigator.appName;
    if(browser == "Microsoft Internet Explorer")
	{
		try 
		{
			ro = new ActiveXObject("MSXML2.XMLHTTP.3.0");
			//ro = null; // to free up memory
		} 
		catch(e) 
		{
			window.location='error.php';
		}
	}
	else
	{
        ro = new XMLHttpRequest();	
    }
    return ro;
}


var request = createRequestObject();

function readMap() 
{
	var url="http://www.autismconnects.com/map/28.xml";
	$("#markerinfo").load("/map/" + catid + ".html", "", HandleLoadedMarkers);
	request.open('GET', url);
    request.onreadystatechange = stateChanged;
    request.send(null);	
}

function loadmap() 
{
 window.onunload = GUnload;
 if (GBrowserIsCompatible()) 
 {
    map = new GMap2(document.getElementById("map"));
    map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl());
    criaLocal();

    // ====== set up marker mouseover tooltip div ======
    document.getElementById("map").appendChild(tooltip);
    tooltip.style.visibility="hidden";
 }
 else 
 {
  alert("Sorry, the Google Maps API is not compatible with this browser");
 }
}

function trimSpaces(sString) 
{
 while (sString.substring(0,1) == ' ') 
 {
     sString = sString.substring(1, sString.length);
 } 
 while (sString.substring(sString.length-1, sString.length) == ' ') 
 {
     sString = sString.substring(0,sString.length-1);
 }
 return sString;
}

function setFilter(turnOn) 
{
  if(!turnOn) 
  {
      document.getElementById("filterInput").value = "";
  }
  document.getElementById("noResults").style.visibility="hidden";
  if (catid != "") 
  {
      readMap();
  }
}

/* Functions for service provider filtering */
// create a checkbox for selecting a service
//
function generateService(serviceName) 
{
 return;
  if(document.getElementById(serviceName) == null) 
  {
      $("#serviceList").html('<li><input type="checkbox" id="'+serviceName
                            +'" onClick="setService(\''+serviceName+'\');"/>'
                            +serviceName+'</li>');
  }
}

function setService(serviceName) 
{
  selectedServices[serviceName] = document.getElementById(serviceName).checked;
  document.getElementById("noResults").style.visibility="hidden";
  if (catid != "") 
  {
      readMap();
  }
}

function RemoveAllFilters() 
{
  $("input[@name='ServiceFilters[]']").each(function() {
      this.checked = false;
  });
  PutMarkersOnMap();
  ReadMap;
  return;
  var catid = document.getElementById("categoryID").value;
  readMap();    
}


function setServiceFilter(ShowAll) 
{
  $("#AllFiltersCheck").checked = false;
  var catid = document.getElementById("categoryID").value;
  PutMarkersOnMap();
  readMap();       
  return;
}
// takes an array of true/false with services as keys and returns
// a list of services that were set to true
//
function getServices() 
{
  var Filters = new Array();

  $("input[@name='ServiceFilters[]']").each(function() {
      if ($(this).attr('checked')) 
	  {
          Filters.push($(this).val());
      }
  });

  return Filters.join(".");
}
                /* End functions for service provider filtering */
function printMapData() 
{
  var services = getServices();
  var SearchTerms   = trimSpaces(document.getElementById("filterInput").value);
  var serviceParam = "";
  var filterParam  = "";
 // var serviceToShowParam="";
  if (services != "") 
  {
      serviceParam = "services/"+services+"/";
  }
  if (SearchTerms != "") 
  {
      filterParam = "filter/"+SearchTerms+"/";
  }
  /*if (serviceToShow != "") {
    serviceToShowParam = "serviceToShow/"+serviceToShow+"/";
  }*/
  openWindow("/usermap/action/print/catid/" + catid + "/"+ serviceParam + filterParam,500,800);
}