﻿// JScript File
var BAOToken;
var BAOLatLong;
var BAOFunction;
var BAORadius;
var BAOMapExtentConnect;
var BAOExtent;
var BAOReports;
var BAOConfig;
var BAOStore;
var BAOStoreItems;
var BAOReportStore;
var BAOXMLURL=null;
var blnIsInit = false;
var baoPrefix = "";
var baoCurrId;
dojo.require("dojox.data.XmlStore");

function clickBAOTab(elementPrefix)
{
    if (elementPrefix == null) elementPrefix = 'prop';
    baoPrefix = elementPrefix;
    hideLayer(baoPrefix+"BAOLoading");
    turnOffMapGraphics();
    
    if (!loadingProperty)
    {
        currentReport = document.getElementById(baoPrefix+"divBAOReport").innerHTML;
        if (currentReport == "") startBAO();
        
        else {            
            turnOnMapGraphics('baoGraphics');
            jsMap.setExtent(BAOExtent, true);
            
        }
    }
    turnOnMapGraphics('selectedPropertyGraphics');
    
}
function clearBAO(elementPrefix)
{
    if(elementPrefix!=null)baoPrefix = elementPrefix;
    var divReport = document.getElementById(baoPrefix+"divBAOReport");
    if (divReport != null) divReport.innerHTML = "";
    BAOStore = null;
        
}

function startBAO(elementPrefix)
{
    blnIsInit = false;
    if(elementPrefix!=null)baoPrefix = elementPrefix;
    showLayer("BusyIndicator");
    showLayer(baoPrefix+"BAOLoading");
    
    clearBAO(baoPrefix);
    BAORadius = document.getElementById(baoPrefix+'txtBAORadius').value;
    baoCurrId = (baoPrefix=='prop')?currPropId:currDemoSiteId;
    var currGraphic = getGraphicById(baoCurrId);
    getBAOLatLong(currGraphic.geometry);
}

function initBAO()
{
    blnIsInit = true;
    var mapBAO = document.getElementById("bbusMap_mapBAO").value;
    if (mapBAO != "")    BAOConfig = dojo.fromJson(mapBAO);
    
    if (BAOConfig)
    {
        setBAO('prop',BAOConfig.bao.type,BAOConfig.bao.radius);
        setBAO('site',BAOConfig.bao.type,BAOConfig.bao.radius);
        
        baoPrefix = '';
        getBAOToken();
    }
}

function setBAO(thebaoPrefix,type,radius)
{
    if (type != null)
    {
        selBAOType = document.getElementById(thebaoPrefix+'selBAOTradeAreaType');
        if (selBAOType != null)
        {
            for(i=0;i<selBAOType.options.length;i++)
            {
                if (selBAOType.options[i].value == type)
                {
                    selBAOType.selectedIndex = i;
                    setBAOUnit(thebaoPrefix,selBAOType);
                    break;
                }
            }   
        } 
    }
    if (radius != null)
    {
        inpBAORadius = document.getElementById(thebaoPrefix+'txtBAORadius');
        if (inpBAORadius != null) 
        {  if (BAOConfig.bao.radius) inpBAORadius.value = radius;}
    }    
}

function setBAOUnit(thebaoPrefix,selBAOType)
{
    typeVal = selBAOType.options[selBAOType.selectedIndex].value;
    BAOUnits = document.getElementById(thebaoPrefix+'labelBAOUnit')
    BAORingUnit = document.getElementById(thebaoPrefix+'selBAORingUnit');
    BAOUnits.innerHTML = (typeVal == "drivetime")? "minutes":"miles";
    BAOUnits.style.display = (typeVal == "drivetime")? "block":"none";
    BAORingUnit.style.display = (typeVal == "drivetime")? "none":"block";
    if (typeVal!="drivetime") setBAORingUnit(thebaoPrefix,BAORingUnit);
}

function setBAORingUnit(thebaoPrefix,selBAORingUnit)
{
    typeVal = selBAORingUnit.options[selBAORingUnit.selectedIndex].value;
    document.getElementById(thebaoPrefix+'labelBAOUnit').innerHTML = typeVal;
}
function getBAOToken()
{
    if (BAOConfig == null)  
    {
        alert('No credentials provided.  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);
                if(blnIsInit)
                    getReports();
                else
                    getDriveTimes();
                },
        error: function(error,ioArgs) {
                hideLayer("BAOLoading");
                hideLayer("BusyIndicator");
                alert('A credentials error has occured.  Please contact site administrator.');
                //setToken(error);
                } };
    dojo.xhrPost(jsonpArgs);
}
function setToken(data)
{
    if(data.results.token)
    {
        BAOToken = data.results.token;
    }
}    
    
function getDriveTimes()
{
    var selBAOType = document.getElementById(baoPrefix+'selBAOTradeAreaType');
    var typeVal = selBAOType.options[selBAOType.selectedIndex].value;
    var selBAORingUnit = document.getElementById(baoPrefix+'selBAORingUnit');
    var BAORingUnit = (selBAORingUnit)? selBAORingUnit.options[selBAORingUnit.selectedIndex].value: '';
    var BAOendpoint = (typeVal=='drivetime')? 'http://baoapi.esri.com/rest/report/DriveTime': 'http://baoapi.esri.com/rest/report/SimpleRings'
    var BAOunit = (typeVal=='drivetime')? 'esriDriveTimeUnitsMinutes':(BAORingUnit=='miles')? 'esriMiles':'esriKilometers';   
       
    var jsonpArgs = {
        url:'bao.aspx',
        handleAs: 'json',    
        content: { ref: BAOendpoint,
                    token: BAOToken,
                    DistanceUnits: BAOunit,
                    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);
    turnOnMapGraphics('selectedPropertyGraphics');
    
    //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).setAttributes({'id':'baoGraphic','type':'bao'}));
        BAOExtent = features[ring].geometry.getExtent();
    }
    esri.config.defaults.io.proxyUrl = null;
    
    jsMap.setExtent(BAOExtent, true);
    hideLayer("BusyIndicator");
    
    //getReports();
    getDriveReport();
}

function getDriveReport(name,format)
{
    var selBAOType = document.getElementById(baoPrefix+'selBAOTradeAreaType');
    var typeVal = selBAOType.options[selBAOType.selectedIndex].value;
    var selBAORingUnit = document.getElementById(baoPrefix+'selBAORingUnit');
    var BAORingUnit = (selBAORingUnit)? selBAORingUnit.options[selBAORingUnit.selectedIndex].value: '';
    var BAOendpoint = (typeVal=='drivetime')? 'http://baoapi.esri.com/rest/report/DriveTime': 'http://baoapi.esri.com/rest/report/SimpleRings'
    var BAOunit = (typeVal=='drivetime')? 'esriDriveTimeUnitsMinutes':(BAORingUnit=='miles')? 'esriMiles':'esriKilometers';   
    var titlePrefix = (BAOConfig.bao.titleprefix)? BAOConfig.bao.titleprefix:"";
    var logoURL = (BAOConfig.bao.logo)? BAOConfig.bao.logo:"";
    var propname = document.getElementById(((baoPrefix=='prop')?"bbusPropertyDetails_demoPropName":"bbusDemographicsDetails_demoPropName")).value;
    var Reports = null
    if(name == null)
    {
        Reports = [{
                    "TemplateName": "market_profile",
                    "ReportFormat": "PDF",
                    "ReportHeader": [
                      {
                        "Key": "subtitle",
                        "Value": titlePrefix+" "+propname
                      },
                      {
                        "Key": "address1",
                        "Value": propname
                      },
                      {
                        "Key": "logo",
                        "Value": logoURL
                      }
                    ]
                  },
                  {
                    "TemplateName": "market_profile",
                    "ReportFormat": "XML",
                    "ReportHeader": [
                      {
                        "Key": "subtitle",
                        "Value": titlePrefix+" "+propname
                      },
                      {
                        "Key": "address1",
                        "Value": propname
                      }
                    ]
                  }
                ];
    }
    else Reports = [{
                    "TemplateName": name,
                    "ReportFormat": format,
                    "ReportHeader": [
                      {
                        "Key": "subtitle",
                        "Value": titlePrefix+" "+propname
                      },
                      {
                        "Key": "address1",
                        "Value": propname
                      },
                      {
                        "Key": "logo",
                        "Value": logoURL
                      }
                    ]
                  }];
    var jsonpArgs = {
        url:'bao.aspx',
        handleAs: 'json',    
        content: { ref: BAOendpoint,
                    token: BAOToken,
                    DistanceUnits: BAOunit,
                    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)
{
    BAOXMLURL = null;
    var BAOReportDIV = document.getElementById(baoPrefix+"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.<br/>"
    var reportText = "<div id='div_BAO_"+data.Reports[0].TemplateName+"'><br/><div class='header' onclick='propertyDetails_ToggleContent(this);'><span>"+BAOReports[repID].title+"</span></div>";
    
    reportText = reportText + "<table cellpadding=\"0\" cellspacing=\"0\" class=\"content\" >";
    reportText = reportText + "<tr class=\"right row0\"><td><div class='baocontent'>"+repDescription;
        
    for(var rep in data.Reports)
    {
        if(data.Reports[rep].ReportFormat == "XML" && data.Reports[rep].TemplateName == "market_profile")
            BAOXMLURL = data.Reports[rep].ReportURL;
        else 
            reportText = reportText + "<a href='"+data.Reports[rep].ReportURL+"' target='_blank' border=0>View "+data.Reports[rep].ReportFormat+"</a><br/>"
    }
    reportText = reportText + "</div></td></tr></table><div class=\"footer\">&nbsp;</div></div>"
    BAOReportDIV.innerHTML = reportText + BAOReportDIV.innerHTML;
    
    var propname = document.getElementById(((baoPrefix=='prop')?"bbusPropertyDetails_demoPropName":"bbusDemographicsDetails_demoPropName")).value;
    var baotrack = "BAO "+BAOReports[repID].title;
    if(baoPrefix=='prop') GACTTrackEvent("Property Details",baotrack,"Property - "+propname);
    if(baoPrefix=='site') GACTTrackEvent("Site Analysis",baotrack,"Site - "+propname);
    if(BAOXMLURL) window.setTimeout("prepareMarketProfile(BAOXMLURL);",500);
    else
    {
        window.setTimeout("ResizeInPane('paneLeftBody', '"+baoPrefix+"divBAOReport', 475, 200, 0, 0);",10);
        hideLayer(baoPrefix+"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;
    
    baoPrefix = 'prop';
    var BAOReportDIV = document.getElementById(baoPrefix+"divBAOReportMenu");
    if (BAOReportDIV)
    {
        var reportText = "<br/><div id='"+baoPrefix+"div_BAO_report_list'><div class='description'>Select Report: </div><select id='"+baoPrefix+"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='"+baoPrefix+"divsel_BAOFormat' class='floatSelect'><select id='"+baoPrefix+"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='"+baoPrefix+"GoReport'><a href='#' onclick='startDriveReport();'>Go</a></div></div><br>";
        BAOReportDIV.innerHTML = reportText;
    }
    
    baoPrefix = 'site';
    var BAOReportDIV = document.getElementById(baoPrefix+"divBAOReportMenu");
    if (BAOReportDIV)
    {
        var reportText = "<br/><div id='"+baoPrefix+"div_BAO_report_list'><div class='description'>Select Report: </div><select id='"+baoPrefix+"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='"+baoPrefix+"divsel_BAOFormat' class='floatSelect'><select id='"+baoPrefix+"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='"+baoPrefix+"GoReport'><a href='#' onclick='startDriveReport();'>Go</a></div></div><br>";
        BAOReportDIV.innerHTML = reportText;
    }
    
    baoPrefix = '';
    blnIsInit = false;
    //getDriveReport();
}

function setRepFormat()
{
    var BAOReportSEL = document.getElementById(baoPrefix+"sel_BAOReport");
    var BAOFormatSEL = document.getElementById(baoPrefix+"divsel_BAOFormat");
    var repID;
    for(var rep in BAOReports)
    {
        if (BAOReports[rep].name == BAOReportSEL.options[BAOReportSEL.selectedIndex].value)
        repID = rep;
    }
    var formText = "<select id='"+baoPrefix+"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(baoPrefix+"BAOLoading");
    var BAOReportSEL = document.getElementById(baoPrefix+"sel_BAOReport");
    var BAOFormatSEL = document.getElementById(baoPrefix+"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"+baoCurrId,
        "description": "location "+baoCurrId,
        "storeID": baoCurrId
        }
        ],
    "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();
}

function prepareMarketProfile(xmlURL)
{
    if(xmlURL==null) xmlURL = BAOXMLURL;
    showLayer(baoPrefix+"BAOLoading");
    
    xmlURL = 'bao.aspx?reftype=xml&ref='+xmlURL  
    
    var sArgs = {
        url:xmlURL,
        rootItem: 'data'
        };
    
    var fArgs = {
        onComplete: function(data,ioArgs){
                createPanesWithItems(data);
                },
        onError: function(error,ioArgs) {
                //alert('An unexpected error occurred reading ESRI BAO XML');
                hideLayer(baoPrefix+"BAOLoading");
                } 
        };
    
    BAOStore = new dojox.data.XmlStore(sArgs);
    BAOStore.fetch(fArgs);
}
function createPanesWithItems(items)
{
    BAOStoreItems = items;
    
    var sArgs = {
        url:'App_Config/baoReport.xml',
        rootItem: 'REPORT'
        };
    
    var fArgs = {
        onComplete: function(data,ioArgs){
                showMarketProfile(data);
                },
        onError: function(error,ioArgs) {
                //alert('An unexpected error occurred reading the report configuration XML');
                hideLayer(baoPrefix+"BAOLoading");
                } 
        };
    
    BAOReportStore = new dojox.data.XmlStore(sArgs);
    BAOReportStore.fetch(fArgs);
    
}
function showMarketProfile(reports)
{
    var BAOReportDIV = dojo.byId(baoPrefix+"divBAOReport");
    var d = new Date();
    var year = d.getFullYear();
    if (d.getMonth() <= 6) year = year-1;
    var profileText = "";
    
    for (var i = 0; i < reports.length; i++)
    {
        var report = reports[i];
        var atts = BAOReportStore.getAttributes(report);
        var items = BAOReportStore.getValues(report,"ITEM");
        profileText = profileText + "<div class='header' onclick='propertyDetails_ToggleContent(this);'><span>"+BAOReportStore.getValues(report,"@Header")+"</span></div>"
        profileText = profileText + "<table cellpadding=\"0\" cellspacing=\"0\" class=\"content\" style=\""+((BAOReportStore.getValues(report,"@expand")=="true")?"display:auto":"display:none")+"\")>";
        strRowClass = "row0";
        profileText = profileText + "<tr class=\"right "+ strRowClass+ "\"><td><b>Description</b></td><td><b>2000<br/>Census</b></td><td><b>"+year+"<br/>Estimated</b></td><td><b>"+(year+5)+"<br/>Projected</b></td>"
        for (var ri = 0; ri < items.length; ri++)
        {
            var item = items[ri]
            var val;
            var dispval= "&nbsp;";
            if(BAOReportStore.isItem(item))
            {
                strRowClass = (strRowClass=="row1") ? "row2" : "row1";
                profileText = profileText + "<tr class=\"right "+ strRowClass+ "\">";
                if(BAOReportStore.hasAttribute(item,"Description"))
                {
                   dispval = ""+BAOReportStore.getValue(item,"Description");
                }
                else
                   dispval= "&nbsp;"
                profileText = profileText + "<td>"+ dispval+ "</td>"; 
                   
                if(BAOReportStore.hasAttribute(item,"C00_VAL"))
                {
                   val = ""+BAOReportStore.getValue(item,"C00_VAL");
                   if(BAOStore.hasAttribute(BAOStoreItems[0],val))
                   {
                    dispval= ""+BAOStore.getValue(BAOStoreItems[0],val);
                    dispval = String(formatNumber(parseFloat(dispval).toFixed(0),0,false,false,true));
                   }
                   else
                    dispval= "&nbsp;"
                }
                else
                   dispval= "&nbsp;"
                profileText = profileText + "<td>"+ dispval+ "</td>"; 
                   
                if(BAOReportStore.hasAttribute(item,"CY_VAL"))
                {
                   val = ""+BAOReportStore.getValue(item,"CY_VAL");
                   if(BAOStore.hasAttribute(BAOStoreItems[0],val))
                   {
                    dispval= ""+BAOStore.getValue(BAOStoreItems[0],val);
                    dispval = String(formatNumber(parseFloat(dispval).toFixed(0),0,false,false,true));
                   }
                   else
                    dispval= "&nbsp;"
                }
                else
                   dispval= "&nbsp;"
                profileText = profileText + "<td>"+ dispval+ "</td>"; 
                
                if(BAOReportStore.hasAttribute(item,"FY_VAL"))
                {
                   val = ""+BAOReportStore.getValue(item,"FY_VAL");
                   if(BAOStore.hasAttribute(BAOStoreItems[0],val))
                   {
                    dispval= ""+BAOStore.getValue(BAOStoreItems[0],val);
                    dispval = String(formatNumber(parseFloat(dispval).toFixed(0),0,false,false,true));
                   }
                   else
                    dispval= "&nbsp;"
                }
                else
                   dispval= "&nbsp;"
                profileText = profileText + "<td>"+ dispval+ "</td>"; 
                profileText = profileText +"</tr>"
            }
        }
        
        profileText = profileText +"</table><div class=\"footer\">&nbsp;</div></div>";
        BAOReportDIV.innerHTML = BAOReportDIV.innerHTML + profileText;
        profileText = "";
    } 
    window.setTimeout("ResizeInPane('paneLeftBody', '"+baoPrefix+"divBAOReport', 475, 200, 0, 0);",10);
    hideLayer(baoPrefix+"BAOLoading");
}