var incidentRequest;

function getXHRObject() {   
    xhr = false;
    if(window.XMLHttpRequest && !(window.ActiveXObject)) {
        try {
            xhr = new XMLHttpRequest();
        } catch(e) {
            xhr = false;
        }
    } else if(window.ActiveXObject) {
           try {
            xhr = new ActiveXObject("Msxml2.XMLHTTP");
          } catch(e) {
            try {
                  xhr = new ActiveXObject("Microsoft.XMLHTTP");
            } catch(e) {
                  xhr = false;
            }
        }
    }
    return xhr;
}

function parseForm() {
	var filterForm = document.getElementById("filterForm");
    var params = "";
    var skip = false;
    for (var i = 0; i < filterForm.elements.length; i++) {
        if (filterForm.elements[i].type == "checkbox") {
            if (filterForm.elements[i].checked) {
                skip = false;
            } else {
                skip = true;
            }
        } else if (!skip /*&& filterForm.elements[i].name != "submit"*/) {
        	var value = "";
            if (filterForm.elements[i].type == "select-multiple") {
                for (var j = 0; j < filterForm.elements[i].length; j++) {
                    if (filterForm.elements[i][j].selected) {
                        value += ((value != "") ? "," : "") + encodeURIComponent(filterForm.elements[i][j].value);
                    }
                }
            } else if (filterForm.elements[i].value.length > 0) {
                value = filterForm.elements[i].value;
            }
            if (value.length > 0) 
            	params += ((params == "") ? "?" : "&") + filterForm.elements[i].name + "=" + value;
        }
    }
    return params;
}

function updateIncidents() {
	var params = parseForm();

    if (params.length > 1)
    	window.location.hash = encodeURI("#" + params.substring(1));
    else if (window.location.hash.length > 1)
    	window.location.hash = "#";
    
    getIncidentsWithParams(params);
}

function getIncidentsWithParams(params) {
    map.clearOverlays();
    currentOverlay = false;
    currentMarkers = false;
    currentLAPD = false;
            
    loadingImage = document.getElementById("loading");
    loadingImage.style.display = "inline";
    
    var region = document.getElementById("listingsRegion");
    while (region.hasChildNodes())
        region.removeChild(region.firstChild);
    
    region = document.getElementById("graphRegion");
    while (region.hasChildNodes())
        region.removeChild(region.firstChild);

    
	incidentRequest = getXHRObject();
    if (incidentRequest) {
        incidentRequest.onreadystatechange = processReqChange;
        incidentRequest.open("GET", encodeURI("get_data.php" + params), true);
        incidentRequest.send(null);
    }
    
    /*var startDate = new Date();
    var year = document.getElementById("start_year").value;
    var month = document.getElementById("start_month").value;
    var day = document.getElementById("start_day").value;
    if (year && month && day) {
        startDate.setYear(year);
        startDate.setMonth(month);
        startDate.setDate(day);
    }*/
    
    var endDate = new Date(new Date().getTime() - 7*24*60*60*1000);
    var endDateString = endDate.getMonth()+"/"+endDate.getDate()+"/"+(endDate.getYear()+1900),
        interval = 7,
        radius = 1,
        lon = -118.287047,
        lat = 34.025163;
    
    enabledLayers["LAPD"] = document.getElementById("lapdEnable").checked;
    currentLayers["LAPD"] = new GGeoXml("http://lapdcrimemaps.org/crime_search_kml.php?endDate="+endDateString+"&interval="+interval+"&radius="+radius+"&lon="+lon+"&lat="+lat+"&"+"c[1]=1&c[2]=1&c[3]=1&c[4]=1&c[5]=1&c[6]=1&c[7]=1&c[8]=1")
    addLAPD();
}

function addLAPD() {
    if (currentLayers["LAPD"] && enabledLayers["LAPD"])
	    map.addOverlay(currentLayers["LAPD"]);
}

function processReqChange() {
    if (incidentRequest.readyState == 4) {
        if (incidentRequest.status == 200) {
        	last_responseXML = incidentRequest.responseXML;
        
            makeTable(last_responseXML);
            
            makeGraphs(last_responseXML);
            
            makeMaps(last_responseXML);
            
            makeOverlay(last_responseXML);
            
            loadingImage = document.getElementById("loading");
            loadingImage.style.display = "none";
            
        } else {
            alert("There was a problem retrieving the XML data:\n" + incidentRequest.statusText);
        }
    }
}

function makeGraphs(xmldoc) {
    var element = document.getElementById("graphRegion");
    var xmlrows = xmldoc.getElementsByTagName("graph");
    
    for (var i = 0; i < xmlrows.length; i++) {
        var graphurl = xmlrows[i].getAttribute("url").replace(/\&\#38\;/g, "&"); // need to fix ampersands for Safari for some reason
        var graphtitle = xmlrows[i].getAttribute("title");
        
        var newGraphImage = document.createElement("img");
        newGraphImage.setAttribute("src", graphurl);
        newGraphImage.setAttribute("class", "graphImage");
        
        element.appendChild(newGraphImage);
    }
}

function makeMaps(xmldoc) {
    var xmlrows = xmldoc.getElementsByTagName("marker");
    
    currentLayers["Markers"] = new Array()
    for(var r=0; r < xmlrows.length; r++) {
        var xmlrow = xmlrows[r];
        var maplocation = xmlrow.getAttribute("location");
        var maplatitude = xmlrow.getAttribute("latitude");
        var maplongitude = xmlrow.getAttribute("longitude");
        
        var icon;
        switch (xmlrow.getAttribute("source")) {
        	case "dps" : icon = dps_icon; break;
        	case "lapd" : icon = lapd_icon; break;
        }
        
        var point = new GLatLng(maplatitude, maplongitude);
        var marker = createMarker(point, maplocation, xmlrow.getAttribute("htmllist"), icon);
        currentLayers["Markers"].push(marker);
    }
	
	addAllMarkers();
}

function addAllMarkers() {
	if (currentLayers["Markers"] && enabledLayers["Markers"])
		for (var i = 0; i < currentLayers["Markers"].length; i++)
			map.addOverlay(currentLayers["Markers"][i]);
}

function createMarker(point, location, html, icon) {
  var marker = new GMarker(point, icon);
  GEvent.addListener(marker, "click", function() {
        marker.openInfoWindowHtml("<div class=\"markerInfo\"><u>" + location + "</u><br />" + html + "</div>");
  });
  return marker;
}

function makeOverlay(xmldoc) {
    
    var xmlrows = xmldoc.getElementsByTagName("overlaypoint");
    
    var data = new Array();
    
    for (var i = 0; i < xmlrows.length && i < 100; i++)
    {
        data.push(xmlrows[i].getAttribute("latitude"));
        data.push(xmlrows[i].getAttribute("longitude"));
        data.push(xmlrows[i].getAttribute("weight"));
    }
    
    try
    {
        var size = map.getSize();

        var heatMap = new GEOHeatmap();
        heatMap.Init(size.width, size.height);
        heatMap.SetData(data);
        heatMap.SetBoost(1);

        currentLayers["Density"] = new HMGoogleOverlay(heatMap.GetURL());

        addDensityMap();
    }
    catch(e)
    {
    }
}

function addDensityMap() {
    if (currentLayers["Density"] && enabledLayers["Density"])
	    map.addOverlay(currentLayers["Density"]);
}

function makeTable(xmldoc) {
    var schema = {
        rowtag: "crime",
        columns: [
            { tagname: "@identifier", label: "ID" },
            { tagname: "@category",   label: "Category"},
            { tagname: "@subcategory",label: "Subcategory"},
            { tagname: "@time",       label: "Date/Time"},
            { tagname: "@location",   label: "Location"},
            /*{ tagname: "@disp",       label: "Disposition"},
            { tagname: "@cc",         label: "CC"},*/
            { tagname: "@summary",    label: "Summary"}
        ]
    };
    
    // Create the <table> element
    var table = document.createElement("table");
    table.setAttribute("class", "listingTable");

    // Create the header row of <th> elements in a <tr> in a <thead>
    var thead = document.createElement("thead");
    var header = document.createElement("tr");
    for(var i = 0; i < schema.columns.length; i++) {
        var c = schema.columns[i];
        var label = (typeof c == "string")?c:c.label;
        if (label != "Summary") {
            var cell = document.createElement("th");
            cell.appendChild(document.createTextNode(label));
            header.appendChild(cell);
        }
    }
    // Put the header into the table
    thead.appendChild(header);
    table.appendChild(thead);

    // The remaining rows of the table go in a <tbody>
    var tbody = document.createElement("tbody");
    table.appendChild(tbody);

    // Now get the elements that contain our data from the xml document
    var xmlrows = xmldoc.getElementsByTagName(schema.rowtag);
    
    // Loop through these elements. Each one contains a row of the table
    for (var r=0; r < xmlrows.length; r++)
    {
        // This is the XML element that holds the data for the row
        var xmlrow = xmlrows[r];
        // Create an HTML element to display the data in the row
        var row = document.createElement("tr");
        var rowSummary = document.createElement("tr");
        
        // Loop through the columns specified by the schema object
        for (var c = 0; c < schema.columns.length; c++)
        {
            var sc = schema.columns[c];
            var tagname = (typeof sc == "string")?sc:sc.tagname;
            
            if (tagname != "@summary")
            {
                var celltext;
                if (tagname.charAt(0) == '@') {
                    // If the tagname begins with '@', it is an attribute name
                    celltext = xmlrow.getAttribute(tagname.substring(1));
                }
                else {
                    // Find the XML element that holds the data for this column
                    var xmlcell = xmlrow.getElementsByTagName(tagname)[0];
                    // Assume that element has a text node as its first child
                    var celltext = xmlcell.firstChild.data;
                }
                // Create the HTML element for this cell
                var cell = document.createElement("td");
                // Put the text data into the HTML cell
                
                if (tagname == "@identifier") {
                    var temp = document.createElement("a");
                    temp.setAttribute("name", xmlrow.getAttribute(tagname.substring(1)));
                    temp.setAttribute("id", xmlrow.getAttribute(tagname.substring(1)));
                    temp.appendChild(document.createTextNode(celltext));
                    cell.appendChild(temp);
                } else {            
                    cell.appendChild(document.createTextNode(celltext));
                }
                // Add the cell to the row
                row.appendChild(cell);
            } else {
                
                var cell = document.createElement("td");
                var celltext = xmlrow.getAttribute(tagname.substring(1));
                cell.appendChild(document.createTextNode(celltext));
                cell.setAttribute("colspan", (schema.columns.length-1)+"");
                rowSummary.appendChild(cell);
            }
        }
        // And add the row to the tbody of the table
        tbody.appendChild(row);
        tbody.appendChild(rowSummary);
    }

    // Set an HTML attribute on the table element by setting a property.
    // Note that in XML we must use setAttribute() instead.
    table.frame = "border";



    element = document.getElementById("listingsRegion");
    element.appendChild(table);
}

