// JavaScript Document

function cm_load() {  
  if (GBrowserIsCompatible()) 
  {
    // create the map
    map = new GMap2(document.getElementById("divMap"));
	map.enableScrollWheelZoom();
	geocoder = new GClientGeocoder();

    map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl());
	showCountry(0, "Canada");

	// Create a base icon for all of our markers that specifies the
	// shadow, icon dimensions, etc.

		
	baseIcon = new GIcon();
	baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
	baseIcon.iconSize = new GSize(20, 34);
	baseIcon.shadowSize = new GSize(37, 34);
	baseIcon.iconAnchor = new GPoint(9, 34);
	baseIcon.infoWindowAnchor = new GPoint(9, 2);
	baseIcon.infoShadowAnchor = new GPoint(18, 25);

    cm_getJSON();
		
  } 
  else 
  {
	alert("Sorry, the Google Maps API is not compatible with this browser");
  } 
}

function cm_getJSON() {

  // Retrieve the JSON feed.
  var script = document.createElement('script');

  //script.setAttribute('src', 'http://spreadsheets.google.com/feeds/list/twSxagtYRqTPnRYOaQJw09w/od6/public/values?alt=json-in-script&callback=cm_getSpreadsheet');
  //script.setAttribute('src', 'https://spreadsheets.google.com/ccc?key=0Au7XQ7rTrI1gdEh1d3ozdnl6RHdNa2xtdE1ad04xMUE&hl=en#gid=0?alt=json-in-script&callback=cm_getSpreadsheet');
  //script.setAttribute('src', 'http://spreadsheets.google.com/feeds/list/twSxagtYRqTPnRYOaQJw09w/od6/public/values?alt=json-in-script&callback=cm_getSpreadsheet');
  //script.setAttribute('src', 'http://spreadsheets.google.com/feeds/list/0Au7XQ7rTrI1gdEh1d3ozdnl6RHdNa2xtdE1ad04xMUE/od6/public/values?alt=json-in-script&callback=cm_getSpreadsheet');
  script.setAttribute('src', 'https://spreadsheets.google.com/feeds/list/0AteNatrmMyWQdE8zcXlEbW96Y3NXVFVKUnpoRktKTGc/od6/public/values?alt=json-in-script&callback=cm_getSpreadsheet');


  script.setAttribute('id', 'jsonScript');

  script.setAttribute('type', 'text/javascript');

  document.getElementById("divBar").appendChild(script);
  
}

function cm_getSpreadsheet(json)
{
	var entry, country, province, city, name, address;
	var i, j, k, counter = 0;
	var point, marker;
	
	// Get raw data from the feed
	
	for (i = 0; i < json.feed.entry.length; i++) 
 	{
    	entry = json.feed.entry[i];
		
		country = entry["gsx$country"].$t.replace("'", "`");
		province = entry["gsx$province"].$t.replace("'", "`");
		city = entry["gsx$city"].$t.replace("'", "`");
		
		rawData.push(new Array(counter, country, province, city, entry["gsx$brokercompany"].$t.replace("'", "`"), 
			entry["gsx$brokername"].$t.replace("'", "`"), entry["gsx$address"].$t.replace("'", "`"), entry["gsx$email"].$t.replace("'", "`") ));
			
		counter++;
			
		countries.push(new Array(0, country));
		provinces.push(new Array(0, country, province));
		cities.push(new Array(0, country, province, city, 0));
			
	}
	
	rawData.sortEx(4);
	
	// Filter raw data to get unique lists of countries, provinces, and cities
	
	countries = countries.unique();
	provinces = provinces.uniqueProvince();
	cities = cities.uniqueCity();
	
	// Sort lists
	
	countries.sortEx(1);
	provinces.sortEx(2);
	cities.sortEx(3);
	
	// Calculate number of mortgage brokers in each city
	
	for (i = 0; i < rawData.length; i++)
	{
		country = rawData[i][1];
		province = rawData[i][2];
		city = rawData[i][3];
		
		for (j = 0; j < cities.length; j++)
		{
			if ((cities[j][1] == rawData[i][1]) && (cities[j][2] == rawData[i][2]) && (cities[j][3] == rawData[i][3]))
			{
				cities[j][4]++;
			}
		}
	}
				
		
	mainTree = new dTree('mainTree');
	
	counter = 0;
	var t = "";
	
	for (i = 0; i < countries.length; i++)
	{
		t += "mainTree.add( " + counter + ", -1, "+ countries[i][1] + ");\n";
		
		mainTree.add(counter, -1, countries[i][1].toUpperCase(), "javascript:showCountry(" + counter.toString() + ", '" + countries[i][1] + "')");
		countries[i][0] = counter;
		
		var currentProvinceCounter = counter;
		counter++;
		
		for (j = 0; j < provinces.length; j++)
		{
			if (provinces[j][1] == countries[i][1])
			{

				t += "mainTree.add( " + counter + ", " + currentProvinceCounter + " , " + provinces[j][2] + ");\n";

				mainTree.add(counter, currentProvinceCounter, provinces[j][2].toUpperCase(), "javascript:showProvince(" + counter.toString() + ", '" + countries[i][1] + "', '" + provinces[j][2] + "')");
				provinces[j][0] = counter;
				
				var currentCityCounter = counter;
				counter++;
				
				for (k = 0; k < cities.length; k++)
				{
					if ((cities[k][2] == provinces[j][2]) && (cities[k][1] == countries[i][1]))
					{
						t += "mainTree.add(" + counter + " ," +  currentCityCounter + ", " + cities[k][3] + ");\n";
						mainTree.add(counter, currentCityCounter, cities[k][3] + " (" + cities[k][4] + ")", "javascript:showCity(" + counter.toString() + ", '" + provinces[j][2] + "', '" + cities[k][3] + "', " + cities[k][4].toString()+ ")");
						cities[k][0] = counter;
						counter++;
					}
					
				}
			}
		}
		
	}
	
	//alert(t);
	
	
	document.getElementById("divList").innerHTML = mainTree;	
	//document.getElementById("divList").innerHTML = cities.valueOf();
	
	
	//alert(document.getElementById("divBar").innerHTML);
	

	// Add map markers for each province where there is at least one broker
	
	pMarkerOpts = {};
	
	pIcon = new GIcon(pBaseIcon);
	
    pIcon.imageOut = "http://gmaps-samples.googlecode.com/svn/trunk/markers/green/blank.png";
    pIcon.imageOver = "http://gmaps-samples.googlecode.com/svn/trunk/markers/blue/blank.png";
    pIcon.image = pIcon.imageOut; 	
	
	feedLoaded = true;
	
	provinceMarkerCounter = 0;	
	
	setTimeout("setProvinceMarkers()", 100);	
	

}

function setProvinceMarkers()
{
	
	if (provinceMarkerCounter < provinces.length)
	{
		setProvinceMarker(provinces[provinceMarkerCounter][0], provinces[provinceMarkerCounter][1], provinces[provinceMarkerCounter][2]);
		provinceMarkerCounter++;
		
		if (provinceMarkerCounter < provinces.length)
		{
			setTimeout("setProvinceMarkers()", 100);
		}
	}
	
}


function setCityMarkers(province_name)
{
	if (cities[cityMarkerCounter][2] == province_name)
	{
		if (cityMarkerCounter < cities.length)
		{
			setCityMarker(cities[cityMarkerCounter][0], cities[cityMarkerCounter][2], cities[cityMarkerCounter][3], cities[cityMarkerCounter][4]);
			cityMarkerCounter++;		
			
			if (cityMarkerCounter < cities.length)
			{
				setTimeout("setCityMarkers(\"" + province_name + "\")", 100);
			}
		}
	
	}
	else
	{
		cityMarkerCounter++;		
		if (cityMarkerCounter < cities.length)
		{
			setTimeout("setCityMarkers(\"" + province_name + "\")", 10);
		}
	}
}

function setBrokerMarkers(province_name, city_name)
{

	if ((rawData[brokerMarkerCounter][2] == province_name) && (rawData[brokerMarkerCounter][3] == city_name))
	{
		//setBrokerMarker(rawData[brokerMarkerCounter][2], rawData[brokerMarkerCounter][3], rawData[brokerMarkerCounter][4], rawData[brokerMarkerCounter][5]);
		if (brokerMarkerCounter < rawData.length)
		{
			setBrokerMarker(rawData[brokerMarkerCounter][0]);
			brokerMarkerCounter++;		
			if (brokerMarkerCounter < rawData.length)
			{			
				setTimeout("setBrokerMarkers(\"" + province_name + "\", \"" + city_name +"\")", 100);
			}
		}
	
	}
	else
	{
		brokerMarkerCounter++;		
		if (brokerMarkerCounter < rawData.length)
		{
			setTimeout("setBrokerMarkers(\"" + province_name + "\", \"" + city_name +"\")", 10);
		}
	}
}


function showCountry(node_id, country_name)
{
	geocoder.getLatLng(country_name,
          function(point) {
            if (!point) 
			{
              //alert(country_name + " not found");
			  return -1;
            } 
			else 
			{
              map.setCenter(point, 3);
			  
			  if (feedLoaded)
			  {
				  clearMarkers();
				  provinceMarkerCounter = 0;	
			
			      mainTree.openTo(node_id);
				  setTimeout("setProvinceMarkers()", 100);			  
			  }
            }
          }
	);
}

function showProvince(node_id, country_name, province_name)
{
	geocoder.getLatLng("province " + province_name + ", " + country_name,
          function(point) {
            if (!point) 
			{
              //alert(province_name + " not found");
			  return -1;
            } 
			else 
			{
			  clearMarkers();
              map.setCenter(point, 6);
			  
			  mainTree.openTo(node_id);
			  cityMarkerCounter = 0;	
			  setTimeout("setCityMarkers(\"" + province_name + "\")", 100);
            }
          }
	);	
}

function showCity(node_id, province_name, city_name, brokers_no)
{

	geocoder.getLatLng(city_name + ", province " + province_name,
          function(point) {
            if (!point) 
			{
              // alert(city_name + " not found");
			  return -1;
            } 
			else 
			{

				clearMarkers();
                map.setCenter(point, 12);		
				
				brokerMarkerCounter = 0;	

				setTimeout("setBrokerMarkers(\"" + province_name + "\", \"" + city_name + "\")", 100);
			
			    // Show list of brokers for current city
				
				var title = "<div><span><b>" + city_name + ", " + province_name + "</b><span></div>";
				title += "<div><span>" + brokers_no.toString() + " brokers total</span></div>";
				
				document.getElementById("divCityTitle").innerHTML = title;
				
				var list = "";
				
				for (var i = 0; i < rawData.length; i++)
				{
				  if ((rawData[i][2] == province_name) && (rawData[i][3] == city_name))
				  {
					  list += "<div class=\"brokerName\"><span onclick=\"showBroker(" + rawData[i][0] + ")\">" + rawData[i][4] + "</span></div>";
					  list += "<div class=\"brokerAddress\"><span>" + rawData[i][6] + "</span></div>";				  
				  }					
				}
				
				document.getElementById("divBrokersList").innerHTML = list;
				
				document.getElementsByName("radioSearch")[1].checked = "checked";
				
				
				switchLists();
            }
          }
	);	
}

function clearMarkers()
{
  for (var i = 0; i < pMarkers.length; i++)
  {
	  map.removeOverlay(pMarkers[i]);
  }	
  for (var i = 0; i < cMarkers.length; i++)
  {
	  map.removeOverlay(cMarkers[i]);
  }			  
  for (var i = 0; i < bMarkers.length; i++)
  {
	  map.removeOverlay(bMarkers[i]);
  }
  pMarkers = new Array();
  cMarkers = new Array();
  bMarkers = new Array(); 
}

function setProvinceMarker(node_id, country_name, province_name)
{
	geocoder.getLatLng("province " + province_name + " , " + country_name,
          function(point) {
            if (!point) 
			{
			  //alert(province_name + " not found in setProvinceMarker(): " + province_name + " , " + country);
              return -1;
            } 
			else 
			{
			  pMarkerOpts.title = province_name;	
			  var marker = new GMarker(point, pMarkerOpts);
			  
			  GEvent.addListener(marker, "click", function() {
				showProvince(node_id, country_name, province_name);
			  });
			  /*GEvent.addListener(marker, "mouseover", function() {
				marker.openInfoWindowHtml("<b>" + province_name + ", " + country_name +"</b>");
			  });
			  GEvent.addListener(marker, "mouseout", function() {
				marker.closeInfoWindow();
			  });*/
	
				  pMarkers.push(marker);
				map.addOverlay(marker);			  

            }
          }
	);		
}


function setCityMarker(node_id, province_name, city_name, brokers_no)
{
	geocoder.getLatLng(city_name + ", " + province_name,
          function(point) {
            if (!point) 
			{
			   //alert(city_name + "not found");
               return -1;
            } 
			else 
			{	
			  pMarkerOpts = {};
			  var marker = new GMarker(point, pMarkerOpts);
			  
			  GEvent.addListener(marker, "click", function() {
				showCity(node_id, province_name, city_name, brokers_no);
			  });
			  GEvent.addListener(marker, "mouseover", function() {
				marker.openInfoWindowHtml("<b>" + city_name + ", " + province_name + "<br><br>" + brokers_no.toString() + " mortgage brokers</b>");
			  });
			  GEvent.addListener(marker, "mouseout", function() {
				marker.closeInfoWindow();
			  });
			  
			  cMarkers.push(marker);
			  map.addOverlay(marker);

            }
          }
	);		
}

//function setBrokerMarker(province_name, city_name, name, address)
function setBrokerMarker(node_id)
{
	var brokerData = getBrokerData(node_id);
	
	if (brokerData == null)
	{
		//alert("Broker ID " + node_id.toString() + " not found");
        return -1;
	}
	province_name = brokerData[2];
	city_name = brokerData[3];
	broker_co = brokerData[4];
	broker_name = brokerData[5];
	address = brokerData[6];	
	email = brokerData[7];
	

	
	geocoder.getLatLng(address + " " + city_name + ", " + province_name,
          function(point) {
            if (!point) 
			{
				//alert(name + " " + address + " not found");
                return -1;
            } 
			else 
			{
			  pMarkerOpts = {};
			  var marker = new GMarker(point, pMarkerOpts);
			  
			  var brokerHTML = "<b>" + broker_co + "</b><br><b>" + broker_name + "</b><br><br>" + address + "<br>";
			  brokerHTML += city_name + ", " + province_name + "<br><br>";
			  brokerHTML += "<span class=\"spanAsLink\" onclick=\"contactBroker(" + node_id.toString() + ")\">Contact this broker</span>";
			  
			  GEvent.addListener(marker, "click", function() {
//				marker.openInfoWindowHtml("<b>" + name + "</b><br><br>" + address + "<br>" + city_name + ", " + province_name);
				marker.openInfoWindowHtml(brokerHTML);
			  });			  
			  GEvent.addListener(marker, "mouseover", function() {
//				marker.openInfoWindowHtml("<b>" + name + "</b><br><br>" + address + "<br>" + city_name + ", " + province_name);
				marker.openInfoWindowHtml(brokerHTML);
			  });
/*			  GEvent.addListener(marker, "mouseout", function() {
				marker.closeInfoWindow();
			  });*/
			  
			  bMarkers.push(marker);
			  map.addOverlay(marker);

            }
          }
	);		

}

function getBrokerInfo(id)
{
	var i = 0;
	var data = null;
	
	while ((i < rawData.length) && (data == null))
	{
		if (rawData[i][0] != id)
		{
			i++;
		}
		else
		{
			data = rawData[i][6] + " " + rawData[i][3] + ", " + rawData[i][2];
		}
	}
	
	return data;
}

function getBrokerData(id)
{
	var i = 0;
	var data = null;
	
	while ((i < rawData.length) && (data == null))
	{
		if (rawData[i][0] != id)
		{
			i++;
		}
		else
		{
			data = rawData[i];
		}
	}
	
	return data;
}

function showBroker(id)
{
	var address = getBrokerInfo(id);
	
	if (address != null)
	{

	  geocoder.getLatLng(address,
			function(point) {
			  if (!point) 
			  {
				  //alert(name + " " + address + " not found");
				  return -1;
			  } 
			  else
			  {
				  map.setCenter(point, 15);
			  }
			}
		   );
	}
}

function findBrokersQty(c_node_id)
{
	var i = 0;
	var qty = -1;
	
	while ((i < cities.length) && (qty == -1))
	{
		if (cities[i][0] != c_node_id)
		{
			i++;
		}
		else
		{
			qty = cities[i][4];
		}
	}
	
	return qty;	
}

function findCountryNode(country_name)
{
	var i = 0;
	var node = -1;
	
	while ((i < countries.length) && (node == -1))
	{
		if (countries[i][1] != country_name)
		{
			i++;
		}
		else
		{
			node = countries[i][0];
		}
	}
	
	return node;
}

function findProvinceNode(country_name, province_name)
{
	var i = 0;
	var node = -1;
	
	while ((i < provinces.length) && (node == -1))
	{
		if ((provinces[i][1] != country_name) || (provinces[i][2] != province_name))
		{
			i++;
		}
		else
		{
			node = provinces[i][0];
		}
	}
	
	return node;
}

function findCityNode(country_name, province_name, city_name)
{
	var i = 0;
	var node = -1;
	
	while ((i < cities.length) && (node == -1))
	{
		if ((cities[i][1] != country_name) || (cities[i][2] != province_name) || (cities[i][3] != city_name))
		{
			i++;
		}
		else
		{
			node = cities[i][0];
		}
	}
	
	return node;
}

function findCountryByProvince(province_name)
{
	var i = 0;
	var data = null;
	
	while ((i < provinces.length) && (data == null))
	{
		if (provinces[i][2] != province_name)
		{
			i++;
		}
		else
		{
			data = provinces[i][1];
		}
	}
	
	return data;
}

