﻿
/****************************************************************************************************
'  File:         GPSMapping.js
'  Author:       K.Winterbine
'  Date:         Monday, 28th February 2011
'  Description:  This page contains the client scripts for the Mapping Page
'----------------------------------------------------------------------------------------------------
'  Modification History
'  Date		Author		Description
'----------------------------------------------------------------------------------------------------		
'  28/02/2011	KW		Initial Version
'****************************************************************************************************/

//***********COMMON DECLARATIONS **************************
var map;
var loader;
var RadiusValue;
var SearchAddressPoint;
var GoogleAddressSearchSuffix = ",Australia";

var resultPoints = [];

google.load('visualization', '1', {packages:['table']}); 

//*********** LOOKUP DECLARATIONS **************************
var churchIcon = "Images/Mapping/ChurchIcon.gif";
var addressIcon = "Images/Mapping/BluePin.gif";

var churchVisualization = null;
var churchList = null;
var infoSelectedInfoWindow;

var cssClassNames = { headerRow: 'SearchHeader', tableRow: 'SearchListRow', selectedTableRow: 'SearchListSelected', hoverTableRow: 'SearchListHover' };



//***************************************************************************************************
//  Common Function
//**************************************************************************************************

function initialize() {
    var defaultGPS = new google.maps.LatLng(-28.5, 135);
    var myOptions = {
      zoom: 4,
      center: defaultGPS,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(document.getElementById("divMapCanvas"), myOptions);
    loader = document.getElementById("UpdateProgress1");
    
    resultPoints = [];
    churchList = new google.visualization.DataTable();
    
    churchVisualization = new google.visualization.Table(document.getElementById('divResults'));
    churchVisualization.draw(churchList, {cssClassNames: cssClassNames, showRowNumber: false, page: 'enable', pageSize: 8, startPage: 0, alternatingRowStyle:false }); 
    
   
}

//***************************************************************************************************
//  Church Lookup
//**************************************************************************************************

function ClearSearch()
{
    initialize();
    document.getElementById("txtLocation").value = "";
    document.getElementById("txtChurchName").value = "";
    var txtLocation = document.getElementById("txtLocation")
    var txtBox=document.getElementById("txtLocation" );
    if (txtBox!=null ) txtBox.focus();

}

function ValidateSearch()
{
    //Validate a address has been selected
    var address = document.getElementById("txtLocation").value;
    var radius = document.getElementById("cmbRadius").value;
    var churchName = document.getElementById("txtChurchName").value

    if (address == 'Enter Address, Suburb or Postcode'  && churchName == '') {
        alert('A Location or Church Name is required.');
        return;
    }
    
    if (address == 'Enter Address, Suburb or Postcode')
        address = '';
    else
        address = address + GoogleAddressSearchSuffix;

    findChurchByAddress(address, churchName, radius)
}

function findChurchByAddress(address, churchName, radius) {

    loader.style.display = "inline";
    clearChurchMarkers();

    getChurchByAddress(address, churchName, radius)
}

function getChurchByAddress(address, churchName, searchRadius) 
{  
    if (address == '')
    {
        //Search by church name
        getChurchesByName(churchName)
    }
    else
    {
        //Geocode Address and plot the point on the map
        var geocoder = new google.maps.Geocoder();
        geocoder.geocode({'address':address}, function(point, status) {
            if (status != google.maps.GeocoderStatus.OK) {
                loader.style.display = "none";
                alert("Invalid location entered.");
                return;
            }
            else {
            
                var AddressLocation = point[0].geometry.location;
                SearchAddressPoint = point[0].geometry.location;
        
                map.setCenter(AddressLocation);
                var marker = new google.maps.Marker({map: map,position: AddressLocation, animation: google.maps.Animation.DROP});
                
                //Remove the Google Address Suffix before displaying the Info Window
                var addressLen = address.length - GoogleAddressSearchSuffix.length;
                address = address.substring(0, addressLen);
                RadiusValue = parseInt(searchRadius);
                var radiusOptions = {
                    map: map,
                    radius: RadiusValue,
                    strokeWeight: 1,
                    center:AddressLocation,
                    fillOpacity:0.02,
                    clickable:false
                }
                var radiusDisplay = new google.maps.Circle(radiusOptions);
                var circleBounds = radiusDisplay.getBounds()
                map.fitBounds(circleBounds);
                
                var infoText = '<strong>Search Location</strong><br />' + point[0].formatted_address ;
                
                var infowindow = new google.maps.InfoWindow({   
                    content: infoText
                });  

                google.maps.event.addListener(marker, 'click', function() {   
                    infowindow.open(map, marker);   
                });  
                
                
                //loader.style.display = "none";
                //return;
                
                getChurchesByPoint(AddressLocation, churchName, searchRadius);
            }
        }); 
    }
}

function getChurchesByPoint(point, churchName, radius) {
    DataAccess.FindAChurch(churchName, point.lat(), point.lng(), radius, processChurchDetails)
}

function getChurchesByName(churchName) {
    DataAccess.FindAChurch(churchName, 0, 0, 0, processChurchNDetails)
}

function processChurchDetails(response) {

    var plotPoints = true;
    var found = 0;
    var bounds = new  google.maps.LatLngBounds();
    
    churchList = new google.visualization.DataTable();
    bounds.extend(SearchAddressPoint);
    
    // Resize the Window to Fit all Points
    for (i = 0; i < response.length; i++) {
        var point = new  google.maps.LatLng(response[i].latitude, response[i].longitude);
        var distanceInMetres = google.maps.geometry.spherical.computeDistanceBetween(SearchAddressPoint, point); 
        if(distanceInMetres < RadiusValue)
        {
            //Place the Point in the Bounds Array so we can resize the Map To Fit
            point = new  google.maps.LatLng(response[i].latitude, response[i].longitude);
            found=found+1;
            bounds.extend(point);
            
            //plot point on the map
            var addressID = response[i].addressID;
            marker = createChurchMarker(point, addressID);
       }
    }
    
    //Create Result Table
    if (found > 0)
    {
        createChurchListHeader(found);
        found = 0;
        for (i = 0; i < response.length; i++) {
            point = new  google.maps.LatLng(response[i].latitude, response[i].longitude);
            distanceInMetres = google.maps.geometry.spherical.computeDistanceBetween(SearchAddressPoint, point); 
            if(distanceInMetres < RadiusValue)
            {
                found=found+1;
                createChurchListRow((found-1), response[i].churchName, response[i].location);
            }
        }
    }
    
    if (response.length == 0 || found == 0)
    {
        loader.style.display = "none";
        alert("No Churches found within this search area.   \n");
        return;
    }
    
    if (response.length > 0 && found>0) {
        map.fitBounds(bounds);
        map.setCenter(bounds.getCenter());
    }
    
    churchVisualization = new google.visualization.Table(document.getElementById('divResults'));
    churchVisualization.draw(churchList, {cssClassNames: cssClassNames, showRowNumber: false, page: 'enable', pageSize: 8, startPage: 0, alternatingRowStyle:false }); 
    google.visualization.events.addListener(churchVisualization, 'select', selectChurchHandler);

    loader.style.display = "none";
    
}

function processChurchNDetails(response) {

    var plotPoints = true;
    var bounds = new  google.maps.LatLngBounds();
    var found = 0;
    
    churchList = new google.visualization.DataTable();
        
    // Resize the Window to Fit all Points
    for (i = 0; i < response.length; i++) {
        var point = new  google.maps.LatLng(response[i].latitude, response[i].longitude);
        
        //Place the Point in the Bounds Array so we can resize the Map To Fit
        bounds.extend(point);
        found=found+1;
            
        //plot point on the map
        var addressID = response[i].addressID;
        marker = createChurchMarker(point, addressID);
    }
    
     //Create Result Table
    if (found > 0)
    {
        createChurchListHeader(found);
        found = 0;
        for (i = 0; i < response.length; i++) {
            found=found+1;
            createChurchListRow((found-1), response[i].churchName, response[i].location);
        }
    }

    if (response.length > 0 && found>0) {
        map.fitBounds(bounds);
        map.setCenter(bounds.getCenter());
    }
    
    if (response.length == 0 || found == 0)
    {
        loader.style.display = "none";
        alert("No Churches found.   \n");
        return
    }
    
    churchVisualization = new google.visualization.Table(document.getElementById('divResults'));
    churchVisualization.draw(churchList, {cssClassNames: cssClassNames, showRowNumber: false, page: 'enable', pageSize: 8, startPage: 0, alternatingRowStyle:false }); 
    google.visualization.events.addListener(churchVisualization, 'select', selectChurchHandler);
    
    loader.style.display = "none";
    
}

function createChurchMarker(point, addressID) {
    var marker = new google.maps.Marker({position: point, map: map, icon: churchIcon});
    google.maps.event.addListener(marker, 'click', function() {   
        getChurchDetailsByID(marker, addressID);   
    });  
    
    resultPoints.push(marker);
}

function selectChurchHandler() {
    var selection = churchVisualization.getSelection();
    if (selection.length > 0) {
        var markerIndex = selection[0].row;
        google.maps.event.trigger(resultPoints[markerIndex], 'click');
    }
}

function createChurchListHeader(NoResults)
{
    churchList.addColumn('string', 'Search Results (' + NoResults + ')');
}

function createChurchListRow(rowNo, churchName, location)
{
    churchList.addRows(1);
    churchList.setCell(rowNo, 0, churchName + ' ' + location);
}

function clearChurchMarkers() {
    initialize();
    
}

function getChurchDetailsByID(marker, addressID) {

    currentMarker = marker;
    DataAccess.GetChurchAddressDetails(addressID, getChurchDetailWindow);
}

function getChurchDetailWindow(response) {

    markerInfo = "";
    if (response.length > 0) {
        markerInfo += "<table class='mapInfoWindowStyle'>";
          markerInfo += "<tr><td><b>" + response[0].churchName + "</b></td></tr>";
          markerInfo += "<tr><td>" + response[0].address1 + "</td></tr>";
          if (response[0].address2 != '')
            markerInfo += "<tr><td>" + response[0].address2 + "</td></tr>";
          
          if (response[0].address3 != '')
            markerInfo += "<tr><td>" + response[0].address3 + "</td></tr>";
            
          markerInfo += "<tr><td>" + response[0].suburb + ' ' + response[0].state + ' ' + response[0].postcode + "</td></tr>";
          markerInfo += "<tr><td></td></tr>";
          
          if (response[0].phone != '')
            markerInfo += "<tr><td>Phone: " + response[0].phone + "</td></tr>";
          
          if (response[0].email != '')
            markerInfo += "<tr><td>Email: " + response[0].email + "</td></tr>"
          
          if (response[0].website != '')
            markerInfo += "<tr><td>Web: <a target='right' href='http://" + response[0].website + "'>" + response[0].website + "</a></td></tr>";
          
          markerInfo += "</table>";
          
    if(infoSelectedInfoWindow) {infoSelectedInfoWindow.close()} 
    infoSelectedInfoWindow = null;
    
    infoSelectedInfoWindow = new google.maps.InfoWindow({   
        content: markerInfo
    });
    
     
     infoSelectedInfoWindow.open(map,currentMarker);
 
 
    }
}
