﻿/*

This file contains the client side data access layer which is responsible
for all server interoperation using AJAX

*/

function DAL(){

    /* Constants */
    
    // Proxy configuration
   var proxyHost = document.location.protocol + "//" + document.location.host + "/SiteLocator/";
    
    //test only (localhost)
   //var proxyHost = document.location.protocol + "//" + document.location.host + "/ATCLocator_VE2/";
    
    
    //test only (QC)
    //var proxyHost = document.location.protocol + "//" + document.location.host + "/SiteLocator2/";
    
    
    var proxyPage = "find.ashx";
    var proxy = proxyHost + proxyPage;

    var ddPrintPage = "PrintRoute.aspx";
    var ddProxy = proxyHost + ddPrintPage;

    var ppResultsPage = "PrintPreview.aspx";
    var ppProxy = proxyHost + ppResultsPage;

    var exportProxyPage = "export.ashx";
    var exportProxy = proxyHost + exportProxyPage;

    var auxProxyPage = "auxiliary.ashx";
    var auxProxy = proxyHost + auxProxyPage;
    
    // Request parameters.
    var ProxyMaxResultsParameter = "max";
    var ProxyDownloadableParameter = "dl";
    var ProxyPrintPreviewParameter = "pp";
    var ProxyActionParameter = "action";

    // Action values
    var ProxyActionFindNearby = "findNearby";
    var ProxyActionFindByState = "findByState";
    var ProxyActionFindByName = "findByName";
    var ProxyActionFindByCode = "findByCode";
    var ProxyActionFindByExtents = "findByExtents";

    // FindNearby action parameters
    var ProxyLatitudeParameter = "latitude";
    var ProxyLongitudeParameter = "longitude";
    var ProxyRadiusParameter = "radius";
    var ProxyFilterParameter = "filter";

    // FindByState action parameters
    var ProxyStateParameter = "state";

    // FindByName action parameters
    var ProxySiteNameParameter = "siteName";
    var ProxySiteNumberParameter = "siteNum";

    // FindByCode action parameters
    var ProxyCodeNameParameter = "codeName";
    var ProxyCodeValueParameter = "codeValue";

    // FindByExtents action parameters
    var ProxyTopLeftLatitudeParameter = "tllat";
    var ProxyTopLeftLongitudeParameter = "tllon";
    var ProxyBottomRightLatitudeParameter = "brlat";
    var ProxyBottomRightLongitudeParameter = "brlon";

    // Filter Parameters
    var ProxyWirelessParameter = "w";
    var ProxyBroadcastParameter = "b";
    var ProxyInBuildingParameter = "i";
    var ProxyInManagedParameter = "m";
    var ProxyRooftopParameter = "r";
    var ProxyUnknownParameter = "u";

    // Filter Driving Directions Print Preview Parameters
    var ProxyDDOriginAddressParameter = "oa";
    var ProxyDDOriginLatitudeParameter = "olat";
    var ProxyDDOriginLongitudeParameter = "olon";
    var ProxyDDDestinationAddressParameter = "da";
    var ProxyDDDestinationLatitudeParameter = "dlat";
    var ProxyDDDestinationLongitudeParameter = "dlon";

    // Auxiliary Proxy Parameters

    var ProxyActionGetTowerImage = "getTowerImage";
    var ProxyActionGetStates = "getStates";
    var ProxyActionGetMSARSAs = "getMSARSAs";
    var ProxyActionGetMTAs = "getMTAs";
    var ProxyActionGetBTAs = "getBTAs";
    var ProxyActionGetImagePrefix = "getImagePrefix";
    
    // Image retrieval parameters
    var ProxyImageIdParameter = "siteId";

    // Error logging parameters
    var ProxyActionErrorLog = "logError";
    var ProxyErrorMessageParameter = "message";
    
    /* End Constants */   

    // Members
    var _proxy = null;
    var _url = null;

    
    
    
    
    _init();
    
    // Constructor
    function _init(){
        _proxy = proxy;
    }
    
    
    /* Find Methods */
    
    // Finds a user specified location and proceeds to do a find nearby.
    function _findAddress(address, callback){
        _callback = callback;
        try{
        //changed in v 6.1
         //map.VE.FindLocation(address, _callback);
         // Find method combines FindLocation and FindNearby into one
         // as Find(what, where, VEFindType.Businesses, ..., callback)
         map.VE.Find(null, address,  null, null, null, null, false, true, true, true,  _callback);         
        }
        catch(err){
            loadingbox.ShowAndStay(err.message);
        }
    }   
        
       
       
    // Create FindNearby /w Filter request & execute.
    function _findNearby(latlong, radius, filter, maxResults, callback){
        _callback = callback;
        
        var keys = new Array(
            ProxyActionParameter, 
            ProxyLatitudeParameter,
            ProxyLongitudeParameter,
            ProxyRadiusParameter,
            ProxyMaxResultsParameter
        );
        
        var values = new Array(
            ProxyActionFindNearby,
            latlong.Latitude,
            latlong.Longitude,
            radius,
            maxResults
        );
        
        _url = _createQueryString(keys, values, filter);
        _startRequest();
    }
    
    // Create find by state request & execute.
    function _findByState(state, filter, maxResults, callback){
        _callback = callback;
        
        var keys = new Array(ProxyActionParameter, ProxyStateParameter, ProxyMaxResultsParameter);
        var values = new Array(ProxyActionFindByState, state, maxResults);
        
        _url = _createQueryString(keys, values, filter);
        _startRequest();
    }
    
    // Create find by site name or number request & execute.
    function _findByName(towerName, towerNumber, filter, maxResults, callback){
    
        _callback = callback;
        
        var keys = new Array(ProxyActionParameter, ProxyMaxResultsParameter);
        var values = new Array(ProxyActionFindByName, maxResults);
        
        _url = _createQueryString(keys, values, filter);

        if (towerName.length > 0){
            _url = _addQueryParameter(_url, ProxySiteNameParameter, escape(towerName));
        }
        if (towerNumber.length > 0){
            _url = _addQueryParameter(_url, ProxySiteNumberParameter, towerNumber);
        }

        _startRequest();
    }

    // Create find by custom AT code request & execute.
    function _findByCode(codeName, codeValue, filter, maxResults, callback){
        _callback = callback;
        
        var keys = new Array(
            ProxyActionParameter, 
            ProxyMaxResultsParameter, 
            ProxyCodeNameParameter,  
            ProxyCodeValueParameter
        );
        
        var values = new Array(
            ProxyActionFindByCode, 
            maxResults, 
            codeName,
            escape(codeValue)
        );
        
        _url = _createQueryString(keys, values, filter);
        _startRequest();
    }
    
    function _findByExtents(topLeftLat, topLeftLon, bottomRightLat, bottomRightLon, filter, maxResults, callback){
    
        _callback = callback;
        
        var keys = new Array(
            ProxyActionParameter, 
            ProxyMaxResultsParameter, 
            ProxyTopLeftLatitudeParameter,  
            ProxyTopLeftLongitudeParameter,
            ProxyBottomRightLatitudeParameter,
            ProxyBottomRightLongitudeParameter
        );
        
        var values = new Array(
            ProxyActionFindByExtents, 
            maxResults, 
            topLeftLat,
            topLeftLon,
            bottomRightLat,
            bottomRightLon
        );
        
        _url = _createQueryString(keys, values, filter);
        _startRequest();        
    }
    
    /* End Find Methods */
    
    /* Getter Methods */
    
    // Gets the currently selected filter options from the search panel.
    function _getFilter(locationTypeArray){
    
        var filter = "";
        
        var locationParameter = Array(
            ProxyWirelessParameter, 
            ProxyBroadcastParameter, 
            ProxyInBuildingParameter, 
            ProxyInManagedParameter, 
            ProxyRooftopParameter, 
            ProxyUnknownParameter
        );
        
        for (var i = 0; i < locationTypeArray.length; i++){
            var value = document.getElementById(locationTypeArray[i]).checked;
            filter += "&" + locationParameter[i] + "=" + getBooleanInteger(value);
        }
        
        return filter;
    }    
    
    // Returns the query string for the last find call (so it can be re-run in pp/export mode)
    function _getLastCallURL(){
        return _url;
    }
    
    // Find a route   
    function _getRoute(originLocation, destinationLocation, callback){
        //loadingbox.Show();
        try{
            // v 6.1 This method is deprecated
            //map.VE.GetRoute(originLocation, destinationLocation, VEDistanceUnit.Miles, null, callback);
            
            var locations;
            var options = new VERouteOptions;
            
            locations = new Array(originLocation, destinationLocation);
            
            
            options.DrawRoute = true;
            
            options.SetBestMapView = true;
            
            options.DistanceUnit = VERouteDistanceUnit.Mile;
            
            // Show the disambiguation dialog
            options.ShowDisambiguation = true;
            
                 
            //call back function
            options.RouteCallback = callback; 

            map.VE.GetDirections(locations, options);
            
        }
        catch(err){
            loadingbox.ShowAndStay("Error retrieving route", false, 2000);
        }
    }
    
    
    // time is an integer representing seconds
         // returns a formatted string
         function _ConvertTime(time)
         {
            if(time == null)
            {
               return("");
            }

            if(time > 60)
            {                                 // if time == 100
               var seconds = time % 60;       // seconds == 40
               var minutes = time - seconds;  // minutes == 60
               minutes     = minutes / 60;    // minutes == 1


               if(minutes > 60)
               {                                     // if minutes == 100
                  var minLeft = minutes % 60;        // minLeft    == 40
                  var hours   = minutes - minLeft;   // hours      == 60
                  hours       = hours / 60;          // hours      == 1

                  return(hours + " hour(s), " + minLeft + " minute(s), " + seconds + " second(s)");
               }
               else
               {
                  return(minutes + " minutes, " + seconds + " seconds");
               }
            }
            else
            {
               return(time + " seconds");
            }
         }

    
    // Sending routing points to PrintRoute page and recalculate route.
    // Addresses used for display only, coordinates used to prevent user from disambiguating a second time.
    function _getPPRouteURL(route,_printStartAddress,_printEndAddress){
        
        var keys = new Array(
            ProxyDDOriginAddressParameter, 
            ProxyDDOriginLatitudeParameter, 
            ProxyDDOriginLongitudeParameter,  
            ProxyDDDestinationAddressParameter,
            ProxyDDDestinationLatitudeParameter,
            ProxyDDDestinationLongitudeParameter
        );
        
       
        var values = new Array(
//            escape(route.StartLocation.Address), 
//            route.StartLocation.LatLong.Latitude, 
//            route.StartLocation.LatLong.Longitude,
//            escape(route.EndLocation.Address),
//            route.EndLocation.LatLong.Latitude,
//            route.EndLocation.LatLong.Longitude
            escape(_printStartAddress),
            route.RouteLegs[0].StartLocation.Latitude,
            route.RouteLegs[0].StartLocation.Longitude,
            escape(_printEndAddress),
            route.RouteLegs[0].EndLocation.Latitude,
            route.RouteLegs[0].EndLocation.Longitude
        );        
        
        var ddURL = ddProxy + _createQueryString(keys, values);
        return ddURL;
    }
    
    // Get corresponding Tower image.
    function _getImage(siteId, callback){
    
        var keys = new Array(ProxyActionParameter, ProxyImageIdParameter);
        var values = new Array(ProxyActionGetTowerImage, siteId);
        
        var imageURL = auxProxy + _createQueryString(keys, values);

        var req = new AjaxRequest(imageURL, callback);
        req.Execute();
    }
    
    function _getImagePrefix(callback){
        var keys = new Array(ProxyActionParameter);
        var values = new Array(ProxyActionGetImagePrefix);
        
        var imageURL = auxProxy + _createQueryString(keys, values);

        var req = new AjaxRequest(imageURL, callback);
        req.Execute();
    }
    
    // Gets tower states from server.
    function _getStates(callback){
        var comboURL = auxProxy + _createQueryString(new Array(ProxyActionParameter), new Array(ProxyActionGetStates));
        
        var req = new AjaxRequest(comboURL, callback);
        req.Execute();
    }

    // Gets tower MSA/RSA codes from server.
    function _getMSARSAs(callback){
        var comboURL = auxProxy + _createQueryString(new Array(ProxyActionParameter), new Array(ProxyActionGetMSARSAs));
        
        var req = new AjaxRequest(comboURL, callback);
        req.Execute();
    }
    
    // Gets tower MTA codes from server.
    function _getMTAs(callback){
        var comboURL = auxProxy + _createQueryString(new Array(ProxyActionParameter), new Array(ProxyActionGetMTAs));
        
        var req = new AjaxRequest(comboURL, callback);
        req.Execute();
    }

    //Gets tower BTA codes from server.
    function _getBTAs(callback){
        var comboURL = auxProxy + _createQueryString(new Array(ProxyActionParameter), new Array(ProxyActionGetBTAs));
        
        var req = new AjaxRequest(comboURL, callback);
        req.Execute();
    }
    
    // Logs client side errors to the server.
    function _logClientsideError(message){
    
        // Abort clientside error logging to server if debugging is off.
        if (!DEBUG){
            return;
        }
        
        var keys = new Array(ProxyActionParameter, ProxyErrorMessageParameter);
        var values = new Array(ProxyActionErrorLog, escape(message));
        var errorURL = auxProxy + _createQueryString(keys, values);
        
        var req = new AjaxRequest(errorURL);
        req.execute;
    }
    
    /* End Getter Methods */
    
    /* Private Methods */
    
    // Creates a query string based on the key value pairs passed.
    function _createQueryString(keyArray, valueArray, filter){
        if (keyArray.length != valueArray.length){
            return null;
        }
        
        var qstring = "?";
        
        for (var i = 0; i < keyArray.length; i++){
            qstring += ("&" + keyArray[i] + "=" + valueArray[i]);
        }
        
        if (isValid(filter)){
            qstring += filter;
        }
        
        return qstring;
    }
    
    function _addQueryParameter(qstring, key, value){
        qstring += ("&" + key + "=" + value);
        return qstring;
    }
    
    // General request for all types of finds.
    function _startRequest(){
        loadingbox.Show();
        var req = new AjaxRequest(_proxy + _url, _callback);
        req.Execute();
    }
    
    /* End Private Methods */
    
    // Public Accessors for search functions.    
    this.FindAddress = _findAddress;
    this.FindNearby = _findNearby;
    this.FindByState = _findByState;
    this.FindByName = _findByName;
    this.FindByCode = _findByCode;
    this.FindByExtents = _findByExtents;
    this.FindRoute = _getRoute;
    
    this.GetFilter = _getFilter;
    this.GetPPRouteURL = _getPPRouteURL;
    this.GetTowerImage = _getImage;
    this.GetLastCallURL = _getLastCallURL;
    this.GetStates = _getStates;
    this.GetMSARSAs = _getMSARSAs;
    this.GetMTAs = _getMTAs;
    this.GetBTAs = _getBTAs;
    this.GetImagePrefix = _getImagePrefix;
    
    this.PPProxy = ppProxy;
    this.ExportProxy = exportProxy;
    
    this.LogClientsideError = _logClientsideError;
    var findPlaceResults = null;
    this.GetTime = _ConvertTime;
}
