﻿
var map;

var progressHolder;
var progressMessage;
var oCrime1Incidents;
var oCrime2Incidents;
var estateGroup;
var estateCluster = [];
var selectedIncidents = [];
//var selectedEstatesIncidents = [];
var viewportwidth;
var viewportheight;
var PageListTotal = 0;
var iPageSize = 20;
var globallistincidents;
var selectTimeout = null;
var multiSelect = null;
// Arrey used to colour the borough boundaries via locationID
var boroughColour = [];
boroughColour[1] = '#FF4100';
boroughColour[2] = '#FF4100';
boroughColour[3] = '#FF4100';
boroughColour[4] = '#FF4100';
boroughColour[5] = '#FF4100';
boroughColour[6] = '#FF4100';
boroughColour[7] = '#FF4100';
boroughColour[8] = '#FF4100';


function pageOnLoad() {
    var mapEvents = {
        "zoomend": mapZoomHandlerPublic,
        "moveend": mapMoveHandler
        };
    
    map = OSgetMap("map", mapEvents);
    
    progressHolder = $('progressHolder');
    progressMessage = $('progressMessage');
    
    OSsetCenter(map,  551805,201800, 0);
    OSsetBase(map, 0);
    
    page_resize();
    setTimeout('showLegend(' + $F(drpCrimeID) + ')', 10);
    
    new Form.Element.Observer('txtLocationSearch', 1, doLocationSearchKeyDown);
}

function mapZoomHandlerPublic(mapEvent) {
    //console.log('mapZoomHandlerPublic');
    if (OSgetZoom(map) >= 2 &&GetDisplayType() >= 2 ) {
        map.setCenter(map.LonLat, 2);
    
        mapZoomHandler(mapEvent);
       
    }
    updatePins();
}



function  mapZoomHandler(mapEvent) {
   
    updateProgress('Changing zoom level');
      
    //Clear vectors on zoom        
    OSclearVectorLayer(0);
    
    switch (mapEvent.object.zoom) {
 
    case 4:
    case 5:
    case 6:
    case 7:
        OSsetBase(map, 1);
        break;
    default:
        OSsetBase(map, 0);
        break;
    }

    // Activate/deactivate Ward button depending on zoom level
    if ($('rbHierarchyLevelEstate')) {
        CheckWardRadio(mapEvent);  
    }
    // updatePins();
    updateProgress('');
}

function mapMoveHandler(mapEvent) {

    doSearch();
}

function mapSelectHandler(feature) {

    if(feature.layer.name == "Pins Layer") {
        
        if(feature.attributes.pinType == "cluster") {
            selectTimeout = setTimeout(function(){expandCluster(feature)},500);
            feature.attributes.expanded = 1;
        } else if(feature.attributes.pinType == "estate") {
            selectTimeout = setTimeout(function(){expandEstatePin(feature)},500);
            feature.attributes.expanded = 1;
        } else if(feature.attributes.pinType=="incident") {
            selectTimeout = setTimeout(function(){showIncidentDetails(feature)},500);
        }  else if(feature.attributes.type=="circle") {
            OSonPopupClose();
            selectTimeout = setTimeout(function(){showIncidentDetails(feature)},500);
        }
    } else {
        cancelSelect();

        selectTimeout = setTimeout(function(){showInfoPopup(feature)},500);
    }
}

function mapUnselectHandler(feature) {

    removeInfoPopup(feature);
}

function mapDblClickHandler(feature) {
    if(feature.attributes.pinType==undefined) {
        cancelSelect();
        var newCentre = OSgetFeatureClickPos(map);
        OSsetCenter(map, newCentre.lon, newCentre.lat, OSgetZoom(map) + 1)
    }
}

function cancelSelect() {
    if (selectTimeout!=null) {
        clearTimeout(selectTimeout);
    }
}

function onChangeCrimeID() {
    //clear existing overlays and redo search
    OSclearVectorLayer(0);
    OSclearVectorLayer(1);
    CheckDisplayType();
    setTimeout('showLegend(' + $F(drpCrimeID) + ')', 10);
    DisplayTypeChange();
}

function onChangeStatisticsView() {
    //clear existing overlays and redo search
    OSclearVectorLayer(0);
    OSclearVectorLayer(1);
    setTimeout('showLegend(' + $F(drpCrimeID) + ')', 10);
    doSearch();
}

function doSearch() {
    // Updated to help display the progress bat in IE
    // Display progress bar first and then do search via a timeout
    
    //Display progress bar
     updateProgress('Retrieving data');
    
    // Call search via timeout
     ReportType = GetDisplayType();
        
        if (ReportType == 1||ReportType == 3) {
            // Thematics selected
            setTimeout("doSearch_Thermatics();", 500);
 
        }
        updateProgress('');
}

function doSearch_Thermatics() {
    
    //Update Hierarchy label
    $('spanHierarchyLevelText').innerHTML = ((OSgetZoom(map)<2) ? ciNeighbourhood : ciEstate);
    
    if (!($('rbPer1000') == null))
    {
        var statisticsViewType = ($('rbPer1000').checked ? true : false);
    }
    else
    {
        //get it from config
        var statisticsViewType = (defStatisticsViewType == '1' ? true : false);
    }
    
    var CrimeID = $F(drpCrimeID);
    
    if (CrimeID!=0) {
        var oSearch = new SearchAPI();
        var searchBounds = OSgetBounds(map);
        var searchParams = {
            CrimeID: CrimeID,
            HierarchyLevel: ((OSgetZoom(map)<2) ? 1 : 2),
            MinX: parseInt(searchBounds.SW.lon),
            MinY: parseInt(searchBounds.SW.lat),
            MaxX: parseInt(searchBounds.NE.lon),
            MaxY: parseInt(searchBounds.NE.lat),
            Zoom: OSgetZoom(map),
            Per1000: statisticsViewType
        };

        var oSearchResult = oSearch.getResults(searchParams);
        
        var newFeatures = [];
        var removedFeatures = [];

        //Create a feature for each search result
        for (var i = 0; i < oSearchResult.length; i++){
            newFeatures.push(OSVectorFeatureFromWKT(oSearchResult[i].boundaryText, {colourCode: oSearchResult[i].colourCode, locationID: oSearchResult[i].locationID, parentLocationID: oSearchResult[i].parentLocationID, hierarchyLevel: ((OSgetZoom(map)<2) ? 1 : 2)}));
        }
        
        //iterate the map features to see which are no longer required
        for (var i = 0; i < OSVectorLayers[0].features.length; i++){
            var thisLocationID = OSVectorLayers[0].features[i].attributes.locationID;
            var locationMatched = null;
            for (var j = 0; j < newFeatures.length; j++){
                if (newFeatures[j].attributes.locationID == thisLocationID) {
                    locationMatched = newFeatures[j];
                    break;
                }
            }
            
            if (locationMatched==null) {
                // no match - remove feature from map
                removedFeatures.push(OSVectorLayers[0].features[i]);
            } else {
                //matched - don't add again (remove from newFeatures array)
               newFeatures = newFeatures.without(locationMatched);
            }
        }
        
        if (removedFeatures.length > 0) {
            OSdestroyVectorFeatures(0, removedFeatures);
        }
        if (newFeatures.length > 0) {
            OSaddVectorFeatures(0, newFeatures);
        }
    }
    updateProgress('');
}


function doSearch_Incidents() {
    if (OSgetZoom(map) >= 5) {
        map.setCenter(map.LonLat, 4);
    }
    doIncidentSearch();
}

function showInfoPopup(feature) {
    //console.log(("showInfoPopup", feature);
    
    var oTabs = new TabsAPI();
    
    if (!($('rbPer1000') == null))
    {
        if ($('rbPer1000').checked)
        {
            var CountPer1000 = "IncidentPer1000";
        }
        else
        {
            var CountPer1000 = "IncidentCount";
        }
    }
    else
    {
        //get it from config
        var CountPer1000 = ((defStatisticsViewType == "1") ? "IncidentPer1000" : "IncidentCount");
    }
    
    var contentHTML = oTabs.getTabsHTML(feature.attributes.locationID, $F(drpCrimeID), CountPer1000);
    
    if (contentHTML.length>=1) {
        OSshowInfoPopup(map, feature, contentHTML[0]);
        //convert to tabs    
        activeTabIndex['dhtmlgoodies_tabView1'] = -1;
        initTabs('dhtmlgoodies_tabView1',contentHTML[1].split(","),0,360,320,Array(false,false,false),contentHTML[1].split(","));
    }
        
    showCrimeNotes(feature.attributes.locationID, feature.attributes.parentLocationID, feature.attributes.hierarchyLevel);    
}

function removeInfoPopup(feature) {
    OSremoveInfoPopup(feature);
    hideCrimeNotes();
}    

function showLegend(CrimeID ) {
    if (CrimeID!=0) {
        var legendDiv = $('divLegendContent');
        var myTemplate = new Template('<div style="float:left;"><div style="height:35px;width:54px;background-color:#{colourCode};filter:alpha(opacity=50);opacity: 0.5;-moz-opacity:0.5;"></div><div style="position:relative;left:0px;top:-35px;height:35px;width:54px;color:#{textColourCode};">#{legend}</div></div>');
        var oLegend = new LegendAPI();
        
        if (!($('rbPer1000') == null))
        {
            var statisticsViewType = ($('rbPer1000').checked ? true : false);
        }
        else
        {
            //get it from config
            var statisticsViewType = (defStatisticsViewType == '1' ? true : false);
        }
        
        var Legends = oLegend.getColours(CrimeID , statisticsViewType?1:0);
        
        legendDiv.innerHTML = '';
        for (var i = 0; i < Legends.length; i++){
            legendDiv.innerHTML += myTemplate.evaluate(Legends[i]);
        }
        
        if (statisticsViewType) {
            $('spanLegendDescription').innerHTML = 'Colours indicate the number per 1000 population by ';
        } else {
            $('spanLegendDescription').innerHTML = 'Colours indicate the total number by ';
        }
        doBoxOpen('Legend');
    } else {
        doBoxHide('Legend');
    }   
}

function showCrimeNotes(location, parentLocation, hierarchyLevel) {
    var LocationName = '';
    var CrimeNotes = '';
    var oCrimeNotes = new CrimeNotesAPI();
    var crimeNote = oCrimeNotes.getCrimeNotes(location);
    
    if(typeof(crimeNote) !== 'undefined' && crimeNote != null) {
        LocationName = crimeNote.locationName;
        CrimeNotes = crimeNote.notes;
    } else {
        //Look up Location Name
        var oLoc = new LocationsAPI();
        var Location = oLoc.readByID(location);
        if(typeof(Location) !== 'undefined' && Location != null) {
            LocationName = Location.name;
        }
    }
    
    $('notesLocationName').innerHTML = LocationName;
    $('boroughContent').innerHTML = CrimeNotes;
    $('boroughContent').innerHTML += '<br /><a href="/nagreport.aspx?location=' + ((hierarchyLevel==1)?location:parentLocation) + '" target="_blank">Neighbourhood Action Group Quarterly Report</a>';
    $('boroughNotes').style.display = '';
}

function hideCrimeNotes() {
    $('boroughNotes').style.display = 'none';
}

function csvExport() {
    // If statistics type is Incident Count, then page is csvexport.aspx?CountPer1000=IncidentCount
        window.open('csvexport.aspx','csvexport','status=0,toolbar=0,width=10,height=10,resizable=0');
}

function updateProgress(sMessage) {
    if (sMessage.length==0) {
          progressHolder.style.left = "-3000px";
    } else {
        progressMessage.innerHTML = sMessage;
        progressHolder.style.left = "0px";
        $('progressimage').src = "/images/progress.gif";
    }
}

/* Update the public radio buttons when a category is selected  */
function CheckDisplayType() {

            ShowStats = CrimeArray[$(drpCrimeID).selectedIndex - 1];
            
            if (ShowStats=="True") {
                //$('ShowInceidents').disabled = '';
                $('ShowBoth').disabled = '';
            } else {
            
              //  $('ShowInceidents').disabled = 'disabled';
                $('ShowBoth').disabled = 'disabled';
                $('ShowThermatics').checked='checked';
            }
     }
     
function DisplayTypeChange() {
//  ShowThermatics ShowInceidents ShowBoth
        
        OSclearVectorLayer(0);
        OSclearVectorLayer(1);
        ReportType = GetDisplayType();
        
        if (ReportType == 1) {
            // Thematics selected
            setTimeout("doSearch_Thermatics();", 500);
            
        } else if (ReportType == 2) {
        
            // Incidents only selected
            if (OSgetZoom(map) > 2 ) {
                map.setCenter(map.LonLat, 2);
                mapZoomHandler(mapEvent);
            }
                doSearch();
         //   setTimeout("doSearch_Incidents();", 500);

        } else if (ReportType == 3) {
            if (OSgetZoom(map) > 2 ) {
                map.setCenter(map.LonLat, 2);
            }
            doSearch();
            // Incidents and Thermatics
           setTimeout("doSearch_Thermatics();", 500);
           setTimeout("doSearch_Incidents();", 500);
        }
     }
    
function GetDisplayType() {
       if ($F('ShowThermatics')) return 1
     //  if ($F('ShowInceidents')) return 2;
       if ($F('ShowBoth')) return 3; 
    }

function showIncidentDetails(feature) {

    
    var popupHtml = '<table>'
                    + '<tr><td>Reference: </td><td>' + feature.attributes.reference + '</td></tr>'
                    + '<tr><td>Estate Name: </td><td>' + feature.attributes.estatename + '</td></tr>'
                    + '<tr><td>Category: </td><td>' + feature.attributes.crimeType + '</td></tr>'
                    + '<tr><td>Incident Date: </td><td>' + feature.attributes.incidentDateDisplayShort  + '</td></tr>'
                    + '<tr><td>Street Name: </td><td>' + feature.attributes.streetname + '</td></tr>'
                    + '</table>';
       
    OSshowInfoPopupSized(map, feature, popupHtml, 200, 100);

}

function mapGroupSelectHandler(feature) {
   
    if (feature.layer.name == "Pins Layer" && feature.attributes.type == "circle") {
        selectedIncidents.push(feature.attributes.incidentID);
    }
    
    if (feature.layer.name == "Pins Layer" && feature.attributes.pinType == "estate") {
        var incidentList = feature.attributes.incidentList
        var selectedEstatesIncidents = incidentList.split(",");
        if (selectedEstatesIncidents.length > 0) {
            for (var i = 0; i < selectedEstatesIncidents.length; i++){
                selectedIncidents.push(selectedEstatesIncidents[i]);
            }  
        }
    }
    
    if (feature.layer.name == "Pins Layer" && feature.attributes.pinType == "cluster") {
        for (var i = 0; i < estateGroup.length; i++){
            if (estateGroup[i].ParentID == feature.attributes.ParentID ) {
                var incidentList = estateGroup[i].incidentList
                var selectedEstatesIncidents = incidentList.split(",");
                if (selectedEstatesIncidents.length > 0) {
                    for (var j = 0; j < selectedEstatesIncidents.length; j++){
                        selectedIncidents.push(selectedEstatesIncidents[j]);
                    }  
                }
            }  
        }
    }
    
    if (multiSelect!=null) {
        clearTimeout(multiSelect);
    }
    multiSelect = setTimeout(mapGroupSelectEnd, 250);
}

function mapGroupSelectEnd() {
    multiSelect = null;
    OStoggleBoxSelect(true);
    DisplayIncidentList(1);
}

function mapGroupUnselectHandler(feature) {

    removeInfoPopup(feature);
}

// Functions for modal box
    function show_modal(modal_title, HTMLContent, footerHTML) 
    {                      
        //Modal functions moved to general.js so other functions have access
        show_lightbox(modal_title, HTMLContent, footerHTML) 
        return false;
    }
        
    function close_modal() {
        
        // Close modal function moved to general.js so other functions have access
        close_lightbox();
        
        if (OSSelectByBoxCtrl.layer.selectedFeatures.length > 0) {
            OSSelectByBoxCtrl.unselectAll();
            //clear selected incidents array
            selectedIncidents = [];
        }

        return false;
    }   
    
    
    function DisplayIncidentList(iPage)    {
	    //This function will display a modal box with a list of the incidents in the requested page
 
    	page_resize();
        iPageSize = Math.round((viewportheight * 0.8) / 38);

	    //Determine the no of pages to ensure chosen page is OK
	    var iLength = selectedIncidents.length ;
	    var iTotalPages = Math.ceil(iLength/iPageSize);

        PageListTotal = iTotalPages;
        
	    var startpoint = ((iPage - 1) * iPageSize);
	    var endpoint = startpoint + Math.min(iPageSize, (iLength-startpoint));

	    var listincidents = [];

	    for(var i=startpoint ; i<endpoint; i++)
        {
	        listincidents.push(selectedIncidents[i]);

        }

        var oListIncidentsAPI = new IncidentAPI();
        var oListIncidents = oListIncidentsAPI.readByIncidentIDArray(listincidents);
        
        globallistincidents = listincidents;

        //Declare the content HTML
        var HTMLListContent = '';
    	
        //Define the 1st company in the list.
        var theCurrentEstate = '';

        //Start the HTML
        HTMLListContent = '<div style="overflow:auto;"><table style=" width: 95%">'
        HTMLListContent += '<tr style="font-weight:bold;">'
        HTMLListContent += '<th ></th>'
        HTMLListContent += '<th width="80px"></th>'
        HTMLListContent += '<th width="130px"></th>'
        HTMLListContent += '<th width=""></th>'
        HTMLListContent += '<th width=""></th>'
        HTMLListContent += '<th width="150px"></th></tr>'

        var origindex = 0;
        
        for (var i = 0; i < oListIncidents.length ; i++) {

                //Check for change of estate
                if (theCurrentEstate  != oListIncidents[i].estateName ) {
                    //Estate changed, output new estate name
                    HTMLListContent += '<tr><td colspan=3 class="listestate" >' + oListIncidents[i].estateName + '</td></tr>';  
                }
                theCurrentEstate = oListIncidents[i].estateName;
    	    
                // Loop thru original array to find original index position.
                for (var x = startpoint; x < endpoint; x++)
                {
                    if (oListIncidents[i].IncidentID == selectedIncidents[x])
                    {
                        origindex = x;
                    }
                }	                
                
            HTMLListContent += '<tr><td>&nbsp;</td><td>' 
                + oListIncidents[i].reference + '</td><td>' 
                + oListIncidents[i].categoryname+ '</td><td>' 
                + oListIncidents[i].NeighbourhoodName + '</td><td>' 
                + oListIncidents[i].IncidentdateShort + '</td><td>' 
                 + oListIncidents[i].Strretname +  '</td></tr>'; 
        }

        HTMLListContent += '</table></div>'

        //Reset the footer
        var footerHTML = '<div id="paging_back"  onclick="pagingListBack('+ (iPage-1) + ',' + iTotalPages + ');" ><a href="#">Back</a></div>'
            footerHTML+= '<div id="paging_count"  style="float: left; width: 80px;">Page ' + iPage + ' of ' + PageListTotal + '</div>'
            footerHTML+= '<div id="paging_forward" onclick="pagingListForward('+ (iPage+1) + ',' + iTotalPages + ');" ><a href="#" >Next</a></div>'
            footerHTML+= '<br/><div style="width: 100%;height: 20px;clear: both;" class="center"><a href="#" onclick="javascript:createIncidentsCSV();">Export to CSV file <a/></div>'

        //Show the selected page
        show_modal('Selected Incidents', HTMLListContent, footerHTML);

    }

function doIncidentSearch() {
    
    // Do we need to cluster the estates 
    ClusterEstates = ((OSgetZoom(map)==2) ? false : true);   
    
    oCrime1Incidents = [];
    oCrime2Incidents = [];
    estateGroup = [];
    estateCluster = [];
    
    var CrimeID = $F(drpCrimeID);
    var CrimeID2 = '';
    //var HierarchyLevel = ($('rbHierarchyLevelNeighbourhood').checked ? 1 : 2);
    var HierarchyLevel = 1;
    
    // Main crime ID routine
    if (CrimeID!=0) {
        var oSearch = new SearchAPI();
        var searchBounds = OSgetBounds(map);
        var searchParams = {
            CrimeID: CrimeID,

            MinX: parseInt(searchBounds.SW.lon),
            MinY: parseInt(searchBounds.SW.lat),
            MaxX: parseInt(searchBounds.NE.lon),
            MaxY: parseInt(searchBounds.NE.lat)
        };

        oCrime1Incidents = oSearch.getIncidents(searchParams);

        //Group incident results by estate
        for (var i = 0; i < oCrime1Incidents.length; i++){
            var estateMatched = false;
            for(var j = 0; j < estateGroup.length; j++){
                if (estateGroup[j].estateEasting == oCrime1Incidents[i].estateEasting && estateGroup[j].estateNorthing == oCrime1Incidents[i].estateNorthing) {
                    estateGroup[j].crime1Count = estateGroup[j].crime1Count + 1;
                    estateGroup[j].incidentList = estateGroup[j].incidentList + ',' + String(oCrime1Incidents[i].incidentID);
                    estateMatched = true;
                    break;
                }
            }
            if(estateMatched == false) {
                var estateObject = new Object;
                estateObject.locationID = oCrime1Incidents[i].locationID;
                estateObject.estateEasting = oCrime1Incidents[i].estateEasting;
                estateObject.estateNorthing = oCrime1Incidents[i].estateNorthing;
                estateObject.incidentList = String(oCrime1Incidents[i].incidentID);
                estateObject.estatename = oCrime1Incidents[i].estatename;
                estateObject.streetname = oCrime1Incidents[i].streetname;
                estateObject.incidentDateDisplay = oCrime1Incidents[i].incidentDateDisplay;
                estateObject.incidentDateDisplayShort = oCrime1Incidents[i].incidentDateDisplayShort;
                estateObject.crime1Count = 1;
                estateObject.crime2Count = 0;
                estateObject.centroidX = oCrime1Incidents[i].centroidX;
                estateObject.centroidY = oCrime1Incidents[i].centroidY;
                estateObject.ParentID = oCrime1Incidents[i].parentLocationID;

                estateGroup.push(estateObject);
            }
        }

        $(drpCrimeID).style.backgroundColor='#fcc';
    } else {
        $(drpCrimeID).style.backgroundColor='#fff';
    }
    var newFeatures = [];
    var removedFeatures = [];
    
    if (ClusterEstates == true) {
        estateCluster = [];
        // Group up the estategroups into clusters
        for (var i = 0; i < estateGroup.length; i++){
            var clusterMatched = false;
        
                for(var j = 0; j < estateCluster.length; j++){
                
                    if (estateCluster[j].ParentID == estateGroup[i].ParentID ) {
                    
                        estateCluster[j].crime1Count += estateGroup[i].crime1Count;
                        estateCluster[j].crime2Count += estateGroup[i].crime2Count;
                        estateCluster[j].centroidX = estateGroup[i].centroidX;
                        estateCluster[j].centroidY = estateGroup[i].centroidY;
                        clusterMatched = true;
                        break;
                    }
                }
                
                if(clusterMatched == false) {
                
                    var clusterObject = new Object;
                    clusterObject.locationID = estateGroup[i].locationID;
                    clusterObject.estateEasting = estateGroup[i].estateEasting;
                    clusterObject.estateNorthing = estateGroup[i].estateNorthing;
                    clusterObject.incidentList = String(estateGroup[i].incidentID);
                    clusterObject.crime1Count = estateGroup[i].crime1Count;
                    clusterObject.crime2Count = estateGroup[i].crime2Count;
                    clusterObject.ParentID = estateGroup[i].ParentID;
                    clusterObject.estatename = estateGroup[i].estatename;
                    clusterObject.streetname = estateGroup[i].streetname;
                    clusterObject.incidentDateDisplay = estateGroup[i].incidentDateDisplay;
                    clusterObject.incidentDateDisplayShort = estateGroup[i].incidentDateDisplayShort;
                    
                    clusterObject.centroidX = estateGroup[i].estateEasting;
                    clusterObject.centroidY = estateGroup[i].estateNorthing;
                    estateCluster.push(clusterObject);
                }
        }

        
        // Output to map
        for (var i = 0; i < estateCluster.length; i++){
            var newFeature = new OpenLayers.Feature.Vector(
                new OpenLayers.Geometry.Point(
                    estateCluster[i].centroidX, 
                    estateCluster[i].centroidY),  
                    {
                        locationID:estateCluster[i].locationID, 
                        pinType:'cluster',
                        incident1Number:estateCluster[i].crime1Count ,
                        incident2Number:estateCluster[i].crime2Count,
                        expanded:0,
                        incidentList:estateCluster[i].incidentList,
                        ParentID:estateCluster[i].ParentID
                    }, 
                    {
                        externalGraphic: '/images/pin_count.aspx?text1='+estateCluster[i].crime1Count+'&text2='+estateCluster[i].crime2Count, 
                        graphicWidth: 21, 
                       graphicHeight: (estateCluster[i].crime1Count>0&&estateCluster[i].crime2Count>0?23:12)

                    }
                );
            newFeatures.push(newFeature);
        }  
    
    
     } else {
    
        for (var i = 0; i < estateGroup.length; i++){
            var newFeature = new OpenLayers.Feature.Vector(
                new OpenLayers.Geometry.Point(
                    estateGroup[i].estateEasting, 
                    estateGroup[i].estateNorthing),  
                    {
                        locationID:estateGroup[i].locationID, 
                        pinType:'estate',
                        incident1Number:estateGroup[i].crime1Count ,
                        incident2Number:estateGroup[i].crime2Count,
                        expanded:0,
                        incidentList:estateGroup[i].incidentList
                    }, 
                    {
                        externalGraphic: '/images/pin_count.aspx?text1='+estateGroup[i].crime1Count+'&text2='+estateGroup[i].crime2Count, 
                        graphicWidth: 21, 
                        graphicHeight: (estateGroup[i].crime1Count>0&&estateGroup[i].crime2Count>0?23:12)
                    }
                );
            newFeatures.push(newFeature);
        }     
     } 
     
     
    //iterate the map features to see which are no longer required
 
    for (var i = 0; i < OSVectorLayers[1].features.length; i++){
        var thisLocationID = OSVectorLayers[1].features[i].attributes.locationID;
        var locationMatched = null;
        for (var j = 0; j < newFeatures.length; j++){
            if (newFeatures[j].attributes.locationID == thisLocationID) {
                locationMatched = newFeatures[j];
                break;
            }
        }
        
        if (locationMatched==null) {
            // no match - remove feature from map
            removedFeatures.push(OSVectorLayers[1].features[i]);
        } else {
            //matched - don't add again (remove from newFeatures array)
           newFeatures = newFeatures.without(locationMatched);
        }
    }
  
    
    if (removedFeatures.length > 0) {
        OSdestroyVectorFeatures(1, removedFeatures);
    }
    if (newFeatures.length > 0) {
        OSaddVectorFeatures(1, newFeatures);
    } 
        updateProgress('');
}
function expandCluster(feature) {

    var newFeatures = [];
    var removedFeatures = [];
    
    for (var i = 0; i < estateGroup.length; i++){
        if (estateGroup[i].ParentID == feature.attributes.ParentID ) {

            var newFeature = new OpenLayers.Feature.Vector(
                new OpenLayers.Geometry.Point(
                    estateGroup[i].estateEasting, 
                    estateGroup[i].estateNorthing),  
                    {
                        locationID:estateGroup[i].locationID, 
                        pinType:'estate',
                        incident1Number:estateGroup[i].crime1Count ,
                        incident2Number:estateGroup[i].crime2Count,
                        expanded:1,
                        incidentList:estateGroup[i].incidentList
                    }, 
                    {
                        externalGraphic: '/images/pin_count.aspx?text1='+estateGroup[i].crime1Count+'&text2='+estateGroup[i].crime2Count, 
                        graphicWidth: 21, 
                        graphicHeight: (estateGroup[i].crime1Count>0&&estateGroup[i].crime2Count>0?23:12)
                    }
                );
            newFeatures.push(newFeature);
        }  
    }

    if (newFeatures.length > 0) {
        OSaddVectorFeatures(1, newFeatures);
    }
    
    // Now remove the cluster pin
    var killFeatures = [];
    killFeatures.push(feature);
    OSVectorLayers[1].destroyFeatures(killFeatures);
}
function expandEstatePin(feature) {
    //alert(feature.attributes.locationID);
    var newFeatures = [];
    var pin1Type = 0;
    var pin2Type = 0;
    var nongeocodedIncidentList = '';
    
    for (var i = 0; i < oCrime1Incidents.length; i++){
        if(oCrime1Incidents[i].locationID == feature.attributes.locationID) {
            //if easting/northing is unknown do not show pin at all
            if (oCrime1Incidents[i].easting > 0 && oCrime1Incidents[i].northing > 0) {
                var newFeature = new OpenLayers.Feature.Vector(
                    new OpenLayers.Geometry.Point(
                        oCrime1Incidents[i].easting, 
                        oCrime1Incidents[i].northing
                    ),  
                    {
                        reference:oCrime1Incidents[i].reference, 
                        locationID:oCrime1Incidents[i].locationID, 
                        incidentID:oCrime1Incidents[i].incidentID, 
                        estateGroup:oCrime1Incidents[i].estateGroup, 
                        estatename:oCrime1Incidents[i].estatename, 
                        streetname:oCrime1Incidents[i].streetname, 
                        expanded:0,
                        incidentDateDisplay:oCrime1Incidents[i].incidentDateDisplay,
                        incidentDateDisplayShort:oCrime1Incidents[i].incidentDateDisplayShort,
                        crimeType:$(drpCrimeID).options[$(drpCrimeID).selectedIndex].text, 
                        type: "circle", radius: ( 10 + (OSgetZoom(map)*10))
                       
                    } 
                );
                newFeatures.push(newFeature);
                pin1Type += 1;
            }
            else
            {
                nongeocodedIncidentList = nongeocodedIncidentList + String(oCrime1Incidents[i].incidentID) + ',';
            }
        }
    }

    if (newFeatures.length > 0) {
        OSaddVectorFeatures(1, newFeatures);
    }
    
    //if number of pins (ie all incidents have easting/northing)
    //estate pin can be removed
    if (newFeatures.length == feature.attributes.incident1Number + feature.attributes.incident2Number) {
        var killFeatures = [];
        killFeatures.push(feature);
        OSVectorLayers[1].destroyFeatures(killFeatures);
    }
    //there are some pins to show
    else if (pin1Type > 0 || pin2Type > 0) {
        //show estate pin with reduced number of incidents
        //drop last comma
        if (nongeocodedIncidentList.lastIndexOf(',') == nongeocodedIncidentList.length){
            nongeocodedIncidentList = nongeocodedIncidentList.substring(1, nongeocodedIncidentList.length -1);
        }           
        feature.attributes.incidentList = nongeocodedIncidentList;
         var changedEstateStyle = new OpenLayers.Style({
            externalGraphic: '/images/pin_count.aspx?text1='
            + String(feature.attributes.incident1Number - pin1Type) 
            + '&text2=' + String(feature.attributes.incident2Number - pin2Type)
            });
        feature.style.externalGraphic = '/images/pin_count.aspx?text1='
        + String(feature.attributes.incident1Number - pin1Type) 
        + '&text2=' + String(feature.attributes.incident2Number - pin2Type);
        // if one of the "estate" pins dissapeared completely - need to make sure the height is reduced
        if (feature.attributes.incident1Number - pin1Type == 0 || feature.attributes.incident2Number - pin2Type == 0) {
            feature.style.graphicHeight = 12
        }
        OSVectorLayers[1].drawFeature(feature);
    }
}
    
    function pagingListBack(iNewPage, iTotal) {
        
        if (iNewPage > 0)
        {
          DisplayIncidentList(iNewPage);
          pagingUpdateButtons(iNewPage-1, iTotal)
        }
    }
    
    function pagingListForward(iNewPage, iTotal) 
    {
    
        if ((iNewPage ) <= iTotal)
        {
          DisplayIncidentList(iNewPage);
          pagingUpdateButtons(iNewPage-1, iTotal)
        }
        
    }
    
    function pagingUpdateCount() {
        $('paging_count').innerHTML = (CurrentRequirement+1) + ' of ' + RequirementTotal + '';
    }
    
    function pagingUpdateButtons(iCurrent,iTotal) {
        
        if (iCurrent < 1 ) {
            $('paging_back').style.opacity = .5;
	        $('paging_back').style.filter = 'alpha(opacity=' + 50 + ')';
        } else {
            $('paging_back').style.opacity = 1;
	        $('paging_back').style.filter = 'alpha(opacity=' + 100 + ')';
        }
                
        if ((iCurrent + 1) >= iTotal ) {
            $('paging_forward').style.opacity = .5;
	        $('paging_forward').style.filter = 'alpha(opacity=' + 50 + ')';
        } else {
            $('paging_forward').style.opacity = 1;
	        $('paging_forward').style.filter = 'alpha(opacity=' + 100 + ')';         
        }   
    
    }
    
      function InitializeRequest(sender, args)
  {
    // Check to be sure this async postback is actually 
    //   requesting the file download.
    if (sender._postBackSettings.sourceElement.id == "DownloadFile")
    {
      // Create an IFRAME.
      var iframe = document.createElement("iframe");
 
      // Get the desired region from the dropdown.
      var region = $get("Region").value;
 
      // Point the IFRAME to GenerateFile, with the
      //   desired region as a querystring argument.
      iframe.src = "GenerateFile.aspx?region=" + region + "; listincidents";
 
      // This makes the IFRAME invisible to the user.
      iframe.style.display = "none";
 
      // Add the IFRAME to the page.  This will trigger
      //   a request to GenerateFile now.
      document.body.appendChild(iframe); 
    }
  }

    
    function saveCSV()
    {
        var oListIncidentsAPI = new IncidentAPI();
        var oListIncidents = oListIncidentsAPI.readByIncidentIDArray(globallistincidents);
        
        var prm = Sys.WebForms.PageRequestManager.getInstance();
 
        // Hook the _initializeRequest event and add our own handler.
        prm.add_initializeRequest(InitializeRequest);
    }
    
    function createIncidentsCSV() {
    var selectedIncidentsCombined;
    
    selectedIncidentsCombined = selectedIncidents.join(",");
    
    window.open('csvSelectedIncidents.aspx?incidentslist=' + selectedIncidentsCombined );
}

function updatePins() {

//console.log('updatePins');

    for (var i = 0; i < OSVectorLayers[1].features.length; i++){
        if (OSVectorLayers[1].features[i].attributes.type=="circle") {
            OSVectorLayers[1].features[i].attributes.radius =  ( 10 + (OSgetZoom(map)*10))
        }
   }
   OSVectorLayers[1].redraw();
   
}
