// some per-project tweakable values 
var maxZoom = 5;
var baseURL = "http://www.scimaps.org/maps/nih/2007/";
var topicBrowserURL = "http://datalab-1.ics.uci.edu/nih/crisp/2007/getdoc.php?did=";
var queryScript = "query.php";
var searchScript = "search.php";
var currentMapDiv = "map";
var map2legend = {
    "NIH Institutes":"institutes-legend"    
};

var LABELS = ["topic-labels","topic-labels1","topic-labels2"];
var INSTITUTES= ["TW","AT","CA","MD","RR","EY","HG","HL","AG","AA","AI","AR", 
                 "EB","HD","DA","DC","DE","DK","ES","GM","MH","NS","NR","LM","OD"];

inst2names = {
    "CA":["NCI","National Cancer Institute"],
    "GM":["NIGMS","National Institute of General Medical Sciences"],
    "HL":["NHLBI","National Heart, Lung, and Blood Institute"],
    "AI":["NIAID","National Institute of Allergy and Infectious Diseases Extramural Activities"],
    "DK":["NIDDK","National Institute of Diabetes and Digestive and Kidney Diseases"],
    "NS":["NINDS","National Institute of Neurological Disorders and Stroke"],
    "MH":["NIMH","National Institute of Mental Health"],
    "HD":["NICHD","National Institute of Child Health and Human Development"],
    "DA":["NIDA","National Institute on Drug Abuse"],
    "AG":["NIA","National Institute on Aging"],
    "EY":["NEI","National Eye Institute "],
    "AR":["NIAMS","National Institute of Arthritis and Musculoskeletal and Skin Diseases"],
    "RR":["NCRR","National Center for Research Resources"],
    "DC":["NIDCD","National Institute on Deafness and other Communication Disorders"],
    "AA":["NIAAA","National Institute on Alcohol Abuse and Alcoholism"],
    "ES":["NIEHS","National Institute of Environmental Health Sciences"],
    "EB":["NIBIB","National Institute of Biomedical Imaging and Bioengineering"],
    "DE":["NIDCR","National Institute of Dental and Craniofacial Research"],
    "NR":["NINR","National Institute of Nursing Research"],
    "TW":["FIC","Fogarty International Center"],
    "AT":["NCCAM","National Center for Complementary and Alternative Medicine"],
    "HG":["NHGRI","National Human Genome Research Institute"],
    "LM":["NLM","National Library of Medicine"],
    "MD":["NCMHD","National Center on Minority Health and Health Disparities"],
    "OD":["OD","Office of the Director"]
};


var inst2overlay = {};
var currentOverlay = {};

var label2overlay = {};
var labelOverlay = null;

// global variables :-/
var proj, map, popoutWindow;

// Constants
var SELECTED = "button-selected";
var UNSELECTED = "button-unselected";

function search() {
    var txt = document.getElementById("searchbox").value;
    
    if ((""+txt).length > 0) {
        getMarkers(searchScript+"?resultsperpg=100&query="+txt,260,true);
    }
}

function toggleInst(me) {
    var inst = me.className.slice(-2);
    if (inst2overlay.hasOwnProperty(inst)) {
        changeInstitute(inst);
        if (currentOverlay.hasOwnProperty(inst) && currentOverlay[inst] != null) {
            me.style.border="2px solid black";
        } else {
            me.style.border="0px solid black";
        }
    }
}

function changeInstitute(inst) {
    if (currentOverlay.hasOwnProperty(inst) && currentOverlay[inst] != null) {
        map.removeOverlay(currentOverlay[inst]);
        currentOverlay[inst] = null;
    } else if (inst2overlay.hasOwnProperty(inst)) {
        currentOverlay[inst] = inst2overlay[inst];
        map.addOverlay(currentOverlay[inst]);
    }
}

function toggleLabel(me) {
    if (labelOverlay == null) {
        labelOverlay = label2overlay['topic-labels2'];
        map.addOverlay(labelOverlay);
        me.innerHTML = "On";
    } else {
        map.removeOverlay(labelOverlay);
        labelOverlay = null;
        me.innerHTML = "Off";
    }
}

function toggleLabels(me) {
    if (labelOverlay != null) {
        map.removeOverlay(labelOverlay);
        labelOverlay = null;
    }
    
    if (label2overlay.hasOwnProperty(me.value)) {
        map.addOverlay(label2overlay[me.value]);
        labelOverlay = label2overlay[me.value];
    }
}

function createTileOverlay(tileDir,zIndex) {
    var copyright = new GCopyright(1,
                    new GLatLngBounds(new GLatLng(0,0),new GLatLng(0,0) ),
                    1, "NIH Institutes Data");
                    
    // Create the tile layer overlay and 
    // implement the three abstract methods                 
    var tilelayer = new GTileLayer(copyright,1,5,{tileUrlTemplate:baseURL+tileDir+"/{X}_{Y}_{Z}.png"});

    tilelayer.isPng = function() { return true;};
    tilelayer.getOpacity = function() { return 0.7; };

    return new GTileLayerOverlay(tilelayer,{zPriority:zIndex});
}

function initMap() {
    proj = createProjection(maxZoom);
    var layers = [ createLayer(proj, "tiles/inst","NIH Institutes","NIH Institutes") ];
    handleResize();
    map = createMap(proj, layers, currentMapDiv, queryScript);

    handleResize();
    clearResults();
    map.checkResize();
    
    // center the map
    map.setCenter(new GLatLng(0,0), 1, map.getMapTypes()[0]);
    
    for (var i=0; i < LABELS.length; i++) {
        var dir = "tiles/"+LABELS[i];
        label2overlay[LABELS[i]] = createTileOverlay(dir,i);
    }
    
    toggleLabel(document.getElementById("labelToggle"));
    //toggleLabels(document.getElementById("labelToggle"));
        
    for (var i=0; i < INSTITUTES.length; i++) {
        var dir = "tiles/"+INSTITUTES[i]+"-inst";
        inst2overlay[INSTITUTES[i]] = createTileOverlay(dir,i);
    }    
}

function popOut() {
    //var sidebar = document.getElementById("sidebar");
    //sidebar.style.display="none";
    
    if (popoutWindow == null) {
        var button = document.getElementById("popper");
        button.className = 'popper-selected';

        popoutWindow = window.open("","Popout Window","scrollbars=yes");
        var doc = popoutWindow.document;
        
        doc.open("text/html");
        doc.write("<html><head>");
        //doc.write('<link href="styles.css" rel="stylesheet" type="text/css" />');
        doc.write('<body><div id="sidebar"><ul style="list-style:none;padding:0;margin:0;" id="sidebar-list">');
        
        var sidebar = document.getElementById("sidebar-list");

        var searchID = "<p id=\"search-matches\">";
        var sidebarStr = sidebar.innerHTML.substring(searchID.length,0);
        if (sidebarStr == searchID) {
            doc.write(sidebar.innerHTML);
            showLegend();
        } else {
            doc.write("<p>0 matches</p>");
        }
        
        doc.write('</ul></div>');
        doc.write('<p><button onclick="popIn()">Close</button></p>');
        doc.write("</html></body>");
        doc.close();
        popoutWindow.popIn = popIn;
        popoutWindow.onunload = popIn;
        popoutWindow.getMarkers = getMarkers;
    } else {
        popIn();
    }
}

function popIn() {
    //var sidebar = document.getElementById("sidebar");
    //sidebar.style.display="block";
    
    if (popoutWindow != null) {
        var button = document.getElementById("popper");
        button.className = 'popper-unselected';
        
        var sidebar = popoutWindow.document.getElementById("sidebar-list");

        var searchID = "<p id=\"search-matches\">";
        var sidebarStr = sidebar.innerHTML.substring(searchID.length,0);
        if (sidebarStr == searchID) {
            var innerSidebar = document.getElementById("sidebar-list");
            innerSidebar.innerHTML = sidebar.innerHTML;
        }
    
        popoutWindow.close();
        popoutWindow = null;
    }
}

function clearResults() {
    map.clearOverlays();
    clickBox = null;
    showLegend();
    document.getElementById("searchbox").value = "";
    clearSidebar();
    labelOverlay = null;
}

function clearSidebar() {
    if (popoutWindow != null) {
        var sidebar = popoutWindow.document.getElementById("sidebar-list");
        sidebar.innerHTML = "<p>0 matches</p>";
    }
}

function possiblyShowLegend() {
    var sidebar = document.getElementById("sidebar-list");

    var searchID = "<p id=\"search-matches\">";
    var sidebarStr = sidebar.innerHTML.substring(searchID.length,0);
    if (sidebarStr != searchID) {
        showLegend();
    }
}

function showLegend() {
    var sidebar = document.getElementById("sidebar-list");
    var helptext = document.getElementById("helptext").innerHTML;

    var currentMap = map.getCurrentMapType().getName();
    if (map2legend.hasOwnProperty(currentMap)) {
        var legendDiv = map2legend[currentMap];
        helptext = document.getElementById(legendDiv).innerHTML + helptext;
    }
       
    sidebar.innerHTML = "<li>"+helptext+"</li>";
}

function getSideList() {
    if (popoutWindow == null) {
        sidelist = document.getElementById("sidebar-list");    
    } else {
        sidelist = popoutWindow.document.getElementById("sidebar-list");                
    }
    
    return sidelist;
}

function getChartURL(hist) {
    var histNames = [];
    var histColors = [];
    var histVals = [];
    var maxVal = -10;
    var i = 0;
    for (var inst=0; inst < INSTITUTES.length; inst++) {
        if (hist.hasOwnProperty(INSTITUTES[inst])) {
            var data = hist[INSTITUTES[inst]];
            histNames[i] = data[2];
            histVals[i] = data[0];
            histColors[i] = data[1].slice(1);
            maxVal = Math.max(data[0],maxVal);
            i++;                
        }         
    }
    
    var tickVals = [];
    for (var t=1; t <= 5; t++) {
        tickVals[t-1] = parseInt(maxVal/5*t);
    }
    
    return "http://chart.apis.google.com/chart?chs=225x"+(25+12*i)+"&chd=t:"+histVals.join(",")+"&cht=bhs&&chbh=8&chco="+histColors.join("|")+"&chds=0,"+maxVal+"&chxt=y,x&chxl=0:|"+histNames.reverse().join("|")+"|1:|0|"+tickVals.join("|")+"&chg=20,0,1,3";
}

function getMarkers(urlstr,maxResults,drawIcons){
    var request = GXmlHttp.create();
    request.open('GET', urlstr , true);	// request JSON from PHP with AJAX call
    request.onreadystatechange = function () {
		if (request.readyState == 4) {
			var response = eval('('+request.responseText+')');
            var locations = response.locations;
		    var numLocations = locations.length;

            if (numLocations > maxResults) {
                alert("Too many results ("+numLocations+")! Please refine your query to have max "+maxResults+" results.");
                return;
            }

            var zoom = map.getZoom();
            var layerSize = 256.0*Math.pow(2,zoom);
            var sidelist = getSideList();

            //show the number and a histogram of the results
            if (response.matches > 0) {
                var chartURL = getChartURL(response.hist);
                sidelist.innerHTML = "<p id=\"search-matches\">"+
                    response.matches+" matches</p><p><center><img src=\""+
                    chartURL+"\"/><p><a target=\"_blank\" href=\""+
                    response['export']+"\">Download as CSV</a></p></center></p>";
            } else {
                sidelist.innerHTML = "<p id=\"search-matches\" >0 matches</p>";        
            }

            if (drawIcons) {
                map.clearOverlays();
                clickBox = null;
            }

            //show found locations
			for (var i = 0; i < numLocations; i++) {
			    var n = locations[i];
			    var color = n.color;
			    var text = "<div id=\"result-item\"><span style=\"background-color: "+color+"; color: "+color+"\" title=\""+inst2names[n.category][1]+"\">Pres. Obama!</span><a target=\"_blank\" href=\""+topicBrowserURL+n.did+"\">"+n.sfnid+"</a> <i>"+n.title+"</i> PI: "+n.authors+"</div>";
			    
                var listItem = document.createElement('li');
                listItem.innerHTML = text;            
                sidelist.appendChild(listItem);
			    				  
			    //draw map icons for locations, if necessary  
			    if (drawIcons) {
				    var x = (n.x+1)/2*layerSize;
				    var y = ((0-n.y)+1)/2*layerSize;
			        var location = proj.fromPixelToLatLng(new GPoint(x,y),zoom);
                    var icon = MapIconMaker.createMarkerIcon({primaryColor:color,cornerColor:color});                    

                    var marker = new GMarker(location,{icon:icon});
                    marker.data = n;
                    marker.markerindex = i;
                    marker.bindInfoWindowHtml(text);

    				map.addOverlay(marker);
				}
			}

            //add pager controls
		    var pages = response.pages;			
			if (pages > 1) {
			    var curpage = response.curpage;
			    var template = response.template;
			    var pager = document.createElement('center');
			    var text = "<p>";

			    if (curpage > 1) {
			        text += "<a href=\"#\" onclick=\"getMarkers('"+(template+(curpage-1))+"',10000,"+drawIcons+")\">prev</a> ";
			    }
			    text += "page "+curpage+" of "+pages+" ";
			    if (curpage < pages) {
			        text += "<a href=\"#\" onclick=\"getMarkers('"+(template+(curpage+1))+"',10000,"+drawIcons+")\">next</a>";
			    }
			    text += "</p>";
			    pager.innerHTML = text;
			    sidelist.appendChild(pager);
			}
		}
	}
	request.send(null);
}

function init() {
    if (GBrowserIsCompatible()) {  
        // Standard browsers (Mozilla, Safari, etc.)
        if (self.innerHeight) {
        } else {
            document.getElementById('popper').style.display = 'none';
        }
    
        initMap();
    }else {
        // display a warning if the browser was not compatible
        alert("Sorry, the Google Maps API is not compatible with this browser");
    }
}

function windowWidth() {
  // Standard browsers (Mozilla, Safari, etc.)
  if (self.innerHeight) {
    return self.innerWidth;
  }
  // IE 6
  if (document.documentElement && document.documentElement.clientWidth) {
   return document.documentElement.clientWidth;
  }
  // IE 5
  if (document.body) {
    return document.body.clientWidth;
  }
  // Just in case. 
  return 0;
}


function handleResize() {
  var offset = 30;
  if (!self.innerHeight) {
    offset = 12;
    var width = windowWidth() - 270 - 20;
    document.getElementById('map-wrapper').style.width = width;  
    document.getElementById('map-wrapper').style.margin = "0 0 -10 0";
  }
  var height = windowHeight() - document.getElementById('toolbar').offsetHeight - offset;
  document.getElementById(currentMapDiv).style.height = height + 'px';
  document.getElementById('sidebar').style.height = height + 'px';
}

window.onresize = handleResize;
window.onload = init;
window.onunload = GUnload;
