﻿//Holds js code for application.
//Copyright 2008 Avencia Inc.

var arcgisWebApp;
var isIE = (Sys.Browser.agent == Sys.Browser.InternetExplorer);

//Used below for ie6 hacks
var is_ie6 = false;
if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) {
    //test for MSIE x.x;
    var ieversion = new Number(RegExp.$1) // capture x.x portion and store as a number
    is_ie6 = (ieversion == 6);
}

Type.registerNamespace('ESRI.ADF.WebMappingApplication');

//*************************
//Modified ESRI code to perform basic mapping functions
//*************************

// function run at startup
function startUp() {
    arcgisWebApp.MapId = "Map1";
    arcgisWebApp.map = $find(arcgisWebApp.MapId);
    map = arcgisWebApp.map
    
    
    // set window resize event handler
    window.setTimeout('$addHandler(window,"resize", arcgisWebApp.adjustMapSizeHandler);', 2000);
    
    //Perform resize to current size
    window.setTimeout('arcgisWebApp.adjustMapSize();', 500);

    //Moves popup div to right place in the DOM
    window.setTimeout('AddPopupDivHolderToDOMLocation();', 1500);

    AddListenerToMap();
}

function setMapLeftPosition() {
    setMapWidth();
}

function getMapLeft() {
    return arcgisWebApp.LeftPanelWidth;
}

function getMapWidth() {
    
    var mLeft = 0;
    var pWidth = arcgisWebApp.getPageWidth();
    var mWidth = 5;

    mLeft = arcgisWebApp.LeftPanelWidth;
    mWidth = arcgisWebApp.getPageWidth() - mLeft;
    
    if (mWidth < 5) mWidth = 5;
    return mWidth;
}

function setMapWidth() {
    var mLeft = getMapLeft();
    arcgisWebApp.MapDisplay.style.left = mLeft + "px";
    var mWidth = getMapWidth() - 10; //shrink it a little bit
    //FF fix
    if (!isIE) { mWidth -= 15; }
    if (mWidth < 5) mWidth = 5;
    arcgisWebApp.MapDisplay.style.width = mWidth + "px";
    arcgisWebApp.CurrentMapWidth = mWidth;
}

//ESRI object which holds much functionality
ESRI.ADF.WebMappingApplication.WebPage = function() {
    this.MapId = "Map1";
    //this.map = null;
    this.MapDisplay = $get("Map_Panel");
    this.ZoomLevel = $get("ZoomLevel1");

    this.LeftPanelWidth = 282;
    this.ToggleWidth = 10;
    this.TopBannerHeight = 110;
    this.WindowWidth = 500;
    this.LeftOffsetX = 0;
    this.RightOffsetX = 0
    this.NavigationLeft = 0;
    this.MapLeft = 262;
    this.LastMapWidth = 512;
    this.LastMapHeight = 512;
    this.CurrentMapWidth = 512;
    this.CurrentMapHeight = 512;

    // function for adjusting element sizes when brower is resized
    this.adjustMapSize = function() {
        // get browser window dimensions 
        var sWidth = this.getPageWidth();
        var sHeight = this.getPageHeight();
        var mHeight = sHeight - this.TopBannerHeight+5; //adjust a little up

        //FF fix
        if (!isIE) { mHeight -= 15; }

        this.LastMapWidth = this.CurrentMapWidth;
        this.LastMapHeight = this.CurrentMapHeight;
        this.MapDisplay.style.height = mHeight + "px";

        //Also set left panel div height to match maps
        var leftPanel = document.getElementById('LeftPanelCellDiv');
        leftPanel.style.height = mHeight + "px";

        this.CurrentMapHeight = mHeight;

        // calc dimensions needed for map
        var mWidth = getMapWidth();
        if (mWidth < 5) mWidth = 5;
        if (mHeight < 5) mHeight = 5;
        setMapLeftPosition();

        var m = $find(this.MapId);
        if (m != null) {
            if (this.LastMapWidth != this.CurrentMapWidth || this.LastMapHeight != this.CurrentMapHeight) {
                m.checkMapsize();
                this.adjustOverviewMapPosition();
            }
        } else
            window.setTimeout("arcgisWebApp.adjustMapSize();", 1000);
        return false;
    }

    this.adjustOverviewMapPosition = function(e) {
        var overview = document.getElementById('OverviewMap1');
        var overviewToggle = document.getElementById('toggleDiv');
        var pageHeight = this.getPageHeight();
        var pageWidth = this.getPageWidth();

        var overviewWidthOffset = 116;

        if (!isIE) {
            overviewWidthOffset += 15;
        }

        var overviewToggleWidthOffset = overviewWidthOffset - 91;
        overview.style.left = pageWidth - overviewWidthOffset + 'px';
        overviewToggle.style.left = pageWidth - overviewToggleWidthOffset + 'px';
    }

    // handler for window resize
    this.adjustMapSizeHandler = function(e) {
        window.clearTimeout(arcgisWebApp.reloadTimer);
        arcgisWebApp.reloadTimer = window.setTimeout("arcgisWebApp.adjustMapSize();", 1000);
    }

    // get the page width
    this.getPageWidth = function() {
        var width = window.innerWidth;
        if (width == null) {
            if (document.documentElement && document.documentElement.clientWidth)
                width = document.documentElement.clientWidth
            else
                width = document.body.clientWidth;
        }
        return width;
    }

    //get the page height
    this.getPageHeight = function() {
        var height = window.innerHeight;
        if (height == null) {
            if (document.documentElement && document.documentElement.clientHeight)
                height = document.documentElement.clientHeight;
            else
                height = document.body.clientHeight;
        }
        return height;
    }

    ESRI.ADF.WebMappingApplication.WebPage.initializeBase(this);
}

//Create above class.
ESRI.ADF.WebMappingApplication.WebPage.registerClass('ESRI.ADF.WebMappingApplication.WebPage');
arcgisWebApp = new ESRI.ADF.WebMappingApplication.WebPage();
if (typeof (Sys) !== 'undefined') { Sys.Application.notifyScriptLoaded(); }

//************************
// Functions added by Avencia
//************************

//Set ADF Timeout
var maximumLapseTime = 120;

//***************
// UI EFFECTS
//***************

//Use Scriptaculous library to add swap in and out effect of overview map 
function ToggleOverview() 
{
    var overviewToggleImg = document.getElementById("imgOverviewToggle");

    if (overviewToggleImg.src.indexOf("images/OverviewClose.png") != -1) {
        overviewToggleImg.src = "images/OverviewOpen.png";
        new Effect.Shrink('OverviewMap1', { duration: .5, direction: 'top-right', opacityTransition: Effect.Transitions.linear });
    }
    else {
        overviewToggleImg.src = "images/OverviewClose.png";
        new Effect.Grow('OverviewMap1', { duration: .5, direction: 'top-right', opacityTransition: Effect.Transitions.linear });
    }

    return false;
}


function ShowGettingInformation() {
    var fpBody = document.getElementById('ResultsDiv');
    fpBody.innerHTML = "<img src='images/callbackActivityIndicator.gif' align='middle'/> Getting Information. . .";
    //showFloatingPanel('Results');
    fpBody = document.getElementById('Results_BodyRow');
}

// ***********
// EVENT HANDLERS
// ************
function FindButtonClick() {
    ShowGettingInformation();
    var addr = escape(document.getElementById('txtAddress').value);
    var serviceAreaDropDown = document.getElementById('ddlServiceAreas');
    var serviceAreaIndex = serviceAreaDropDown.selectedIndex;
    var serviceAreaString = serviceAreaDropDown.options[serviceAreaIndex].text;
    InvokeCallback_Custom('Map1', 'ControlID=btnFind&ControlType=Button&EventArg=FindAddress&Selection=' + serviceAreaString + '&Address=' + addr);
}

function PDFButtonClick() {
    var addr = document.getElementById('txtAddress').value;
    var serviceAreaDropDown = document.getElementById('ddlServiceAreas');
    var serviceAreaIndex = serviceAreaDropDown.selectedIndex;
    var serviceAreaString = serviceAreaDropDown.options[serviceAreaIndex].text;

    var fpBody = document.getElementById('ResultsDiv');
    var spatialJoinText = fpBody.innerHTML;

    var imgPDFLoading = document.getElementById('imgPdfLoading');
    imgPDFLoading.src = "images/pdfloading.gif";

    var box = calcElementPosition("Map_Panel");

    InvokeCallback_Custom('Map1', 'ControlID=btnMakePDF&ControlType=Button&EventArg=MakePDF&Selection=' + serviceAreaString + '&Address=' + addr + '&SpatialJoinText=' + spatialJoinText + '&CurrentImageWidth=' + box.width + '&CurrentImageHeight=' + box.height);
}

//Handles click for Identification on Map
function AddListenerToMap() {
    var oDiv = document.getElementById('Map1');
    var oPopupDiv = document.getElementById('divIR');

    //FF
    if (oPopupDiv.addEventListener != null) 
    {
        oPopupDiv.addEventListener('click', function(e) {
            //disable event propagation.
            e.stopPropagation();
        }, false);

        oPopupDiv.addEventListener('dblclick', function(e) {
            //disable event propagation.
            e.stopPropagation();
        }, false);
        
    }
    else //IE
    {
        oPopupDiv.attachEvent('onclick', function(e) {
            //disable event propagation.
            window.event.cancelBubble = true;
        });

    }
    arcgisWebApp.map.add_click(identify);
}

function identify(sender, args) {
    InvokeCallback_Custom('Map1', 'ControlID=Map1&ControlType=Map&EventArg=MapIdentify&minx=' + args.coordinate.get_x() + '&miny=' + args.coordinate.get_y());
}

//Attached Popup div to MapAnnotation layer
function AddPopupDivHolderToDOMLocation() {
    var divAnnotation = document.getElementById('MapAnnotationDiv_Map1');
    var divPopupHolder = document.getElementById('PopupHolder');

    if ((divAnnotation != null) && (divPopupHolder != null)) {
        divAnnotation.appendChild(divPopupHolder);
    }
}

//*****************
// Popup Infobubble Routines
//*****************


//Stores current popup information
var popupData= null;

function DeserializePopupContent(content) {
    var arrayOfFacilities = content.split("@|@");
    popupData = new Array(arrayOfFacilities.length);

    for (var i = 0; i < arrayOfFacilities.length; i++) {
        var dataForThisFacility = arrayOfFacilities[i].split("@@");
        popupData[i] = dataForThisFacility;
    }
}

function RenderPopupContent(index) {
    //check if prev or next exceeded bounds
    if (index < 0) return;
    if (index > popupData.length - 1) return;

    var dataSet = popupData[index];

    var retHTML = [];

    retHTML.push("<TABLE width=\"290px\" class=\"popup\" cellspacing=\"0\" cellpadding=\"0\">" +
            "<TR><TH class=\"popup\" colspan=\"2\">" + dataSet[0] + "</TH></TR>");


    //Start at 2nd index. First element has colname, 2nd has data.

    for (var i = 1; i < dataSet.length; i += 2) {
        var rowclass = ((i - 1) / 2 % 2 == 0) ? "popup" : "odd";
        retHTML.push("<TR><TD class=\"" + rowclass + "\">" + dataSet[i] + "</TD><TD class=\"" + rowclass + "\">" + dataSet[i + 1] + "</TD></TR>");
    }

    retHTML.push("<TR><TD class=\"popup\">" + (index + 1) + " of " + (popupData.length) + "</TD>");
    retHTML.push("<TD class=\"popup\" align=\"right\" > ");
    retHTML.push("&lt; <A onclick=\"\" HREF=\"javascript:RenderPopupContent(" + (index - 1) + ");\">prev</a> ");
    retHTML.push("| <A onclick=\"\" HREF=\"javascript:RenderPopupContent(" + (index + 1) + "); \">next</a> &gt; ");
    retHTML.push("</TD></TR>");

    retHTML.push("</TABLE><P>");

    var contentDiv = document.getElementById('divIRContent');
    contentDiv.innerHTML = retHTML.join('');
}

function PlacePopupDiv(mapX, mapY) {
    // get the map coords
    var mapPoint = new ESRI.ADF.Geometries.Point(mapX, mapY);
    var screenPoint = arcgisWebApp.map.toScreenPoint(mapPoint);

    // get the popup div
    var divIR = document.getElementById('divIR');
    var imgIRPointer = document.getElementById('imgIRPointer');
    
    if (divIR != null) {
        var x = screenPoint.offsetX;
        var y = screenPoint.offsetY;
        
        var facilitiesDiv = document.getElementById('MapContainerDiv_Map1');

        var hOffset = parseInt(facilitiesDiv.style.left.replace('px', ''));
        var vOffset = parseInt(facilitiesDiv.style.top.replace('px', ''));

        // Compute the coords
        x -= hOffset;
        y -= vOffset;
        
        divIR.style.left = (x + 17) + 'px';
        imgIRPointer.style.left = -17 + 'px';
        
        divIR.style.top = (y - 26) + 'px';
        imgIRPointer.style.top = 7 + 'px';
    }
}

function ShowPopup() {
    RenderPopupContent(0);
    o = document.getElementById('divIR');
    if (o != null) {
        o.style.visibility = 'visible';
    }
}

function ClosePopup() {
    o = document.getElementById('divIR'); 
    if (o != null) {
        o.style.visibility = 'hidden';
        InvokeCallback_Custom('Map1', 'ControlID=divIR&ControlType=Map&EventArg=ClosePopup');
    }
}