﻿
// Global Variables.    
var ucAdvancedSearch = null;

(function($) {

    window["load_AutoOwners_AgencyLocator_ucAdvancedSearch"] = function(obj) {
    
    
        // Variables.
        ucAdvancedSearch = {};
        var isAddressValid = false;
        var isCityValid = false;
        var isStateValid = false;
        var isAOState = false;
        var isPWQState = false;
        var isZipCodeValid = false;

        // Error Message Constants
        var INVALID_ZIP_CODE_MESSAGE = "A valid Zip Code is required.";
        var NON_AO_ZIP_CODE_MESSAGE = "Auto-Owners does not operate in the state of the Zip Code provided. Please try entering a different Zip Code.";
        var NON_PWQ_ZIP_CODE_MESSAGE = "Quoting is not available for the Zip Code provided. Please click <a href='http://agency.auto-owners.com/?adv=true'>here</a> to find an agent.";
        var ZIP_CODE_VALIDATION_ERROR = "An error has occurred validating the Zip Code provided. Please try again later.";
        var ADDRESS_VALIDATION_ERROR = "An error has occurred validating the Address provided. Please try again later.";
        var INVALID_STATE_MESSAGE = "Auto-Owners does not operate in the State selected. Please try selecting a different State.";
        var INVALID_PWQ_STATE_MESSAGE = "Quoting is not available for the State selected. Please click <a href='http://agency.auto-owners.com/?adv=true'>here</a> to find an agent.";
        var INVALID_STATE_ZIP_CODE_MESSAGE = "Auto-Owners does not operate in the state of the Address provided. Please try selecting a different State.";
        var INVALID_PWQ_STATE_ZIP_CODE_MESSAGE = "Quoting is not available in the state of the Address provided. Please click <a href='http://agency.auto-owners.com/?adv=true'>here</a> to find an agent.";
        var ADDRESS_REQUIRED_MESSAGE = "Address is required.";
        var CITY_REQUIRED_MESSAGE = "City is required.";
        var STATE_REQUIRED_MESSAGE = "State is required.";
        var ZIP_CODE_REQUIRED_MESSAGE = "Zip Code is required.";
        
        
        // Attach Watermarks to input fields.
        $.Artemis.InputMask.Watermark($("input[id$='txtZipCodeOnly']"), { 
            initialValue: "enter a zip code",
            setInitialValue: false
        });
        $.Artemis.InputMask.Watermark($("input[id$='txtAddress']"), { 
            initialValue: "enter an address",
            setInitialValue: false
        });
        $.Artemis.InputMask.Watermark($("input[id$='txtCity']"), { 
            initialValue: "enter a city",
            setInitialValue: false
        });
        $.Artemis.InputMask.Watermark($("input[id$='txtZipCode']"), { 
            initialValue: "enter a zip code",
            setInitialValue: false
        });
        
        
        // Keydown event handler for the zip code search input.
        $("input[id$='txtZipCodeOnly']").keydown(function(event) {
            if (event.which == 13) 
            {
                event.preventDefault();
                event.stopPropagation();
                $("input[id$='btnZipSearch']").click();
            }
        }).blur();


        //Click event handler for the zip code search input.
        $("input[id$='txtZipCodeOnly']").mouseup(function(event) {
            if ($("a.more_options").hasClass("arrow_down")) {
                ucAdvancedSearch.hideSearchOptions();
            }
        });

        
        // Click event handler for the zip code search button.
        $("input[id$='btnZipSearch']").click(function(event) {
            event.preventDefault();
            event.stopPropagation();
            if ($("a.more_options").hasClass("arrow_down")) {
                ucAdvancedSearch.hideSearchOptions();
            }
            ucAdvancedSearch.DoZipCodeSearch();
        });
        

        // Keydown event handler for the address search fields.
        $("input[id$='txtZipCode'],input[id$='txtCity'],input[id$='txtAddress']").keydown(function(event) {
            if (event.which == 13)
            {
                event.preventDefault();
                event.stopPropagation();
                $("input[id$='btnAddressSearch']").click();
            }
        }).blur();


        // Click event handler for the address search button.
        $("input[id$='btnAddressSearch']").click(function(event) {
            event.preventDefault();
            event.stopPropagation();
            ucAdvancedSearch.DoAddressSearch();
        });
        
        
        // Click event handler for the more options (show address search) button.
        $("a.more_options").click(function(event) {
            event.preventDefault();
            
            var self = $(this);
            
            if (self.hasClass("arrow_right"))
            {                
                ucAdvancedSearch.showSearchOptions();
            }
            else if (self.hasClass("arrow_down"))
            {
                ucAdvancedSearch.hideSearchOptions();

            }
        });
        
        
        // Click event handler for the cancel button.
        $("a.cancel").click(function(event) {
            event.preventDefault();
            ucAdvancedSearch.hideSearchOptions();
        });
        
        
        
        // Shows the search options (address search).
        ucAdvancedSearch.showSearchOptions = function() {
            ucAdvancedSearch.clearErrorMessages();
            $(".search_options").slideDown("medium");
            $("a.more_options").removeClass("arrow_right").addClass("arrow_down");
        };
        
        
        // Hides the search options (advanced search).
        ucAdvancedSearch.hideSearchOptions = function() {
            ucAdvancedSearch.clearErrorMessages();
            $(".search_options").slideUp("medium");
            $("a.more_options").removeClass("arrow_down").addClass("arrow_right");
        };


        // Performs a zip code search.
        ucAdvancedSearch.DoZipCodeSearch = function() {
            ucAdvancedSearch.clearErrorMessages();
            ucAdvancedSearch.isZipCodeValid($("input[id$='txtZipCodeOnly']"), ZIP_CODE_VALIDATION_ERROR, function() {
                if (isZipCodeValid) {
                    $("#__EVENTTARGET").val("ctl00$Content$ctl00$btnZipSearch");
                    $("#aspnetForm").submit();
                } else {
                    $("div[id$='errorBanner']").css('display', 'block');
                    $("legend[id$='zipSearchLegend']").addClass("error_text");

                }
            });
        };


        // Performs an address search.
        ucAdvancedSearch.DoAddressSearch = function() {
            ucAdvancedSearch.clearErrorMessages();
            ucAdvancedSearch.isAddressSearchAddressValid(function() {
                if (isAddressValid && isCityValid && isStateValid && isZipCodeValid) {
                    $("#__EVENTTARGET").val("ctl00$Content$ctl00$btnAddressSearch");
                    $("#aspnetForm").submit();
                } else {
                    $("div[id$='errorBanner']").css('display', 'block');
                    $("legend[id$='addressSearchLegend']").addClass("error_text");
                }
            });
        };


        // Determines if the search performed is a quote search.
        ucAdvancedSearch.isQuoteSearch = function() {
            if (window.location.href.indexOf("QuoteSearch.aspx") != -1) {
                return true;
            } else {
                return false;
            }
        };


        // Validates a search address (street address).
        ucAdvancedSearch.isAddressSearchAddressValid = function(callback) {
            if ($("input[id$='txtAddress']").val() == null || $("input[id$='txtAddress']").val() == "" || $("input[id$='txtAddress']").val() == "enter an address") {
                $("input[id$='txtAddress']").parent().addClass("error_image");
                ucAdvancedSearch.addErrorMessage(ADDRESS_REQUIRED_MESSAGE);
                isAddressValid = false;
                ucAdvancedSearch.isAddressSearchCityValid(callback);
            } else {
                isAddressValid = true;
                ucAdvancedSearch.isAddressSearchCityValid(callback);
            }
        };


        // Validates a search city.
        ucAdvancedSearch.isAddressSearchCityValid = function(callback) {
            if ($("input[id$='txtCity']").val() == null || $("input[id$='txtCity']").val() == "" || $("input[id$='txtCity']").val() == "enter a city") {
                $("input[id$='txtCity']").parent().addClass("error_image");
                ucAdvancedSearch.addErrorMessage(CITY_REQUIRED_MESSAGE);
                isCityValid = false;
                ucAdvancedSearch.isAddressSearchStateValid(callback);
            } else {
                isCityValid = true;
                ucAdvancedSearch.isAddressSearchStateValid(callback);
            }
        };


        // Validates a search state for both agency and PWQ searches.
        ucAdvancedSearch.isAddressSearchStateValid = function(callback) {
            if ($("select[id$='ddlState']").val() == "-1") {
                $("select[id$='ddlState']").parent().addClass("error_image");
                ucAdvancedSearch.addErrorMessage(STATE_REQUIRED_MESSAGE);
                isStateValid = false;
                ucAdvancedSearch.isZipCodeValid($("input[id$='txtZipCode']"), ADDRESS_VALIDATION_ERROR, callback);
            } else {
                obj.invoke("IsStateActive", {
                    params: [$("select[id$='ddlState']").val()],
                    onSuccess: function(result) {
                        if (result.Result === true) {
                            if (!ucAdvancedSearch.isQuoteSearch()) {
                                isStateValid = true;
                                isAOState = true;
                                ucAdvancedSearch.isZipCodeValid($("input[id$='txtZipCode']"), ADDRESS_VALIDATION_ERROR, callback);
                            } else {
                                obj.invoke("IsStateOptedIn", {
                                    params: [$("select[id$='ddlState']").val()],
                                    onSuccess: function(result) {
                                        if (result.Result === true) {
                                            isStateValid = true;
                                            isAOState = true;
                                            isPWQState = true;
                                            ucAdvancedSearch.isZipCodeValid($("input[id$='txtZipCode']"), ADDRESS_VALIDATION_ERROR, callback);
                                        } else {
                                            $("select[id$='ddlState']").parent().addClass("error_image");
                                            ucAdvancedSearch.addErrorMessage(INVALID_PWQ_STATE_MESSAGE);
                                            isStateValid = false;
                                            isAOState = true;
                                            isPWQState = false;
                                            ucAdvancedSearch.isZipCodeValid($("input[id$='txtZipCode']"), ADDRESS_VALIDATION_ERROR, callback);
                                        }
                                    }, onFailure: function(result) {
                                        ucAdvancedSearch.addErrorMessage(ADDRESS_VALIDATION_ERROR);
                                        isStateValid = false;
                                        isAOState = false;
                                        isPWQState = false;
                                        ucAdvancedSearch.isZipCodeValid($("input[id$='txtZipCode']"), ADDRESS_VALIDATION_ERROR, callback);
                                    }
                                });
                            }
                        } else {
                            $("select[id$='ddlState']").parent().addClass("error_image");
                            ucAdvancedSearch.addErrorMessage(INVALID_STATE_MESSAGE);
                            isStateValid = false;
                            isAOState = false;
                            isPWQState = false;
                            ucAdvancedSearch.isZipCodeValid($("input[id$='txtZipCode']"), ADDRESS_VALIDATION_ERROR, callback);
                        }
                    }, onFailure: function(result) {
                        ucAdvancedSearch.addErrorMessage(ADDRESS_VALIDATION_ERROR);
                        isStateValid = false;
                        isAOState = false;
                        isPWQState = false;
                        ucAdvancedSearch.isZipCodeValid($("input[id$='txtZipCode']"), ADDRESS_VALIDATION_ERROR, callback);
                    }
                });
            }
        };


        // Validates a zip code for agency and quote searches.
        ucAdvancedSearch.isZipCodeValid = function(input, errorMessage, callback) {
            if (input.val() == null || input.val() == "" || input.val() == "enter a zip code") {
                input.parent().addClass("error_image");
                ucAdvancedSearch.addErrorMessage(ZIP_CODE_REQUIRED_MESSAGE);
                isZipCodeValid = false;
                callback(isZipCodeValid);
            } else {
                obj.invoke("IsZipCodeValid", {
                    params: [input.val()],
                    onSuccess: function(result) {
                        if (result.Result === true) {
                            obj.invoke("IsZipCodeInAutoOwnersState", {
                                params: [input.val()],
                                onSuccess: function(result) {
                                    if (result.Result === true) {
                                        if (!ucAdvancedSearch.isQuoteSearch()) {
                                            isZipCodeValid = true;
                                            callback(isZipCodeValid);
                                        } else {
                                            obj.invoke("IsZipCodeInPublicQuotingState", {
                                                params: [input.val()],
                                                onSuccess: function(result) {
                                                    if (result.Result === true) {
                                                        isZipCodeValid = true;
                                                        callback(isZipCodeValid);
                                                    } else {
                                                        input.parent().addClass("error_image");
                                                        if ($("a.more_options").hasClass("arrow_down")) {
                                                            if (isAOState && !isPWQState) {
                                                                ucAdvancedSearch.removeLastErrorMessage();
                                                                ucAdvancedSearch.addErrorMessage(INVALID_PWQ_STATE_ZIP_CODE_MESSAGE);
                                                            } else {
                                                                ucAdvancedSearch.addErrorMessage(NON_PWQ_ZIP_CODE_MESSAGE);
                                                            }
                                                        } else {
                                                            ucAdvancedSearch.addErrorMessage(NON_PWQ_ZIP_CODE_MESSAGE);
                                                        }
                                                        isZipCodeValid = false;
                                                        callback(isZipCodeValid);
                                                    }
                                                }, onFailure: function(result) {
                                                    ucAdvancedSearch.addErrorMessage(errorMessage);
                                                    isZipCodeValid = false;
                                                    callback(isZipCodeValid);
                                                }
                                            });
                                        }
                                    } else {
                                        input.parent().addClass("error_image");
                                        if ($("a.more_options").hasClass("arrow_down")) {
                                            if (isAOState) {
                                                ucAdvancedSearch.addErrorMessage(NON_AO_ZIP_CODE_MESSAGE);
                                            } else {
                                                ucAdvancedSearch.removeLastErrorMessage();
                                                ucAdvancedSearch.addErrorMessage(INVALID_STATE_ZIP_CODE_MESSAGE);
                                            }
                                        } else {
                                            ucAdvancedSearch.addErrorMessage(NON_AO_ZIP_CODE_MESSAGE);
                                        }
                                        isZipCodeValid = false;
                                        callback(isZipCodeValid);
                                    }
                                }, onFailure: function(result) {
                                    ucAdvancedSearch.addErrorMessage(errorMessage);
                                    isZipCodeValid = false;
                                    callback(isZipCodeValid);
                                }
                            });
                        } else {
                            input.parent().addClass("error_image");
                            ucAdvancedSearch.addErrorMessage(INVALID_ZIP_CODE_MESSAGE);
                            isZipCodeValid = false;
                            callback(isZipCodeValid);
                        }
                    }, onFailure: function(result) {
                        ucAdvancedSearch.addErrorMessage(errorMessage);
                        isZipCodeValid = false;
                        callback(isZipCodeValid);
                    }
                });
            }
        };


        // Removes all error messages from the error banner, hides the banner, and hides all error icons.
        ucAdvancedSearch.clearErrorMessages = function() {
            $("div[id$='errorBanner']").hide();
            $(".error_list").html("");
            $(".error_image").removeClass("error_image");
            $("legend[id$='zipSearchLegend']").removeClass("error_text");
            $("legend[id$='addressSearchLegend']").removeClass("error_text");
        };


        // Adds an error message to the error banner near the top of the page.
        ucAdvancedSearch.addErrorMessage = function(message) {
            var messageHTML = "<li class='error_message_list_item'>" + message + "</li>";
            $(messageHTML).appendTo($(".error_list"));
        };


        // Removes an error message from the error banner near the top of the page.
        ucAdvancedSearch.removeLastErrorMessage = function() {
            $(".error_message_list_item").last().remove();
        };
    };
})(jQuery.noConflict());
