// Initialise variables
var map;
var mManager;
var xmlDocument;
var resultBounds;

// Icon Markers
var comminfIcon;
var eduIcon;
var houseIcon;
var insulIcon;
var roadrailIcon;
var solarIcon;
var currentPos;
var currentES;
var currentPostcode;
var currentSuburbTown

var markers = [];
markers[0] = new Array();
markers[1] = new Array();
markers[2] = new Array();
markers[3] = new Array();
markers[4] = new Array();
markers[5] = new Array();
markers[6] = new Array();
var coordHash;

var noOfResults; // Number of results in the list
var initialMarkersDisplayed; // Number of markers displayed on initial search

var pType;


// You are here location image
var currentLocation = [];
currentLocation["CurrentLoc"] = new Array();
currentLocation["CurrentLoc"][0] = 6;
currentLocation["CurrentLoc"][1] = "location_pin.png";  //Set default image for "You Are Here" icon
currentLocation["CurrentLoc"][2] = "elec_sum_sml.png";  //Set default image for "Electorate Summary" icon
currentLocation["CurrentLoc"][3] = "postcode_sum_sml.png";  //Set default image for "Postcode Summary" icon
//currentLocation["CurrentLoc"][4] = "suburbtown_sum_sml.png";  //Set default image for "Suburb/Town Summary" icon

// Project type names - This has to match the project type names in the database.
var projectTypeNames = new Array();
projectTypeNames[0] = "Community Infrastructure";
projectTypeNames[1] = "Education";
projectTypeNames[2] = "Housing";
projectTypeNames[3] = "Ceiling Insulation";
projectTypeNames[4] = "Road and Rail";
projectTypeNames[5] = "Solar Hot Water";

var projectTypes = [];
projectTypes[projectTypeNames[0]] = new Array();
projectTypes[projectTypeNames[0]][0] = 0;
projectTypes[projectTypeNames[0]][1] = "chkCom";
projectTypes[projectTypeNames[0]][2] = "comminf_pin.png";
projectTypes[projectTypeNames[0]][3] = "comminf_detail.png";
projectTypes[projectTypeNames[0]][5] = "comminf_pincluster.png";
projectTypes[projectTypeNames[0]][6] = "CommunityInfrastructureDiv";
projectTypes[projectTypeNames[0]][7] = "summaryCommunityInfrastructure";
projectTypes[projectTypeNames[0]][8] = "summaryCommunityInfrastructureCountValue"; // Name of input field for count.
projectTypes[projectTypeNames[0]][9] = "summaryCommunityInfrastructureFundingValue"; // Name of input field for value.
projectTypes[projectTypeNames[0]][10] = "summaryCommunityInfrastructureSharedCountValue"; // Name of input field for shared count.
projectTypes[projectTypeNames[0]][11] = "summaryCommunityInfrastructureSharedFundingValue"; // Name of input field for shared value.

projectTypes[projectTypeNames[1]] = new Array();
projectTypes[projectTypeNames[1]][0] = 1;
projectTypes[projectTypeNames[1]][1] = "chkEdu";
projectTypes[projectTypeNames[1]][2] = "edu_pin.png";
projectTypes[projectTypeNames[1]][3] = "edu_detail.png";
projectTypes[projectTypeNames[1]][5] = "edu_pincluster.png";
projectTypes[projectTypeNames[1]][6] = "EducationDiv";
projectTypes[projectTypeNames[1]][7] = "summaryEducation";
projectTypes[projectTypeNames[1]][8] = "summaryEducationCountValue";
projectTypes[projectTypeNames[1]][9] = "summaryEducationFundingValue";
projectTypes[projectTypeNames[1]][10] = "summaryEducationSharedCountValue";
projectTypes[projectTypeNames[1]][11] = "summaryEducationSharedFundingValue";

projectTypes[projectTypeNames[2]] = new Array();
projectTypes[projectTypeNames[2]][0] = 2;
projectTypes[projectTypeNames[2]][1] = "chkHous";
projectTypes[projectTypeNames[2]][2] = "house_pinblock.png";
projectTypes[projectTypeNames[2]][3] = "house_detail.png";
projectTypes[projectTypeNames[2]][5] = "house_pincluster.png";
projectTypes[projectTypeNames[2]][6] = "HousingDiv";
projectTypes[projectTypeNames[2]][7] = "summaryHousing";
projectTypes[projectTypeNames[2]][8] = "summaryHousingCountValue";
projectTypes[projectTypeNames[2]][9] = "summaryHousingFundingValue";
projectTypes[projectTypeNames[2]][10] = "summaryHousingSharedCountValue";
projectTypes[projectTypeNames[2]][11] = "summaryHousingSharedFundingValue";

projectTypes[projectTypeNames[3]] = new Array();
projectTypes[projectTypeNames[3]][0] = 3;
projectTypes[projectTypeNames[3]][1] = "chkInsul";
projectTypes[projectTypeNames[3]][2] = "insul_pinblock.png";
projectTypes[projectTypeNames[3]][3] = "insul_detail.png";
projectTypes[projectTypeNames[3]][5] = "insul_pincluster.png";
projectTypes[projectTypeNames[3]][6] = "InsulationDiv";
projectTypes[projectTypeNames[3]][7] = "summaryInsulation";
projectTypes[projectTypeNames[3]][8] = "summaryInsulationCountValue";
projectTypes[projectTypeNames[3]][9] = "summaryInsulationFundingValue";
projectTypes[projectTypeNames[3]][10] = "summaryInsulationSharedCountValue";
projectTypes[projectTypeNames[3]][11] = "summaryInsulationSharedFundingValue";

projectTypes[projectTypeNames[4]] = new Array();
projectTypes[projectTypeNames[4]][0] = 4;
projectTypes[projectTypeNames[4]][1] = "chkRoadRail";
projectTypes[projectTypeNames[4]][2] = "roadrail_pin.png";
projectTypes[projectTypeNames[4]][3] = "roadrail_detail.png";
projectTypes[projectTypeNames[4]][5] = "roadrail_pincluster.png";
projectTypes[projectTypeNames[4]][6] = "RoadsAndRailCountDiv";
projectTypes[projectTypeNames[4]][7] = "summaryRoadAndRail";
projectTypes[projectTypeNames[4]][8] = "summaryRoadAndRailCountValue";
projectTypes[projectTypeNames[4]][9] = "summaryRoadAndRailFundingValue";
projectTypes[projectTypeNames[4]][10] = "summaryRoadAndRailSharedCountValue";
projectTypes[projectTypeNames[4]][11] = "summaryRoadAndRailSharedFundingValue";

projectTypes[projectTypeNames[5]] = new Array();
projectTypes[projectTypeNames[5]][0] = 5;
projectTypes[projectTypeNames[5]][1] = "chkSolar";
projectTypes[projectTypeNames[5]][2] = "solar_pinblock.png";
projectTypes[projectTypeNames[5]][3] = "solar_detail.png";
projectTypes[projectTypeNames[5]][5] = "solar_pincluster.png";
projectTypes[projectTypeNames[5]][6] = "SolarDiv";
projectTypes[projectTypeNames[5]][7] = "summarySolar";
projectTypes[projectTypeNames[5]][8] = "summarySolarCountValue";
projectTypes[projectTypeNames[5]][9] = "summarySolarFundingValue";
projectTypes[projectTypeNames[5]][10] = "summarySolarSharedCountValue";
projectTypes[projectTypeNames[5]][11] = "summarySolarSharedFundingValue";

var defaultCenterPoint;
var defaultZoomLevel = 4;
var markerClusterers = new Array();

// Starting Method - Load the xml document
// This is called by the getResults call back for a postcode to point lookup. 
function loadMap(xmlDoc) {

    var index = 0;
    var latOffset = 0.0005;
    var longOffset = 0.001;
    xmlDocument = xmlDoc;
    noOfResults = 0; //Number of results currently displayed in list

    coordHash = new Hash(); //Empty Hash Table
    emptyMarkers(); //Empty markers array
    initialMarkersDisplayed = 0; //Reset markers displayed total

    initialiseMap();

    while (!(xmlDocument.getElementsByTagName("Project_ID")[index] == null)) //Show results on map and results table
    {
        pType = getXMLNode(index, "Project_Type");
        var point = new GLatLng(parseFloat(getXMLNode(index, "GIS_Loc_Latitude")), parseFloat(getXMLNode(index, "GIS_Loc_Longitude")));

        point = arrangeMultiplePoints(point, index);

//        if (projectTypes[pType][0] == 0 || projectTypes[pType][0] == 1 || projectTypes[pType][0] == 4) {
            setMarker(index, point); //3
//        }
        index++;
    }

    noOfResults = index;
//    mapRemainingResults();

    // KB -You are here points
    // point2 will be used to center map on results
    var point2 = new GLatLng(parseFloat(selectedUserPoint.lat()), parseFloat(selectedUserPoint.lng()));
    // point3 will be applied latOffset and longOffset and used to set the marker You Are Here
    var point3 = new GLatLng(parseFloat(selectedUserPoint.lat()) - latOffset, parseFloat(selectedUserPoint.lng()) - longOffset);
    point2 = arrangeCurrentMarkerPoint(point2);
    setMarkerYouAreHere(point3); //3
    //setMarkerYouAreHere(resultBounds.getCenter()); //3

    markerClusterers[0] = new MarkerClusterer(map, markers[0], { maxZoom: null, gridSize: null, styles: null }, projectTypes[projectTypeNames[0]][5], 42, 35);
    markerClusterers[1] = new MarkerClusterer(map, markers[1], { maxZoom: null, gridSize: null, styles: null }, projectTypes[projectTypeNames[1]][5], 43, 35);
    markerClusterers[2] = new MarkerClusterer(map, markers[2], { maxZoom: null, gridSize: null, styles: null }, projectTypes[projectTypeNames[2]][5], 42, 35);
    markerClusterers[3] = new MarkerClusterer(map, markers[3], { maxZoom: null, gridSize: null, styles: null }, projectTypes[projectTypeNames[3]][5], 42, 35);
    markerClusterers[4] = new MarkerClusterer(map, markers[4], { maxZoom: null, gridSize: null, styles: null }, projectTypes[projectTypeNames[4]][5], 42, 35);
    markerClusterers[5] = new MarkerClusterer(map, markers[5], { maxZoom: null, gridSize: null, styles: null }, projectTypes[projectTypeNames[5]][5], 42, 35);
    if (forceAddressSearchCheck == true) {
        markerClusterers[6] = new MarkerClusterer(map, markers[6], { maxZoom: null, gridSize: null, styles: null }, currentLocation["CurrentLoc"][1], 23, 32);
    }
    else if (forcePostcodeSearchCheck == true) {
        markerClusterers[6] = new MarkerClusterer(map, markers[6], { maxZoom: null, gridSize: null, styles: null }, currentLocation["CurrentLoc"][3], 67, 34);
    }
//    else if (forceSuburbOrTownSearchCheck == true) {
//        markerClusterers[6] = new MarkerClusterer(map, markers[6], { maxZoom: null, gridSize: null, styles: null }, currentLocation["CurrentLoc"][4], 67, 34);
//    }
    else {
        markerClusterers[6] = new MarkerClusterer(map, markers[6], { maxZoom: null, gridSize: null, styles: null }, currentLocation["CurrentLoc"][2], 67, 34);
    }

    //Center map on results
    if (initialMarkersDisplayed != 0) {
        //alert("map.getBoundsZoomLevel(resultBounds) = " + (map.getBoundsZoomLevel(resultBounds)));
        //alert("point2.lat() = " + point2.lat());
        //alert("point2.lng() = " + point2.lng());
        // KB - Auto zoom to do best fit and center the map on you are here.
        if (isPostcodeSelected == true || forcePostcodeSearchCheck == true)
        {
//            map.setCenter(new google.maps.LatLng(point2.lat(), point2.lng()), map.getBoundsZoomLevel(resultBounds));
            map.setCenter(resultBounds.getCenter(), map.getBoundsZoomLevel(resultBounds));
            map.panDirection(0, 0.04505); //Pan a little so that the most north marker is also in view
        }
        else if (isSuburbOrTownSelected == true || forceSuburbOrTownSearchCheck == true)
        {
            map.setCenter(resultBounds.getCenter(), map.getBoundsZoomLevel(resultBounds));
        }
        else if (isElectorateSelected == true)
        {
            //            map.setCenter(resultBounds.getCenter(), map.getBoundsZoomLevel(resultBounds)); // Set to center of the map results.
            map.setCenter(new google.maps.LatLng(point2.lat(), point2.lng()), map.getBoundsZoomLevel(resultBounds));
            map.panDirection(0, 0.04505); //Pan a little so that the most north marker is also in view
        }
        else
        {
            map.setCenter(new google.maps.LatLng(point2.lat(), point2.lng()), map.getBoundsZoomLevel(resultBounds) + 1);
            map.panDirection(0, 0.04505); //Pan a little so that the most north marker is also in view
        }
        //map.setCenter(new google.maps.LatLng(point2.lat(), point2.lng()), 15);
        //map.setCenter(resultBounds.getCenter(), Math.min(map.getBoundsZoomLevel(resultBounds), 15));
        //map.panDirection(0, 0.04505); //Pan a little so that the most north marker is also in view
    }
    else {
        map.setCenter(defaultCenterPoint, defaultZoomLevel);
    }

    var resultTableNode = xmlDocument.getElementsByTagName("resultTable")[0];
    if (resultTableNode.childNodes.length != 0) {
        if (typeof (resultTableNode.textContent) != "undefined") {
            document.getElementById("resultList").innerHTML = "<table>" + resultTableNode.textContent + "</table>";
        }
        else {
            document.getElementById("resultList").innerHTML = "<table>" + resultTableNode.childNodes[0].nodeValue + "</table>";
        }
    }
    //Hide markers and results if their checkbox is unticked
    initialResultFilter();

}

// Initialise map, this is called on the page load.
function initialiseMap() {

    // Hide the overlay on first load.
    $('#overlay').hide();

    if (map == null) {
        map = new GMap2(document.getElementById("NationBuildingMap"));

        map.addControl(new GLargeMapControl3D());
        map.addControl(new GMenuMapTypeControl());
        map.addMapType(G_PHYSICAL_MAP);
        map.setMapType(G_PHYSICAL_MAP);

        defaultCenterPoint = new GLatLng(-28.0, 135.7333984375);
        map.setCenter(defaultCenterPoint, defaultZoomLevel);

        //2010-03-15 LD2558. Commented out, no longer required regarding not showing Electorate buttons request
//        // Add custom control - Electorate buttons - to the map
//        map.addControl(new electorateOverlayControl());

        //2010-03-15 LD2558. Commented out, no longer required regarding not showing Electorate buttons request
//        // Add custom control - Electorate message - to the map but hide it
//        map.addControl(new electorateMessageControl());

        // Add custom control - Suburb/Town suggestion to the map but hide it
        map.addControl(new suburbTownSuggestionControl());

        createIcons();
    }

    // Set marker clusters for all 6 types
    if (markerClusterers.length != 0) {
        for (var index = 0; index < 7; index++) {
            markerClusterers[index].clearMarkers();
        }
    }

    resultBounds = new GLatLngBounds();
    mManager = new GMarkerManager(map);
}



// Reset markers to null
function emptyMarkers() {
    markers[0] = new Array();
    markers[1] = new Array();
    markers[2] = new Array();
    markers[3] = new Array();
    markers[4] = new Array();
    markers[5] = new Array();
    markers[6] = new Array(); //You Are Here or Electorate Summary marker 
}

// Initialise and create marker icons
function createIcons() {
    // Commmunity Infrastructure icon marker
    comminfIcon = new GIcon(G_DEFAULT_ICON);
    comminfIcon.image = "../images/" + projectTypes[projectTypeNames[0]][2];
    comminfIcon.shadow = "../images/pin_shadow.png";
    comminfIcon.iconSize = new GSize(23, 32);
    comminfIcon.iconAnchor = new GPoint(12, 32);
    comminfIcon.infoWindowAnchor = new GPoint(12, 0);
    projectTypes[projectTypeNames[0]][4] = comminfIcon;

    // Education icon marker
    eduIcon = new GIcon(G_DEFAULT_ICON);
    eduIcon.image = "../images/" + projectTypes[projectTypeNames[1]][2];
    eduIcon.shadow = "../images/pin_shadow.png";
    eduIcon.iconSize = new GSize(23, 32);
    eduIcon.iconAnchor = new GPoint(12, 32);
    eduIcon.infoWindowAnchor = new GPoint(12, 0);
    projectTypes[projectTypeNames[1]][4] = eduIcon;

    // Housing icon marker
    houseIcon = new GIcon(G_DEFAULT_ICON);
    houseIcon.image = "../images/" + projectTypes[projectTypeNames[2]][2];
    houseIcon.shadow = "../images/pinblock_shadow.png";
    houseIcon.iconSize = new GSize(25, 24);
    houseIcon.iconAnchor = new GPoint(12, 16);
    houseIcon.infoWindowAnchor = new GPoint(16, 0);
    projectTypes[projectTypeNames[2]][4] = houseIcon;

    // Insulation icon marker
    insulIcon = new GIcon(G_DEFAULT_ICON);
    insulIcon.image = "../images/" + projectTypes[projectTypeNames[3]][2];
    insulIcon.shadow = "../images/pinblock_shadow.png";
    insulIcon.iconSize = new GSize(25, 24);
    insulIcon.iconAnchor = new GPoint(12, 16);
    insulIcon.infoWindowAnchor = new GPoint(16, 0);
    projectTypes[projectTypeNames[3]][4] = insulIcon;

    // Road and Rail icon marker
    roadrailIcon = new GIcon(G_DEFAULT_ICON);
    roadrailIcon.image = "../images/" + projectTypes[projectTypeNames[4]][2];
    roadrailIcon.shadow = "../images/pin_shadow.png";
    roadrailIcon.iconSize = new GSize(23, 32);
    roadrailIcon.iconAnchor = new GPoint(12, 32);
    roadrailIcon.infoWindowAnchor = new GPoint(12, 0);
    projectTypes[projectTypeNames[4]][4] = roadrailIcon;

    // Solar icon marker
    solarIcon = new GIcon(G_DEFAULT_ICON);
    solarIcon.image = "../images/" + projectTypes[projectTypeNames[5]][2];
    solarIcon.shadow = "../images/pinblock_shadow.png";
    solarIcon.iconSize = new GSize(25, 24);
    solarIcon.iconAnchor = new GPoint(12, 16);
    solarIcon.infoWindowAnchor = new GPoint(16, 0);
    projectTypes[projectTypeNames[5]][4] = solarIcon;

    // You Are Here icon marker
    currentPos = new GIcon(G_DEFAULT_ICON);
    currentPos.image = "../images/" + currentLocation["CurrentLoc"][1];
    currentPos.shadow = "../images/pin_shadow.png";
    currentPos.iconSize = new GSize(23, 32);
    currentPos.iconAnchor = new GPoint(12, 32);
    currentPos.infoWindowAnchor = new GPoint(12, 0);
    currentLocation["CurrentLoc"][5] = currentPos;

    // Electorate Summary icon marker
    currentES = new GIcon();    //Reason of not use G_DEFAULT_ICON here: to have the entire icon image be clickable
    currentES.image = "../images/" + currentLocation["CurrentLoc"][2];
    currentES.shadow = "../images/pin_shadow.png";
    currentES.iconSize = new GSize(67, 34);
    currentES.iconAnchor = new GPoint(33, 34);
    currentES.infoWindowAnchor = new GPoint(33, 0);
    currentLocation["CurrentLoc"][6] = currentES;

    // Postcode Summary icon marker
    currentPostcode = new GIcon(); //Reason of not use G_DEFAULT_ICON here: to have the entire icon image be clickable
    currentPostcode.image = "../images/" + currentLocation["CurrentLoc"][3];
    currentPostcode.shadow = "../images/pin_shadow.png";
    currentPostcode.iconSize = new GSize(67, 34);
    currentPostcode.iconAnchor = new GPoint(33, 34);
    currentPostcode.infoWindowAnchor = new GPoint(33, 0);
    currentLocation["CurrentLoc"][7] = currentPostcode;

//    // Suburb/Town Summary icon marker
//    currentSuburbTown = new GIcon(); //Reason of not use G_DEFAULT_ICON here: to have the entire icon image be clickable
//    currentSuburbTown.image = "../images/" + currentLocation["CurrentLoc"][4];
//    currentSuburbTown.shadow = "../images/pin_shadow.png";
//    currentSuburbTown.iconSize = new GSize(67, 34);
//    currentSuburbTown.iconAnchor = new GPoint(33, 34);
//    currentSuburbTown.infoWindowAnchor = new GPoint(33, 0);
//    currentLocation["CurrentLoc"][8] = currentSuburbTown;
}

function setMarker(index, point) //Create marker 3
{
    markers[(projectTypes[pType][0])].push(new GMarker(point, projectTypes[pType][4])); //GMarker(position,custom icon)
    projectTypeIndex = projectTypes[pType][0];

    if (document.getElementById(projectTypes[pType][1]).checked) {
        resultBounds.extend(point); //Include marker in bounds reference
        initialMarkersDisplayed = initialMarkersDisplayed + 1;
    }

    createInformationWindow(markers[projectTypeIndex][(markers[projectTypeIndex].length - 1)], index); //4
}

// Update the properties of You Are Here or Electorate and Postcode Summary icons then create markers
function setMarkerYouAreHere(point)
{
    var title = "";
    var description = "";

    if (forceAddressSearchCheck == true) {
        markers[(currentLocation["CurrentLoc"][0])].push(new GMarker(point, currentLocation["CurrentLoc"][5])); //GMarker(position,custom icon)
        projectTypeIndex = currentLocation["CurrentLoc"][0];
        resultBounds.extend(point); //Include marker in bounds reference
        initialMarkersDisplayed = initialMarkersDisplayed + 1;
        //Display the search location information window
        title = "Your current search location";
        description = userQuery;
        createInformationWindowForYouAreHere(markers[projectTypeIndex][(markers[projectTypeIndex].length - 1)], title, description); //4
    }
    else if (forcePostcodeSearchCheck == true) {
        markers[(currentLocation["CurrentLoc"][0])].push(new GMarker(point, currentLocation["CurrentLoc"][7])); //GMarker(position,custom icon)
        projectTypeIndex = currentLocation["CurrentLoc"][0];
        resultBounds.extend(point); //Include marker in bounds reference
        initialMarkersDisplayed = initialMarkersDisplayed + 1;
        //Display the search location information window
        title = "Your current search location";
        description = providedPostcode;
        createInformationWindowForYouAreHere(markers[projectTypeIndex][(markers[projectTypeIndex].length - 1)], title, description); //4
    }
//    else if (forceSuburbOrTownSearchCheck == true) {
////        markers[(currentLocation["CurrentLoc"][0])].push(new GMarker(point, currentLocation["CurrentLoc"][8])); //GMarker(position,custom icon)
//        projectTypeIndex = currentLocation["CurrentLoc"][0];
//        resultBounds.extend(point); //Include marker in bounds reference
//        initialMarkersDisplayed = initialMarkersDisplayed + 1;
//        //Display the search location information window
////        title = "Your current search location";
////        description = providedPostcode;
////        createInformationWindowForYouAreHere(markers[projectTypeIndex][(markers[projectTypeIndex].length - 1)], title, description); //4
//    }
    else if (isElectorateSelected == true) {
        markers[(currentLocation["CurrentLoc"][0])].push(new GMarker(point, currentLocation["CurrentLoc"][6])); //GMarker(position,custom icon)
        projectTypeIndex = currentLocation["CurrentLoc"][0];
        resultBounds.extend(point); //Include marker in bounds reference
        initialMarkersDisplayed = initialMarkersDisplayed + 1;
    }
}

function createInformationWindowForYouAreHere(marker, title, description) {

    var infoWindow = buildInfoWindowMessage(title, "", description, "location_detail.png", -1);
    GEvent.addListener(marker, "click", function() //When user clicks, open information window for that marker
    {
        retrieveResultsList(0);
        marker.openInfoWindowHtml(infoWindow);
    });   
}

function createInformationWindow(marker, index) {
    //var projectID = getXMLNode(index, "Project_ID");
    var title = getXMLNode(index, "Title");
    var snapshot = getXMLNode(index, "Snapshot");
    var description = getXMLNode(index, "Description");

    var infoWindow = buildInfoWindowMessage(title, "", snapshot, projectTypes[pType][3], index);

    GEvent.addListener(marker, "click", function() //When user clicks, open information window for that marker
    {
        retrieveResultsList(0);
        marker.openInfoWindowHtml(infoWindow);
    });
}

function getXMLNode(index, node) //Get XML Node value 5
{
    try {
        var parentXMLElement = xmlDocument.getElementsByTagName("result")[index];
        var parentXMLnode = parentXMLElement.getElementsByTagName(node)[0];
        var childNodeValue = parentXMLnode.childNodes[0].nodeValue;
        return childNodeValue;
    } catch (e) {
        return null;
    }
    return null;
}

//-----filter markers-----------------------------------------------
function filterMarkers(chkBox, serviceTypeToFilter) {
    if (chkBox.checked) {
        showServiceType(projectTypes[serviceTypeToFilter][0]);
        showServiceTypeResults(serviceTypeToFilter);
        showServiceTypeResultsGroup(projectTypes[serviceTypeToFilter][6]);
        showServiceTypeResultsSummary(projectTypes[serviceTypeToFilter][7]);
    }
    else {
        hideServiceType(projectTypes[serviceTypeToFilter][0]);
        hideServiceTypeResults(serviceTypeToFilter);
        hideServiceTypeResultsGroup(projectTypes[serviceTypeToFilter][6]);
        hideServiceTypeResultsSummary(projectTypes[serviceTypeToFilter][7]);
    }

    // If Electorate or Postcode search is active,
    // Then Calculate the total count from the selected project types.
    if (document.getElementById('summaryTotalCountValue') != null) {
        var totalCount = 0;
        for (var index = 0; index < projectTypeNames.length; index++) {
            var projectTypeName = projectTypeNames[index];
            if (document.getElementById(projectTypes[projectTypeName][1]).checked) {
                totalCount += parseInt(document.getElementById(projectTypes[projectTypeName][8]).value, 10);
            }
        }

        document.getElementById('summaryTotalCountValue').firstChild.nodeValue = totalCount;
    }

    // and Calculate the total shared count from the selected project types.
    if (document.getElementById('summaryTotalSharedCountValue') != null) {
        var totalSharedCount = 0;
        for (var index = 0; index < projectTypeNames.length; index++) {
            var projectTypeName = projectTypeNames[index];
            if (document.getElementById(projectTypes[projectTypeName][1]).checked) {
                totalSharedCount += parseInt(document.getElementById(projectTypes[projectTypeName][10]).value, 10);
            }
        }

        document.getElementById('summaryTotalSharedCountValue').firstChild.nodeValue = totalSharedCount;
    }

    // Calculate the 'summaryTotalFundingValue' from the funding values.
    // Format funding value into currency.
    if (document.getElementById('summaryTotalFundingValue') != null) {
        var totalFunding = 0;
        for (var index = 0; index < projectTypeNames.length; index++) {
            var projectTypeName = projectTypeNames[index];
            if (document.getElementById(projectTypes[projectTypeName][1]).checked) {
                totalFunding += parseFloat(document.getElementById(projectTypes[projectTypeName][9]).value);
            }
        }
        totalFunding = Math.round(totalFunding);

        document.getElementById('summaryTotalFundingValue').firstChild.nodeValue = totalFunding;
        $('#summaryTotalFundingValue').formatCurrency();
        // Trim the cents from the currency. The formatCurreny method above is not able to drop the decimals due to a bug in the javascript.
        $('#summaryTotalFundingValue').text($('#summaryTotalFundingValue').text().substr(0, $('#summaryTotalFundingValue').text().length - 3));
        if ($('#summaryTotalFundingValue').text() == "$0")
            $('#summaryTotalFundingValue').text("N/A");
    }

    // Calculate the 'summaryTotalSharedFundingValue' from the funding values.
    // Format funding value into currency.
    if (document.getElementById('summaryTotalSharedFundingValue') != null) {
        var totalSharedFunding = 0;
        for (var index = 0; index < projectTypeNames.length; index++) {
            var projectTypeName = projectTypeNames[index];
            if (document.getElementById(projectTypes[projectTypeName][1]).checked) {
                totalSharedFunding += parseFloat(document.getElementById(projectTypes[projectTypeName][11]).value);
            }
        }
        totalSharedFunding = Math.round(totalSharedFunding);

        document.getElementById('summaryTotalSharedFundingValue').firstChild.nodeValue = totalSharedFunding;
        $('#summaryTotalSharedFundingValue').formatCurrency();
        // Trim the cents from the currency. The formatCurreny method above is not able to drop the decimals due to a bug in the javascript.
        $('#summaryTotalSharedFundingValue').text($('#summaryTotalSharedFundingValue').text().substr(0, $('#summaryTotalSharedFundingValue').text().length - 3));
        if ($('#summaryTotalSharedFundingValue').text() == "$0")
            $('#summaryTotalSharedFundingValue').text("N/A");
    }

    // We now need to update the InfoWindow in the map.
    description = $('<div>').append($('#summaryBlock').clone()).remove().html();
    
    while (description.indexOf("id=summary", 0) != -1) {
        description = description.replace("id=summary", "id=iWindowSummary");
    }
    
    $('#iWindowSummaryBlock').replaceWith(description);
}

function initialResultFilter() {
    for (var index = 0; index < projectTypeNames.length; index++)
    {
        var projectTypeName = projectTypeNames[index];
        if (!document.getElementById(projectTypes[projectTypeName][1]).checked) {
            filterMarkers(document.getElementById(projectTypes[projectTypeName][1]), projectTypeName);
        }
    }

    // Collapse the project categories by default.
    $('.projectCategoryHead').each(function() {
       CategoryExpandMinimise($(this));
    });
}

function showServiceType(projectTypeIndex) {

    if (markerClusterers.length != 0) {
        markerClusterers[projectTypeIndex].chkShow();
        markerClusterers[projectTypeIndex].resetViewport();
    }
}

function hideServiceType(projectTypeIndex) {

    if (markerClusterers.length != 0)
        markerClusterers[projectTypeIndex].chkHide();

}

function showServiceTypeResults(projectType) {
    for (var index = 0; index < noOfResults; index++) {
        var resultLine = document.getElementById("result" + index.toString());

        if (resultLine.getAttribute("projecttype") == projectType) {
            resultLine.style.display = "block";
        }
    }
}

function hideServiceTypeResults(projectType) {
    for (var index = 0; index < noOfResults; index++) {
        var resultLine = document.getElementById("result" + index.toString());
        if (resultLine.getAttribute("projecttype") == projectType) {
            resultLine.style.display = "none";
        }
    }
}

function showServiceTypeResultsGroup(projectType) {
    $('#' + projectType).show();
}

function hideServiceTypeResultsGroup(projectType) {
    $('#' + projectType).hide();
}

function showServiceTypeResultsSummary(projectType) {
    $('#' + projectType).show();
}

function hideServiceTypeResultsSummary(projectType) {
    $('#' + projectType).hide();
}

function appendResultTable(index) {

    resultTable += "<tr id=\"result" + noOfResults.toString() + "\" projecttype=\"" + pType + "\" style=\"display:block;\">" +
    "<td style=\"width:30px\"><img align=\"center\" src=\"../images/" + projectTypes[pType][2] + "\" alt=\"" + projectTypes[pType][2] + "\"/></td>" +
    "<td style=\"width:450px\"><b><a href='javascript:retrieveResultsList(" + index + ");'  onclick='retrieveDetails(" + index + ");'>" + getXMLNode(index, "Project_ID") + " - " + getXMLNode(index, "Title") + "</a></b><br/>";

    var description = getXMLNode(index, "Description");
    if (description != null)
        resultTable += description + "</td>";
    else
        resultTable += "<br /></td>";

    resultTable += "<td style=\"width:90px\">" + getXMLNode(index, "Status") + "</td></tr>";
    noOfResults = noOfResults + 1;
}

//--------- Multiple Points ---------------
function arrangeMultiplePoints(point, index) //Recursive function for singular points
{
    var newPoint = point;
    var projectInformation;
    var pointString = point.lat().toString() + "," + point.lng().toString();

    switch (pType) {
        case projectTypeNames[0]:
        case projectTypeNames[1]:
        case projectTypeNames[2]:
        case projectTypeNames[3]:
        case projectTypeNames[5]:
        case projectTypeNames[4]:
            if (coordHash.hasItem(pointString))
                newPoint = arrangeMultiplePoints(new GLatLng(point.lat(), point.lng() + 0.001), index);
            else
                coordHash.setItem(pointString, "");
            break;
        default:

            var title = getXMLNode(index, "Title");
            var projectID = getXMLNode(index, "Project_ID");
            var snapshot = getXMLNode(index, "Snapshot");
            var projectType = getXMLNode(index, "Project_Type");
            var postcode = getXMLNode(index, "Postcode");

            projectInformation = coordHash.getItem(pointString);

            if (!coordHash.hasItem(pointString) || projectInformation == "")
                projectInformation = new Array(6);

            projectInformation[projectTypes[pType][0]] = buildInfoWindowMessage(title, postcode, snapshot, projectTypes[pType][3], index);
            coordHash.setItem(pointString, projectInformation);
    }
    return newPoint;
}

function mapRemainingResults() {
    var point;
    var pointString;
    var infoWindows;
    var markerOffset = 0.01;
    for (var i in coordHash.items) {
        pointString = i.split(",");
        infoWindows = coordHash.items[i];

        if (infoWindows[2] != null) {
            point = new GLatLng(parseFloat(pointString[0]), parseFloat(pointString[1]));
            markers[2].push(new GMarker(point, projectTypes[projectTypeNames[2]][4]));
            setBlockMarker(markers[2][(markers[2].length - 1)], infoWindows[2], projectTypes[projectTypeNames[2]][1]);
        }

        if (infoWindows[3] != null) {
            point = new GLatLng(parseFloat(pointString[0]), parseFloat(pointString[1]) + markerOffset);
            markers[3].push(new GMarker(point, projectTypes[projectTypeNames[3]][4]));
            setBlockMarker(markers[3][(markers[3].length - 1)], infoWindows[3], projectTypes[projectTypeNames[3]][1]);
        }

        if (infoWindows[5] != null) {
            point = new GLatLng(parseFloat(pointString[0]), parseFloat(pointString[1]) - markerOffset);
            markers[5].push(new GMarker(point, projectTypes[projectTypeNames[5]][4]));
            setBlockMarker(markers[5][(markers[5].length - 1)], infoWindows[5], projectTypes[projectTypeNames[5]][1]);
        }
    }
}

function setBlockMarker(marker, informationWindow, chkBox) {

    GEvent.addListener(marker, "click", function() {
        retrieveResultsList(0);
        marker.openInfoWindowHtml("<div style='line-height:1.4em;font-size:12px'>" + informationWindow + "</div>");
    });

    if (document.getElementById(chkBox).checked) {
        resultBounds.extend(marker.getLatLng());
        initialMarkersDisplayed = initialMarkersDisplayed + 1;
    }
}



function arrangeCurrentMarkerPoint(point) //KB - Create you are here marker
{
    var newPoint = point;
    var projectInformation;
    var multipleProjectStart = "<div style='line-height:1.4em;font-size:10px'><table width='330px;'>";
    var pointString = point.lat().toString() + "," + point.lng().toString();

    projectInformation = coordHash.getItem(pointString);
    if (!coordHash.hasItem(pointString) || projectInformation == "") {

        projectInformation = new Array(6);
        projectInformation[0] = multipleProjectStart + "<tr><td colspan='2'><b>" + "test";
        projectInformation[0] += "</b></td></tr><tr>";
        projectInformation[0] += "</table></div>";

        coordHash.setItem(pointString, projectInformation);
    }
    multipleProjectStart += "</div>";
    return newPoint;
}

//Hash Table Code
function Hash() {
    this.length = 0;
    this.items = new Array();
    for (var i = 0; i < arguments.length; i += 2) {
        if (typeof (arguments[i + 1]) != 'undefined') {
            this.items[arguments[i]] = arguments[i + 1];
            this.length++;
        }
    }

    this.removeItem = function(in_key) {
        var tmp_previous;
        if (typeof (this.items[in_key]) != 'undefined') {
            this.length--;
            tmp_previous = this.items[in_key];
            delete this.items[in_key];
        }

        return tmp_previous;
    }

    this.getItem = function(in_key) {
        return this.items[in_key];
    }

    this.setItem = function(in_key, in_value) {
        var tmp_previous;
        if (typeof (in_value) != 'undefined') {
            if (typeof (this.items[in_key]) == 'undefined') {
                this.length++;
            }
            else {
                tmp_previous = this.items[in_key];
            }

            this.items[in_key] = in_value;
        }

        return tmp_previous;
    }

    this.hasItem = function(in_key) {
        return typeof (this.items[in_key]) != 'undefined';
    }
}


function buildInfoWindowMessage(title, postcode, description, icon, index) {
    var url = "";

    if (index != -1)
        url = "</br><a href='javascript:retrieveDetails(" + index + ");' onclick='retrieveDetails(" + index + ");'>More<br />Details</a><br /><br />";

    var infoWindow = "<div style='line-height:1.2em; font-size:10pt;'><table style='width:340px;'>";
    infoWindow += "<tr>";
    infoWindow += "<td style='width:50px; text-align:center;line-height:1em; font-size:10pt; vertical-align:top;'>"
    infoWindow += "<p>"
    infoWindow += "<img src='../images/" + icon + "' style='border:0px; padding-bottom:5px;' />";
    infoWindow += url;
    infoWindow += "</p>";
    infoWindow += "</td>";
    infoWindow += "<td style='width:290px; padding-left:5px; vertical-align:top;'>";
    infoWindow += "<p>";

    if (postcode != "") {
        //Replace apostrophe with single quote to display correctly
        title = title.replace(/&apos;/gi, "'");
        infoWindow += "<strong>" + title + " - " + postcode + "</strong><br />";
    }
    else {
        //Replace apostrophe with single quote to display correctly
        title = title.replace(/&apos;/gi, "'");
        infoWindow += "<strong>" + title + "</strong><br />";
    }

    //Replace apostrophe with single quote to display correctly
    description = description.replace(/&apos;/gi, "'");
    infoWindow += description;
    infoWindow += "</p>";
    infoWindow += "</td>";
    infoWindow += "</tr>";
    infoWindow += "</table></div>";





    return infoWindow;
}

function CategoryExpandMinimise(obj) {
    $(obj).next().next().next('.projectCategoryBody').toggle();
    if ($(obj).next().next().next('.projectCategoryBody').is(':visible')) {
        $(obj).html("<img align='center' src='/mycommunity/images/mycomm_results_minimise.png' alt='Minimise' />");
    }
    else {
        $(obj).html("<img align='center' src='/mycommunity/images/mycomm_results_expand.png' alt='Expand' />");
    }
}

function CategoryExpandMinimiseProject(obj) {
    $(obj).next().next('.projectCategoryBody').toggle();
    if ($(obj).next().next('.projectCategoryBody').is(':visible')) {
        $(obj).prev().html("<img align='center' src='/mycommunity/images/mycomm_results_minimise.png' alt='Minimise' />");
    }
    else {
        $(obj).prev().html("<img align='center' src='/mycommunity/images/mycomm_results_expand.png' alt='Expand' />");
    }
}

function CategoryExpandMinimiseImage(obj) {
    $(obj).next().next().next().next('.projectCategoryBody').toggle();
    if ($(obj).next().next().next().next('.projectCategoryBody').is(':visible')) {
        $(obj).next().html("<img align='center' src='/mycommunity/images/mycomm_results_minimise.png' alt='Minimise' />");
    }
    else {
        $(obj).next().html("<img align='center' src='/mycommunity/images/mycomm_results_expand.png' alt='Expand' />");
    }
}

// A suburbTownSuggestionControl is a GControl that displays the suggestions
// for other close suburb/town matches. When the user enters a suburb/town that
// has more than one location, e.g. Richmond is in six locations
// Richmond, NSW, 2753
// Richmond, QLD, 4740
// Richmond, QLD, 4822
// Richmond, SA, 5033
// Richmond, TAS, 7025
// Richmond, VIC, 3121
function suburbTownSuggestionControl() {
}
suburbTownSuggestionControl.prototype = new GControl();

// Creates a one DIV for each of the buttons and places them in a container
// DIV which is returned as our control element. We add the control to
// to the map container and return the element for the map class to
// position properly.
suburbTownSuggestionControl.prototype.initialize = function(map) {
    var container = document.createElement("div");

    var messageDiv = document.createElement("div");
    messageDiv.setAttribute('id', 'suburbTownSuggestionMessage');
    //messageDiv.appendChild(document.createTextNode("<p>We have found multiple results for the name \"{0}\" did you mean one of the following options?</p>{1}"));

    container.appendChild(messageDiv);

    map.getContainer().appendChild(container);
    $('div#suburbTownSuggestionMessage').addClass("mapDisplaySuburbTownSuggestionMessage");
    $('#suburbTownSuggestionMessage').hide();
    return container;
}

// By default, the control will appear in the top left corner of the
// map with 100 pixels of padding.
suburbTownSuggestionControl.prototype.getDefaultPosition = function() {
    return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(100, 100));
}

