﻿//
var currPropId = "";
var currPropX = 0;
var currPropY = 0;
var currPropPoints;
var currPropGraphic = null;
var currPropDemoRadius = 0;
var theResizePropConnect;
var theZoomPopUpConnect;
var theZoomExtentConnect;
var busPoints = "";
var theBusinessConnect;
var theAddGraphicConnect;
var theClearPropConnect;
var tabstripPropertyDetails;
var thePortPropDrawPolygonGeom = null;
var loadingProperty = false;
var selectedPropertyGraphicsLayer = null;

function clickPropertyTab()
{
    theResizePropConnect = dojo.connect(jsMap,"onResize",function(){
            blnResizing = false;
		    dojo.disconnect(theResizePropConnect);
		    window.setTimeout('switchtoCurrentProperty();',10);
		    });
    if(mapisvisible)
    {
    	restorePanes();
    }
    else
    {
        restorePanes();
        RepositionMap();
        ResizeMap();
    }
    selectRadTab('Map');
}
function resizePropertyControl()
{
    var arrSize;
	arrSize = ResizeInPane('paneLeftBody', 'bbusPropertyDetails_panelContent', 475, 200, 0, 0);
	arrSize = ResizeInPane('paneLeftBody', 'bbusPropertyDetails_demoContent', 475, 200, 0, 0);
	arrSize = ResizeInPane('paneLeftBody', 'bbusPropertyDetails_businessContent', 475, 200, 0, 0);
	arrSize = ResizeInPane('paneLeftBody', 'bbusPropertyDetails_panelPropertyImage', 475, 200, 0, 0);
	arrSize = ResizeInPane('paneLeftBody', 'propdivBAOReport', 475, 200, 0, 0);
	arrSize = ResizeInPane('paneLeftBody', 'divDrawing', 475, 200, 0, 0);
	
	//ResizePropertyDetails(arrSize);
}
function ResizePropertyDetails(arrSize)
{
	if (arrSize == null)	return;

	var intWidth  = arrSize[0];

	var divPropertyDetails = document.getElementById('divPropertyDetails');
	if (divPropertyDetails)
	{
		divPropertyDetails.style.width = (intWidth - 20) + "px";
		
	}
	var multipageDetails = document.getElementById('bbusPropertyDetails_multipageDetails');
	if (multipageDetails)
	
	{
		multipageDetails.style.width = (intWidth - 20) + "px";
		
	}
}

function OnPropertyDetailsTabCreated(sender,eventArgs)
{
    tabstripPropertyDetails = sender;
    tabstripPropertyDetails.OnClientTabSelected = OnPropertyDetailsTabSelectedHandler;

}

function OnPropertyDetailsTabSelectedHandler(sender, eventArgs)
{
    resizePropertyControl();
    if (eventArgs.Tab.Value.length > 0)
	{
		eval(eventArgs.Tab.Value);
	}
}

function unselectDetailsTab(strTabText)
{
	var tab = tabstripPropertyDetails.FindTabByText(strTabText);
	if (tab)
	{
		tab.UnSelect();
	}
}
function selectDetailsTab(strTabText)
{
	var tab = tabstripPropertyDetails.FindTabByText(strTabText);
	if (tab)
	{
		tab.Enable();
		tab.Select();
	}
}

function clickDescription()
{
    turnOffMapGraphics();
    if (!loadingProperty)
    {
    turnOnMapGraphics("bufferFilterGraphics");
    turnOnMapGraphics("searchResultsFilterGraphics");
    turnOnMapGraphics("filterPointGraphics");
        theZoomExtentConnect = dojo.connect(jsMap, "onExtentChange", function(){
            dojo.disconnect(theZoomExtentConnect);
            highlightFeature(currfeatureSet);
            });
        zoomToPoint(currPropX,currPropY);
        
        var propname = document.getElementById("bbusPropertyDetails_demoPropName").value;
        GACTTrackEvent("Property Details","Description","Property - "+propname);
    }
}
function clickDemographics()
{
    turnOffMapGraphics();
    var units = document.getElementById('bbusSearchForm_siteUnits').value;
    var radius = document.getElementById('bbusPropertyDetails_buffradius').value;
    if (units=="ENGLISH") units="miles";
    else if (units=="METRIC") units="km";
    else units=null;
    currPropDemoRadius = radius;
    mapResultset = "propertyDemographics";
    bufferPoint(currPropGraphic,radius,units);
    
    var propname = document.getElementById("bbusPropertyDetails_demoPropName").value;
    GACTTrackEvent("Property Details","Demographics","Property - "+propname);
}
function clickBusiness()
{
    
    turnOffMapGraphics();
    var units = document.getElementById('bbusSearchForm_siteUnits').value;
    var radius = document.getElementById('bbusPropertyDetails_buffRadiusBusiness').value;
    if (units=="ENGLISH") units="miles";
    else if (units=="METRIC") units="km";
    else units=null;
    
    theBusinessConnect = dojo.connect(jsMap,"onExtentChange",function(){
        mapResultset = "propertyBusinesses";
        showLayer("BusyIndicator");
        window.setTimeout('plotBusinesses(busPoints)',10);
        dojo.disconnect(theBusinessConnect);
        });
        
    bufferPoint(currPropGraphic,radius,units);
    
    
    var propname = document.getElementById("bbusPropertyDetails_demoPropName").value;
    GACTTrackEvent("Property Details","Businesses","Property - "+propname);
    
}
function clickDetailsDrawing()
{
    turnOffMapGraphics();
    turnOnMapGraphics("selectedPropertyGraphics");
    hideLayer('divPortfolioPropDrawingResults');
    hideLayer('divPortfolioPropDrawingInstructions');
}

//this is called after the property details finishes loading on the server
function setPropertyDetailsMap(strPropertyId,x,y,points)
{
    currPropId = strPropertyId;
	currPropX = x;
	currPropY = y;
	currPropPoints = points;
	
    loadShareThisBtn();
	var rsSet = 'selectedProperty';
	var graphicID = rsSet+'Graphics';
    var rlayer = jsMap.getLayer(graphicID);
    if (rlayer != null) jsMap.removeLayer(rlayer);
    
    selectedPropertyGraphicsLayer = new esri.layers.GraphicsLayer({id: 'selectedPropertyGraphics'});
    jsMap.addLayer(selectedPropertyGraphicsLayer);
    dojo.connect(selectedPropertyGraphicsLayer, "onClick", clickLocGraphic);
    jsMap.reorderLayer(selectedPropertyGraphicsLayer,jsMap.layerIds.length+jsMap.graphicsLayerIds.length-1);
    
    showPropPoint();
}
function showPropPoint()
{
	loadingProperty = true;
	var rsSet = 'selectedProperty';
	
	theAddGraphicConnect = dojo.connect(selectedPropertyGraphicsLayer,"onGraphicAdd",function(graphic){
        dojo.disconnect(theAddGraphicConnect);
        currPropGraphic = graphic;
        window.setTimeout('gotoCurrentProperty();',10);
        });
    
    setMapPoints(rsSet,null,currPropPoints);
	
}
function loadShareThisBtn()
{
    if (dojo.isIE){
        loadAddThisScript("js/addthis/addthis_widget.js#domready=1", "js");
        loadAddThisScript("js/addthis/menu64.js", "js");
        loadAddThisScript("js/addthis/widget50.css", "css");
    }
    else
        loadAddThisScript("http://s7.addthis.com/js/250/addthis_widget.js#domready=1", "js");
    


    window.setTimeout("setShareThisBtn();",10);
     
}

function loadAddThisScript(url, type)
{
    var attribute="src";
    var tag = "script";
    var texttype="text/javascript"
    if(type== "css")
    {
        attribute="href";
        tag = "link";
        texttype="text/css";
    }
    var allsuspects=document.getElementsByTagName(tag);
    for (var i=allsuspects.length; i>=0; i--)
    { 
     //search backwards within nodelist for matching elements to remove
      if (allsuspects[i] && allsuspects[i].getAttribute(attribute)!=null && allsuspects[i].getAttribute(attribute).indexOf(url)!=-1)
       allsuspects[i].parentNode.removeChild(allsuspects[i]); //remove element by calling parentNode.removeChild()
    }
    var fileref=document.createElement(tag);
    fileref.setAttribute("type",texttype);
    if(type=="css")fileref.setAttribute("rel","stylesheet");
    fileref.setAttribute(attribute, url);
    if (typeof fileref!="undefined")
        document.getElementsByTagName("head")[0].appendChild(fileref);
     
}

function setShareThisBtn()
{
    var propname = document.getElementById("bbusPropertyDetails_demoPropName").value;
    var propurl = window.location.host+window.location.pathname+"?PropID="+currPropId;
    var btnShareThis = document.getElementById("btnShareThis");
    btnShareThis.href = "http://api.addthis.com/oexchange/0.8/offer?url="+propurl+"&title="+propname.replace(/ /g,"");
    var btnEmailThis = document.getElementById("btnEmailThis");
    btnEmailThis.href = "http://api.addthis.com/oexchange/0.8/forward/email/offer?url="+propurl+"&title="+propname.replace(/ /g,"");
    var btnTwitterThis = document.getElementById("btnTwitterThis");
    btnTwitterThis.href = "http://api.addthis.com/oexchange/0.8/forward/twitter/offer?url="+propurl+"&title="+propname.replace(/ /g,"");
    var btnLinkedInThis = document.getElementById("btnLinkedInThis");
    btnLinkedInThis.href = "http://api.addthis.com/oexchange/0.8/forward/linkedin/offer?url="+propurl+"&title="+propname.replace(/ /g,"");
    var addthis_share = {url: propurl, title: propname};
    //addthis.button("#btnEmailThis", {services_compact: "email"}, {url: propurl, title: propname});
    addthis.button("#btnShareThis", {services_compact: "facebook,google,linkedin,digg,stumbleupon,reddit"}, {url: propurl, title: propname});
    if (dojo.isIE){  
        dojo.query('#btnShareThis,#btnEmailThis,#btnTwitterThis,#btnLinkedInThis').forEach(function(node, index, array){
          node.onclick = null;
          node.onmouseover = null;
          node.onmouseout = null;
        });
        dojo.query('#btnTwitterThis,#btnLinkedInThis,#btnEmailThis').forEach(function(node, index, array){
          dojo.style(node, "display","block");
        });
        dojo.query('#btnShareThis').forEach(function(node, index, array){
          dojo.style(node, "display","none");
        });
    }
    else
    {
        dojo.query('#btnTwitterThis,#btnLinkedInThis').forEach(function(node, index, array){
          dojo.style(node, "display","none");
        });
        dojo.query('#btnShareThis,#btnEmailThis').forEach(function(node, index, array){
          dojo.style(node, "display","block");
        });
    }
}
function plotBusinesses(points)
{
    if (points.length > 0)
    {
        pArray = points.split(";;;;");
        arraylength = pArray.length;
        var pt_graphic;
        var pt_symbol;
        var pt_point;
        var nullLine = new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_NULL,new dojo.Color([255,255,255,1]),1);
        
        var i;
        for(i in pArray)
        {
            pointsArray = pArray[i].split("||||");
            pt_point = new esri.geometry.Point(pointsArray[0], pointsArray[1], jsSR);
            pt_symbol = new esri.symbol.SimpleMarkerSymbol(esri.symbol.SimpleMarkerSymbol.STYLE_SQUARE, 6, nullLine, new dojo.Color(pointsArray[2]));
            pt_graphic = new esri.Graphic(pt_point,pt_symbol);
            pt_graphic.attributes = { "id":"business"+i, "type":"business" };
            jsMap.graphics.add(pt_graphic);
        }
    }
    hideLayer("BusyIndicator");
}

function setBusinessPoints(points)
{
    busPoints = points;
    //alert(points);
}

function switchtoCurrentProperty()
{
    if (!loadingProperty)
    {
        //   showPropPoint();
        //loadCurrentProperty();
        
		unselectDetailsTab("Description");
		selectDetailsTab("Description");
        //window.setTimeout('showPopUp(currPropGraphic,false,true);',10);
    }    
}

function gotoCurrentProperty()
{
    if (loadingProperty)
        loadCurrentProperty();
}

function loadCurrentProperty()
{
    selectDetailsTab("Description");
    turnOnMapGraphics("bufferFilterGraphics");
    turnOnMapGraphics("searchResultsFilterGraphics");
    turnOnMapGraphics("filterPointGraphics");
    theZoomExtentConnect = dojo.connect(jsMap, "onExtentChange", showCurrentProperty);

    window.setTimeout('zoomToPoint(currPropX,currPropY);',100);
}

function showCurrentProperty()
{
    dojo.disconnect(theZoomExtentConnect);
    mapResultset = "selectedProperty";
    loadingProperty = false;
    zoomPopUp(currPropGraphic);
    window.setTimeout('showPopUp(currPropGraphic,true,true);',500);
    
    var propname = document.getElementById("bbusPropertyDetails_demoPropName").value;
    GACTTrackEvent("Property Details","Description","Property - "+propname);
}

function gotoPropertyDetails(strPropertyId, x, y)
{
    loadingProperty = true;
    
	currPropId = strPropertyId;
	currPropX = x;
	currPropY = y;
	currPropGraphic = getGraphicById(currPropId);
	currPropDemoRadius = 5; //default radius
	
	//zoomToPoint(x,y);
	//window.setTimeout('zoomPopUp('+strPropertyId+')',100);
    
	// load Property Details
	if (strPropertyId)
	{
	//    __doPostBack('bbusPropertyDetails$updatePropertyDetails', 'Event=updatePropertyDetails&strPropertyId='+strPropertyId+'&MapEvent=ZoomPoint&x='+ x +'&y='+ y);
        __doPostBack('bbusPropertyDetails$updatePropertyDetails', 'Event=updatePropertyDetails&strPropertyId='+strPropertyId);
        GACTTrack("Property Details");
    }
	// show "loading..." display

	// go to Property Details page
	hideRadTab('DemoDetails');
	showRadTab('Details');
	selectRadTab('Details');
	selectDetailsTab('Description');
    clearBAO('prop');
	//ResizeInPane('paneLeftBody', 'divPropertyDetails', 345, 200, 27, 0);
}

function addCurrentPropertyToPortfolio()
{
    addPropertyToPortfolio(currPropId,'');
}

function generatePropertyDemographics()
{
    clickDemographics();
    __doPostBack("bbusPropertyDetails$updateDemoProfile", "Event=PrepareDemographics");
    GACTTrack("Property Demographics");
}

function performBusinessAnalysis()
{
    clickBusiness();
    __doPostBack("bbusPropertyDetails$updateBusinessAnalysis", "Event=PrepareBusinessProfile");
    GACTTrack("Property Business Analysis");
}


function showBusinessAnalysis(strType,strDESC,strNAICS,strPrevSPEC)
{
    var strPostBack
    if(strType!='MAPBUSINESS')
        strPostBack = 'Event=updateBusinessAnalysis'
    if(strType == 'SPECIFIC')
        strPostBack += '&SHOW=SPECIFIC&SPECIFIC='+strDESC+'&SPECIFIC_NAICS='+strNAICS
    if(strType == 'BUSINESSES')
        strPostBack += '&SHOW=BUSINESSES&BUSINESSES='+strDESC+'&BUSINESSES_NAICS='+strNAICS+strPrevSPEC
	// load BusinessAnalysis
	if (strPostBack)
	{   
	    //selectRadTab('Map');
        //window.setTimeout('selectRadTab("Details");__doPostBack("bbusPropertyDetails$updateBusinessAnalysis", strPostBack);',10);
        __doPostBack("bbusPropertyDetails$updateBusinessAnalysis", strPostBack);
        GACTTrack("Property Business Analysis");
    }
	// show "loading..." display

}

function showBusinessMap(strType,strNAICS,busX,busY,strColor)
{
    //var strPostBack
    if(strType='MAPBUSINESS')
    {    
        busPoints = busX+"||||"+busY+"||||"+strColor;
        clickBusiness();
    }
    
        //strPostBack = 'Event=updateBusinessMap&COLOR='+strColor+'&busX='+x+'&busY='+y
    // load BusinessMap
	//if (strPostBack)
	//{   
	    
	    //selectRadTab('Map');
        //window.setTimeout('selectRadTab("Details");__doPostBack("bbusPropertyDetails$updateBusinessAnalysis", strPostBack);',10);
        //__doPostBack("bbusPropertyDetails$updateBusinessAnalysis", strPostBack);
    //}
	// show "loading..." display

}

function ShowPropertyImage(strImageName)
{
	var imgPropertyImage = document.getElementById('bbusPropertyDetails_imagePropertyImage');
	if (imgPropertyImage)
	imgPropertyImage.src = strImageName;
	
	
    var propname = document.getElementById("bbusPropertyDetails_demoPropName").value;
    GACTTrackEvent("Property Details","Images","Property - "+propname);
}

function printDetails(strID, strFormat)
{
    GACTTrack("Print Property Details");
    var propname = document.getElementById("bbusPropertyDetails_demoPropName").value;
    GACTTrackEvent("Property Details","Print","Property - "+propname);
    
    if(strID == null) strID = currPropId;
//    strPostBack = 'Event=printPropertyDetails';
//    if(strID)
//        strPostBack = strPostBack + '&strPropertyID='+strID
//    __doPostBack('', strPostBack);
    if (strFormat=='HTML') 
    {
        printMapHTML(jsMap, strID)
        return;
    }
    
    var d = new Date();
	var showmap = true;
	mapminx = jsMap.extent.xmin;
    mapmaxx = jsMap.extent.xmax;
    mapminy = jsMap.extent.ymin;
    mapmaxy = jsMap.extent.ymax;
    var mapw = jsMap.width;
    var maph = jsMap.height;
    var srid = jsSR.wkid;
    var mapurl;
    for (var j=0, jl=jsMap.layerIds.length; j<jl; j++) {
      var layer = jsMap.getLayer(jsMap.layerIds[j]);
      if (layer.declaredClass == "esri.layers.ArcGISDynamicMapServiceLayer") //if there is a dynamic layer
      {
        showmap = false;
        break;
      }
      if (currentMapView == layer.id) {
        mapurl = layer.url;
      }
    }
    
    if (showmap == false)
    {
        printMapHTML(jsMap, strID)
        return;
    }
    
    
    
    var mapname = currentMapView;
    var mapNames = document.getElementById("bbusMap_mapServiceMapNames").value;
    if (mapNames!= "")
    {
        var arrMapNames = mapNames.split(",");
	    var arrMapServices = document.getElementById("bbusMap_mapServices").value.split(",");
	    for (var am in arrMapServices)
	    {
	        if(arrMapServices[am]==currentMapView)
	            mapname = arrMapNames[am];
	    }
	}
    
    var pPropGraphic, pPropX, pPropY, pPropPid
    pPropGraphic = getGraphicById(strID);
    if (pPropGraphic != null)
    {
        pPropX =  pPropGraphic.geometry.x;
        pPropY =  pPropGraphic.geometry.y;
        pPropPid = pPropGraphic.attributes.pid;    
    }
	
    var url = 'Dialogs/print_map.aspx?t='+d.getTime()+'&type=PropertyDetails&MapURL='+mapurl+'&MapName='+mapname+'&MinX='+mapminx+'&MinY='+mapminy+'&MaxX='+mapmaxx+'&MaxY='+mapmaxy+'&MapW='+mapw+'&MapH='+maph+'&SRID='+srid;
    url = url + '&props='+strID+'&x='+pPropX+'&y='+pPropY+'&pin='+pPropPid;
    
    var pFrame = document.getElementById('iframePrintMap');
    pFrame.src = url;
}

function printDemographics(strID)
{
    if(strID == null) strID = currPropId;
    currPropGraphic = getGraphicById(currPropId);
    pGeom = currPropGraphic.geometry;
	var mapGsvc = document.getElementById("bbusMap_mapGeometryService").value;
    if (mapGsvc == "") mapGsvc = "http://maps.binarybus.net/BBgis/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( pGeom ) ], outSR, buildDemographicsPrint);

}
    
function buildDemographicsPrint(features) 
{
        pt = features[0].geometry;
        
    //    strPostBack = 'Event=printDemographics';
    //    if(strID)
    //        strPostBack = strPostBack + '&strPropertyID='+strID
    //    __doPostBack('', strPostBack);
        
        var d = new Date();
    	var minx = jsMap.extent.xmin;
        var maxx = jsMap.extent.xmax;
        var miny = jsMap.extent.ymin;
        var maxy = jsMap.extent.ymax;
    
	    var srid = jsSR.wkid;
        var mapurl, units;
        for (var j=0, jl=jsMap.layerIds.length; j<jl; j++) {
          var layer = jsMap.getLayer(jsMap.layerIds[j]);
          if (currentMapView == layer.id) {
            mapurl = layer.url;
            units = layer.units;
          }
        }
        
        var radiusDistance;
        var siteUnits = document.getElementById('bbusSearchForm_siteUnits').value;
        if (units == "esriFeet")
        {
            if (siteUnits=="ENGLISH")
                radiusDistance = currPropDemoRadius*5280;
            else 
                radiusDistance = currPropDemoRadius/0.3048*1000;
        }
        if (units == "esriMeters") 
        {
            if (siteUnits=="ENGLISH")
                radiusDistance = currPropDemoRadius*0.3048*5280;
            else
                radiusDistance = currPropDemoRadius*1000;
        }
        //if (maxx<=(parseFloat(currPropX)+radiusDistance)) maxx = maxx+(radiusDistance);
        //if (maxy<=(parseFloat(currPropY)+radiusDistance)) maxy = maxy+(radiusDistance);
        //if (minx>=(parseFloat(currPropX)-radiusDistance)) minx = minx-(radiusDistance);
        //if (miny>=(parseFloat(currPropY)-radiusDistance)) miny = miny-(radiusDistance);
        maxx=parseFloat(currPropX)+(radiusDistance)
        maxy=parseFloat(currPropY)+(radiusDistance)
        minx=parseFloat(currPropX)-(radiusDistance)
        miny=parseFloat(currPropY)-(radiusDistance)
        
        var mapw = jsMap.width;
        var maph = jsMap.height;
        var mapname = currentMapView;
        var mapNames = document.getElementById("bbusMap_mapServiceMapNames").value;
        if (mapNames!= "")
        {
            var arrMapNames = mapNames.split(",");
	        var arrMapServices = document.getElementById("bbusMap_mapServices").value.split(",");
	        for (var am in arrMapServices)
	        {
	            if(arrMapServices[am]==currentMapView)
	                mapname = arrMapNames[am];
	        }
	    }
        
        var propname = document.getElementById("bbusPropertyDetails_demoPropName").value;
        var siteUnits = document.getElementById('bbusSearchForm_siteUnits').value;
        
        var printurl = 'Dialogs/print_map.aspx?t='+d.getTime()+'&type=Demographics&MapURL='+mapurl+'&MapName='+mapname+'&MinX='+minx+'&MinY='+miny+'&MaxX='+maxx+'&MaxY='+maxy+'&MapW='+mapw+'&MapH='+maph+'&SRID='+srid;
        printurl = printurl + '&x='+currPropX+'&y='+currPropY+'&long='+pt.y.toFixed(7)+'&lat='+pt.x.toFixed(7)+'&radius='+currPropDemoRadius+'&mapradius='+radiusDistance+'&site='+propname+'&units='+siteUnits;
        
        var pFrame = document.getElementById('iframePrintMap');
        pFrame.src = printurl;
        GACTTrack("Print Demographics");
        GACTTrackEvent("Property Details","Print Demographics","Property - "+propname);
}

function propertyDetails_ToggleContent(divHeaderDiv)
{
	var divContentDiv = divHeaderDiv.nextSibling;
	if (divContentDiv)
		divContentDiv.style.display = (divContentDiv.style.display == 'none') ? '' : 'none';
}

function propertyDetails_ExpandAll(blnExpand,divID)
{
	var divSection;
    if (divID!=null) divSection = document.getElementById(divID);
    if (!divSection) divSection = document.getElementById('divPropertyDetails_Right');
	if (!divSection)	return;
	
	var arrPanels = divSection.getElementsByTagName('table');
	for (var ix=0; ix < arrPanels.length; ix++)
	{
		if (arrPanels[ix].className == 'content')
			arrPanels[ix].style.display = (blnExpand) ? '' : 'none';
	}
}

function demoProfile_ExpandAll(blnExpand)
{
	var divSection = document.getElementById('divDemoProfile_Right');
	if (!divSection)	return;
	
	var arrPanels = divSection.getElementsByTagName('table');
	for (var ix=0; ix < arrPanels.length; ix++)
	{
		if (arrPanels[ix].className == 'content')
			arrPanels[ix].style.display = (blnExpand) ? '' : 'none';
	}
}

function businessAnalysis_ExpandAll(blnExpand)
{
	var divSection = document.getElementById('divBusinessAnalysis_Right');
	if (!divSection)	return;
	
	var arrPanels = divSection.getElementsByTagName('table');
	for (var ix=0; ix < arrPanels.length; ix++)
	{
		if (arrPanels[ix].className == 'content')
			arrPanels[ix].style.display = (blnExpand) ? '' : 'none';
	}
}

function bbusAlert(strText, strTitle, blnShow)
{
	if (!strTitle)
		strTitle = strText;

	radalert(strText, 300, 200, strTitle);
}

function doDrawPortfolioPropPolygon(geometry)
{
    var mapGsvc = document.getElementById("bbusMap_mapGeometryService").value;
    if (mapGsvc == "") mapGsvc = "http://maps.binarybus.net/BBgis/rest/services/Geometry/GeometryServer";
    if(gsvc == null) gsvc = new esri.tasks.GeometryService(mapGsvc);
    var mg = getGraphicById("drawPortfolioPropPolygon");
    if (mg) jsMap.graphics.remove(mg);
    mGeom = geometry;
    thePortPropDrawPolygonGeom = mGeom;
    mGeom.setSpatialReference(jsSR);
    if (mGeom.type == "polygon")    mSymbol = new esri.symbol.SimpleFillSymbol();
    else    mSymbol = new esri.symbol.SimpleLineSymbol();
    mGraphic = new esri.Graphic(mGeom,mSymbol);
    mGraphic.attributes = { "id":"drawPortfolioPropPolygon", "type":"drawPortfolioPropPolygon" };
    jsMap.graphics.add(mGraphic);
        
    if (mGeom.type == "polygon") gsvc.simplify([mGraphic], function(graphics) {
            gsvc.areasAndLengths(graphics,showDrawPortfolioPropPolygonResults);
        });
        
    activateMapTool('pan');
    
}

function showPortPropDrawing(sXs, sYs)
{
    var arrPoints = [];
    var arrPoint = [];
    var arrXs = sXs.split(",");
    var arrYs = sYs.split(",");
    for (var ix = 0; ix < arrXs.length; ix++)
    {
        arrPoints.push([parseFloat(arrXs[ix]),parseFloat(arrYs[ix])]);
    }
    var geometry = new esri.geometry.Polygon(jsSR);
    geometry.addRing(arrPoints);
    
    var mg = getGraphicById("drawPortfolioPropPolygon");
    if (mg) jsMap.graphics.remove(mg);
    mGeom = geometry;
    thePortPropDrawPolygonGeom = mGeom;
    mGeom.setSpatialReference(jsSR);
    mSymbol = new esri.symbol.SimpleFillSymbol();
    mGraphic = new esri.Graphic(mGeom,mSymbol);
    mGraphic.attributes = { "id":"drawPortfolioPropPolygon", "type":"drawPortfolioPropPolygon" };
    jsMap.graphics.add(mGraphic);
    
}

function showDrawPortfolioPropPolygonResults(results)
{
    var units;
    for (var j=0, jl=jsMap.layerIds.length; j<jl; j++) {
      var layer = jsMap.getLayer(jsMap.layerIds[j]);
      if (currentMapView == layer.id) {
        units = layer.units;
      }
    }
    
    var ft, meters, sqft, sqm, acres, ha;
    var length = results.lengths[0];
    var area = results.areas[0];
    if (units == "esriFeet")
    {
        ft = length;
        meters = length*0.3048;
        sqft = area;
        acres = sqft/43560;
        sqm = area*0.3048*.3048;
        ha = sqm/10000;
    }
    if (units == "esriMeters") 
    {
        ft = length/0.3048;
        meters = length;
        sqft = area/0.3048/.3048;
        acres = sqft/43560;
        sqm = area;
        ha = sqm/10000;
    }
    
    var unitAreaSelect = "<select id='selAreaUnits' class='measureUnits' onchange='changeAreaMeasure(this.options[this.selectedIndex].value)' >"
    unitAreaSelect+= "<option value='"+sqft.toFixed(2)+"' selected>sq ft</option>"
    unitAreaSelect+= "<option value='"+acres.toFixed(2)+"'>acres</option>"
    unitAreaSelect+= "<option value='"+sqm.toFixed(2)+"'>sq m</option>"
    unitAreaSelect+= "<option value='"+ha.toFixed(2)+"'>hectares</option></select>"
    var unitLenSelect = "<select id='selLengthUnits' class='measureUnits' onchange='changeLenMeasure(this.options[this.selectedIndex].value)' >"
    unitLenSelect+= "<option value='"+ft.toFixed(2)+"' selected>feet</option>"
    unitLenSelect+= "<option value='"+meters.toFixed(2)+"'>meters</option></select>"
    
    var content = "<span class='value'>Area:</span><span class='value' id='measureArea'>"+sqft.toFixed(2)+"</span>"+unitAreaSelect+"<br><span class='value'>Perimeter:</span><span class='value' id='measureLength'>"+ft.toFixed(2)+"</span>"+unitLenSelect
    content+="<br><br><div class='links' style='display:block; float:left; white-space:nowrap;'><a href='#' onclick='activateMapTool(&quot;drawPortfolioPropPolygon&quot;);'>Redraw Polygon</a> | <a href='#' onclick='savePortPropDrawing(&quot;FOOTPRINT&quot;);'>Save as Footprint</a> | <a href='#' onclick='savePortPropDrawing(&quot;SITE&quot;);'>Save as Site</a></div>"
    
    showLayer("divPortfolioPropDrawingResults");
    setContent("divPortfolioPropDrawingResults",content);
    resizePropertyControl();
}

function savePortPropDrawing(type)
{
    var strXs = "";
    var strYs = "";
    
    if(thePortPropDrawPolygonGeom!=null)
    {
        therings = thePortPropDrawPolygonGeom.rings;
        var theXs = [];
        var theYs = [];
        for (var rx=0; rx < therings.length; rx++)
        {
	        thering = therings[rx];
	        for(var px=0; px < thering.length; px++)
	        {
	            thepoint = thering[px];
	            theXs.push(thepoint[0]);
	            theYs.push(thepoint[1]);
	        }
	    }   
	    strXs = theXs.join(",");
	    strYs = theYs.join(",");    
    }
    
    strPropertyId = currPropId;
	__doPostBack('bbusPropertyDetails$updateDrawing', 'Event=updatePropertyDrawing&DrawType='+type+'&strPropertyId='+strPropertyId+'&Xs='+strXs+'&Ys='+strYs);
    GACTTrack("Property Details");
}
