﻿/// <reference path="call_remote_1.4.js" />
/// <reference name="MicrosoftAjax.js" />

function dblClick() {
    ///<summary>This function is called whenever
    ///a search operation is performed, in order
    ///to track it through DoubleClick.</summary>

    page.logIt("dblClick() called...");

    // Store the value of the "location" input box in locationText
    var locationText = $(page.txtAddressClientID).value.trim();

    // Store the value of the "name" input box in searchName
    var searchName = $(page.txtNameClientID).value.trim();

    // If searchName is equal to the initial value
    // of the "name" input box...
    if (searchName == page.nameInitialValue) {
        // Clear searchName
        searchName = "";
    }

    // Generate a random number
    var axel = Math.random() + "";
    var a = axel * 10000000000000;

    // Write an IFRAME to the "spotlights" layer,
    // containing the third party id, search location,
    // search name, and the random number.
    $('spotlights').innerHTML = "<IFRAME SRC='https://fls.doubleclick.net/activityi;src=1430391;type=fbfsi885;cat=fbfsf044;u6=" + page.fbfsThirdPartyId + ";u12=" + escape(locationText) + ";u13=" + searchName + ";ord=1;num=" + a + "?' WIDTH=1 HEIGHT=1 FRAMEBORDER=0></IFRAME>";
}

function showInvalidLocation() {
    ///<summary>Updates the display when user
    ///attempts to search on an invalid location.</summary>

    page.logIt("showInvalidLocation() called...");

    // Show the "invalid location" text
    // (also conatins the "see examples" text).
    $("invalidLocation").style.display = "block";
    
    // Hide the "see examples" text
    $("seeExamples").style.display = "none";

    // Get a reference to the address textbox
    var addressTextBox = $(page.txtAddressClientID);

    // Change the address textbox border color to Red
    addressTextBox.style.borderColor = '#FF0000';
    
    // Clear the address textbox text
    addressTextBox.value = "";
    
    // Change the address textbox text color to Black
    addressTextBox.style.color = '#000000';
    
    // Give the address textbox focus
    addressTextBox.focus();
}

function hideInvalidLocation() {
    ///<summary>Updates the display to hide the
    ///"invalid location" text.</summary>

    page.logIt("hideInvalidLocation() called...");

    // Hide the "invalid location" text
    // (also conatins the "see examples" text).
    $("invalidLocation").style.display = "none";
    
    // Show the "see examples" text
    $("seeExamples").style.display = "block";
    
    // Change the address textbox border color to blue
    $(page.txtAddressClientID).style.borderColor = '#7f9db9';
}

function hideAllFeedback() {
    ///<summary>Hide the layer containing
    ///all of the feedback display elements.</summary>

    page.logIt("hideAllFeedback() called...");

    // Hide the "feedback" layer
    $("divFeedback").style.display = "none";
}

function showNameTextBox() {
    ///<summary>Shows the "search by name"
    ///input field.</summary>

    page.logIt("showNameTextBox() called...");

    // Show the "name" textbox
    $("tblNameSearch").style.display = "block";
    
    // Hide the "search by name" link
    $("lnkSearchByName").style.display = "none";

    // Set a variable to indicate that
    // the "name" textbox should remain visible
    // between partial-postbacks.
    page.leaveNameVisible = true;

    refreshGMap();
}

function refreshGMap() {
    ///<summary>This is a work-around for an IE browser
    /// bug that causes the GMap control to
    /// vanish whenever any rerendering is done.
    ///
    /// Hide, then show, the GMap control's
    /// containing element.</summary>

    page.logIt("refreshGMap() called...");

    var mapContainer = $(page.GMap1ClientID);
    if (mapContainer) {
        mapContainer.style.display = "none";
        mapContainer.style.display = "block";
    }
}

function toggleExamples() {
    ///<summary>Toggles the visibility
    ///of the searchEx element, which
    ///contains example search text.</summary>

    page.logIt("toggleExamples() called...");

    // If the searchEx element is not visible
    if ($('divSearchEx').style.display != 'block') {
        // Show the searchEx element
        $('divSearchEx').style.display = 'block';
    }
    else {
        // Hide the searchEx element
        $('divSearchEx').style.display = 'none';
    }
}

function handleSearchButtonClick() {
    ///<summary>This function is called when the
    ///"Go" button is clicked to perform a location
    ///search.</summary>
    page.logIt("handleSearchButtonClick() called...");

    // Clear the search data values
    PageMethods.ClearSearchData();

    page.logIt("<strong>Cleared search data from Session...</strong>");

    // Hide all current feedback elements
    hideAllFeedback();

    // If a valid address has been entered...
    if (validateAddress()) {
        // Call getLatLngForAddress() to kick-off the
        // search, and display the "waiting..." image
        // if the search successfully began.
        if (getLatLngForAddress($(page.txtAddressClientID).value, null)) {
            $("loader").style.display = 'block';
        }
    }
}

function selectMarker(index) {
    ///<summary>This function will select the
    ///specified marker on the map, causing
    ///the map to center on the marker, and
    ///display the marker's info window.</summary>
    ///<param name="index" type="int">The index of the
    ///marker to be selected.</param>

    page.logIt("selectMarker(" + index + ") called...");

    // Call the selectMarker() method of the map object
    eval(page.GMap1MapObjectJavaScriptIdentifier).selectMarker(index);
}

function handleMarkerClicked(index) {
    ///<summary>This function will act as the click
    ///event handler for the markers on the map. This
    ///function is also called from initializeDisplay()
    ///to display the most recently selected office.</summary>
    ///<param name="index" type="int">The index of the
    ///marker that was clicked.</param>

    page.logIt("handleMarkerClicked(" + index + ") called...");

    // Get a reference to the list of officeAdresses DIV's
    var officeAdresses = $$("td div.officeAddress");

    // Attempt to select the specified map marker
    // and expand the corresponding office menu item.
    try {
        // Select the map marker
        selectMarker(index);
        
        // Expand the office details
        officeAdresses[index].onclicked();

        // Clear the interval to prevent
        // the function from running again.
        clearInterval(page.handleMarkerClickedInterval);
    }
    catch (e) {
    }
}

function initializeOfficeMenu() {
    ///<summary>Initializes the office "accordion" menu</summary>

    page.logIt("initializeOfficeMenu() called...");

    // If the menu structure is present...
    if ($(page.lstOfficeListClientID)) {
        // Get the list of collapsible DIV's
        var list = $$("td div.officeAgents");

        // Get the list of header DIV's
        var headings = $$("td div.officeAddress");

        // Create an array to hold references to
        // the individual Slide effect objects.
        var collapsibles = new Array();

        // For each "office address" DIV...
        headings.each(function(heading, i) {
            // Create a Slide effect object
            var collapsible = new Fx.Slide(list[i], {
                duration: 100,
                transition: Fx.Transitions.quadIn
            });

            // Place a reference to the 
            // Slide effect object in the array.
            collapsibles[i] = collapsible;

            // Attach a method to the header (the
            // "office address" DIV) that will be
            // called when the header is clicked
            // (the onclick handler for the DIV
            // will in-turn call this handler).
            heading.onclicked = function() {
                // Set the officeIndex value
                PageMethods.SetAgentOfficeIndex(i.toString());
                page.logIt("<strong>Set Office Index to Session (" + i.toString() + ")...</strong>");

                // For each collapsible item...
                for (var j = 0; j < collapsibles.length; j++) {
                    // Hide the item, if it's not the currently
                    // selected one.
                    if (j != i) collapsibles[j].slideOut();
                }
                
                // Show the collapsible item (office agents DIV)
                collapsible.slideIn().chain(refreshGMap);

                return false;
            }

            // Hide the header
            collapsible.hide();
        });
    }
}

function clickButton(e, keyCode, buttonId) {
    ///<summary>This function is called by the 
    ///onkeypress handler for the location
    ///search text box (txtAddress). It's
    ///purpose is to trigger the click handler
    ///of a specified button when a specific
    ///key is pressed.</summary>
    ///<param name="e">The event passed to the caller</param>
    ///<param name="keyCode">The character code that
    ///needs to have been pressed in order to trigger
    ///the button click.</param>
    ///<param name="buttonid">The Id of the
    ///button whose click handler is to be called.</param>
    // Get the event object

    //page.logIt("clickButton(" + e + ", " + keyCode.toString() + ", \"" + buttonId.toString() + "\") called...");
    
    var evt = e ? e : window.event;

    // Get a reference to the specified button
    var bt = $(buttonId);

    // If the button reference is valid...
    if (bt) {
        // If the keyCode of the keypress
        // matches the specified value...
        if (evt.keyCode == keyCode || evt.charCode == keyCode) {
            // Call the button's onclick handler
            if (bt.onclick) {
                bt.onclick();
            }
            else if (bt.click) {
                bt.click();
            }
            return false;
        }
    }
}

function overBackground(id) {
    ///<summary>The mouseover handler
    ///for the office address DIV's. Changes
    ///the background and foreground colors
    ///of the spcified DIV element.</summary>
    ///<param name="id">The Id of the target
    ///element.</param>

    $(id).style.backgroundColor = '#528CE0';
    $(id).style.color = '#FFFFFF';
}

function outBackground(id) {
    ///<summary>The mouseout handler
    ///for the office address DIV's. Changes
    ///the background and foreground colors
    ///of the spcified DIV element.</summary>
    ///<param name="id">The Id of the target
    ///element.</param>

    $(id).style.backgroundColor = "";
    $(id).style.color = "";
}

function initializeInputFields() {
    ///<summary>Initializes all input fields.</summary>

    page.logIt("initializeInputFields() called...");

    initializeAddressTextBox();
    initializeNameTextBox();
}

function initializeAddressTextBox() {
    ///<summary>Initializes the "location" search
    ///text box.</summary>

    page.logIt("initializeAddressTextBox() called...");

    // Get a reference to the "location" search textbox
    var addressTextBox = $(page.txtAddressClientID);

    // If the "location" search textbox contains the
    // initial value then change the text color to grey.
    if (addressTextBox.value.trim() == page.locationInitialValue) {
        addressTextBox.style.color = '#999999';
    }
    // Else, change the text color to black
    else {
        addressTextBox.style.color = '#000000';
    }
}

function initializeNameTextBox() {
    ///<summary>Initializes the "name" search
    ///text box.</summary>

    page.logIt("initializeNameTextBox() called...");

    // Get a reference to the "name" textbox
    var nameTextBox = $(page.txtNameClientID);

    if (nameTextBox) {
        // If the "name" textbox still contains the initial
        // value, then change the text color to grey.
        if (nameTextBox.value.trim() == page.nameInitialValue) {
            nameTextBox.style.color = '#999999';
        }
        // Else, change the text color to black
        else {
            nameTextBox.style.color = '#000000';
        }
    }
}

function validateAddress() {
    ///<summary>Validates the value entered into
    ///the "location" search textbox. Has the side-effect
    ///of clearing the "location" textbox, changing its
    ///text color to Black and changing its border color to
    ///Red if the "location" input is invalid.</summary>
    ///<returns>true if valid, false otherwise</returns>

    page.logIt("validateAddress() called...");

    // Initialize the return value to true
    var retVal = true;

    // Get a reference to the "location" textbox
    var addressTextBox = $(page.txtAddressClientID);

    // Hide invalid location message
    hideInvalidLocation();

    // Reset the global flag that is used to determine
    // whether or not to keep the feedback elements
    // hidden between page loads.
    page.feedbackIsOutdated = false;

    // If the textbox is empty or contains
    // the initial value...
    if (addressTextBox.value.trim() == page.locationInitialValue || addressTextBox.value.trim().length == 0) {
        // Display invalid location message
        showInvalidLocation();
        
        // Set the return value to false
        retVal = false;

        // Set the global flag that is used to determine
        // whether or not to keep the feedback elements
        // hidden between page loads. It's being set to
        // true here since this last search was invalid,
        // and we don't want any previous search results
        // displayed if the page is loaded again before
        // a valid search request is made.
        page.feedbackIsOutdated = true;
    }
    return retVal;
}

function mapLoaded() {
    ///<summary>Called when the map has
    ///completely loaded.</summary>

    page.logIt("mapLoaded() called...");

    // Get a reference to the map's script object
    var mapObject = eval(page.GMap1MapObjectJavaScriptIdentifier);

    // If the map's script object was found, and
    // exactly one marker has been placed on the map...
    if (mapObject && mapObject.googleMapObjectMarkers.length == 1) {
        // Clear any previous interval to prevent
        // handleMarkerClicked() from being called
        // multiple times.
        clearInterval(page.handleMarkerClickedInterval);
        
        // Select the first, and only, office
        page.handleMarkerClickedInterval = setInterval("handleMarkerClicked(0)", 100);
    }
}

function initializeDisplay() {
    ///<summary>This function is called when
    ///the page is initially loaded, as well as
    ///after any partial-postbacks. It is called
    ///just before the pageLoaded() function below
    ///is called.
    /// 
    ///This is where any page elements that are
    ///not managed by ViewState should be updated
    ///to reflect the most recent user actions.
    ///</summary>

    page.logIt("initializeDisplay() called...");

    // If the feedback is outdated...
    if (page.feedbackIsOutdated) {
        // Hide all feedback elements
        hideAllFeedback();
    }

    // Initialize all input fields
    initializeInputFields();

    // Clear the mostRecentSearchData variable
    page.mostRecentSearchData = null;

    // Get the most recent search data
    PageMethods.GetAgentOfficeSearchData(GetAgentOfficeSearchData_Callback, GetAgentOfficeSearchData_Callback);
}

function GetAgentOfficeSearchData_Callback(result) {
    // If an address was provided in the page's
    // "location" URL parameter...
    if (page.searchLocationFromUrlParameter.length > 0) {
        page.logIt("Found an address in the \"location\" URL parameter: \"" + page.searchLocationFromUrlParameter + "\"");
        // Clear the result parameter's values
        result = "{locationText:\"\",officeIndex:\"\",agentName:\"\"}";
    }

    // Parse the JSON string that was returned
    page.mostRecentSearchData = eval("(" + result + ")");

    page.logIt("Received most recent search data --> [location: " + page.mostRecentSearchData.locationText + " Office Index: " + page.mostRecentSearchData.officeIndex + " Name: " + page.mostRecentSearchData.agentName + "]...");

    // Setup the accordion menu that displays
    // all of the office locations, and their
    // associated agents.
    initializeOfficeMenu();

    // If a previous office index has been found...
    if (page.mostRecentSearchData.officeIndex.length > 0) {
        // Clear any previous interval to prevent
        // handleMarkerClicked() from being called
        // multiple times.
        clearInterval(page.handleMarkerClickedInterval);

        // Call handleMarkerClicked() to Select the office
        page.handleMarkerClickedInterval = setInterval("handleMarkerClicked(" + parseInt(page.mostRecentSearchData.officeIndex) + ")", 100);
    }

    // If the user previously chose to show the
    // "name" input textbox, or the most recent search results
    // indicate that a name was used in the most recent search...
    if (page.leaveNameVisible || page.mostRecentSearchData.agentName.length > 0) {
        // Show the "name" textbox
        showNameTextBox();
    }

    // If the most recent search results indicate
    // that a name was used in the last search...
    if (page.mostRecentSearchData.agentName.length > 0) {
        // Update the "name" textbox to hold
        // the name from the previous search.
        $(page.txtNameClientID).value = page.mostRecentSearchData.agentName;
    }

    refreshGMap();

    // If an address was provided in the page's
    // "location" URL parameter...
    if (page.searchLocationFromUrlParameter.length > 0) {
        page.logIt("Setting search text to \"" + page.searchLocationFromUrlParameter + "\", and calling handleSearchButtonClick() to initiate the agent search.");
        $(page.txtAddressClientID).value = page.searchLocationFromUrlParameter;
        page.searchLocationFromUrlParameter = "";
        handleSearchButtonClick();
    }
}

function pageLoaded() {
    ///<summary>This function is called anytime
    ///the page is completely reloaded (typically
    ///via the intitial page load or the browser's
    ///"next", "back" or the "refresh" buttons).
    ///</summary>

    page.logIt("pageLoaded() called...");

    // If the most recent search data has been
    // retrieved from the server...
    if (page.mostRecentSearchData != null) {
        // If previous location search text has been found...
        if (page.mostRecentSearchData.locationText.length > 0) {
            // Set the "location" search text
            $(page.txtAddressClientID).value = page.mostRecentSearchData.locationText;

            // Kick-off the search operation
            getLatLngForAddress(page.mostRecentSearchData.locationText, null);
        }
    }
    // Else, the most recent search data has not yet been retrieved...
    else {
        // Call pageLoaded() again, on delay
        setTimeout("pageLoaded()", 100);
    }
}

// Define the addEvent function, which makes
// it easier to add events to objects.
window.addEvent2 = function(e, ev, f, c) { if (e.addEventListener) { e.addEventListener(ev, f, c); } else if (e.attachEvent) { var r = e.attachEvent('on' + ev, f); return r; } else { e['on' + ev] = f; } };

// Add the "pageLoaded()" function as an
// onload handler for the window.
window.addEvent2(window, "load", pageLoaded, false);

page.logIt("*******************************");
page.logIt("AgentOfficeLocator.js loaded...");
page.logIt("*******************************");
