// Census Display JavaScript

	var map_CV;
	var s;
	var pageState = -1;
	var rezoomHandler;
	
	// required for subzone overlays
	var xml;
	var mm;
	
	//required for marker overlays
	var markers = [];
	var subzones;
	var subid = [];
	var zoneCenter = [];
	var popBiggest = 137152; // used for scaling of proportional dots
	
	if (document.images)
	{
	  smDot= new Image(); 
	  smDot.src="images/dot.png";
	}
	
	function closeHelp() {
		document.getElementById('help').style.display = 'none';
		helpSwitch = 0;
	}
	
	var helpSwitch = 1;
	
	function toggleHelp() {
		if (helpSwitch==0) document.getElementById('help').style.display = 'block';
		else document.getElementById('help').style.display = 'none';
		helpSwitch = 1 - helpSwitch;
	}
	
	function openPanel() {
		document.getElementById('panel').style.display = "block";
	}
	
	function closePanel() {
		document.getElementById('panel').style.display = "none";
	}
	
	function flashDiv(divId, originalBG, state, duration, times) {
		if (state==1) {
			document.getElementById(divId).style.backgroundColor = '#FE6505';
		}
		else {
			document.getElementById(divId).style.backgroundColor = originalBG;
		}
		if (times>0) setTimeout("flashDiv('"+divId+"','"+originalBG+"',"+(1-state)+","+duration+","+(times-1)+");", duration);
	}
		
	function loadOptions(option) {
		pageState = option;
		if (pageState==0) { // age
			var options_age = "Distribution of Population <select id=\"optionsList\" onchange=\"loadDots()\" class=\"cv\">";
			options_age += "<option value=\"0\">below 19 years old</option>";
			options_age += "<option value=\"1\">between 20 - 29 years old</option>";
			options_age += "<option value=\"2\">between 30 - 39 years old</option>";
			options_age += "<option value=\"3\">between 40 - 49 years old</option>";
			options_age += "<option value=\"4\">above 50 years old</option>";
			options_age += "</select> in Singapore (2000)";
			document.getElementById('dotMapTitle').innerHTML = options_age;
		}
		else if (pageState==1) { // gender
			var options_gender = "Distribution of <select id=\"optionsList\" onchange=\"loadDots()\" class=\"cv\">";
			options_gender += "<option value=\"0\">Male</option>";
			options_gender += "<option value=\"1\">Female</option>";
			options_gender += "</select> Population in Singapore (2000)";
			document.getElementById('dotMapTitle').innerHTML = options_gender;
		}
		else if (pageState==2) { // race
			var options_race = "Distribution of <select id=\"optionsList\" onchange=\"loadDots()\" class=\"cv\">";
			options_race += "<option value=\"0\">Chinese</option>";
			options_race += "<option value=\"1\">Malay</option>";
			options_race += "<option value=\"2\">Indian</option>";
			options_race += "<option value=\"3\">non-CMI</option>";
			options_race += "</select> Population in Singapore (2000)";
			document.getElementById('dotMapTitle').innerHTML = options_race;
		}
		else if (pageState==3) { // housing
			var options_housing = "Distribution of Population staying in <select id=\"optionsList\" onchange=\"loadDots()\" class=\"cv\">";
			options_housing += "<option value=\"0\">3 rooms & below</option>";
			options_housing += "<option value=\"1\">4 - 5 rooms</option>";
			options_housing += "<option value=\"2\">Condominium</option>";
			options_housing += "<option value=\"3\">Landed Property</option>";
			options_housing += "</select> in Singapore (2000)";
			document.getElementById('dotMapTitle').innerHTML = options_housing;
		}
		loadDots();
		flashDiv('dotMapTitle', '#666666', 0, 4000, 2);
	}
	
	function loadDots() {
		var dbArr = [["age_below19", "age_2029", "age_3039", "age_4049", "age_above50"],
						["gender_m", "gender_f"],
						["race_c", "race_m", "race_i", "race_o"],
						["housing_below3", "housing_45", "housing_condo", "housing_landed"]];
		/*var valMax = [[44874, 17401, 27225, 25754, 21898],
						[68127, 69025],
						[93158, 32931, 8530, 2533],
						[43881, 105737, 8651, 21424]];*/
		var valMax = [[44874, 44874, 44874, 44874, 44874],
						[69025, 69025],

						[93158, 93158, 93158, 93158],
						[105737, 105737, 105737, 105737]];
		clearDots();
		for (var i = 0; i < subzones.length; i++) {
			var valSZ;
			var ratio;
			if (pageState==-1) {
				valSZ = parseInt(subzones[i].getAttribute("gender_m")) + parseInt(subzones[i].getAttribute("gender_f"));
				ratio = valSZ/(1.0*popBiggest);
			}
			else {
				valSZ = parseInt(subzones[i].getAttribute(dbArr[pageState][document.getElementById('optionsList').value]));
				ratio = valSZ/(1.0*valMax[pageState][document.getElementById('optionsList').value]);
			}
			var mark = createDot(zoneCenter[i], subid[i], ratio, i);
			markers.push(mark);
		}
		mm.addMarkers(markers, 11); //markers will only display at zoom >= 11
		mm.refresh();
	}
	
	function clearDots() {
		if (markers.length>0) {
			for (var i=0; i<markers.length; i++) {
				map_CV.removeOverlay(markers[i]);
			}
			mm.clearMarkers();
			markers = [];
		}
	}
	
	//This function will create a proportional dot where each marker will be clickable for census information
	function createDot(point, ID, ratio, index) {
		var zoomVar = map_CV.getZoom();
		var fullDot = 120;
		var scaleFactor = Math.tan(0.35*(zoomVar/20.))*(zoomVar-10);
		var dotSize = (scaleFactor*fullDot)*Math.pow(ratio,.57);
		var dottie = new GIcon();
		dottie.image = "http://www.gis.nus.edu.sg/images/dot.png";
		//dottie.image = "http://econym.googlepages.com/coldmarker.png";
		dottie.iconSize = new GSize(dotSize, dotSize);
		dottie.iconAnchor = new GPoint(dotSize/2, dotSize/2);
		var marker = new GMarker(point, dottie);
		GEvent.addListener(marker, 'click', function() {
			s.loadDemoPanel(''+ID, function(response) { 
			
					var xml = GXml.parse(response.result);
					
					//get each subzone
					var sz = xml.documentElement.getElementsByTagName("subzone");
					//get point data from each subzone
					var markers = [];
											 
					 var subzoneName = sz[0].getAttribute("name");

					 // commence data extraction and calculations for table
					
					 //Demographic Data - Age
					var age19 = parseFloat(sz[0].getAttribute("age_below19"));
					var age29 = parseFloat(sz[0].getAttribute("age_2029"));
					var age39 = parseFloat(sz[0].getAttribute("age_3039"));
					var age49 = parseFloat(sz[0].getAttribute("age_4049"));
					var age50 = parseFloat(sz[0].getAttribute("age_above50"));
					var grp_11 = parseFloat(sz[0].getAttribute("grp_11"));
					
					//Demographic Data - Race and Gender
					var male1 = parseFloat(sz[0].getAttribute("gender_m"));
					var female1 = parseFloat(sz[0].getAttribute("gender_f"));
					var c = parseFloat(sz[0].getAttribute("race_c"));
					var m = parseFloat(sz[0].getAttribute("race_m"));
					var ind = parseFloat(sz[0].getAttribute("race_i"));
					var o = parseFloat(sz[0].getAttribute("race_o"));
					
					//Demographic Data - Housing
					var rm3_1 = parseFloat(sz[0].getAttribute("housing_below3"));
					var rm5_1 = parseFloat(sz[0].getAttribute("housing_45"));
					var condo1 = parseFloat(sz[0].getAttribute("housing_condo"));
					var landed1 = parseFloat(sz[0].getAttribute("housing_landed"));
					
					var maxBar = 128;
					
					document.getElementById('demo_title').innerHTML = subzoneName + " DATA (2000)";
					
					document.getElementById('race_c_n').innerHTML = c;
					document.getElementById('race_c_b1').style.width = c/(c+m+ind+o)*maxBar + 'px';
					
					document.getElementById('race_m_n').innerHTML = m;
					document.getElementById('race_m_b1').style.width = m/(c+m+ind+o)*maxBar + 'px';
					
					document.getElementById('race_i_n').innerHTML = ind;
					document.getElementById('race_i_b1').style.width = ind/(c+m+ind+o)*maxBar + 'px';
					
					document.getElementById('race_o_n').innerHTML = o;
					document.getElementById('race_o_b1').style.width = o/(c+m+ind+o)*maxBar + 'px';
					
					document.getElementById('gender_m_n').innerHTML = male1;
					document.getElementById('gender_m_b1').style.width = male1/(male1+female1)*maxBar + 'px';
					
					document.getElementById('gender_f_n').innerHTML = female1;
					document.getElementById('gender_f_b1').style.width = female1/(male1+female1)*maxBar + 'px';
					
					document.getElementById('age_below19_n').innerHTML = age19;
					document.getElementById('age_below19_b1').style.width = age19/(age19+age29+age39+age49+age50)*maxBar + 'px';
					
					document.getElementById('age_2029_n').innerHTML = age29;
					document.getElementById('age_2029_b1').style.width = age29/(age19+age29+age39+age49+age50)*maxBar + 'px';
					
					document.getElementById('age_3039_n').innerHTML = age39;
					document.getElementById('age_3039_b1').style.width = age39/(age19+age29+age39+age49+age50)*maxBar + 'px';
					
					document.getElementById('age_4049_n').innerHTML = age49;
					document.getElementById('age_4049_b1').style.width = age49/(age19+age29+age39+age49+age50)*maxBar + 'px';
					
					document.getElementById('age_above50_n').innerHTML = age50;
					document.getElementById('age_above50_b1').style.width = age50/(age19+age29+age39+age49+age50)*maxBar + 'px';
					
					document.getElementById('housing_below3_n').innerHTML = rm3_1;
					document.getElementById('housing_below3_b1').style.width = rm3_1/(rm3_1+rm5_1+condo1+landed1)*maxBar + 'px';
					
					document.getElementById('housing_45_n').innerHTML = rm5_1;
					document.getElementById('housing_45_b1').style.width = rm5_1/(rm3_1+rm5_1+condo1+landed1)*maxBar + 'px';
					
					document.getElementById('housing_condo_n').innerHTML = condo1;
					document.getElementById('housing_condo_b1').style.width = condo1/(rm3_1+rm5_1+condo1+landed1)*maxBar + 'px';
					
					document.getElementById('housing_landed_n').innerHTML = landed1;
					document.getElementById('housing_landed_b1').style.width = landed1/(rm3_1+rm5_1+condo1+landed1)*maxBar + 'px';
			
			}); // loadDemoPanel
			openPanel();
			
		}); // addLisntener
		
		return marker;
		
	}
	
	function initHandlers() {
	
		document.getElementById("instructions").onclick = toggleHelp;
		document.getElementById("instructions").onmouseover = function() {
			document.getElementById('instructions').style.backgroundColor ='#FF6600';
			document.getElementById('instructions').style.color ='#000000';
		}
		document.getElementById("instructions").onmouseup = function() {
			document.getElementById('instructions').style.color ='#000000';
		}
		document.getElementById("instructions").onmouseout = function() {
			document.getElementById('instructions').style.backgroundColor ='#DDDDDD';
			document.getElementById('instructions').style.color ='#000000';
		}
		document.getElementById("instructions").onmousedown = function() {
			document.getElementById('instructions').style.color ='#FFFFFF';
		}
		document.getElementById("help").onclick = closeHelp;
		document.getElementById("sz_close").onmouseup = closePanel;
		document.getElementById("sz_close").onmouseover = function() {
			document.getElementById('sz_close').style.backgroundColor='white';
		}
		document.getElementById("sz_close").onmousedown = function() {
			document.getElementById('sz_close').style.backgroundColor='#EEEEEE';
		}
		document.getElementById("sz_close").onmouseout = function() {
			document.getElementById('sz_close').style.backgroundColor='#CCCCCC';
		}
	
	}

    function load() {
	  
      if (GBrowserIsCompatible()) {
        
		s = new CensusDisplay();
		
		document.getElementById("map").style.height = ''+(document.body.clientHeight-130-51)+'px';
		window.onresize = function () {
			document.getElementById("map").style.height = ''+(document.body.clientHeight-130-51)+'px';
		}
				
        map_CV = new GMap2(document.getElementById("map"));
        map_CV.setCenter(new GLatLng(1.3518795527836271, 103.81942749023438), 11);  //Initialise map and set zoom to 14.
		map_CV.setMapType(G_NORMAL_MAP);
		//map_CV.setMapType(G_SATELLITE_MAP);
		//map_CV.setMapType(G_HYBRID_MAP);
		map_CV.addControl(new GLargeMapControl()); //Add in the map control
		//map_CV.addControl(new GMapTypeControl()); //Add in the Map Type Trigger
		map_CV.enableContinuousZoom();
		map_CV.enableScrollWheelZoom();
		
		GDownloadUrl("xml/points.XML", function(data, responseCode) {
         
          xml = GXml.parse(data);
		  mm = new MarkerManager(map_CV);
		  
          //get each subzone
          subzones = xml.documentElement.getElementsByTagName("subzone");
          for (var i = 0; i < subzones.length; i++) 
          {
            //get point data from each subzone
            var points = subzones[i].getElementsByTagName("point");
            var poly = [];
            var bounds = new GLatLngBounds();
            
            //we need to order the array so that the polygon will form properly
            //insert 1st point into array
            for (var j = 0; j < points.length; j++) 
            {
                var point = new GLatLng(parseFloat(points[j].getAttribute("lat")),
                                            parseFloat(points[j].getAttribute("lng")));
                bounds.extend(point);
                poly.push(point);
             }//for
            
             var line = new GPolygon(poly,'#FFFFFF', 2, 1,'#0000FF',0.2);
             map_CV.addOverlay(line);
             
             zoneCenter[i] = new GLatLng(
                (bounds.getSouthWest().lat() + bounds.getNorthEast().lat()) / 2.,
                (bounds.getSouthWest().lng() + bounds.getNorthEast().lng()) / 2.
             );
             
             subid[i] = subzones[i].getAttribute("subzoneid");
			 var popSZ = parseInt(subzones[i].getAttribute("gender_m")) + parseInt(subzones[i].getAttribute("gender_f"));
			 var ratio = popSZ/(1.0*popBiggest);
			 var mark = createDot(zoneCenter[i], subid[i], ratio);
             markers.push(mark);
          }
		  	mm.addMarkers(markers, 11); //markers will only display at zoom >= 11
			mm.refresh();
			GEvent.addListener(map_CV, "zoomend", function(oldzoom,zoom) { 		
				loadDots(); 
			});
        });
        
      }
	  initHandlers();
	  setTimeout("doremi(4,4);",8000);
    }//end of function
	
	function doremi(total, sequence) {
		flashDiv('navi'+(total-sequence+1), '#000000', 0, 500, 2);
		if (sequence>1) setTimeout("doremi("+total+","+(sequence-1)+");",500);
	}
