﻿var bCheckOrigin = false; //when the checkbox is checked, it first changes its checked status, then my flipflag function is called, which flips it back.
var Filter = { "COUNTRY": "-1", "PROFILECOLLECTION": "-1"};
var arLatLng=[];
var z=0;
var sMatch='';
var markers = {};
//need to keep track of when the check originates from a checkbox and when from the row, so it only checks/unchecks once  GD 


function initLoad() {
    Filter = { "PROFILECOLLECTION": "-1", "COUNTRY": "-1" };
    reloadSelects();
    loadMap();
    
}
function reloadSelects() {
    loadSelect("ProfileCollection", "selProfileCollection", Filter.PROFILECOLLECTION,profilesJSON.profilecollections);
    loadSelect("Country", "selCountries", Filter.COUNTRY,profilesJSON.items);
}

function loadSelect(whichCriteria, divToLoad, selectedValue, objIterate) {
    var sCountryList = '';
    document.getElementById(divToLoad).innerHTML = '';
    if (whichCriteria=='ProfileCollection'){
        var sInnerText = "<TR style='background-color:#ffcc66;'><td></td><TD></TD><TD align=center>Value</TD></TR>";
    } else {
        var sInnerText = "<TR style='background-color:#ffcc66;'><TD></TD><TD align=center>Value</TD></TR>";
    }
    var z = 0;
    var sFieldValue = "";

    for (var y = 0; y < objIterate.length; y++) {
            if(whichCriteria=='ProfileCollection'){
                sFieldValue = objIterate[y].label;
            }else{
            sFieldValue = objIterate[y].country;
            }
            if (sCountryList.indexOf(sFieldValue) == -1) {
                sCountryList += ',' + sFieldValue;
                // if ((whichCriteria == 'ProfileCollection' && objIterate[y].type == 'profilecollection') || (whichCriteria == 'Country' && profilesJSON.items[y].type != 'profilecollection')) {
                var sTest = "flipflag('" + divToLoad + z + "');";
                var iconColor;
                switch (sFieldValue) {
                    case 'Asia and the Near East Profiles':
                        iconColor = 'FFFF66';
                        break;
                    case 'Early Childhood Development Profiles':
                        iconColor = 'FFCC66';
                        break;
                    case 'EFA Fast Track Initiative Profiles':
                        iconColor = '66CC66';
                        break;
                    case 'Kenya District Primary Education Profiles':
                        iconColor = '33CCFF';
                        break;
                    case 'National Education Profiles':
                        iconColor = 'FFAAAA';
                        break;
                    case 'Nigeria Regional Basic Education Profiles':
                        iconColor = 'CC99FF';
                        break;
                }
                sInnerText += "<TR class='checklist' onclick=" + sTest + ">";
                if (whichCriteria=='ProfileCollection'){
                    sInnerText+="<TD valign=top><img alt='' src='http://chart.apis.google.com/chart?cht=mm&chs=16x16&chco=ffffff," + iconColor + ",000000&ext=.png'/></td>"

                }
                sInnerText += "<TD valign=top>";
                sInnerText += "<input type='checkbox' id='" + divToLoad + z + "' value='" + sFieldValue + "'";
                if (selectedValue.indexOf(sFieldValue) > -1) {
                    sInnerText += " checked=true";
                }
                sInnerText += " onclick='bCheckOrigin=true'></TD>";
                sInnerText += "<TD valign=top style='border-left:1px solid #ffcc66;width:95px'>" + sFieldValue + "</TD></TR>";
                z = z + 1;
                // }
            }
    }
    sInnerText = "<TABLE cellspacing='0' cellpadding='1'>" + sInnerText + "</TABLE>";
    document.getElementById(divToLoad).uBound = z;

    document.getElementById(divToLoad).innerHTML = sInnerText;

}
function flipflag(scheckBox) {
    if (bCheckOrigin == false) {
        if (document.getElementById(scheckBox).checked == true) {
            document.getElementById(scheckBox).checked = false;
            //sTR.background-color=black;  
        } else {
            document.getElementById(scheckBox).checked = true;
            //sTR.background-color=blue;
        }
    }
    bCheckOrigin = false;
    loadMap();
}

function loadMap() {
    var currentCriteria;
    gatherSelectedCriteria();
    var map = new GMap2(document.getElementById("map"));
    map.setCenter(new GLatLng(32.54, 13.1), 2);
    map.enableScrollWheelZoom();
    map.addControl(new GLargeMapControl3D());
    var iconColor;
    markers = {};

        for (var i = 0; i < profilesJSON.items.length; i++) {
            currentCriteria = profilesJSON.items[i];

            if (currentCriteria.type != 'profilecollection') {
                    switch(currentCriteria.profilecollection)
                    {
                    case 'Asia and the Near East Profiles':
                      iconColor='#FFFF66';
                      break;
                    case 'Early Childhood Development Profiles':
                      iconColor='#FFCC66';
                      break;
                    case 'EFA Fast Track Initiative Profiles':
                      iconColor='#66CC66';
                      break;
                    case 'Kenya District Primary Education Profiles':
                      iconColor='#33CCFF';
                      break;
                    case 'National Education Profiles':
                      iconColor='#FFAAAA';
                      break;
                    case 'Nigeria Regional Basic Education Profiles':
                      iconColor='#CC99FF';
                      break;
              }
                  if (meetsCriteria(Filter.PROFILECOLLECTION, currentCriteria.profilecollection) && meetsCriteria(Filter.COUNTRY, currentCriteria.country)) {
                      //fill out an array of the thumbs urls
                        var label = profilesJSON.items[i].label;
                        var sURL = profilesJSON.items[i].url;
                        var sPhysicalName = profilesJSON.items[i].physicalname;
                        var latlng = profilesJSON.items[i].latlng;
                        var profile = { latlng: latlng, url: sURL, label: label, iconColor:iconColor };
//                        var latlngHash = (latlng.lat().toFixed(6) + "" + latlng.lng().toFixed(6));
//                        latlngHash = latlngHash.replace(".","").replace(".", "").replace("-","");
                        if (markers[latlng] == null) {
                            markers[latlng] = []
                            z = z + 1;
                        }
                        markers[latlng].push(profile);
                  }
              }
          }
 
      for (var latlng in markers) {
          var profiles = markers[latlng];
          if (profiles.length > 1) {
              map.addOverlay(createClusteredMarker(profiles));
          } else {
              map.addOverlay(createMarker(profiles));
          }
      }

}
function createMarker(profiles) {
    var profile= profiles[0];
   var newIcon = MapIconMaker.createMarkerIcon({ width: 32, height: 32, primaryColor: profile.iconColor });
   var latlng = GLatLng.fromUrlValue(profile.latlng);
   var marker = new GMarker((latlng), newIcon);
   var html = "<div><a class='infoWindow' href='" + profile.url + "'>" + profile.label + "<br/></a></div><BR>";
   GEvent.addListener(marker, 'click', function() {
   marker.openInfoWindowHtml(html);
   });
   return marker;

}

function createClusteredMarker(profiles) {

//   var newIcon = MapIconMaker.createLabeledMarkerIcon({ width: 44, height: 44, label: "'" + profiles.length + "'", primaryColor: profiles[0].iconColor });
    var sNum = profiles.length;
   var newIcon = MapIconMaker.createLabeledMarkerIcon({ width: 44, height: 44, label: String(sNum), primaryColor: profiles[0].iconColor });
   var latlng = GLatLng.fromUrlValue(profiles[0].latlng);
   var marker = new GMarker(latlng,newIcon);
   var html = "<div><ul>";
   for (var i = 0; i < profiles.length; i++) {
       html += "<li><a class='infoWindow' href='" + profiles[i].url + "'>" + profiles[i].label + "<br/></a>";
   }
   html += "</ul></div><BR>";
   GEvent.addListener(marker, 'click', function() {
       marker.openInfoWindowHtml(html);
   });
   return marker;
}

function gatherSelectedCriteria() {
    Filter.COUNTRY = getDivCriteria("selCountries");
    Filter.PROFILECOLLECTION = getDivCriteria("selProfileCollection");
}
function getDivCriteria(selToGet) {
    var x = document.getElementById(selToGet).uBound;
    var selString = "";
    var chkBox="";
    for (y = 0; y < x; y++) {
        chkBox=selToGet + y;
        if (document.getElementById(chkBox).checked == true) {
            selString += document.getElementById(chkBox).value;
        }
    }
    if (selString==""){
        selString="-1";
    }
    return selString;
}

function meetsCriteria(sValueSelected, sJSONValue){
    var bRet=false;
    if ((sValueSelected.indexOf(sJSONValue)>-1||sValueSelected=="-1")) {
        bRet = true;
    } else {
        if (sValueSelected==null){
            //no value was selected for this criteria
            bRet=true;
        }
    }
    return bRet;
}


