﻿/// <reference path="call_remote_1.4.js" />
/// <reference name="MicrosoftAjax.js" />
/// <reference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.Core.js" />   
/// <reference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.jQuery.js" />   
/// <reference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.jQueryInclude.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 locationAddressText = $("#" + page.TxtStreetAddressClientID).val().trim();
    var locationZipText = $("#" + page.TxtZipCodeClientID).val().trim();
    var locationCityText = $("#" + page.TxtCityClientID).val().trim();
    var locationStateText = $("#" + page.StateClientID).val().trim();


    var locationText = locationAddressText + "/" + locationZipText + "/" + locationCityText + "/" + locationStateText;

    // Store the value of the "name" input box in searchName
    var searchName = $("#" + page.TxtAgentNameClientID).val().trim();
    var locationAgentStateText = $("#" + page.AgentStateClientID).val().trim();

    // if the user entered an agent name, use the agent state as the location.
    if (searchName != "") { var locationText = locationAgentStateText; }

    // 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.
    document.getElementById("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 hideAllFeedback() {
    ///<summary>Hide the layer containing
    ///all of the feedback display elements.</summary>

    page.logIt("hideAllFeedback() called...");

    // Hide the "feedback" layer
    $("#" + "divFeedback").css("display", "none");
}

function showNameTextBox() {
    ///<summary>Shows the "search by name"
    ///input field.</summary>

    page.logIt("showNameTextBox() called...");

    // Show the "name" textbox
    $("#" + "tblNameSearch").css("display", "block");

    // Hide the "search by name" link
    $("#" + "lnkSearchByName").css("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.css("display", "none");
        mapContainer.css("display", "block");
    }

    var locationCityText = $("#" + page.TxtCityClientID).val().trim();
    var locationStateText = $("#" + page.StateClientID).val().trim();

    if (locationCityText.length > 0 || locationStateText.length > 0) {
        showAdditionalOptions();
    }

}

function showAdditionalOptions() {
    $('.additionalSearchOptions').css('background-position', '0 0');
    $('.additionalSearch').show();
    $('#aSAgentLocatorBottomRepeat').removeClass('agentLocatorBottomRepeat');
    $('#aSAgentLocatorBottomRepeat').addClass('agentLocatorBottomRepeat2');
    $('#aSAgentLocatorRepeat').addClass('agentLocatorRepeat2');
    $('#aSAgentLocatorBottomLeft').css('display', 'none');
    $('#aSAgentLocatorBottomRight').css('display', 'none');
}

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').css("display") != "block") {
        // Show the searchEx element
        $('#' + 'divSearchEx').css("display", "block");
    }
    else {
        // Hide the searchEx element
        $('#' + 'divSearchEx').css("display", "none");
    }
}

function handleSearchButtonClick1() {
    Search1();
}

function handleSearchButtonClick2() {
    Search2();
}

function handleSearchButtonClick3() {
    Search3();
}

function Search1() {

    ///<summary>This function is called when the
    ///"Go" button is clicked to perform a location
    ///search.</summary>
    page.logIt("handleSearchButtonClick1() 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.

        //Clear values in the other search form.
        $("#" + page.TxtAgentNameClientID).val('');
        var agntVldtr = $get(page.AgentStateValidatorID);
        ValidatorEnable(agntVldtr, false);
        if (page.AgentStateClientID) {
            var cmbAgentState = $find(page.AgentStateClientID);
            if (cmbAgentState) {
                cmbAgentState.clearSelection();
            }
        }

        $("#" + page.TxtCityClientID).val('');
        if (page.StateClientID) {
            var cmbState = $find(page.StateClientID);
            if (cmbState) {
                cmbState.clearSelection();
            }
        }


        var locationAddressText = $("#" + page.TxtStreetAddressClientID).val().trim();
        var locationZipText = $("#" + page.TxtZipCodeClientID).val().trim();

        // Combine all variables into one.
        var locationText = locationAddressText + "/" + locationZipText;

        if (locationZipText.length > 0) {
            if (getLatLngForAddress(locationText, null)) {
                $("#" + "loader").css("display", "block");
            }
        }
    }

}

function Search2() {

    ///<summary>This function is called when the
    ///"Go" button is clicked to perform a location
    ///search.</summary>
    page.logIt("handleSearchButtonClick2() 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.

        //Clear values in the other search form.
        $("#" + page.TxtStreetAddressClientID).val('');
        $("#" + page.TxtZipCodeClientID).val('');
        $("#" + page.TxtAgentNameClientID).val('');
        var agntVldtr = $get(page.AgentStateValidatorID);
        ValidatorEnable(agntVldtr, false);
        if (page.AgentStateClientID) {
            var cmbAgentState = $find(page.AgentStateClientID);
            if (cmbAgentState) {
                cmbAgentState.clearSelection();
            }
        }

        var locationCityText = $("#" + page.TxtCityClientID).val().trim();
        var locationStateText = $("#" + page.StateClientID).val().trim();


        // Combine all variables into one.
        var locationText = locationCityText + "/" + locationStateText;

        if (getLatLngForAddress(locationText, null)) {
            $("#" + "loader").css("display", "block");
        }
    }

}

function Search3() {

    var agntVldtr = $get(page.AgentStateValidatorID);
    var agntNameVldtr = $get(page.TxtAgentNameValidatorClientID);
    
    ValidatorEnable(agntVldtr);
    ValidatorEnable(agntNameVldtr);

    if (!agntVldtr.isvalid || !agntNameVldtr.isvalid)
        return;

    ///<summary>This function is called when the
    ///"Go" button is clicked to perform an agent
    ///search.</summary>
    page.logIt("handleSearchButtonClick3() 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.

        //Clear values in the other search form.
        $("#" + page.TxtStreetAddressClientID).val('');
        $("#" + page.TxtZipCodeClientID).val('');
        $("#" + page.TxtCityClientID).val('');
        if (page.StateClientID) {
            var cmbState = $find(page.StateClientID);
            if (cmbState) {
                cmbState.clearSelection();
            }
        }

        var agentNameText = $("#" + page.TxtAgentNameClientID).val().trim();
        var agentStateText = $("#" + page.AgentStateClientID).val().trim();

        // Combine all variables into one.

        if (getLatLngForAddress(agentStateText, null)) {
            $("#" + "loader").css("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
    clearInterval(page.handleMarkerClickedInterval);

    try {
        var officeAdresses = $(".officeAddress");
        var s = '#' + officeAdresses[index].id;
        $(s).click();
    } catch (e) {
        try {
            var clickOfficeAddress = function () {
                selectMarker(index);
                var officeAdresses = $(".officeAddress");
                var s = '#' + officeAdresses[index].id;
                var f = function () { $(s).click() }
                setTimeout(f, 100);
                Sys.Application.remove_load(clickOfficeAddress);
            };
            // Expand the office details
            Sys.Application.add_load(clickOfficeAddress);
        }
        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 = $(".officeAgents");

        // Get the list of header DIV's
        var headings = $(".officeAddress");

        $('.officeAgents').hide();
        //$('.officeAgents:first').show();



        // For each "office address" DIV...
        $.each(headings, function (i, heading) {

            // Attach a method to the headings (the
            // "office address" DIV) that will be
            // called when the headings are clicked
            heading.onclicked = function () {


                PageMethods.SetAgentOfficeIndex(i.toString());
                page.logIt("<strong>Set Office Index to Session (" + i.toString() + ")...</strong>");

                //determine if current clicked heading is already visible, if so return false.
                var checkElement = $(this).next();
                if (checkElement.is(':visible')) {
                    return false;
                }

                //if clicked heading is not visible, slideUp any headings that are visible and slideDown clicked heading.
                if (!checkElement.is(':visible')) {
                    $('.officeAgents:visible').slideUp();
                    checkElement.slideDown();
                    $('.officeAddress').removeClass('agentOfficeListBackgroundActive')
                    $('.officeAgents').removeClass('officeAgentsActive');
                    $(this).addClass('agentOfficeListBackgroundActive')
                    $(this).next().addClass('officeAgentsActive');
                    return false;
                }
            };
        });
    }
}

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).css("backgroundColor", "#da332a");
    $("#" + id).css("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).css("backgroundColor", "");
    $("#" + id).css("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 StreetAddressTextBox = $("#" + page.TxtStreetAddressClientID);
    var ZipCodeTextBox = $("#" + page.TxtZipCodeClientID);
    var CityTextBox = $("#" + page.TxtCityClientID);
    var StateSelectBox = $("#" + page.StateClientID);

}

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) {

    }
}


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 StreetAddressTextBox = $("#" + page.TxtStreetAddressClientID);
    var ZipCodeTextBox = $("#" + page.TxtZipCodeClientID);
    var CityTextBox = $("#" + page.TxtCityClientID);
    var StateSelectBox = $("#" + page.StateClientID);


    var AgentNameTextBox = $("#" + page.TxtAgentNameClientID);
    var AgentStateSelectBox = $("#" + page.AgentStateClientID);

    // 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 (StreetAddressTextBox.val().trim().length == 0) {

        if (ZipCodeTextBox.val().trim().length == 0) {

            if (CityTextBox.val().trim().length == 0) {

                if (StateSelectBox.val().trim().length == 0) {

                    if (AgentNameTextBox.val().trim().length == 0 && AgentStateSelectBox.val().trim().length == 0) {

                        // 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.gMarkers.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 + ")");

    //alert(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) {

        //alert(page.mostRecentSearchData.handleMarkerClickedInterval);
        // 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.TxtAgentNameClientID).val(page.mostRecentSearchData.agentName);
    }

    refreshGMap();

    // If an address was provided in the page's
    // "location" URL parameter...
    if (page.searchLocationFromUrlParameter.length > 0) {
        page.logIt("page.TxtZipCodeClientID = \"" + page.TxtZipCodeClientID + "\".");
        $("#" + page.TxtZipCodeClientID).val(page.searchLocationFromUrlParameter);
        page.searchLocationFromUrlParameter = "";
        handleSearchButtonClick1();
    }
}

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

            var recent = page.mostRecentSearchData.locationText.toString();

            recentArray = recent.split("/");

            var locationAddressText = recentArray[0];
            var locationZipText = recentArray[1];
            var locationCityText = recentArray[2];
            var locationStateText = recentArray[3];
            var agentLocationText = recentArray[4];

            $("#" + page.TxtStreetAddressClientID).val(locationAddressText);
            $("#" + page.TxtZipCodeClientID).val(locationZipText);
            $("#" + page.TxtCityClientID).val(locationCityText);

            if (page.StateClientID) {
                var cmbState = $find(page.StateClientID);
                if (cmbState) {
                    var cmbItemState = cmbState.findItemByValue(locationStateText);
                    if (cmbItemState) cmbItemState.select();
                }
            }

            var agentNameText = page.mostRecentSearchData.agentName;

            $("#" + page.TxtAgentNameClientID).val(agentNameText);

            if (page.AgentStateClientID) {
                var cmbAgentState = $find(page.AgentStateClientID);
                if (cmbAgentState) {
                    var cmbAgentItemState = cmbAgentState.findItemByValue(agentLocationText);
                    if (cmbAgentItemState) cmbAgentItemState.select();
                }
            }


            var searchName = $("#" + page.TxtAgentNameClientID).val().trim();
            var locationAgentStateText = $("#" + page.AgentStateClientID).val().trim();

            if (searchName.length > 0 || locationAgentStateText.length > 0) {
                // Kick-off the search operation by agent location
                getLatLngForAddress(locationAgentStateText, null);
            } else {
                // Kick-off the search operation by location
                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("*******************************");

