﻿/// <reference assembly="ESRI.ArcGIS.ADF.Web.UI.WebControls" name="ESRI.ArcGIS.ADF.Web.UI.WebControls.Runtime.JavaScript.references.js"/>

var map;
var toolMode;
var doNewMapQuery = true;
var popupMapX, popupMapY;
var showPopup;

function init(){
    jQuery('#PopupHolder').hide();
    map = Sys.Application.findComponent('WardMap');
    toolbar = Sys.Application.findComponent("Toolbar1");
    toolbar.add_onToolSelected(toolSelect);
    
    // set up the jQuery slider
    jQuery("#mapScroll").slider({
        min: 2651600,
        max: 2659900,
        change: updateMapFromSlider
    });
    
	map.add_extentChanged(updateSliderFromMap);
	
	map.add_zoomCompleted(updatePopupLocation);
	map.add_zoomStart(preUpdatePopupLocation);
	
	var initialEnvelope = new ESRI.ADF.Geometries.Envelope(2651000, 324000, 2660000, 326500);
	map.zoomToBox(initialEnvelope, false);
	
	// When starting up, we want to sync up the slider with the map extents.
	var extentsObj = {'current': map.get_extent()};
	updateSliderFromMap(map, extentsObj);
	
	// set up the jQuery tabs
	jQuery('#actionTabs').simpletabs({ selected: 0 });
	
	// add a click event for the map
	map.add_click(mapClicked);
	
	addPopupDivHolderToDOMLocation();
}

function toolSelect(sender, args) {
    if (args.name) {
        toolMode = args.name;
    }
}

var doMapUpdate = true;
function updateMapFromSlider(event, ui){
    doSliderUpdate = false;
    if (doMapUpdate){
        var extent = map.get_extent();
        var minx = ui.value - (extent.get_width() / 2);
        var maxx = ui.value + (extent.get_width() / 2);
        var newEnvelope = new ESRI.ADF.Geometries.Envelope(minx, extent._ymin, maxx, extent._ymax);
        map.panTo(newEnvelope.get_center(), true);
    }
    doSliderUpdate = true;
}

var doSliderUpdate = true;
function updateSliderFromMap(map, extents){
    doMapUpdate = false;
    if (doSliderUpdate){
        var x = extents.current.get_center().get_x();
        jQuery("#mapScroll").slider('value', x);
    }
    doMapUpdate = true;
}

function checkForEnter(e){
    if (e.keyCode == 13){
        findAddress(document.getElementById('txtAddress').value);
        e.returnValue=false;
        e.cancel = true;
    }
}

function mapClicked(map,event,isAddress){
    if (
        event.rawEvent && event.rawEvent.target && event.rawEvent.target.id == 'closeImage' ||          // FF
        event.rawEvent && event.rawEvent.srcElement && event.rawEvent.srcElement.id == 'closeImage'        // IE
    ){
        closePopup();
        return;
    }
    jQuery('#PopupHolder').hide();
    if (toolMode == "IdBubble" || isAddress === true){
        var mapx = event.coordinate.coordinates[0];
        var mapy = event.coordinate.coordinates[1];
        
        // Fill the identify tab's info
        jQuery("#identifyFull").load("Identify.aspx?x=" + mapx + "&y=" + mapy);
        
        // If the current tab is not the identify tab, then show the popup.
        popupMapX = mapx;
        popupMapY = mapy;
        var selectedTab = jQuery('#actionTabs').simpletabs('select');
        if (selectedTab !== '#tabs-identify') {
            placePopupDiv();
        }
        
        // Highlight the selected parcel
        jQuery.ajax({
            data: {
                x: mapx,
                y: mapy
            },
            dataType: 'json',
            error: findAddressError,
            success: findPointComplete,
            type: 'POST',
            url: 'ParcelHandler.ashx'
        });
    }
}

function preUpdatePopupLocation(){
    showPopup = jQuery('#PopupHolder').is(':visible');
    jQuery('#PopupHolder').hide();
}

function updatePopupLocation(a,b,c){
    if (showPopup) {
        jQuery('#PopupHolder').show();
        placePopupDiv();
    }
}

function addPopupDivHolderToDOMLocation() {
    var divAnnotation = document.getElementById('MapContainerDiv_WardMap');
    var divPopupHolder = document.getElementById('PopupHolder');

    if ((divAnnotation != null) && (divPopupHolder != null)) {
        divAnnotation.appendChild(divPopupHolder);
    }
}

function placePopupDiv() {
    // get the map coords
    var mapPoint = new ESRI.ADF.Geometries.Point(popupMapX, popupMapY);
    var screenPoint = map.toScreenPoint(mapPoint);
    
    // if the point is close to the edge, then adjust where the popup is placed
    var extent = map.get_extent();
    var bottomRight = new ESRI.ADF.Geometries.Point(extent.get_xmax(), extent.get_ymin());
    var screenBottomRight = map.toScreenPoint(bottomRight);
    // we have to use estimates here, because we don't know the actual size
    var popupDivHeight = 85;
    var popupDivWidth = 200;
    if (screenBottomRight.offsetX - screenPoint.offsetX < popupDivWidth){
        screenPoint.offsetX -= popupDivWidth;
    }
    if (screenBottomRight.offsetY - screenPoint.offsetY < popupDivHeight){
        screenPoint.offsetY -= popupDivHeight;
    }


    // get the popup div
    var divIR = jQuery('#PopupHolder');
    
    if (divIR != null) {
        var x = screenPoint.offsetX;
        var y = screenPoint.offsetY;
        
        var facilitiesDiv = jQuery('#MapContainerDiv_WardMap');

        var hOffset = parseInt(facilitiesDiv.css('left'));
        var vOffset = parseInt(facilitiesDiv.css('top'));

        // Compute the X coord
        divIR.css('left', (x - hOffset) + 'px');

        // Compute the Y coord
        divIR.css('top', (y - vOffset) + 'px');

    }
}

function findPointComplete(parcel){
    // clear the existing graphics
    for (i = 0; i < map._graphicFeatures.length; i++){
        map.removeGraphic(map._graphicFeatures[i]);
    }
    
    // if the response has a geometry string (parcel polygon), then draw it
    if (parcel.GeomString){
        var selectedTab = jQuery('#actionTabs').simpletabs('select');
        if (selectedTab !== '#tabs-identify') {
            jQuery('#PopupHolder').load("IdentifyMini.aspx?x=" + popupMapX + "&y=" + popupMapY).show();
        }
        var cc = new ESRI.ADF.Geometries.CoordinateCollection();
        var pointList = parcel.GeomString.substring(9, parcel.GeomString.length-2);
        var pairs = pointList.split(',');
        for (var i = 0; i < pairs.length; i++){
            var coords = pairs[i].split(' ');
            cc.add(new ESRI.ADF.Geometries.Point(coords[0], coords[1]));
        }
        
        var poly = new ESRI.ADF.Geometries.Polygon(cc, map._spatialReference);
        
        var hlSymbol = new ESRI.ADF.Graphics.FillSymbol('Yellow', 'Black', 2);
        
        var gFeature = new ESRI.ADF.Graphics.GraphicFeature(poly, hlSymbol);
        
        map.addGraphic(gFeature);
    }
}

function findAddress(address){
    jQuery.ajax({
        data: {
            address: address
        },
        dataType: 'json',
        error: findAddressError,
        success: findAddressComplete,
        type: 'POST',
        url: 'AddressHandler.ashx'
    });
}

function findAddressComplete(geocodeResponse){
    if (geocodeResponse){
        if (geocodeResponse.notFound){
            alert('The address ' + geocodeResponse.notFound + ' could not be located.');
            return;
        }
        var x = geocodeResponse.Candidate.Longitude;
        var y = geocodeResponse.Candidate.Latitude;
        popupMapX = x;
        popupMapY = y;
        var point = new ESRI.ADF.Geometries.Point(x, y);
        
        clickEvent = {
            coordinate: {
                coordinates: [x, y]
            }
        };
        mapClicked(null, clickEvent, true);
        map.panTo(point, true);
    }
}

function closePopup() {
    doNewMapQuery = false;
    jQuery('#PopupHolder').hide();
}

function findAddressError(a,b,c){
    alert('error');
}