var userQuery;
var selectedUserPoint; //KB - You are here point
var providedElectorateName = ""; //Will be used for this js file only
var providedPostcode = ""; //Will be used for this js file only
var providedSuburbOrTown = ""; //Will be used for this js file only
//2010-03-15 LD2558. The below line is commented out, no longer required regarding not showing Electorate buttons request
//var displayDiv; //Declared as a global variable here for further uses accross js files
var isElectorateSelected = false; //Declared as a global variable here for further uses accross js files
var isPostcodeSelected = false; //Declared as a global variable here for further uses accross js files
var isSuburbOrTownSelected = false; //Declared as a global variable here for further uses accross js files
var forceAddressSearchCheck = false; //Declared as a global variable here for further uses accross js files
var forceElectorateSearchCheck = false; //Declared as a global variable here for further uses accross js files
var forcePostcodeSearchCheck = false; //Declared as a global variable here for further uses accross js files
var forceSuburbOrTownSearchCheck = false; //Declared as a global variable here for further uses accross js files
var doSuburbTownSearch = false; //To force a suburb/town search, even though there are multiple suburb/town, state, postcode combinations.
//2010-03-15 LD2558. Commented out, no longer required regarding not showing Electorate buttons request
//var addMapClickCount = 0;   //Declared as a global variable here for further uses accross js files
var electorateOverlayPolygons = new Array();   //Declared as a global variable here for further uses accross js files
//2010-03-15 LD2558. The below line is commented out, no longer required regarding not showing Electorate buttons request
//var currentElectorate = -1; //Declared as a global variable here for further uses accross js files
var asAtDateText = "*As at 06/07/2010"; // Update this whenever a data refresh is performed.

$(document).ready(function() {
	// monitor electorate select: if an electorate is chosen, clear the address field
	$('#electorateSelect').change(function() {
		$("#txtSearch").val("");
	});
});

// called on keypress in address field
function checkEnter(e) {
	// typing in address field, so reset electorate
	if ($("#electorateSelect").attr("selectedIndex") > 0) $("#electorateSelect option[value='DEFAULT']").attr('selected', 'selected');
	
	// check to see if it is the enter key that has been pressed.
    if (e.keyCode == 13) {
        retreiveUserLocation();
        return false;
    }
    return true;
}

// called on keypress in suburb or town field
function checkEnterForSuburbTown(e) {
	// typing in suburb or town field, so reset electorate
	if ($("#electorateSelect").attr("selectedIndex") > 0) $("#electorateSelect option[value='DEFAULT']").attr('selected', 'selected');
	
	// check to see if it is the enter key that has been pressed.
    if (e.keyCode == 13) {
        retreiveSuburbTown();
        return false;
    }
    return true;
}

// called on keypress in postcode field
function checkEnterForPostcode(e) {
	// typing in postcode field, so reset electorate
	if ($("#electorateSelect").attr("selectedIndex") > 0) $("#electorateSelect option[value='DEFAULT']").attr('selected', 'selected');
	
	// check to see if it is the enter key that has been pressed.
    if (e.keyCode == 13) {
        retreivePostcode();
        return false;
    }
    return true;
}

// Called when the param is set.
function forcesearch(query) {
    document.getElementById("txtSearch").value = query;
    initialiseMap();
    $('#suburbTownSuggestionMessage').hide();
    retreiveUserLocation();
}

function retrieveDetails(index) {

    var resultDetails = "<div><b><a href='javascript:retrieveResultsList(" + index + ");' onclick='retrieveResultsList(" + index + ");'><img src='../images/results_back.png' alt='Return to search results' style='Border:none'/></a></b><br /><br />";

    var title = getXMLNode(index, "Title");
    if (title != null)
        //Replace apostrophe with single quote to display correctly
        title = title.replace(/&apos;/gi, "'");
        resultDetails += "<b>Title:&nbsp;</b>" + title + "<br />";

    var projecttype = getXMLNode(index, "Project_Type");
    if (projecttype != null)
        resultDetails += "<b>Project Type:&nbsp;</b>" + projecttype + "<br />";

    var snapshot = getXMLNode(index, "Snapshot");
    if (snapshot != null)
        //Replace apostrophe with single quote to display correctly
        snapshot = snapshot.replace(/&apos;/gi, "'");
        resultDetails += "<b>Snapshot:&nbsp;</b>" + snapshot + "<br />";

    var description = getXMLNode(index, "Description");
    if (description != null)
        resultDetails += "<b>Description:&nbsp;</b>" + description + "<br />";

    var program = getXMLNode(index, "Program");
    if (program != null)
        resultDetails += "<b>Program:&nbsp;</b>" + program + "<br />";

    var approvedFunding = getXMLNode(index, "Approved_Funding");
    if (approvedFunding != null)
        resultDetails += "<b>Australian Government Funding:</b>&nbsp;" + approvedFunding + "<br />";

    var agency = getXMLNode(index, "Agency");
    if (agency != null)
        resultDetails += "<b>Agency:</b>&nbsp;" + agency + "<br />";

    var status = getXMLNode(index, "Status");
    if (status != null)
        resultDetails += "<b>Status:</b>&nbsp;" + status + "<br />";

    var commencementDate = getXMLNode(index, "Commencement_Date");
    if (commencementDate != null)
        resultDetails += "<b>Commencement Date:</b>&nbsp;" + commencementDate + "<br />";

    var completionDate = getXMLNode(index, "Completion_Date");
    if (completionDate != null)
        resultDetails += "<b>Completion Date:</b>&nbsp;" + completionDate + "<br />";

    var PartnerOrg1 = getXMLNode(index, "Partner_Organisation_1");
    if (PartnerOrg1 != null)
        resultDetails += "<b>Partner Organisation 1:</b>&nbsp;" + PartnerOrg1 + "<br />";

    var PartnerOrg2 = getXMLNode(index, "Partner_Organisation_2");
    if (PartnerOrg2 != null)
        resultDetails += "<b>Partner Organisation 2:</b>&nbsp;" + PartnerOrg2 + "<br />";

    var PartnerOrg3 = getXMLNode(index, "Partner_Organisation_3");
    if (PartnerOrg3 != null)
        resultDetails += "<b>Partner Organisation 3:</b>&nbsp;" + PartnerOrg3 + "<br />";

    var RelatedLink1 = getXMLNode(index, "Related_Link_1");
    if (RelatedLink1 != null)
        resultDetails += "<b>Related Link 1:</b>&nbsp;<a href='" + RelatedLink1 + "'>" + RelatedLink1 + "</a><br />";

    var RelatedLink2 = getXMLNode(index, "Related_Link_2");
    if (RelatedLink2 != null)
        resultDetails += "<b>Related Link 2:</b>&nbsp;<a href='" + RelatedLink2 + "'>" + RelatedLink2 + "</a><br />";

    var RelatedLink3 = getXMLNode(index, "Related_Link_3");
    if (RelatedLink3 != null)
        resultDetails += "<b>Related Link 3:</b>&nbsp;<a href='" + RelatedLink3 + "'>" + RelatedLink3 + "</a><br />";

    var facility = getXMLNode(index, "Facility");
    if (facility != null)
        resultDetails += "<b>Facility:</b>&nbsp;" + facility + "<br />";

    var streetAddress = getXMLNode(index, "Street_Address");
    if (streetAddress != null)
        resultDetails += "<b>Street Address:</b>&nbsp;" + streetAddress + "<br />";

    var suburnTown = getXMLNode(index, "Suburb_Or_Town");
    if (suburnTown != null)
        resultDetails += "<b>Suburb or Town:</b>&nbsp;" + suburnTown + "<br />";

    var state = getXMLNode(index, "State");
    if (state != null)
        resultDetails += "<b>State:</b>&nbsp;" + state + "<br />";

    var postcode = getXMLNode(index, "Postcode");
    if (postcode != null)
        resultDetails += "<b>Postcode:</b>&nbsp;" + postcode + "<br />";

    var photos1 = getXMLNode(index, "Photos_1");
    if (photos1 != null)
        resultDetails += "<b>Photos 1:</b>&nbsp;" + photos1 + "<br />";

    var photos2 = getXMLNode(index, "Photos_2");
    if (photos2 != null)
        resultDetails += "<b>Photos 2:</b>&nbsp;" + photos2 + "<br />";

    var photos3 = getXMLNode(index, "Photos_3");
    if (photos3 != null)
        resultDetails += "<b>Photos 3:</b>&nbsp;" + photos3 + "<br />";

    var video1 = getXMLNode(index, "Video_1");
    if (video1 != null)
        resultDetails += "<b>Video 1:</b>&nbsp;" + video1 + "<br />";

    if (title != null && projecttype != null) {
        tempTitle = title.toLowerCase();
        tempProjecttype = projecttype.toLowerCase();
        
        // projectTypeNames[2] == 'Housing'
        if (tempProjecttype == projectTypeNames[2].toLowerCase() &&
            (tempTitle == 'Social Housing - Stage 1 Construction'.toLowerCase() ||
             tempTitle == 'Social Housing - Stage 2 Construction'.toLowerCase() ||
             tempTitle == 'Social Housing - Repairs and Maintenance'.toLowerCase())
           )
        {
            resultDetails += "<br />";
            resultDetails += "Funding for dwellings in the identified location represents an estimate only of proposed Commonwealth funding. This amount does not take into consideration any other proposed funding or equity from either the State or Territory Government or not for profit/community housing providers. Variations in the number of dwellings identified in each location and the value of proposed funding may be revised in subsequent reports.";
            resultDetails += "<br />";
        }
    }

    resultDetails += "</div>";
    document.getElementById("resultDetails").innerHTML = resultDetails;

    $('#resultList').hide();
    $('#resultDetails').show();
}

function retrieveResultsList(index) {
    $('#resultDetails').hide();
    $('#resultList').show();
}

// Perform a lookup with google to get the lat/lng of the location
// as specified by the user.
function retreiveUserLocation() {
    $('#mapsintro').hide();
    $('#datarefresh').children(0).html(asAtDateText); $('#datarefresh').show();
    $('#overlay').show();

    userQuery = $("#txtSearch").val();
	var selectedElectorate = null;
	// if #electorateSelect is present, get the selected electorate
	if ( $("#electorateSelect").length && $("#electorateSelect").attr("selectedIndex") > 0 ) selectedElectorate = $("#electorateSelect").val();
	
    //reset vars
    isElectorateSelected = false;
    isPostcodeSelected = false;
    isSuburbOrTownSelected = false;
	forceAddressSearchCheck = false;
    forceElectorateSearchCheck = false;
    forcePostcodeSearchCheck = false;
    forceSuburbOrTownSearchCheck = false;
    //currentElectorate = -1; //2010-03-15 LD2558. Commented out, no longer required regarding not showing Electorate buttons request
	
	// if we have electorate...
    if (selectedElectorate != null)
	{
	    //...do an electorate search
		isElectorateSelected = true;
		forceElectorateSearchCheck = true;
		forceElectorateSearch(selectedElectorate, false);
	}
	else
	{
		// if sanity check on userQuery fails...
		if (userQuery == '' || userQuery == null || userQuery == undefined) {
			// ...exit
			$('#overlay').hide();
			alert('If you would like to conduct another search, please enter an Address/Postcode or click on the Search by electorate link.');
			return;
        }
        else if (/^\d\d\d\d$/.test(userQuery))
        {
            // ...it's a postcode
            isPostcodeSelected = true;
            forcePostcodeSearchCheck = true;
            forcePostcodeSearch(userQuery, false);
        }
		else
		{
		    // not a postcode, not an electorate... do an suburb/town search
		    isSuburbOrTownSelected = true;
		    forceSuburbOrTownSearchCheck = true;
		    forceSuburbOrTownSearch(userQuery, false);
//			var geocoder = new GClientGeocoder();
//			geocoder.getLatLng(userQuery + ", australia",
//				function(point) {
//				    if (point != null) {
//				        retrieveSearchData(point);
//				    }
//				    else {
//				        $('#overlay').hide();
//				        alert("Your search criteria could not be located on the map. Please try a different address or postcode.");
//				    }
//				});
		}
	}
}

// Perform a lookup of postcode as specified by the user.
function retreivePostcode() {
    $('#mapsintro').hide();
    $('#overlay').show();

    userQuery = $("#txtSearch").val();
    var selectedElectorate = null;
    // if #electorateSelect is present, get the selected electorate
    if ($("#electorateSelect").length && $("#electorateSelect").attr("selectedIndex") > 0) selectedElectorate = $("#electorateSelect").val();

    //reset vars
    isElectorateSelected = false;
    isPostcodeSelected = false;
    isSuburbOrTownSelected = false;
    forceAddressSearchCheck = false;
    forceElectorateSearchCheck = false;
    forcePostcodeSearchCheck = false;
    forceSuburbOrTownSearchCheck = false;
    //currentElectorate = -1;   //2010-03-15 LD2558. Commented out, no longer required regarding not showing Electorate buttons request

    // if sanity check on userQuery fails...
    if (userQuery == '' || userQuery == null || userQuery == undefined) {
        // ...exit
        $('#overlay').hide();
        alert('If you would like to conduct another search, please enter a 4 digit postcode or click on the Search by electorate link.');
        return;
    }
    else {
        // do a postcode search
        isPostcodeSelected = true;
        forcePostcodeSearchCheck = true;
        forcePostcodeSearch(userQuery);
    }
}

// Perform a lookup of suburb/town as specified by the user.
function retreiveSuburbTown() {
    $('#mapsintro').hide();
    $('#overlay').show();

    userQuery = $("#txtSearch").val();
    var selectedElectorate = null;
    // if #electorateSelect is present, get the selected electorate
    if ($("#electorateSelect").length && $("#electorateSelect").attr("selectedIndex") > 0) selectedElectorate = $("#electorateSelect").val();

    //reset vars
    isElectorateSelected = false;
    isPostcodeSelected = false;
    isSuburbOrTownSelected = false;
    forceAddressSearchCheck = false;
    forceElectorateSearchCheck = false;
    forcePostcodeSearchCheck = false;
    forceSuburbOrTownSearchCheck = false;
    //currentElectorate = -1;   //2010-03-15 LD2558. Commented out, no longer required regarding not showing Electorate buttons request

        // if sanity check on userQuery fails...
    if (userQuery == '' || userQuery == null || userQuery == undefined) {
        // ...exit
        $('#overlay').hide();
        alert("Your search for " + userQuery + " could not be found. Please check the spelling and try again.");
        return;
    }
    else {
        // do a suburb/town search
        isSuburbOrTownSelected = true;
        forceSuburbOrTownSearchCheck = true;
        forceSuburbOrTownSearch(userQuery);
    }
}

// electorateName: electorate to search for.
// resetMap: initialiseMap only if necesssary. If user performs a search through the map search control, a resetMap should be set to false.
function forceElectorateSearch(electorateName, resetMap) {
    $('#mapsintro').hide();
    $('#datarefresh').children(0).html(asAtDateText); $('#datarefresh').show();

    // Hide suburb/town suggestion
    $('#suburbTownSuggestionMessage').hide();
    
    providedElectorateName = electorateName;

    if (resetMap == true) {
        initialiseMap();
    }

    $('#overlay').show();

    //Remove all previous overlays from the map
    if (electorateOverlayPolygons.length != 0) {
        var numPolygons = electorateOverlayPolygons.length;
        for (var index = 0; index < numPolygons; index++) {
            map.removeOverlay(electorateOverlayPolygons[index]);
        }
    }
    
    // Clear out the poly data in case we are on a re-search.
    electorateOverlayPolygons = new Array();
    electorateNames = new Array();
    polygonIds = new Array();

    //2010-03-15 LD2558. Commented out, no longer required regarding not showing Electorate buttons request
//    //Set the text of electorateButton to 'Hide Electorates'
//    $('#electorateButton').html("Hide Electorates");
//    $('#electorateButton').show(); // 2010-03-12 IK0043: Commented out so that electorate buttons do not show.

    //2010-03-15 LD2558. Commented out, no longer required regarding not showing Electorate buttons request
//    // Hide suburb/town suggestion
//    $('#suburbTownSuggestionMessage').hide();

    //Set the forceElectorateSearchCheck to true
    forceElectorateSearchCheck = true;

    //Reset address, postcode and suburb/town search boolean values
    isPostcodeSelected = false;
    isSuburbOrTownSelected = false;
    forceAddressSearchCheck = false;
    forcePostcodeSearchCheck = false;
    forceSuburbOrTownSearchCheck = false;

    // Get the overlay data
    $.getJSON("/data/GetElectorateOverlays.aspx", { userLat: 0, userLng: 0, userElectorate: electorateName, responsetype: 'json' }, electorateProvided_OverlayReturned);
    isElectorateSelected = true;
}

// postcode: postcode to search for.
// resetMap: initialiseMap only if necesssary. If user performs a search through the map search control, a resetMap should be set to false.
function forcePostcodeSearch(postcode, resetMap) {
    $('#mapsintro').hide();
    $('#datarefresh').children(0).html(asAtDateText); $('#datarefresh').show();
    providedPostcode = postcode;

    if (resetMap == true)
        initialiseMap();

    document.getElementById("txtSearch").value = postcode;
    $('#overlay').hide();

    //Remove all previous overlays from the map    
    if (electorateOverlayPolygons.length != 0) {
        var numPolygons = electorateOverlayPolygons.length;
        for (var index = 0; index < numPolygons; index++) {
            map.removeOverlay(electorateOverlayPolygons[index]);
        }
    }

    // Clear out the poly data in case we are on a re-search.
    electorateOverlayPolygons = new Array();
    electorateNames = new Array();
    polygonIds = new Array();

    $('#overlay').show();

    //2010-03-15 LD2558. Commented out, no longer required regarding not showing Electorate buttons request
//    //Set the text of electorateButton to 'Hide Electorates'
//    //$('#electorateButton').html("Hide Electorates");
//    
//    //Hide the electorateButton and electorateMessage
//    $('#electorateButton').hide();
//    $('#electorateMessage').hide();

    // Hide suburb/town suggestion
    $('#suburbTownSuggestionMessage').hide();

    //Set the forcePostcodeSearchCheck to true
    forcePostcodeSearchCheck = true;

    //Reset the address and electorate values to false
    forceAddressSearchCheck = false;
    forceElectorateSearchCheck = false;
    forceSuburbOrTownSearchCheck = false;
    isElectorateSelected = false;
    isSuburbOrTownSelected = false;

    //Retrieve xml data and display results for the specified postcode
//    var postcode = providedPostcode
    $.getJSON("/data/GetPostcodeResultSet.aspx", { postcode: postcode, responsetype: 'json' }, postcodeProvided_Returned);
    isPostcodeSelected = true;
}

// suburbOrTown: suburb or town to search for.
// resetMap: initialiseMap only if necesssary. If user performs a search through the map search control, a resetMap should be set to false.
function forceSuburbOrTownSearch(suburbOrTown, resetMap) {
    $('#mapsintro').hide();
    $('#datarefresh').children(0).html(asAtDateText); $('#datarefresh').show();
    providedSuburbOrTown = suburbOrTown;

    //Comment out because if the error message appears, means there is no data retured or not successfully returned, we do not change the contents of map
    if (resetMap == true)
        initialiseMap();

    document.getElementById("txtSearch").value = suburbOrTown;
    $('#overlay').hide();

    //Remove all previous overlays from the map
    if (electorateOverlayPolygons.length != 0) {
        var numPolygons = electorateOverlayPolygons.length;
        for (var index = 0; index < numPolygons; index++) {
            map.removeOverlay(electorateOverlayPolygons[index]);
        }
    }

    // Clear out the poly data in case we are on a re-search.
    electorateOverlayPolygons = new Array();
    electorateNames = new Array();
    polygonIds = new Array();

    $('#overlay').show();

    //Set the text of electorateButton to 'Hide Electorates'
    //$('#electorateButton').html("Hide Electorates");
    //$('#electorateButton').show();

    // Hide suburb/town suggestion
    $('#suburbTownSuggestionMessage').hide();

    //Set the forceSuburbOrTownSearchCheck to true
    forceSuburbOrTownSearchCheck = true;

    //Reset the address and electorate values to false
    forceAddressSearchCheck = false;
    forceElectorateSearchCheck = false;
    forcePostcodeSearchCheck = false;
    isElectorateSelected = false;
    isPostcodeSelected = false;

    // Determine there is only one Suburb/Town, [State], [Postcode] combination.
    $.getJSON("/data/GetDistinctSuburbOrTowns.aspx", { suburbOrTown: suburbOrTown, responsetype: 'json' }, suburbOrTownProvided_DistinctReturned);
    isSuburbOrTownSelected = true;
}

function suburbOrTownProvided_DistinctReturned(data) {
    if (data != null) {
        if (data.results.SuburbTowns.SuburbTown.length == 1 ||
        (data.results.SuburbTowns.SuburbTown.length > 0 && doSuburbTownSearch == true)) {
            doSuburbTownSearch = false; // reset do suburb/town search to false so that future searches work as normal.
            suburbOrTown = data.results.SuburbTowns.SuburbTown[0].SuburbOrTownStatePostcode;
            //Retrieve xml data and display results for the specified suburb or town
            $.getJSON("/data/GetSuburbOrTownResultSet.aspx", { suburbOrTown: suburbOrTown, responsetype: 'json' }, suburbOrTownProvided_Returned);
        }
        else if (data.results.SuburbTowns.SuburbTown.length > 1) {
            $('#overlay').hide();

            suburbTownSuggestion = $('#suburbTownSuggestionMessage').html("<div style=\"font-weight: bold\">We have found multiple results for the name \"{0}\" did you mean one of the following options?<br></br></div>{1}");
            suburbTownSuggestion = $('#suburbTownSuggestionMessage').html().replace("{0}", data.results.Query);
            $('#suburbTownSuggestionMessage').html(suburbTownSuggestion);

            for (i = 0; i < data.results.SuburbTowns.SuburbTown.length; i++) {
                suburbOrTownStatePostcode = data.results.SuburbTowns.SuburbTown[i].SuburbOrTownStatePostcode;
                suburbOrTownStatePostcodeEscaped = suburbOrTownStatePostcode.replace("'", "\\'");
                endBit = "{1}"
                if (i == data.results.SuburbTowns.SuburbTown.length - 1)
                    endBit = "";
                suburbTownSuggestion = $('#suburbTownSuggestionMessage').html().replace("{1}", "<div><a href=\"javascript:setAndSuburbTownSearchTextBox('" + suburbOrTownStatePostcodeEscaped + "')\">" + suburbOrTownStatePostcode + "</a><br></br></div>\r\n" + endBit);
                $('#suburbTownSuggestionMessage').html(suburbTownSuggestion);
            }
            
            $("#suburbTownSuggestionMessage").show();
        }
        else if (data.results.SuburbTowns.SuburbTown.length == 0) {
           if (data.results.PostcodesForSuburbTowns.SuburbTown.length > 0) {
               $('#overlay').hide();
               
               suburbTownSuggestion = $('#suburbTownSuggestionMessage').html("<div style=\"font-weight: bold\">There are no results available for \"{0}\". Please try a wider search to find nearby items. Would you like to perform a search for the following postcodes?<br></br></div>{1}");
               suburbTownSuggestion = $('#suburbTownSuggestionMessage').html().replace("{0}", data.results.Query);
               $('#suburbTownSuggestionMessage').html(suburbTownSuggestion);

               for (i = 0; i < data.results.PostcodesForSuburbTowns.SuburbTown.length; i++) {
                   postcodeForSuburbOrTown = data.results.PostcodesForSuburbTowns.SuburbTown[i].Postcode;
                   endBit = "{1}"
                   if (i == data.results.PostcodesForSuburbTowns.SuburbTown.length - 1)
                       endBit = "";
                   suburbTownSuggestion = $('#suburbTownSuggestionMessage').html().replace("{1}", "<div><a href=\"javascript:setAndPostcodeSearchTextBox('" + postcodeForSuburbOrTown + "')\">" + postcodeForSuburbOrTown + "</a><br></br></div>\r\n" + endBit);
                   $('#suburbTownSuggestionMessage').html(suburbTownSuggestion);
               }

               $("#suburbTownSuggestionMessage").show();
           }
           else {
               $('#overlay').hide();
               alert("Your search for " + providedSuburbOrTown + " could not be found. Please check the spelling and try again.");
           }
        }
    }
    else {
        $('#overlay').hide();
        alert("Your search for " + providedSuburbOrTown + " could not be found. Please check the spelling and try again.");
    }
}

function setAndSuburbTownSearchTextBox(suburbTown) {
    doSuburbTownSearch = true;
    $("#txtSearch").val(suburbTown);
    retreiveSuburbTown();
}

function setAndPostcodeSearchTextBox(postcode) {
    $("#txtSearch").val(postcode);
    retreivePostcode();
}

//TODO: This will be removed when the business update the search control. 
function retrieveResults() {
    retreiveUserLocation();
}

// Perform the call to the feeds for the search data.
function retrieveSearchData(userPoint) {
    // Used across js files so watch it!
    selectedUserPoint = userPoint;

    //Remove all previous overlays from the map
    if (electorateOverlayPolygons.length != 0) {
        var numPolygons = electorateOverlayPolygons.length
        for (var index = 0; index < numPolygons; index++) {
            map.removeOverlay(electorateOverlayPolygons[index]);
        }
    }

    // Clear out the poly data in case we are on a re-search.
    electorateOverlayPolygons = new Array();
    electorateNames = new Array();
    polygonIds = new Array();

    $('#overlay').show();

    // Get the overlay data.
    $.getJSON("/data/GetElectorateOverlays.aspx", { userLat: userPoint.lat(), userLng: userPoint.lng(), responsetype: 'json' }, overlayReturned);

    // Get the marker data.
    $.get("/data/ResultSet.aspx", { userQuery: userQuery, userLat: userPoint.lat(), userLng: userPoint.lng() }, projectsReturned, 'xml');

}

// This is called when the overlay data is returned.
function overlayReturned(data) {
    if (data != null) {
        displayElectorateOverlay(data);
        //2010-03-15 LD2558. Commented out, no longer required regarding not showing Electorate buttons request
//        //Reset the text of electorateButton to 'Display Electorates' and hide electorateMessage
//        if ($('#electorateButton').html() == "Hide Electorates") {
//            //Remove the electorate message from the map
//            $('#electorateMessage').hide();
//            $('#electorateButton').css({ 'background-color': '#FFFFFF', 'font-weight': 'normal', 'border-width': '1px' });
//            $('#electorateButton').html("Display Electorates");
//        }
    }
    else {
        $('#overlay').hide();
        alert("Your search criteria could not be located on the map. Please try a different address or postcode.");
    }
}

// When electorate name is provided, this is called after the overlay data is returned from $.getJSON
// We need this separate function because the sequence of steps must be $.getJSON, generate JSON, $.get and generate XML
function electorateProvided_OverlayReturned(data) {
    if (data != null) {
        displayElectorateOverlay(data);
        //2010-03-15 LD2558. Continue to retrieve xml data.
        //Retrieve xml data and display results for the specified electorate name
        var electorateName = providedElectorateName;
        $.get("/data/GetElectorateResultSet.aspx", { electoratename: electorateName, responsetype: 'xml' }, projectsReturned, 'xml');

        //2010-03-15 LD2558. Commented out, no longer required regarding not showing Electorate buttons request
//        //Continue to add new electorate overlays to the map only if the status of electorateButton is 'ON'
//        if ($('#electorateButton').html() == "Hide Electorates") {
//            //Reset the text of electorateButton to 'Display Electorates' and hide electorateMessage
//            //before triggering the click event
//            $('#electorateButton').html("Display Electorates");
//            $('#electorateMessage').hide();
//            GEvent.trigger(displayDiv, "click");

//            //Retrieve xml data and display results for the specified electorate name
//            var electorateName = providedElectorateName;
//            $.get("/data/GetElectorateResultSet.aspx", { electoratename: electorateName, responsetype: 'xml' }, projectsReturned, 'xml');
//        }
//        
//        //Remove the electorate map event listener
//        if (addMapClickCount > 0) {
//            GEvent.clearInstanceListeners(map);
//            addMapClickCount = 0;   //Reset the addMapClickCount
//        }
    }
    else {
        $('#overlay').hide();
        alert("Your search criteria could not be located on the map. Please try a different address or postcode.");
    }
}

function getPostcodeSelectedUserPoint(postcodeJson)
{
    if (postcodeJson != null)
    {
        for (var i = 0; i < postcodeJson.results.Projects.Project.length; i++) {
            var projectData = postcodeJson.results.Projects.Project[i];
            var suburbOrTown = projectData.Suburb_Or_Town;
            var postcode = projectData.Postcode;
            var electorateName = projectData.Electorate_Name;
            var projectLat = projectData.GIS_Loc_Latitude;
            var projectLng = projectData.GIS_Loc_Longitude;
            if (projectLat != undefined && projectLng != undefined) {
                selectedUserPoint = new GLatLng(parseFloat(projectLat), parseFloat(projectLng));
            }
        }
    }
}

function getSuburbOrTownSelectedUserPoint(suburbOrTownJson) {
    if (suburbOrTownJson != null) {
        for (var i = 0; i < suburbOrTownJson.results.Projects.Project.length; i++) {
            var projectData = suburbOrTownJson.results.Projects.Project[i];
            var suburbOrTown = projectData.Suburb_Or_Town;
            var postcode = projectData.Postcode;
            var electorateName = projectData.Electorate_Name;
            var projectLat = projectData.GIS_Loc_Latitude;
            var projectLng = projectData.GIS_Loc_Longitude;
            if (projectLat != undefined && projectLng != undefined) {
                selectedUserPoint = new GLatLng(parseFloat(projectLat), parseFloat(projectLng));
            }
        }
    }
}

function postcodeProvided_Returned(data)
{
    if (data != null)
    {
        getPostcodeSelectedUserPoint(data);
//        displayElectorateOverlay(data);
//        //Continue to add new electorate overlays to the map only if the status of electorateButton is 'ON'
//        if ($('#electorateButton').html() == "Hide Electorates") {
//            //Reset the text of electorateButton to 'Display Electorates' and hide electorateMessage
//            //before triggering the click event
//            $('#electorateButton').html("Display Electorates");
//            $('#electorateMessage').hide();
//            GEvent.trigger(displayDiv, "click");

            //Retrieve xml data and display results for the specified electorate name
//            var electorateName = providedElectorateName;
            $.get("/data/GetPostcodeResultSet.aspx", { postcode: providedPostcode, responsetype: 'xml' }, projectsReturned, 'xml');
//        }

//        //Remove the electorate map event listener
//        if (addMapClickCount > 0) {
//            GEvent.clearInstanceListeners(map);
//            addMapClickCount = 0;   //Reset the addMapClickCount
//        }
    }
    else
    {
        $('#overlay').hide();
        alert("Your search criteria could not be located on the map. Please try a different postcode.");
    }
}

function suburbOrTownProvided_Returned(data) {
    if (data != null) {
        getSuburbOrTownSelectedUserPoint(data);
        //        displayElectorateOverlay(data);
        //        //Continue to add new electorate overlays to the map only if the status of electorateButton is 'ON'
        //        if ($('#electorateButton').html() == "Hide Electorates") {
        //            //Reset the text of electorateButton to 'Display Electorates' and hide electorateMessage
        //            //before triggering the click event
        //            $('#electorateButton').html("Display Electorates");
        //            $('#electorateMessage').hide();
        //            GEvent.trigger(displayDiv, "click");

        //Retrieve xml data and display results for the specified electorate name
        //            var electorateName = providedElectorateName;
        $.get("/data/GetSuburbOrTownResultSet.aspx", { suburbOrTown: providedSuburbOrTown, responsetype: 'xml' }, projectsReturned, 'xml');
        //        }

        //        //Remove the electorate map event listener
        //        if (addMapClickCount > 0) {
        //            GEvent.clearInstanceListeners(map);
        //            addMapClickCount = 0;   //Reset the addMapClickCount
        //        }
    }
    else {
        $('#overlay').hide();
        alert("Your search for " + providedSuburbOrTown + " could not be found. Please check the spelling and try again.");
    }
}

// This is called when the pin data is returned from the web service.
function projectsReturned(data, textStatus) {
    if (data != null)
    {
        if (textStatus == 'success' && data.getElementsByTagName("result").length > 0) {
            // check the Data.
            $('#resultDetails').hide();
            $('#resultList').show();
            loadMap(data);

            //Display the Electorate overlay information window including the Electorate summary
            if (isElectorateSelected) {
                title = "Electorate Summary";
                //Get the description of the information window by cloning data
                description = $('<div>').append($('#summaryBlock').clone()).remove().html();
                description = "<div><a href=\"/pages/disclaimer.aspx#map\" title=\"Disclaimer\" target=\"_blank\">" + asAtDateText + "</a></div>" + description;
                createInformationWindowForElectOverlay(markers[projectTypeIndex][(markers[projectTypeIndex].length - 1)], title, description); //4
                GEvent.trigger(markers[projectTypeIndex][(markers[projectTypeIndex].length - 1)], 'click');

                //Add overlays to the map
                if (forceElectorateSearchCheck) {
                    addOverlayToMap();
                }
            }
            else if (forcePostcodeSearchCheck) {
                title = "Postcode Summary";
                //Get the description of the information window by cloning data
                description = $('<div>').append($('#summaryBlock').clone()).remove().html();
                description = "<div><a href=\"/pages/disclaimer.aspx#map\" title=\"Disclaimer\" target=\"_blank\">" + asAtDateText + "</a></div>" + description;
                createInformationWindowForPostcode(markers[projectTypeIndex][(markers[projectTypeIndex].length - 1)], title, description); //4
                GEvent.trigger(markers[projectTypeIndex][(markers[projectTypeIndex].length - 1)], 'click');
            }
            else if (forceSuburbOrTownSearchCheck) {
                title = "Suburb or Town Summary";
                //Get the description of the information window by cloning data
                description = $('<div>').append($('#summaryBlock').clone()).remove().html();
                description = "<div><a href=\"/pages/disclaimer.aspx#map\" title=\"Disclaimer\" target=\"_blank\">" + asAtDateText + "</a></div>" + description;
//                createInformationWindowForSuburbOrTown(markers[projectTypeIndex][(markers[projectTypeIndex].length - 1)], title, description); //4
//                GEvent.trigger(markers[projectTypeIndex][(markers[projectTypeIndex].length - 1)], 'click');
            }
            $('#overlay').hide();
        }
        else {
            $('#overlay').hide();
            alert("Your search criteria could not be located on the map. Please try a different address or postcode.");
        }
    }
    else {
        $('#overlay').hide();
        alert("Your search criteria could not be located on the map. Please try a different address or postcode.");
    }
}

function createInformationWindowForElectOverlay(marker, title, description) {
    description = $('<div>').append($('#summaryBlock').clone()).remove().html();
    description = "<div><a href=\"/pages/disclaimer.aspx#map\" title=\"Disclaimer\" target=\"_blank\">" + asAtDateText + "</a></div>" + description;
    while (description.indexOf("id=summary", 0) != -1) {
        description = description.replace("id=summary", "id=iWindowSummary");
    }

    var infoWindow = buildInfoWindowForElectOverlay(title, "", description, "elec_sum_lrg.png", -1);
    GEvent.addListener(marker, "click", function() //When user clicks, open information window for that marker
    {
        retrieveResultsList(0);
        marker.openInfoWindowHtml(infoWindow);
        // 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 buildInfoWindowForElectOverlay(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:410px;height:240px'>";
    infoWindow += "<tr>";
    infoWindow += "<td style='width:50px; text-align:top;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:360px; padding-left:5px; vertical-align:top;'>";
    infoWindow += "<p>";

    if (postcode != "")
        infoWindow += "<strong>" + title + " - " + postcode + "</strong><br />";
    else
        infoWindow += "<strong>" + title + "</strong><br />";

    infoWindow += "</p>";
    infoWindow += "</td>";
    infoWindow += "</tr>";
    infoWindow += "<tr>";
    infoWindow += "<td colspan='2'>";
    infoWindow += "<p>"
    infoWindow += description;
    infoWindow += "</p>";
    infoWindow += "</td>";
    infoWindow += "</tr>";
    infoWindow += "</table></div>";
    
    return infoWindow;
}

function createInformationWindowForPostcode(marker, title, description) {
    description = $('<div>').append($('#summaryBlock').clone()).remove().html();
    description = "<div><a href=\"/pages/disclaimer.aspx#map\" title=\"Disclaimer\" target=\"_blank\">" + asAtDateText + "</a></div>" + description;
    while (description.indexOf("id=summary", 0) != -1) {
        description = description.replace("id=summary", "id=iWindowSummary");
    }

    var infoWindow = buildInfoWindowForPostcode(title, "", description, "postcode_sum_lrg.png", -1);
    GEvent.addListener(marker, "click", function() //When user clicks, open information window for that marker
    {
        retrieveResultsList(0);
        marker.openInfoWindowHtml(infoWindow);
        // 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 buildInfoWindowForPostcode(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:410px;height:240px'>";
    infoWindow += "<tr>";
    infoWindow += "<td style='width:50px; text-align:top;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:360px; padding-left:5px; vertical-align:top;'>";
    infoWindow += "<p>";

    if (postcode != "")
        infoWindow += "<strong>" + title + " - " + postcode + "</strong><br />";
    else
        infoWindow += "<strong>" + title + "</strong><br />";

    infoWindow += "</p>";
    infoWindow += "</td>";
    infoWindow += "</tr>";
    infoWindow += "<tr>";
    infoWindow += "<td colspan='2'>";
    infoWindow += "<p>"
    infoWindow += description;
    infoWindow += "</p>";
    infoWindow += "</td>";
    infoWindow += "</tr>";
    infoWindow += "</table></div>";

    return infoWindow;
}

//function createInformationWindowForSuburbOrTown(marker, title, description) {
//    description = $('<div>').append($('#summaryBlock').clone()).remove().html();
//    description = "<div><a href=\"/pages/disclaimer.aspx#map\" title=\"Disclaimer\" target=\"_blank\">" + asAtDateText + "</a></div>" + description;
//    while (description.indexOf("id=summary", 0) != -1) {
//        description = description.replace("id=summary", "id=iWindowSummary");
//    }

//    var infoWindow = buildInfoWindowForSuburbOrTown(title, "", description, "suburbOrTown_sum_lrg.png", -1);
//    GEvent.addListener(marker, "click", function() //When user clicks, open information window for that marker
//    {
//        retrieveResultsList(0);
//        marker.openInfoWindowHtml(infoWindow);
//        // 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 buildInfoWindowForSuburbOrTown(title, suburbOrTown, 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:410px;height:240px'>";
//    infoWindow += "<tr>";
//    infoWindow += "<td style='width:50px; text-align:top;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:360px; padding-left:5px; vertical-align:top;'>";
//    infoWindow += "<p>";

//    if (suburbOrTown != "")
//        infoWindow += "<strong>" + title + " - " + suburbOrTown + "</strong><br />";
//    else
//        infoWindow += "<strong>" + title + "</strong><br />";

//    infoWindow += "</p>";
//    infoWindow += "</td>";
//    infoWindow += "</tr>";
//    infoWindow += "<tr>";
//    infoWindow += "<td colspan='2'>";
//    infoWindow += "<p>"
//    infoWindow += description;
//    infoWindow += "</p>";
//    infoWindow += "</td>";
//    infoWindow += "</tr>";
//    infoWindow += "</table></div>";

//    return infoWindow;
//}