/* Minification failed. Returning unminified contents.
(1059,28-29): run-time error JS1014: Invalid character: `
(1059,32-33): run-time error JS1004: Expected ';': {
(1059,44-45): run-time error JS1004: Expected ';': {
(1059,53-54): run-time error JS1014: Invalid character: `
(1061,17-21): run-time error JS1034: Unmatched 'else'; no 'if' defined: else
 */
//create namespace for the application.  Can change to be specific
var WSLApp = WSL.EnsureNamespace('WSL.App');

;
/// <reference path="../_references.js" />
WSLApp.ResponsiveElements = (function () {
    var mobileSearch;
    var navPanel;

    var init = function () {
        //initialize default values  (selector cache)
        mobileSearch = $('#divMobileSearch');
        navPanel = $('#navPanel');
    };

    var appendNavigation = function (controlId) {
        $('#navigationList').appendTo(controlId);
    };

    var displayMobileSearch = function (show) {
        if (mobileSearch) {
            if (show) {
                navPanel.panel("open");
            }
            else {
                navPanel.panel("close");
            }
        }
    };

    var displayNavPanel = function (show) {
        if (navPanel) {
            if (show) {
                mobileSearch.show();
            }
            else {
                mobileSearch.hide();
            }
        }
    };
                  
    return {
        init: init,
        appendNavigation: appendNavigation,
        displayMobileSearch: displayMobileSearch,
        displayNavPanel: displayNavPanel
    };
})();
;
/// <reference path="../_references.js" />

//the value of these (i.e. small, medium, large) should match what is set in css
WSLApp.MediaQueryBreakPoints = {
    "xsmall": 1, //mobile first, no breakpoint
    "small": 2, //phone in landscape
    "medium": 3, //tablet portrait
    "large": 4, //larger tablet landscape and desktop
    "xlarge": 5  //larger desktop
};

WSLApp.JSMediaQueries = (function () {
    var resizeThrottleTime = 250; //only responsd to the resize event every quarter second
    var resizeTimeoutId; //keep track of timeOutId
    //used to track if processMediaQuery shoudl be re-run
    var lastMediaQuery = "small";
    var lastPage = "";
    //variables used for caching selectors
    var externalContentControl = '';
    var externalContentHeaderId = '';
    var externalContentNavId = '';
    var externalContentFooterId = '';    
    var pageHeader;
    var navigation;
    var footer;

    var init = function () {
        //initialize default values  
        externalContentControl = $('#headerNavigationFooter');
        externalContentHeader = externalContentControl.find('#headerElements');
        externalContentNav = externalContentControl.find('#navigationLinks');
        externalContentFooter = externalContentControl.find('#footer');

        //initialize all selectors
        pageHeader = $('#headerElements');
        navigation = $('#navPanel');
        footer = $('#footer');

        //load header/footer/nav
        externalContentHeader.appendTo(pageHeader);
        externalContentNav.appendTo(navigation);
        externalContentFooter.appendTo(footer);
        //initialize responsive elements
        WSLApp.ResponsiveElements.init();
    };

    var onResize = function () {
        //throttle resize calls (so page doesn't flicker and for performance)	        
        clearTimeout(resizeTimeoutId);
        resizeTimeoutId = setTimeout(apply, resizeThrottleTime);
    };   

    var getMediaQuery = function () {
        //get the value set in css content to determine what media query was applied.
        //http://seesparkbox.com/foundry/breakpoint_checking_in_javascript_with_css_user_values
        var breakpoint = window.getComputedStyle(document.getElementById("mediaquery"), ":after").getPropertyValue("content");
        //if content wasn't set, look at font family.  This is just a work around for IE8 that we can remove later
        if (breakpoint == null) {
            breakpoint = window.getComputedStyle(document.getElementById("mediaquery"), "").getPropertyValue("font-family");
        }
        // fix for firefox, remove double quotes
        breakpoint = breakpoint.replace(/"/g, '');
        return breakpoint;
    };

    var apply = function (page) {
        WSL.Logger.log("window.screen.width=" + window.screen.width);        
        WSL.Logger.log("lastMediaQuery=" + lastMediaQuery);
        WSL.Logger.log("lastPage=" + lastPage);
        WSL.Logger.log("currentPage=" + page);

        var currentMediaQuery = getMediaQuery();
        // if the document width or the current page has changed : fire the media queries
        // this was put in to keep the nexus from resizing when the keyboard came up.
        if (currentMediaQuery != lastMediaQuery || lastPage != page) {
            lastMediaQuery = currentMediaQuery;            
            processMediaQuery(currentMediaQuery);
        }
        lastPage = page;
    };

    var processMediaQuery = function (breakpoint) {
        try {
            WSL.Logger.log("breakpoint=" + breakpoint);
            WSL.Logger.log("WSLApp.MediaQueryBreakPoints[breakpoint]=" + WSLApp.MediaQueryBreakPoints[breakpoint]);
            //mobile first, default values
            var navigationId = '#navPanel';

            ////xSMALL BREAKPOINT (aka mobile first, no breakpoint)////        
            if (WSLApp.MediaQueryBreakPoints[breakpoint] >= WSLApp.MediaQueryBreakPoints.xsmall) {
            }

            ////SMALL BREAKPOINT////       
            if (WSLApp.MediaQueryBreakPoints[breakpoint] >= WSLApp.MediaQueryBreakPoints.small) {

            }

            ////MEDIUM BREAKPOINT////
            if (WSLApp.MediaQueryBreakPoints[breakpoint] >= WSLApp.MediaQueryBreakPoints.medium) {

            }

            ////THIRD BREAKPOINT////
            if (WSLApp.MediaQueryBreakPoints[breakpoint] >= WSLApp.MediaQueryBreakPoints.large) {
                //load desktop header 
                //hide the mobile search
                WSLApp.ResponsiveElements.displayMobileSearch(false);
                //close the navPanel if it's open
                WSLApp.ResponsiveElements.displayNavPanel(false);
                navigationId = '#desktopNavigation';
            }

            ////FOURTH BREAKPOINT////
            if (WSLApp.MediaQueryBreakPoints[breakpoint] >= WSLApp.MediaQueryBreakPoints.xlarge) {
                //nothing
            }

            WSLApp.ResponsiveElements.appendNavigation(navigationId);
        }
        catch (e) {
            WSL.Logger.log("Error in processMediaQuery=" + e.message);
        }
    };
       
    return {
        init: init,
        onResize: onResize,        
        apply: apply
    };
}());

//trigger js media queries on window resize
if (window.addEventListener) {
    window.addEventListener("resize", WSLApp.JSMediaQueries.onResize);
}
else if (window.attachEvent) {
    window.attachEvent("onresize", WSLApp.JSMediaQueries.onResize);
}

//feature testing.  if window.computedStyle does not exist, add a work around. I have only found this to be the case in IE8.
//found here http://snipplr.com/view/13523/
if (!window.getComputedStyle) {
    window.getComputedStyle = function (el, pseudo) {
        this.el = el;
        this.getPropertyValue = function (prop) {
            var re = /(\-([a-z]){1})/g;
            if (prop == 'float') prop = 'styleFloat';
            if (re.test(prop)) {
                prop = prop.replace(re, function () {
                    return arguments[2].toUpperCase();
                });
            }
            return el.currentStyle[prop] ? el.currentStyle[prop] : null;
        }
        return this;
    }
};
/// <reference path="../_references.js" />
WSLApp.Search = (function () {

    var init = function () {
        if (!WSL.Logger) {
            throw "WSLApp.Search requires WSL.Logger";
        }
        if (!SubmitWebsiteSearch) {
            throw "WSLApp.Search requires WSL.Utilities SubmitWebsiteSearch";
        }
    }()

    var initializeContainer = function (searchLinkId, searchDivId) {
        $(searchLinkId).click(function () {
            $(searchDivId).slideToggle("fast");
        });
    }

    var initializeControls = function (searchInputBoxId, searchButtonId) {
        //hook up enter key to submit search 
        $(searchInputBoxId).bind("keyup", function (e) {
            if (e.which && e.which == 13 || e.keyCode && e.keyCode == 13) {
                $(searchButtonId).click();
            }
        });
        //submit search when clicking the search button
        $(searchButtonId).click(function () {
            //SubmitWebsiteSearch function lives in the framework Utilities file.
            SubmitWebsiteSearch($(searchInputBoxId).val());
        });
    }

    return {
        initializeControls: initializeControls,
        initializeContainer: initializeContainer
    }

})();

var WSLeComments = WSL.EnsureNamespace('WSL.eComments');

WSLeComments.Constants = (function () {
    return {
        CCRadioHide: "CCRadioHide"
    };
}());

WSLeComments.TextArea = function () {
    var disableSubmit = function () {
        var submitButton = $('#FormSubmitButton')[0];
        var submitDiv = $('.ui-input-btn');
        submitDiv.addClass('disabled');
        submitButton.disabled = true;
    }
    var updateOutput = function (textArea, outputContainer, charactersAllowed) {
        var left = charactersAllowed - $(textArea).val().length;
        if (left < 0) {
            left = 0;
            disableSubmit();
        } else {
            WSLeComments.Form.enableSubmit();
        }
        $(outputContainer).text(left);
    };
    var charactersRemaining = function (textArea, outputContainer, charactersAllowed) {

        $(textArea).on('input', function (e) {
            $(textArea).val($(textArea).val().replace(/([\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2694-\u2697]|\uD83E[\uDD10-\uDD5D])/g, ''));
            updateOutput(textArea, outputContainer, charactersAllowed);
        });
        //$(textArea).keyup(function () {
        //    alert("key up");
        //    // Remove any emoji characters
        //    $(textArea).val($(textArea).val().replace(/([\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2694-\u2697]|\uD83E[\uDD10-\uDD5D])/g, ''));
        //    updateOutput(textArea, outputContainer, charactersAllowed);
        //});

        //update output once on load - in case there is already data in the textbox
        updateOutput(textArea, outputContainer, charactersAllowed);
    };
    return {
        charactersRemaining: charactersRemaining
    };
}();



WSLeComments.BillLookUp = function () {
    var billNumberFromTextBox = function () {
        var billNumber = $("#BillNumber").val();
        return billNumber;
    };
    return {
        billNumberFromTextBox: billNumberFromTextBox
    };
}();

WSLApp.Analytics = function () {
    var trackGoogleUIEvent = function (category, action) {
        ga('send', 'event', category, action, shortBillId, {
            'hitCallback':
            function () {
                shortBillId = $('#shortBillId').text();
            }
        });
    }
    return {
        trackGoogleUIEvent: trackGoogleUIEvent
    }
}();

WSLeComments.Form = function () {

    var submit = function (event) {

        WSLApp.Analytics.trackGoogleUIEvent('ButtonClick', 'BillCommentFormSubmit');

        var submitButton = $("#FormSubmitButton");
        submitButton.prop("disabled", "disabled").val("Sending...").button("refresh");

        var form = submitButton.closest("form");
        form.submit();

    };
   
    var enableSubmit = function () {
        var submitButton = $("#FormSubmitButton");
        if (!WSLeComments.TextArea.charactersRemaining <= 0) {
            var submitDiv = $('.ui-input-btn');
            submitDiv.removeClass('disabled');
            submitButton.removeProp("disabled").val("Send Comment").button("refresh");
        }
    };

    return {
        submit: submit,
        enableSubmit: enableSubmit
    };

}();

;
/// <reference path="../_references.js" />
WSLeComments.ValidateDistrict = function () {
    //function which is called if the ajax call succeeds/returns
    var populateValidatedResults = function (data) {
        $("#HiddenDistrict").val(data.District); //set the district that is returned to account for district 0
        //set the address IsValidated hidden field
        $("#HiddenAddressIsValidated").val(true);
        //run the Address Is Validated validation - to clear any possible messages
        $("#HiddenAddressIsValidated").valid();
        WSLeComments.ClientActions.clearValidationBorders();
        WSL.Logger.log("HiddenDistrict value: " + data.District);
        WSLeComments.ClientActions.showOrHideResponseRequested(data.District);
        var primaryResponseMemberDistrict = $("#PrimaryResponseMember_District").val();
        WSL.Logger.log("PrimaryResponseMemberDistrict: " + primaryResponseMemberDistrict);
        //remove any previous validation classes
        $("#DistrictLabel").removeClass("notFoundAddressColor");
        $("#mayContinueMessage").removeClass("notFoundAddressColor");
        $("#mayContinueMessage").removeClass("validationred");
        $("#mayContinueMessageContainer").hide(); //hide the may continue message, we don't know if we need it yet

        //first make sure the validation was successful
        if (!data.District || data.District == 0) {
            data.District = 0;
            populateValidationFailElements(primaryResponseMemberDistrict, data);
        }
        else {
            populateValidationSucceedsElements(primaryResponseMemberDistrict, data);
        }
        $("#ValidateAddressButton").removeClass("ui-btn-active"); // remove the pressed button styling
    };

    var populateValidationFailElements = function (primaryResponseMemberDistrict, data) {
        WSL.Logger.log("Validation fails");
        $("#DistrictLabel").html(data.UnableToValidateMessage).addClass("notFoundAddressColor");
        $("#mayContinueMessageContainer").show();
        if (primaryResponseMemberDistrict == null || primaryResponseMemberDistrict == "") {
            //this is on the bill comment page
            $('[type="submit"]').button('disable').button("refresh");
            $("#MemberRoutingSection").empty();            
            $("#mayContinueMessage").html("Comments may only be sent from a verified address.").addClass("notFoundAddressColor");
        } else if (primaryResponseMemberDistrict >= 0) {
            //this is on the member email page
            //hide the secondary members control
            WSLeComments.ClientActions.showOrHideSecondaryMembers();
            if (data.State != "WA") {                
                $("#mayContinueMessage").html("A valid Washington state address is required to send a message to legislators.").addClass("validationred");
                $('[type="submit"]').button('disable').button("refresh");
            } else {
                //set the hide cc session variable, users cannot CC other members if they are not in district
                ClientStorage.set(WSLeComments.Constants.CCRadioHide, "Hide"); 
                //user is not in selected district
                populateOutOfDistrictView(data.District, primaryResponseMemberDistrict, $("#PrimaryResponseMember_Position").val());
                //$("#mayContinueMessage").html("Even if your address is not verified, you may still send a message to this legislator.").addClass("notFoundAddressColor");
                // enable the submit button
                $('[type="submit"]').button('enable').button("refresh");
            }

        }
    };

    var populateValidationSucceedsElements = function (primaryResponseMemberDistrict, data) {
        WSL.Logger.log("Validation succeeds");
        // enable the submit button
        $('[type="submit"]').button('enable').button("refresh");
        //clear any cc radio values in session
        ClientStorage.set(WSLeComments.Constants.CCRadioHide, "CCRadioHide");
        $("#Address_Street").val(data.Street);
        $("#Address_City").val(data.City);
        $("#Address_State").val(data.State);
        $("#Address_Zip").val(data.Zip);
        //if we are on the bill comment page we stop here
        if (primaryResponseMemberDistrict == null || primaryResponseMemberDistrict == "") {
            $('[type="submit"]').button('enable').button("refresh");
            $("#DistrictLabel").html("The address entered is in <strong>District " + data.District + "</strong>"); // just display their district

            //we need to display all district members along with response requested option            
            WSLeComments.ClientActions.populateMemberRouting();

            //if the district member checkboxes have been populated, update them
            //if($("#MemberResponse").css("display") == "block")
            //{
            //    WSL.Logger.log("Member response checkboxes have been populated");
            //    WSLeComments.ClientActions.populateMemberResponse();
            //}
        }
            //if we are on the member email page, we have some more work to do, 
        else {
            //if the secondary response members has already been set to true, show it
            WSLeComments.ClientActions.showOrHideSecondaryMembers($('#SecondaryResponseRequested_True').is(':checked'));
                       // now we need to check and see if the validated district matches the specified district
            var isUserInSelectedDistrict = compareToSelectedDistrict(data.District);
            WSL.Logger.log("isUserInSelectedDistrict: " + isUserInSelectedDistrict);
            if (isUserInSelectedDistrict == true) {
                $("#DistrictLabel").html("The address entered is in <strong>District " + data.District + "</strong>"); // just display their district
            } else {
                //set the hide cc session variable, users cannot CC other members if they are not in district
                ClientStorage.set(WSLeComments.Constants.CCRadioHide, "Hide"); 
                //user is not in selected district
                populateOutOfDistrictView(data.District, primaryResponseMemberDistrict, $("#PrimaryResponseMember_Position").val());
                //show links to their district legislators
                populateAlternativeMemberView(data.District);
            }

        }

    };

    var populateOutOfDistrictView = function (validatedDistrict, memberDistrict, memberPosition) {
        WSL.Logger.log("User is out of district, get new view to give them some options.");
        $.ajax(
        {
            url: WSLeComments.Url.resolve("~/" + "OutOfDistrict" + "/" + validatedDistrict + "/" + memberDistrict + "/" + memberPosition),
            data: {},
            datatype: "json",
            traditional: true,
            async: true,
            success: function (data) {
                $("#DistrictLabel").html(data).enhanceWithin();
            },
            error: function (data, status, xhr) {
                onError(data);
            },

        });
    };

    var populateAlternativeMemberView = function (validatedDistrict) {
        WSL.Logger.log("show user their district legislators.");
        $.ajax(
        {
            url: WSLeComments.Url.resolve("~/" + "DistrictMembers" + "/" + validatedDistrict),
            data: {},
            datatype: "json",
            traditional: true,
            async: true,
            success: function (data) {
                $("#DistrictLegislators").html(data).enhanceWithin();
            },
            error: function (data, status, xhr) {
                onError(data);
            },

        });
    };

    var compareToSelectedDistrict = function (validatedDistrict) {
        WSL.Logger.log("validatedDistrict " + validatedDistrict);
        //hidden input field that has the selected member's district
        var primaryResponseMemberDistrict = $("#PrimaryResponseMember_District").val();
        WSL.Logger.log("primaryResponseMemberDistrict " + primaryResponseMemberDistrict);
        if (validatedDistrict == primaryResponseMemberDistrict) {
            return true;
        } else {
            return false;
        }
    };

    var addressIsValid = function () {
        //validate every address field even if the first one 
        //fails - that way the user sees all the validations
        var addressIsValid = true;
        if (!$("#Address_Street").valid()) {
            addressIsValid = false;
        }
        if (!$("#Address_City").valid()) {
            addressIsValid = false;
        }
        if (!$("#Address_State").valid()) {
            addressIsValid = false;
        }
        if (!$("#Address_Zip").valid()) {
            addressIsValid = false;
        }
        return addressIsValid;
    };
    //function which is called right before the ajax call
    var beginAddressValidation = function (control) {        
        if (!addressIsValid()) {
            WSL.Logger.log("address failed client validation...");
            //cancel the ajax call
            return false; 
        }
        $("#DistrictLegislators").html(""); //clear out the district legislator buttons
        $("#DistrictLabel").html(""); // clear the district radios
        $("#mayContinueMessage").html(""); //clear the may continue message
        $(control).html("Validating...");
    };
    //function which is called if the ajax call errors out
    var showErrorMessage = function (control) {
        //if we cancel the ajax call due to client validation failing
        //then the error function is still called
        //check that this isn't the case before we response as if the server
        //didn't find the address.
        WSL.Logger.log("Ajax call failed.");
        WSL.Logger.log("addressIsValid value: " + addressIsValid);
        if (addressIsValid()) {
            $(control).html("There was an error communicating with the server, please check your entry and try again.");
        }
    };
    //public api
    return {
        addressIsValid : addressIsValid,
        populateValidatedResults: populateValidatedResults,
        beginAddressValidation: beginAddressValidation,
        showErrorMessage: showErrorMessage
    };
}();
;
/// <reference path="../_references.js" />
WSLeComments.ClientActions = function () {

    //for ie8 and earlier...
    if (!String.prototype.trim) {
        String.prototype.trim = function () {
            return this.replace(/^\s+|\s+$/g, '');
        }
    }

    var call302errorRoute = function (street, city, state, zip) {
        //assemble the url to call with the parameters passed in
        var customRoute = WSLeComments.Url.resolve("~/" + "custom302route"
            + "/" + street
            + "/" + city
            + "/" + state
            + "/" + zip);
        //call the custom route to write the values to the IIS log
        $.ajax(customRoute, {
            type: 'GET',
            async: true
        });
    };

    var showLoadingMessage = function (divToPopulate) {
        $(divToPopulate).html("Loading...");
    };


    var validateBillNumberSuccess = function () {
        $("#EditBillButton").removeClass("ui-btn-active"); // remove the pressed button styling
        $("#dynamicPosition").html("<span class='validationred'>*</span>"); //change the position label to an asterisk
    };

    var validateBillNumberFail = function () {
        $("#EditBillButton").removeClass("ui-btn-active"); // remove the pressed button styling
        $("#BriefDescription").html("There was an error communicating with the server, please check your entry and try again.");

    };

    var formatUserInput = function (entry) {
        if (!entry || entry.length == 0) {
            return entry;
        }

        entry = encodeURIComponent(entry.trim());

        WSL.Logger.log("Formatting complete, output: '" + entry + "'");
        return entry;
    };

    var setSelectedConstituentValue = function (value, id) {
        WSL.Logger.log("IsConstituent radio changed, setting value - " + value + " and Id - " + id);
        $("#HiddenIsPossibleConstituent").val(id);
    };

    var formValidationPainter = function (validator) {
        var errors = validator.numberOfInvalids();
        var message = errors + " validation errors.";
        WSL.Logger.log(message);
        for (var x = 0; x < validator.errorList.length; x++) {
            var id = validator.errorList[x].element.id;
            var $element = $("#" + id);
            if ($element.is(":visible")) {
                $element.parent().addClass("generalValidationBorder");
            }
        }
    };

    var clearValidationBorders = function () {
        //setting a timeout here to push this execution to the last in line so that the previous validation functions can execute
        setTimeout(function () {

            $.each($('.generalValidationBorder').children('input'), function (index, value) {
                var $value = $(value);
                if ($value.valid()) {
                    $value.parent('.generalValidationBorder').removeClass('generalValidationBorder');
                }
            });
        }, 10);
    };

    var populateMemberRouting = function () {

        WSL.Logger.log("Member Routing YES- fire ajax call");
        var district = $('#HiddenDistrict').val();
        $("#FormSubmitButton").prop('disabled', true);
        WSL.Logger.log("District: " + district);
        $.ajax(
        {
            url: WSLeComments.Url.resolve("~/" + "MemberRouting" + "/" + district),
            data: {},
            datatype: "json",
            traditional: true,
            async: true,
            success: function (data) {
                $("#MemberRoutingSection").html(data).enhanceWithin();
                $("#FormSubmitButton").prop('disabled', false);
            },
            error: function (data, status, xhr) {
                onError(data);
                $("#FormSubmitButton").prop('disabled', false);
            },
        });
    };

    var populateMemberResponse = function () {

        WSL.Logger.log("rr YES- fire ajax call");
        var district = $('#HiddenDistrict').val();
        $("#FormSubmitButton").prop('disabled', true);
        WSL.Logger.log("District: " + district);
        $.ajax(
        {
            url: WSLeComments.Url.resolve("~/" + "ResponseRequested" + "/" + district),
            data: {},
            datatype: "json",
            traditional: true,
            async: true,
            success: function (data) {
                $("#MemberResponse").html(data).enhanceWithin();
                $("#FormSubmitButton").prop('disabled', false);
            },
            error: function (data, status, xhr) {
                onError(data);
                $("#FormSubmitButton").prop('disabled', false);
            },

        });
    };

    var clearValidationBorder = function (element) {
        $(element).removeClass('generalValidationBorder');
    };

    var showOrHideResponseRequested = function (district) {
        WSL.Logger.log("inside showOrHideResponseRequested,District: " + district);
        if (district === null || district === "") {
            WSL.Logger.log("inside district is null or district is ''");
            //member email can still get a response from district 0 users
            //Would you like a response from PrimaryResponseMember? -- _MemberEmailResponse
            $('#ResponseRequested_EmailForm').hide();
        }
        else if (district == 0) {
            //if the district is 0, hide the bill comment response
            WSL.Logger.log("ResponseRequested district = 0, checking the false box for them")
            //Would you like a response from your legislators to your comment? - _BillCommentResponse
            $('#ResponseRequested').hide();
            //if they are district 0 - they still need to be able to submit a comment, so check the false on response requested even though the control is still hidden
            //$("#ResponseRequested_False").prop("checked", true).checkboxradio("refresh");
        }
        else {
            //Would you like a response from your legislators to your comment? - _BillCommentResponse
            $('#ResponseRequested').show();
            //$("#ResponseRequested_False").prop("checked", false).checkboxradio("refresh");
            //Would you like a response from PrimaryResponseMember? -- _MemberEmailResponse
            $('#ResponseRequested_EmailForm').show();
        }
    };
    var showOrHideSecondaryMembers = function(responseRequested) {
        if (responseRequested) {
            //Would you like to send a copy of your comments to the other legislators in District? - _MemberEmailResponse
            $('#MemberResponse_EmailForm').show();
            $('#MemberResponse').show();
        } else {
            //Would you like to send a copy of your comments to the other legislators in District? - _MemberEmailResponse
            $('#MemberResponse_EmailForm').hide();
            $('#MemberResponse').hide();
        }
    };

    var getInitiativeNumber = function (initiativeNumberInput) {
        try {
            return WslInitiativeParser.getLegislationNumber(initiativeNumberInput);
        }
        catch (error) {
            return 0;
        }
    };

    return {
        showLoadingMessage: showLoadingMessage,
        formValidationPainter: formValidationPainter,
        clearValidationBorders: clearValidationBorders,
        clearValidationBorder: clearValidationBorder,
        showOrHideResponseRequested: showOrHideResponseRequested,
        showOrHideSecondaryMembers: showOrHideSecondaryMembers,
        setSelectedConstituentValue: setSelectedConstituentValue,
        validateBillNumberSuccess: validateBillNumberSuccess,
        populateMemberResponse: populateMemberResponse,
        populateMemberRouting: populateMemberRouting,
        formatUserInput: formatUserInput,
        call302errorRoute: call302errorRoute,
        validateBillNumberFail: validateBillNumberFail,
        getInitiativeNumber: getInitiativeNumber
    };
}();
;
/// <reference path="../_references.js" />
$(document).on("mobileinit", function (event, data) {
    WSL.Logger.on();
    $.mobile.ajaxEnabled = false; //disable ajax caching of pages.

});

$(document).on("pagebeforeshow", "[data-role=page]", function (event, data) {
    //get the global header and side nav from the assets
    //WSLeComments.ExternalContent.loadExternalContent();
    //remove body class from page content, it is added further up the DOM
    $("#pageContent").removeClass("ui-body-a");
    //reset session variables
    ClientStorage.set(WSLeComments.Constants.CCRadioHide, "CCRadioHide");

    //initialize javascript media queries
    WSLApp.JSMediaQueries.init();
    WSLApp.JSMediaQueries.apply();

    //pass in the ids for the search boxes/buttons 
    WSLApp.Search.initializeControls('#bannerSearchInput', '#bannerSubmitSearchBtn');
    WSLApp.Search.initializeControls('#mobileSearchInput', '#mobileSubmitSearchBtn');
    WSLApp.Search.initializeContainer('#searchPanel', '#divMobileSearch');
});

$(document).on("pagecontainershow", function (event, data) {
    //check to make sure we are on either the bill or member email form before we execute the rest of this code
    if ($.contains(document.documentElement, $("#mainForm")[0])) {
        WSL.Logger.log("we are on a form page");
        //clear any previous validation fails
        WSLeComments.ClientActions.clearValidationBorders();
        var charactersAllowed = $("#Comment").attr("maxLength");
        //this listens for keypresses and updates the text field accordingly
        WSLeComments.TextArea.charactersRemaining("#Comment", "#charactersRemaining", charactersAllowed);

        $('.AddressField').on('paste keypress', function (e) {
            $("#HiddenAddressIsValidated").val(false);
            $("#DistrictLabel").empty();
            $("#HiddenDistrict").val('');
        });

        // Disable PhoneExtension field unless PhoneNumber or PhoneExtension field have a value.
        var checkPhoneExtDisabled = function () {
            var $phoneNum = $('input[id$=PhoneNumber]');
            var $phoneExt = $('input[id$=PhoneExtension]');

            return $phoneNum.val() === '' && $phoneExt.val() === '';
        };
        // Set the initial state of the PhoneExtension field.
        $('input[id$=PhoneExtension]').prop("disabled", checkPhoneExtDisabled());
        // Update the state of the PhoneExtension field after changes to PhoneNumber.
        $('input[id$=PhoneNumber]').on('paste keypress cut blur', function (e) {
            $('input[id$=PhoneExtension]').prop("disabled", checkPhoneExtDisabled());
        });

        //any any blur check for validation borders and remove them if appropriate
        $("input").blur(function () {
            WSLeComments.ClientActions.clearValidationBorders();
        });

        //tie into the jquery validate library event to paint fields on validation fail
        $('#mainForm').bind('invalid-form.validate', function (form, validator) {
            //paint the elements that failed validation
            WSLeComments.ClientActions.formValidationPainter(validator);
            WSLeComments.Form.enableSubmit();
        });
        //this section handles showing and hiding member response controls based on district info
        WSLeComments.ClientActions.showOrHideResponseRequested($('#HiddenDistrict').val());

        WSLeComments.ClientActions.showOrHideSecondaryMembers($('#ResponseRequested_True').is(':checked'));

        //hide the maycontinue message container until its needed
        $("#mayContinueMessageContainer").hide();
    }

  

});
$(document).on('click', ".alternateMember", function () {
    var $link = $(this);
    var url = $link.prop('href');
    $link.prop('href', url + '?' + $("input:visible,textarea:visible", "#mainForm").serialize());
});

$(document).on('click', "#PrintConfirmationButton", function () {
    window.print();
});

//force menu buttons to revert to inactive state
$(document).on('click', ".userInteractionButton", function () {
    $(this).removeClass("ui-btn-active");
});

$('.play_navigation').on('click', 'a', function (e) {
    console.log('this is the click');
    e.preventDefault();
});

$(document).on("click", '#EditBillButton', function () {
    WSL.Logger.log("EditBillButton clicked");

    if (!$("#BillNumber").valid()) {
        return false;
    }

    WSLeComments.ClientActions.showLoadingMessage($("#BriefDescription"));    

    var billNumber = WSLeComments.ClientActions.formatUserInput($("#BillNumber").val());
    var url = WSLeComments.Url.resolve("~/" + "GetBriefDescriptionForBill" + "/" + billNumber);
    WSL.Logger.log("find bill " + billNumber);
    
    $.ajax(url, {
        type: 'GET',
        datatype: "json",
        traditional: true,
        async: true    
}).fail(function () {
    WSLeComments.ClientActions.validateBillNumberFail();
})
  .success(function (data) {
      $("#BriefDescription").html(data);
      $("#IsInitiative").val(false);
      $("#InitiativeNumber").val("");
      WSLeComments.ClientActions.validateBillNumberSuccess();
  });
});

$(document).on("click", '#EditInitiativeButton', function () {
    WSL.Logger.log("EditInitiativeButton clicked");

    if (!$("#InitiativeNumber").valid()) {
        return false;
    }

    WSLeComments.ClientActions.showLoadingMessage($("#BriefDescription"));

    var initiativeNumberInput = WSLeComments.ClientActions.formatUserInput($("#InitiativeNumber").val());
    var initiativeNumber = WSLeComments.ClientActions.getInitiativeNumber(initiativeNumberInput);
    var url = WSLeComments.Url.resolve("~/" + "GetBriefDescriptionForInitiative" + "/" + initiativeNumber);
    WSL.Logger.log("find bill " + initiativeNumber);

    $.ajax(url, {
        type: 'GET',
        datatype: "json",
        traditional: true,
        async: true
    }).fail(function () {
        WSLeComments.ClientActions.validateBillNumberFail();
    }).success(function (data) {
        $("#BriefDescription").html(data);
        $("#IsInitiative").val(true);
        $("#BillNumber").val("");
        WSLeComments.ClientActions.validateBillNumberSuccess();
    });
});

$(document).on("click", '#ValidateAddressButton', function (event) {

    WSL.Logger.log("ValidateAddressButton clicked");
    
    if (!WSLeComments.ValidateDistrict.addressIsValid()) {
        WSL.Logger.log("address failed client validation...");
        //cancel the button click
        event.stopImmediatePropagation();
        event.preventDefault();
        return false;
    }
    $("#DistrictLegislators").html(""); //clear out the district legislator buttons
    $("#mayContinueMessage").html(""); //clear the may continue message
    $("#DistrictLabel").html("Validating...");
    


    var street = WSLeComments.ClientActions.formatUserInput($("#Address_Street").val());
    var city = WSLeComments.ClientActions.formatUserInput($("#Address_City").val());
    var state = WSLeComments.ClientActions.formatUserInput($("#Address_State").val());
    var zip = WSLeComments.ClientActions.formatUserInput($("#Address_Zip").val());

    if (!street || street.length === 0
       || !city || city.length === 0
       || !state || state.length === 0
       || !zip || zip.length === 0) {
        WSL.Logger.log("address failed client validation...");
        $("#DistrictLabel").html("Street, City, State and Zip are all required for address validation.");
        //cancel the button click
        event.stopImmediatePropagation();
        event.preventDefault();
        return false;
    }

    var url = WSLeComments.Url.resolve("~/" + "ValidateAddress"
        + "?street=" + street
        + "&city=" + city
        + "&state=" + state
        + "&zip=" + zip);
    WSL.Logger.log("validate address " + street + " " + city + " " + state + " " + zip);
    

    $.ajax(url, {
        type: 'GET',
        datatype: "json",
        traditional: true,
        async: true,
        statusCode: {
            302: function () {
                //302 was returned from the server, call the custom error route to write the values to the iis log.
                WSLeComments.ClientActions.call302errorRoute(street, city, state, zip);
            }
        }
    }).fail(function () {
        WSLeComments.ValidateDistrict.showErrorMessage($("#DistrictLabel"));
    })
      .success(function(data) {
          WSLeComments.ValidateDistrict.populateValidatedResults(data);
      });

});

$(document).on("change", "input[name='IsPossibleConstituent']", function () {
    var radioValue = $(this).val();
    WSL.Logger.log("IsPossibleConstituent changed to: " + radioValue);
    if (radioValue === "True") {
        ClientStorage.set(WSLeComments.Constants.CCRadioHide, "");
        WSLeComments.ClientActions.showOrHideSecondaryMembers($('#ResponseRequested_True').is(':checked'));
    } else if (radioValue === "False") {
        ClientStorage.set(WSLeComments.Constants.CCRadioHide, "Hide");
        WSLeComments.ClientActions.showOrHideSecondaryMembers(false);
        //set the secondary members to false if they had been previously selected
        $("#SecondaryResponseRequested_False").prop("checked", true).checkboxradio("refresh");
        $("#SecondaryResponseRequested_True").prop("checked", false).checkboxradio("refresh");
    }
});

//this change handler is on the member email page
$(document).on("change", "#RRControlGroupEmailForm input[name='ResponseRequested']", function () {
    var radioValue = $(this).val();
    WSL.Logger.log("ResponseRequested_EmailForm changed to: " + radioValue);
    if (radioValue === "True" && ClientStorage.get(WSLeComments.Constants.CCRadioHide) !== "Hide") {
        $('#MemberResponse_EmailForm').show();
    } else if (radioValue === "False") {
        $('#MemberResponse_EmailForm').hide();
    }
});

//this is on the bill comment page
//would like to replace this with a Ajax.radio html helper extension
$(document).on("change", "#RRControlGroupCommentForm input[name='ResponseRequested']", function () {
    var radioValue = $(this).val();
    WSL.Logger.log("ResponseRequested changed to: " + radioValue);
    if (radioValue === "True") {
        $('#MemberResponse').show().html("Loading...");
        WSLeComments.ClientActions.populateMemberResponse();
    } else if (radioValue === "False") {
        $('#MemberResponse').hide();
    }
});


//if the form has passed validation, enable it
//$(document).on('invalid-form.validate', 'form', function () {
//    var button = $(this).find('input[type="submit"]');
//    //checking for validated district is the only validation we are using outside of JQuery unobtrusive
//    //so check for that before we enable the button
//    if (!$("#mayContinueMessage").hasClass("validationred")) {
//        setTimeout(function () {
//            button.removeAttr('disabled');
//        }, 1);
//    }
//});
//this disables the submit button
//$(document).on('submit', 'form', function () {
//    var button = $(this).find('input[type="submit"]');
//    setTimeout(function () {
//        button.attr('disabled', 'disabled');
//    }, 0);
//});
;
var WslInitiativeParser = (function () {
    var pre2025InitiativeFormat = /^[0-9]{3,4}$/;
    var post2025InitiativeFormat = /^([Ii][Ll])?\d{2}-?\d{3}$/;

    return {
        // Parses initiative inputs to their digit format. For example, if you supply "IL24-999", "24-999", or "IL24999", it will return "24999".
        getLegislationNumber: function (input) {
            if (this.isOldFormat(input)) {
                return parseInt(input);
            }
            else if (this.isNewFormat(input)) {
                var extracted = this.extractLegislationNumber(input);
                return parseInt(extracted);
            }

            throw new Error("Invalid Legislation Number");
        },

        // Converts the 5 digit initiative inputs to their proper display format. For example, if you supply "24999", it will return "IL24-999"
        getLegislationDisplayNumber: function (input) {
            if (!this.isNullOrWhitespace(input)) {
                var inputString = this.getLegislationNumber(input).toString();

                if (inputString.length === 5) {
                    var bienPart = inputString.substring(0, 2);
                    var legPart = inputString.substring(2, 5);

                    return `IL${bienPart}-${legPart}`;
                }
                else if (inputString.length < 5) {
                    return inputString;
                }
            }

            throw new Error("Invalid Legislation Number");
        },

        isOldFormat: function (input) {
            return pre2025InitiativeFormat.test(input);
        },

        isNewFormat: function (input) {
            return post2025InitiativeFormat.test(input);
        },

        extractLegislationNumber: function (input) {
            return input.replace(/[Ii][Ll]/, "").replace("-", "");
        },

        isNullOrWhitespace: function (input) {
            return !input || input.trim().length === 0;
        }
    };
})();

// Module export for Jest test framework
if (typeof module !== 'undefined' && module.exports) {
    module.exports = WslInitiativeParser;
}
;
