var map = null;
var markers = null;
var currentPosition = null;
var directions = null;
var startAddress = "";
var endAddress = "";
var divPlaces = null;
var divPlaceLast = null;
var divRightColumn = null;
var placesCount = 0;
var placesLoadedCount = 0;
var infoWSCallBack = null;
var divDirections = null;
var appPath = "http://www.downtownclevelandalliance.com/parking";
var divDirectionsSearch = null;
var divDirectionsSearchNew = null;
var divDirectionsSearchHTML = null;
var baseIcon = null;
var markerIcon = null;
var parkingMarkerOptions = null;

function getPlacesByCurrentPosition()
{
    showLoading();
    placesCount = 0;
    placesLoadedCount = 0;
    var div = document.createElement("div");
    div.id = "loadingDivPlaces";
    div.innerHTML = "Loading parking locations.";
    divPlaces.appendChild(div);
    
    DCA.Web.WebServices.Service.GetPlacesByLatitudeLongitude(currentPosition.getPoint().lat(),currentPosition.getPoint().lng(), getPlacesResponse);
}

function getPlacesByAddress(address)
{
    var div = document.createElement("div");
    div.id = "loadingDivPlaces";
    div.innerHTML = "Loading parking locations.";
    divPlaces.appendChild(div);
    
    DCA.Web.WebServices.Service.GetPlacesByAddress(address, currentPosition.getPoint().lat(),currentPosition.getPoint().lng(), getPlacesResponse);
}

function getPlacesByPhoneNumber(phone)
{
    var div = document.createElement("div");
    div.id = "loadingDivPlaces";
    div.innerHTML = "Loading parking locations.<br><br>";
    divPlaces.appendChild(div);
    
    DCA.Web.WebServices.Service.GetPlacesByPhoneNumber(phone, currentPosition.getPoint().lat(),currentPosition.getPoint().lng(), getPlacesResponse);
}

function getPlacesByZipCodeNumber(zipCodeNumber)
{
    var div = document.createElement("div");
    div.id = "loadingDivPlaces";
    div.innerHTML = "Loading parking locations.";
    divPlaces.appendChild(div);
    
    DCA.Web.WebServices.Service.GetPlacesByZipCodeNumber(zipCodeNumber, currentPosition.getPoint().lat(),currentPosition.getPoint().lng(), getPlacesResponse);
}

function clearAll()
{
    while (divPlaces.childNodes.length > 0)
    {
        divPlaces.removeChild(divPlaces.childNodes[0]);
    }
    for (var x = 0; x < markers.length; x++)
    {
        map.removeOverlay(markers[x].GMarker);
    }
    map.removeOverlay(currentPosition);
    directions.clear();
    //map.clearOverlays();
}

function getPlacesResponse(response)
{
    markers = new Array(response.length);
    
    //var addressExists = false;
    placesCount = response.length;
    
    for (var x = 0; x < response.length; x++)
    {
        markers[x] = new Object();
    }
    for (var x = 0; x < response.length; x++)
    {
        markers[x].PlaceID = response[x];
        getPlacesByPlaceID(response[x]);
        //var point = new GLatLng(response[x].Latitude, response[x].Longitude);
        //var gmarker = new GMarker(point);
        //var obj = response[x];
        //GEvent.addListener(gmarker, "click", function() { markerClick( this ); } );
        //if (endAddress == response[x].Address) { addressExists = true; }
        //response[x].GMarker = gmarker;
        //addPlaceDetail(response[x]);
        //map.addOverlay(gmarker);
    }
    //if (!addressExists)
    //{
    //    endAddress = "";
    //}
    if (response.length == 0)
    {
        var div = document.createElement("div");
        div.innerHTML = "No results found.";
        divPlaces.appendChild(div);
    }
    map.addOverlay(currentPosition);
    map.setCenter(currentPosition.getPoint(), 14);
}


function getPlacesByPlaceID(placeID)
{
    DCA.Web.WebServices.Service.GetPlacesByPlaceID(placeID, currentPosition.getPoint().lat(),currentPosition.getPoint().lng(), getPlacesByPlaceIDResponse);
}


function getPlacesByPlaceIDResponse(response)
{
    for (var x = 0; x < markers.length; x++)
    {
        if (markers[x].PlaceID == response.PlaceID)
        {
            markers[x] = response;
            break;
        }
    }
    var point = new GLatLng(markers[x].Latitude, markers[x].Longitude);
    
    
    var gmarker = new GMarker(point, parkingMarkerOptions);
    //var gmarker = new GMarker(point);
    
    GEvent.addListener(gmarker, "click", function() { markerClick( this ); } );
    if (endAddress == markers[x].Address) { addressExists = true; }
    markers[x].GMarker = gmarker;
    //addPlaceDetail(markers[x]);
    map.addOverlay(gmarker);
    placesLoadedCount++;
    
    if (placesLoadedCount == placesCount)
    {
        placesOrderAndDisplay();
    }
    else
    {
        divPlaces.childNodes[0].innerHTML = "Loading " + placesLoadedCount.toString() + " of " + placesCount.toString() + " parking locations.";
    }
}

function order(x, y)
{
    if ( x < y ) return -1; 
    if ( x > y ) return 1; 
    return 0;
}

function placesOrderAndDisplay()
{
    //order();
    var orderDistance = new Array(markers.length);
    var markersOrdered = new Array(markers.length);
    for (var x = 0; x < markers.length; x++)
    {
        orderDistance[x] = markers[x].Distance;
    }
    orderDistance.sort(order);
    var orderedCount = 0;
    for (var x = 0; x < orderDistance.length; x++)
    {
        for ( var y = 0; y < markers.length; y++)
        {
            if (markers[y] != null)
            {
                if (markers[y].Distance == orderDistance[x])
                {
                    markersOrdered[orderedCount] = markers[y];
                    markers[y] = null;
                    orderedCount++;
                }
            }
        }
    }
    
    markers = markersOrdered;
    
    markersOrdered = null;
    orderDistance = null;
    
    for (var x = 0; x < markers.length; x++)
    {
        addPlaceDetail(markers[x]);
    }
    divPlaces.removeChild(divPlaces.childNodes[0]);
    hideLoading();
}

function onDirectionsLoad()
{
/*
    if (direc.childNodes[0] != null)
    {
        direc.childNodes[0].childNodes[0].childNodes[0].childNodes[0].style.backgroundColor = "#cae6b4";
        direc.childNodes[0].childNodes[0].childNodes[2].childNodes[0].style.backgroundColor = "#cae6b4";
    }
*/
    if (directions.getNumRoutes() > 0)
    {
        clearAll();
    }
    else
    {
        alert("Directions not found.");
    }
}

function addPlaceDetail(marker)
{
    var div = document.createElement("div");
    div.id = "div-" + marker.PlaceID;
    div.className = "placeUnselected";
    div.innerHTML = "<font color=\"#000000\"><b>" + marker.PlaceName + "</b><br>" + marker.Address.replace(/,/,"<br>") + "<br><b>" + marker.Distance + "mi</b></font>";
    divPlaces.appendChild(div);
    var br = document.createElement("br");
    divPlaces.appendChild(br);
    div.onclick = function () { markerClick( marker.GMarker ); };
}

function markerClick(markerObj)
{
    //infoWSCallBack = DCA.Web.WebServices.Service.GetInfoByPlaceID
    //if (infoWSCallBack != null)
    //{
    //    alert(infoWSCallBack);
    //    infoWSCallBack.abortPostBack();
    //    infoWSCallBack = null;
    //}
    var x;
    for (x = 0; x < markers.length; x++)
    {
        if (markers[x].GMarker == markerObj)
        {
            break;
        }
    }
    endAddress = markers[x].Address;
    if (divPlaceLast != null)
    {
        divPlaceLast.className = "placeUnselected";
        var divInfo = document.getElementById("divInfo");
        var lastPlaceID = divPlaceLast.id.replace(/div-/, "");
        var xlast = 0;
        for (xlast = 0; xlast < markers.length; xlast++)
        {
            if (markers[xlast].PlaceID == lastPlaceID)
            {
                break;
            }
        }
        divDirectionsSearchNew = document.getElementById("divDirectionsSearch");
        divPlaceLast.onclick = function () { markerClick(markers[xlast].GMarker) };
        if (divInfo != null)
        {
            divPlaceLast.removeChild(divInfo);
            divPlaceLast.removeChild(divDirectionsSearchNew);
        }
    }
    var di = document.getElementById("div-" + markers[x].PlaceID);
    di.className = "placeSelected";
    var divInfoNew = document.createElement("div");
    divInfoNew.id = "divInfo";
    divInfoNew.className = "divInfo";
    divInfoNew.innerHTML = "<b>Loading Info.</b>";
    DCA.Web.WebServices.Service.GetInfoByPlaceID(markers[x].PlaceID, getInfoByPlaceIDResponse);
    di.onclick = function () {};
    di.appendChild(divInfoNew);
    
    var divDirectionsSearchNew = document.createElement("div");
    divDirectionsSearchNew.id = "divDirectionsSearch";
    divDirectionsSearchNew.className = "divDirectionsSearch";
    
    divDirectionsSearchNew.innerHTML = divDirectionsSearchHTML;
    
    di.appendChild(divDirectionsSearchNew);
    divPlaceLast = di;
    markers[x].GMarker.openInfoWindowHtml(markers[x].PlaceName + "<br>" + markers[x].Address + "<br>" + parseFloat(markers[x].Distance) + " miles.<br>" + divDirectionsSearchHTML );
    
    if (navigator.appName == "Microsoft Internet Explorer")
    {
        divRightColumn.scrollTop = di.offsetTop;
    }
    else
    {
        divRightColumn.scrollTop = di.offsetTop - divRightColumn.offsetTop;
    }
    
}

function getInfoByPlaceIDResponse(response)
{
    var divInfo = document.getElementById("divInfo");
    divInfo.innerHTML = response;
}

function getDirections(buttonObj)
{
    var address = "";
    for (var x = 0; x < buttonObj.parentNode.childNodes.length; x++)
    {
        if (buttonObj.parentNode.childNodes[x].tagName == "INPUT")
        {
           address = buttonObj.parentNode.childNodes[x].value + "";
           break;
        }
    }
    //var txtStartAddress = document.getElementById("txtStartAddress");
    if (endAddress == "")
    {
        alert("No destination was selected.");
    }
    if (address == "")
    {
        alert("No start address was entered.");
    }
    else
    {
        startAddress = address + ", Cleveland, OH, United States";
        var geocoder = new GClientGeocoder();
        geocoder.getLatLng(startAddress, function(point) { if (!point) { alert(startAddress + " not found"); } else { getDirectionsResponse(); } } );
    }
}

function getDirectionsResponse()
{
    clearAll();
    directions = new GDirections(map, divDirections);
    
    directions.load(startAddress + " to " + endAddress);
}

function refineSearch()
{
    var txtAddress = document.getElementById("txtAddress");
    var txtPhone = document.getElementById("txtPhoneNumber");
    var txtZipCodeNumber = document.getElementById("txtZipCodeNumber");
    
    if (txtAddress.value == "" && txtZipCodeNumber.value == "")
    {
        alert("Nothing to find was selected");
    }
    else
    {
        var currentPositionAddress = "";
        
        currentPositionAddress = currentPositionAddress + txtAddress.value;
        
        if (currentPositionAddress != "" && txtZipCodeNumber.value != "") { currentPositionAddress = currentPositionAddress + ", " } 
        
        currentPositionAddress = currentPositionAddress + txtZipCodeNumber.value;
        
        if (currentPositionAddress != "") { currentPositionAddress = currentPositionAddress + ", " } 
        
        currentPositionAddress = currentPositionAddress + "Cleveland, Ohio, United States";
        
        //alert(currentPositionAddress);
        
        var geocoder = new GClientGeocoder();
        geocoder.getLatLng(currentPositionAddress, function (point) { refineSearchResponse(point, currentPositionAddress); });
    }
}


function refineSearchResponse(point, address)
{
    if (!point) 
    { 
        var geocoder = new GClientGeocoder();
        geocoder.getLocations(address, function (result) { if (result.Status.code == G_GEO_SUCCESS) { placeCurrentPosition( new GLatLng( result.Placemark[0].Point.coordinates[1], result.Placemark[0].Point.coordinates[0]) ); } else { alert("The address that you entered is not valid. Please try again."); } });
    }
    else
    {
        placeCurrentPosition(point);
    }

    
}

function placeCurrentPosition(point)
{
    clearAll();
    
    currentPosition = new GMarker(point); 
    getPlacesByCurrentPosition();
    
    var txtAddress = document.getElementById("txtAddress");
    var txtPhone = document.getElementById("txtPhoneNumber");
    var txtZipCodeNumber = document.getElementById("txtZipCodeNumber");
    
    hideForm();
}

function ini()
{
    divRightColumn = document.getElementById("divRightColumn");
    divPlaces = document.getElementById("divPlaces");
    divDirections = document.getElementById("direc");
    divDirectionsSearch = document.getElementById("divDirectionsSearch");
    
    divDirectionsSearchHTML = divDirectionsSearch.innerHTML;
    
    divRightColumn.removeChild(divDirectionsSearch);
    
    baseIcon = new GIcon();
    baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
    baseIcon.iconSize = new GSize(20, 34);
    baseIcon.shadowSize = new GSize(37, 34);
    baseIcon.iconAnchor = new GPoint(9, 34);
    baseIcon.iconAnchor = new GPoint(9, 34);
    baseIcon.infoWindowAnchor = new GPoint(9, 2);
    baseIcon.infoShadowAnchor = new GPoint(18, 25);
        
    markerIcon = new GIcon(baseIcon);
    markerIcon.image = appPath + "/images/blue_MarkerP.png";
    
    parkingMarkerOptions = { icon:markerIcon };
       
    map = new GMap2(document.getElementById("map_google_div_DCA"), null);
    map.addControl(new GSmallMapControl());
    
    directions = new GDirections(map, document.getElementById("direc"));
    GEvent.addListener(directions, "load", onDirectionsLoad);
    //getPlacesByCurrentPosition();
    startAddress = "500 ontario st, Cleveland, OH, United States";
    var geocoder = new GClientGeocoder();
    geocoder.getLatLng
    (
        startAddress, 
        function(point)
        { 
            if (!point) { 
                alert(startAddress + " not found"); 
            } 
            else 
            { 
                if (currentPosition != null) 
                { 
                    map.removeOverlay(currentPosition); 
                } 
                currentPosition = new GMarker(point); 
                //map.addOverlay(currentPosition); 
                map.setCenter(point, 14); 
                getPlacesByCurrentPosition(); 
            } 
        } 
    );
}

function showForm()
{
    if (document.getElementById("divRefineSearchCanvas").style.display=="inline")
    {
        hideForm();
    }
    else
    {
        document.getElementById("divRefineSearchCanvas").style.display="inline";
        document.getElementById("divRefineSearchForm").style.display="inline";
    }
}

function hideForm()
{
    document.getElementById("divRefineSearchCanvas").style.display="none";
    document.getElementById("divRefineSearchForm").style.display="none";
}

function showLoading()
{
    document.getElementById("divLoadingCanvas").style.display="inline";
}

function hideLoading()
{
    document.getElementById("divLoadingCanvas").style.display="none";
}

