﻿// JScript File
var BAOToken;
var BAOLatLong;
var BAOFunction;
var BAORadius;
var BAOMapExtentConnect;
var BAOExtent;
var BAOReports;

function clickBAOTab()
{
    hideLayer("BAOLoading");
    jsMap.graphics.clear();
    jsMap.graphics.add(currPropGraphic);
    
    if (!loadingProperty)
    {
        currentReport = document.getElementById("divBAOReport").innerHTML;
        if (currentReport == "") startBAO();
        
        else {
            var bgLayer = jsMap.getLayer('baoGraphics');
            bgLayer.show();
            jsMap.setExtent(BAOExtent, true);
        }
    }
}
function clearBAO()
{
    var divReport = document.getElementById("divBAOReport");
    if (divReport != null) divReport.innerHTML = "";
        
}

function startBAO()
{
    showLayer("BusyIndicator");
    showLayer("BAOLoading");

    BAORadius = document.getElementById('bbusPropertyDetails_txtBAORadius').value;
    currPropGraphic = getGraphicById(currPropId);
    getBAOLatLong(currPropGraphic.geometry);
	
}

function getBAOToken()
{
    var BAOconfig;
    var mapBAO = document.getElementById("bbusMap_mapBAO").value;
    if (mapBAO != "")    BAOconfig = dojo.fromJson(mapBAO);
    else
    {
        alert('A credentials error has occured.  Please contact site administrator.');
        return;
    }     
    var jsonpArgs = {
        url:'bao.aspx',
        handleAs: 'json',    
        content: { ref: 'https://baoapi.esri.com/rest/authentication',
                    request: 'getToken',
                    username: BAOconfig.bao.username,
                    password: BAOconfig.bao.password,
                    f: 'JSON'
                },     
        load: function(data,ioArgs){
                //alert('Data is returned');
                setToken(data);
                getDriveTimes();
                },
        error: function(error,ioArgs) {
                alert('An unexpected error occurred');
                //setToken(error);
                } };
    dojo.xhrPost(jsonpArgs);
}
function setToken(data)
{
    if(data.results.token)
    {
        BAOToken = data.results.token;
    }
}    
    
function getDriveTimes()
{
    var jsonpArgs = {
        url:'bao.aspx',
        handleAs: 'json',    
        content: { ref: 'http://baoapi.esri.com/rest/report/DriveTime',
                    token: BAOToken,
                    DistanceUnits: 'esriDriveTimeUnitsMinutes',
                    Radii: BAORadius,
                    Stores: dojo.toJson(BAOLatLong),
                    TaskOutputType:'GetFeatureClass',
                    f: 'JSON'
                },     
        load: function(data,ioArgs){
                //alert('Data is returned');
                projectDriveTimes(data);
                },
        error: function(error,ioArgs) {
                alert('An unexpected error occurred');
                } };
    dojo.xhrPost(jsonpArgs);
}

function projectDriveTimes(data)
{
    var BAORings = [];
    for(var ring in data.RecordSet.features)
    {
        var baoGeo = esri.geometry.fromJson(data.RecordSet.features[ring].geometry);
        baoGeo.spatialReference=new esri.SpatialReference({ wkid: 4326});
        var feature = new esri.Graphic(baoGeo);
        BAORings.push(feature);
    }
    
    var mapGsvc = document.getElementById("bbusMap_mapGeometryService").value;
    if (mapGsvc == "") mapGsvc = "http://maps.binarybus.net/arcgis/rest/services/Geometry/GeometryServer";
    if(gsvc == null) gsvc = new esri.tasks.GeometryService(mapGsvc);
    esri.config.defaults.io.proxyUrl = "proxy.ashx";
    gsvc.project(BAORings, jsSR, addDriveTimes);
    
}

function addDriveTimes(features)
{
    var symbol = new esri.symbol.SimpleMarkerSymbol();
    symbol.setColor(new dojo.Color([255,0,0]));

    //Create graphics layer for rings
    var blayer = jsMap.getLayer('baoGraphics');
    if (blayer != null) jsMap.removeLayer(blayer);
    
    baoGraphics = new esri.layers.GraphicsLayer({id: 'baoGraphics'});
    jsMap.addLayer(baoGraphics);
    jsMap.reorderLayer(baoGraphics,jsMap.layerIds.length+jsMap.graphicsLayerIds.length-1);
    
    //Add rings to the graphics layer
    for (var ring in features) 
    {
        symbol.setColor(new dojo.Color([255,0,0,.5]));
        baoGraphics.add(features[ring].setSymbol(symbol));
        BAOExtent = features[ring].geometry.getExtent();
    }
    esri.config.defaults.io.proxyUrl = null;
    
    jsMap.setExtent(BAOExtent, true);
    
    hideLayer("BusyIndicator");
    
    getReports();
}

function getDriveReport(name,format)
{
    var propname = document.getElementById("bbusPropertyDetails_demoPropName").value;
    var Reports = null
    if(name == null)
    {
        Reports = [{
                    "TemplateName": "market_profile",
                    "ReportFormat": "excel",
                    "ReportHeader": [
                      {
                        "Key": "subtitle",
                        "Value": propname+" Profile"
                      },
                      {
                        "Key": "address1",
                        "Value": propname
                      }
                    ]
                  },
                  {
                    "TemplateName": "market_profile",
                    "ReportFormat": "PDF",
                    "ReportHeader": [
                      {
                        "Key": "subtitle",
                        "Value": propname+" Profile"
                      },
                      {
                        "Key": "address1",
                        "Value": propname
                      }
                    ]
                  }
                ];
    }
    else Reports = [{
                    "TemplateName": name,
                    "ReportFormat": format,
                    "ReportHeader": [
                      {
                        "Key": "subtitle",
                        "Value": propname+" Profile"
                      },
                      {
                        "Key": "address1",
                        "Value": propname
                      }
                    ]
                  }];
    var jsonpArgs = {
        url:'bao.aspx',
        handleAs: 'json',    
        content: { ref: 'http://baoapi.esri.com/rest/report/DriveTime',
                    token: BAOToken,
                    DistanceUnits: 'esriDriveTimeUnitsMinutes',
                    Radii: BAORadius,
                    Stores: dojo.toJson(BAOLatLong),
                    TaskOutputType:'GetReport',
                    ReportOptions:dojo.toJson(Reports),
                    f: 'JSON'
                },     
        load: function(data,ioArgs){
                //alert('Data is returned');
                showDriveReport(data);
                },
        error: function(error,ioArgs) {
                alert('An unexpected error occurred');
                } };
    dojo.xhrPost(jsonpArgs);
}

function showDriveReport(data)
{
    var BAOReportDIV = document.getElementById("divBAOReport");
    var repID;
    for(var rep in BAOReports)
    {
        if (BAOReports[rep].name == data.Reports[0].TemplateName)
        {
            repID = rep;
            break;
        }
    }
    var repDescription = "";
    if (data.Reports[0].TemplateName == "market_profile")
        repDescription = "This report provides an overview of key demographic attributes and consumer spending patterns for the specified area."
    var reportText = "<div id='div_BAO_"+data.Reports[0].TemplateName+"'><br/><div class='header' onclick='propertyDetails_ToggleContent(this);'>"+BAOReports[repID].title+"</div><div class='baocontent'>"+repDescription+"<br/>"
    for(var rep in data.Reports)
    {
        reportText = reportText + "<a href='"+data.Reports[rep].ReportURL+"' target='_blank' border=0>View "+data.Reports[rep].ReportFormat+"</a><br/>"
    }
    reportText = reportText + "</div></div>"
    BAOReportDIV.innerHTML = BAOReportDIV.innerHTML + reportText;
    
    window.setTimeout("ResizeInPane('paneLeftBody', 'divBAOReport', 475, 200, 0, 0);",10);
    hideLayer("BAOLoading");
}

function getReports()
{
    var jsonpArgs = {
        url:'bao.aspx',
        handleAs: 'json',    
        content: { ref: 'http://baoapi.esri.com/rest/report/GetReportTemplates',
                    token: BAOToken,
                    f: 'JSON'
                },     
        load: function(data,ioArgs){
                //alert('Data is returned');
                seeReports(data);
                },
        error: function(error,ioArgs) {
                //alert('An unexpected error occurred');
                //seeReports(error);
                } };
    dojo.xhrPost(jsonpArgs);
}
function seeReports(data)
{
    BAOReports = data.results;
    var BAOReportDIV = document.getElementById("divBAOReport");
    var reportText = "<br/><div id='div_BAO_report_list'><div class='description'>Select Report: </div><select id='sel_BAOReport' class='floatSelect' onchange='setRepFormat();'>";
    for(var rep in BAOReports)
    {
        reportText = reportText + "<option value='"+BAOReports[rep].name+"'>"+BAOReports[rep].title+"</option>";
    }
    reportText = reportText + "</select><div id='divsel_BAOFormat' class='floatSelect'><select id='sel_BAOFormat'>"
    for(var format in BAOReports[0].formats)
    {
        reportText = reportText + "<option value='"+BAOReports[0].formats[format]+"'>"+BAOReports[0].formats[format]+"</option>";
    }
    reportText = reportText + "</select></div><div class='goButton' id='GoReport'><a href='#' onclick='startDriveReport();'>Go</a></div></div><br>";
    
    BAOReportDIV.innerHTML = reportText;
    
    getDriveReport();
}

function setRepFormat()
{
    var BAOReportSEL = document.getElementById("sel_BAOReport");
    var BAOFormatSEL = document.getElementById("divsel_BAOFormat");
    var repID;
    for(var rep in BAOReports)
    {
        if (BAOReports[rep].name == BAOReportSEL.options[BAOReportSEL.selectedIndex].value)
        repID = rep;
    }
    var formText = "<select id='sel_BAOFormat'>";
    BAOFormatSEL.innerHTML = formText;
    
    for(var format in BAOReports[repID].formats)
    {
        formText = formText + "<option value='"+BAOReports[repID].formats[format]+"'>"+BAOReports[repID].formats[format]+"</option>";
    }
    formText = formText + "</select>";
    
    BAOFormatSEL.innerHTML = formText;
}

function startDriveReport()
{
    showLayer("BAOLoading");
    var BAOReportSEL = document.getElementById("sel_BAOReport");
    var BAOFormatSEL = document.getElementById("sel_BAOFormat");
    
    if (BAOReportSEL != null)
        getDriveReport(BAOReportSEL.options[BAOReportSEL.selectedIndex].value,BAOFormatSEL.options[BAOFormatSEL.selectedIndex].value);
    
}
        
function getBAOLatLong(BAOPoint)
{
    var mapGsvc = document.getElementById("bbusMap_mapGeometryService").value;
    if (mapGsvc == "") mapGsvc = "http://maps.binarybus.net/arcgis/rest/services/Geometry/GeometryServer";
    if(gsvc == null) gsvc = new esri.tasks.GeometryService(mapGsvc);
    var outSR = new esri.SpatialReference({ wkid: 4326});
    gsvc.project([ new esri.Graphic( BAOPoint ) ], outSR, setBAOLatLong);
    //setBAOLatLong(BAOPoint);
}
function setBAOLatLong(features)
{
    BAOLatLong = {"Points": [
        {
        "longitude": features[0].geometry.x,
        "latitude": features[0].geometry.y,
        "name": "location"+currPropId,
        "description": "location "+currPropId,
        "storeID": currPropId
        }
        ],
    "spatialReference": {"wkid": 4326}
    };
    
//    BAOLatLong =  {
//      "RecordSet": {
//        "geometryType": "esriGeometryPoint",
//        "spatialReference": {"wkid": 4326},
//        "features": [
//          {
//            "geometry": {
//              "x": features[0].geometry.x,
//              "y": features[0].geometry.y,
//              "spatialReference": {"wkid": 4326}
//            },
//            "attributes": {
//              "STORE_ID": currPropId
//            }
//          }
//        ]
//      },
//      "SpatialReference": {"wkid": 4326}
//    }

    getBAOToken();
}