﻿
// Define element ids referenced in script.
// Note that script for both dropdowns and splitter use other hard-coded values referenced in markup.
var coordinateDivId = "#coordinateDiv";
var directionsMenuDivId = "#directionsMenuDiv";
var fromAddressInputId = "#fromAddressInput";
var headerDivId = "#headerDiv";
var logoDivId = "#logoDiv";
var mapDivId = "#mapDiv";
var optimizeDivId = "#optimizeDiv";
var progressImageId = "#progressImage";
var showRouteAnchorId = "#showRouteAnchor";
var splitterBottomDivId = "#splitterBottomDiv";
var splitterParentDivId = "#splitterParentDiv";
var splitterTopDivId = "#splitterTopDiv";
var streetviewDivId = "#streetviewDiv";
var streetviewDropdownId = "#streetviewDropdown";
var streetviewTrackingCheckboxId = "#streetviewTrackingCheckbox";
var streetviewTrackingDivId = "#streetviewTrackingDiv";
var textDivId = "#textDiv";
var titleDivId = "#titleDiv";
var toolDivId = "#toolDiv";
var trafficCheckboxId = "#trafficCheckbox";
var trafficDivId = "#trafficDiv";
var useStreetviewCheckboxId = "#useStreetviewCheckbox";

// Define a flag to be set by code-behind on page request errors.
var hideAll;

// Define fields for VEMap and Streetview tools.
var routeFromAddress = "";
var routeFromStartMessage = " < enter address or landmark >";
var routeMode = "drive";
var routeOptimize = "fastest";
var routeUseTraffic = false;
var streetviewOn = false;
var streetviewTracking = false;

// Define variables for resizing functionality.
var clientHeight, clientWidth;
var mapPadding = 3; //Chrome may need more padding here.
var panoPadding = 2;
var splitterResizeTimer = null;
var splitterResizeTimerInterval = 250;
var splitterMinimumHeight = 200;
var splitterMinimumWidth = 200;
var splitterOffsetHeight; // = 125;
var splitterOffsetWidth = 50;


$(document).ready(function() {

    //
    // Element initialization
    //

    // Set text from members updated in code-behind.
    $(titleDivId).html(title);

    // Hide everything else if page parameters were invalid.
    if (hideAll) {
        $(toolDivId).hide();
        $(splitterParentDivId).hide();
        return;
    }

    // Set initial message for directions input.
    $(fromAddressInputId)[0].value = routeFromStartMessage;

    // Hide tracking option since Streetview is disabled on load.
    $(streetviewTrackingDivId).hide();

    // Define a div as a splitter element.
    // Note that this div will hereafter behave more like a control than a div.
    $(splitterParentDivId).splitter({ type: 'h', accessKey: 's', sizeTop: true });

    // Prevent selecting text in most browsers.
    //$(textDivId).disableSelection();
    $(logoDivId).disableSelection();
    $(titleDivId).disableSelection();
    $(".menuTitle").disableSelection();
    $("label").disableSelection();
    $("a").disableSelection();



    //
    // Event wiring
    //

    // Wire splitter events.
    $(".hsplitbar").click(function(e) {
        resizeSplitter();
    });
    $(".hsplitbar").mouseover(function(e) {
        $(splitterTopDivId).css("background-color", "#EADCC0");
        $(splitterBottomDivId).css("background-color", "#EADCC0");
    });
    $(".hsplitbar").mouseout(function(e) {
        $(splitterTopDivId).css("background-color", "#F0E8D5");
        $(splitterBottomDivId).css("background-color", "#F0E8D5");
    });

    // Wire both dropdown click events to show menu normally and hide with slow animation.
    $(".dropdown .menuTitle a").click(function(e) {
        var target = e.currentTarget;
        if ($(target).hasClass("openMenuTitle")) {
            hideMenus();
        }
        else {
            hideMenus();
            $("#" + target.parentElement.parentElement.id + " .menu").show();
            $(target).addClass("openMenuTitle");
            $(fromAddressInputId).focus().select();
        }
    });

    // Wire other click events to hide all dropdown menus if not within a dropdown structure.
    $(document).bind("click", function(e) {
        var $clicked = $(e.target);
        if (!$clicked.parents().hasClass("dropdown")) {
            hideMenus();
        }
    });

    // Wire first keydown in address input to change style.
    $(fromAddressInputId).keydown(function(e) {
        $(fromAddressInputId).unbind("keydown");
        $(fromAddressInputId).addClass("inputText");
    });

    // Wire address input validation.
    $(fromAddressInputId).keyup(function() {
        validateAddress();
    });

    // Wire Enter key to toggle route display if the directions menu is open.
    $(directionsMenuDivId).keypress(function(e) {
        if (isEnterKey(e) && $(showRouteAnchorId).is(":visible")) {
            toggleDirections();
        }
    });

    // Wire mode radio input to set the routeMode member and toggle display of other routing elements.
    $("input[name='mode']").click(function(e) {
        if ($("input[name='mode']:nth(1)").attr("checked")) {
            routeMode = "walk";
            $(optimizeDivId).hide();
            $(trafficDivId).hide();
        }
        else {
            routeMode = "drive";
            $(optimizeDivId).show();
            $(trafficDivId).show();
        }
    });

    // Wire optimize radio input to set the routeOptimize member. 
    $("input[name='optimize']").click(function(e) {
        if ($("input[name='optimize']:nth(1)").attr("checked")) {
            routeOptimize = "straight";
        }
        else {
            routeOptimize = "fast";
        }
    });

    // Wire traffic checkbox to set the routeUseTraffic member.
    $(trafficCheckboxId).click(function(e) {
        routeUseTraffic = e.currentTarget.checked;
    });

    // Wire "Show/Hide" anchor to directions method.
    $(showRouteAnchorId).click(function(e) {
        toggleDirections();
    });

    // Wire Streetview-enabled checkbox to toggle display of this feature.
    $(useStreetviewCheckboxId).click(function(e) {
        setStreetview(e.currentTarget.checked);
    });

    // Wire Streetview tracking checkbox to toggle display of this feature.
    $(streetviewTrackingCheckboxId).click(function(e) {
        streetviewTracking = e.currentTarget.checked;
        updateMapWithStreetview();
    });

    // Wire resize functions to browser events.
    jQuery.event.add(window, "load", BrowserResizeEvent2);
    jQuery.event.add(window, "resize", BrowserResizeEvent2);
    window.setTimeout('resizeSplitter()', 3000); // Add extra resize here for Chrome.

    // Dispose Google objects on browser unload.
    jQuery.event.add(window, "unload", disposeStreetview);

    // Define a timer to execute resizeSplitter() after a short delay. 
    // Note that BrowserResizeEvent() is defined in script emitted by the Richmond BingMapControl.
    function BrowserResizeEvent2() {
        if (splitterResizeTimer != null) {
            window.clearTimeout(splitterResizeTimer);
            splitterResizeTimer = null;
        }
        if (typeof (resizeSplitter) != 'undefined') {
            splitterResizeTimer = window.setTimeout('resizeSplitter()', splitterResizeTimerInterval);
        }
    }



    //
    // Helper functions
    //

    function isEnterKey(e) {
        e = e || window.event || {};
        var charCode = e.charCode || e.keyCode || e.which;
        if (charCode == 13) {
            return true;
        }
    }

    // Enables or disables Streetview based on input value.
    function setStreetview(enabled) {
        streetviewOn = enabled;
        if (streetviewOn) {
            $(streetviewTrackingDivId).show();
            showPanorama(initialMapCenter.Latitude, initialMapCenter.Longitude);
        }
        else {
            $(streetviewTrackingDivId).hide();
            hidePanorama();
        }

        resizeSplitterPanes(true);
    }

    // Toggles direction display based on value of button label.
    function toggleDirections() {
        var target = $(showRouteAnchorId);
        if (target.html() === "Show") {
            // Route not currently displayed. Attempt to show it.
            getRouteMap();
        }
        else {
            // Route is currently displayed. Reset label, map, and input.
            target.html("Show");
            veMap.DeleteRoute();
            $(fromAddressInputId)[0].value = "";
            validateAddress();
            $(fromAddressInputId).focus();
        }
    }

    // Displays "Show/Hide" button if address input has at least two characters.
    // Also sets button text to "Show", and sets routeFromAddress member.
    function validateAddress() {
        var elem = $(fromAddressInputId);
        if (elem && elem[0].value && elem[0].value.length > 1) {
            $(showRouteAnchorId).show().html("Show");

            // Set from address.
            routeFromAddress = elem[0].value;
        }
        else {
            $(showRouteAnchorId).hide().html("Show");

            // Clear from address.
            routeFromAddress = "";
        }
    }
});



// jQuery extension to disable text selection.
jQuery.fn.extend({
    disableSelection: function() {
        this.each(function() {
            this.onselectstart = function() { return false; };
            this.unselectable = "on";
            jQuery(this).css('-moz-user-select', 'none');
        });
    }
});



//
// Functions called from both inside and outside jQuery.
//

function hideMenus() {
    $(".dropdown .menu").animate({ height: 'hide', opacity: 'hide' }, 400);
    $(".dropdown .menuTitle a").removeClass("openMenuTitle").addClass("closedMenuTitle");
}

function resizeSplitter() {

    // Adjust height of header div to ensure it contains the tool div since title content may push it downward. 
    var toolDivTop = $(toolDivId).offset().top;
    var mapTop = toolDivTop + $(".dropdown .menuTitle").height();
    $(headerDivId).css("height", mapTop + "px");

    // Position and update the requested coordinates. Note one vertical pixel is added to align with tool div since it has a border.
    var coordinateDiv = $(coordinateDivId);
    coordinateDiv.css("top", toolDivTop + 1 + "px");
    coordinateDiv.html(initialMapCenter.Latitude.toFixed(6) + "&deg;&nbsp;&nbsp;&nbsp;" + initialMapCenter.Longitude.toFixed(6) + "&deg;");

    // Update vertical offset using header div height.
    splitterOffsetHeight = mapTop + 25;

    // Scale down the splitter parent div to fit the available browser dimensions.
    clientHeight = $(window).height();
    clientWidth = $(window).width();
    h = clientHeight - splitterOffsetHeight;
    w = clientWidth - splitterOffsetWidth;
    if (h < splitterMinimumHeight) {
        h = splitterMinimumHeight;
    }
    if (w < splitterMinimumWidth) {
        w = splitterMinimumWidth;
    }
    $(splitterParentDivId).css("height", h + "px").trigger("resize");
    $(splitterParentDivId).css("width", w + "px").trigger("resize");

    resizeSplitterPanes(false);
}

function resizeSplitterPanes(isOnStreetviewToggle) {
    var topPaneH = parseInt($(splitterTopDivId).css("height"));
    var topPaneW = parseInt($(splitterTopDivId).css("width"));
    var bottomPaneH = parseInt($(splitterBottomDivId).css("height"));
    var bottomPaneW = parseInt($(splitterBottomDivId).css("width"));
    var totalH = topPaneH + bottomPaneH;
    var mapH; 
    if (streetviewOn) {
        if (isOnStreetviewToggle) {
            mapH = parseInt(totalH / 2);
        }
        else {
            mapH = topPaneH;
        }
        $(streetviewDivId).css('width', bottomPaneW - panoPadding + 'px').css('height', bottomPaneH - panoPadding + 'px');
        $(splitterParentDivId).trigger("resize", [mapH]);
        resizePanorama();
    }
    else {
        mapH = totalH;
        $(streetviewDivId).css('height', '0px');
        $(splitterParentDivId).trigger("resize", [mapH]);
    }
    
    if (veMap) {
        veMap.Resize(topPaneW - mapPadding, mapH - mapPadding);
    }
}

