/* Minification failed. Returning unminified contents.
(297,19-20): run-time error JS1014: Invalid character: `
(297,25-26): run-time error JS1193: Expected ',' or ')': :
(297,46-47): run-time error JS1014: Invalid character: `
(297,47-48): run-time error JS1195: Expected expression: )
(299,3-4): run-time error JS1002: Syntax error: }
 */
$(function () {
    UpgradeASPNETValidation();
});


/** 
* Extends the classic ASP.NET validation to add a class to the parent span when invalid 
*/
function UpgradeASPNETValidation() {
    //alert("hello upgrade");
    // Hi-jack the ASP.NET error display only if required 
    if (typeof (Page_ClientValidate) != "undefined") {
        TempValidatorUpdateDisplay = ValidatorUpdateDisplay;
        ValidatorUpdateDisplay = NicerValidatorUpdateDisplay;

        AspPage_ClientValidate = Page_ClientValidate;
        Page_ClientValidate = NicerPage_ClientValidate;
    }
}

/** 
* Extends the classic ASP.NET validation to add a class to the parent span when invalid 
*/
function NicerValidatorUpdateDisplay(val) {
    TempValidatorUpdateDisplay(val);
    var trigger = $("#" + val["controltovalidate"]);

    //totalInvalid finds out if there is any other validator for the same control is invalid.
    var totalInvalid = $("span[data-val-controltovalidate='" + val['controltovalidate'] + "']:visible").length;
    if (!val.isvalid)
    {
        //If validator is invalid, add custom error class
        trigger.addClass("ErrorHighlighted");
    }
    else
    {
        //If the validator is valid and all other validators for the same control are valid, then remove the custom error class
        if (totalInvalid === 0) {
            trigger.removeClass("ErrorHighlighted");
        }
    }
}

/*
This is hijacking the Page_ClientValidate. So when the Main asp Page_ClientValidate is called, this NicerPage function is called.
Internally AspPage_ClientVaildate is called which is the original build-in Page_ClientValidate
*/
function NicerPage_ClientValidate(validationGroup) {
    var valid = AspPage_ClientValidate(validationGroup);
    if (!valid) {
        var ctrl = $(".ErrorHighlighted:visible:first");
        ScrollToFocus(ctrl,75);
    }
    //Page_IsValid = false; // I don't remember why I have it but seems This is some hack for jQuery Watermark and ASP.NET Validation to work.
    return valid;
};
document.addEventListener("DOMContentLoaded", function () {
    if (window.innerWidth > 992) {

        document.querySelectorAll('.navbar .nav-item').forEach(function (everyitem) {

            everyitem.addEventListener('mouseover', function (e) {

                let el_link = this.querySelector('a[data-bs-toggle]');

                if (el_link != null) {
                    let nextEl = el_link.nextElementSibling;
                    el_link.classList.add('show');
                    nextEl.classList.add('show');
                }

            });
            everyitem.addEventListener('mouseleave', function (e) {
                let el_link = this.querySelector('a[data-bs-toggle]');

                if (el_link != null) {
                    let nextEl = el_link.nextElementSibling;
                    el_link.classList.remove('show');
                    nextEl.classList.remove('show');                
                }


            })
        });

    }
});
$(function () {
    var firstZip = getCookie('zipcode');
    $('.zip-input').val(firstZip);
    $('.currentzipcode').html(firstZip);
    $(".btn-updatezip").text(firstZip ? "Update" : "Submit");
    var firstState = getCookie('statecode');
    if (firstState != null && firstState == 'CA')
        $('.californiaonly').show();

    $('.zip-input').change(function () {
        var $this = $(this);
        var val = $this.val();
        if (val.length < 5 || !+val)
            return;
        $('.zip-input').not($this).val(val);
        $('.currentzipcode').html(val);
    });
    
    $('.mbr-program').click(function () {
        var $this = $(this);
        var url = $this.data('url');
        if (!url || !url.length) {
            console.log('no URL - exiting');
            return false;
        }
        var zip = $('.zip-input').val();
        if (zip != null && zip.length > 4 && +zip) {
            opentracker('r=zipcodenav&p=' + url);
            window.location.href = url;
            return false;
        }
        $('#zipCodeModal').data('url', url);
        showZipModal($this);
        return false;
    });

    $(".mobileupdatezipavailable").click(function () {
        try {
            var $this = $(this);
            var url = $this[0].dataset.url;            
            $('#zipCodeModal').data('url', url);
            showZipModal($this);
        } catch (err) {
            console.log(err);
            return false;
        }
        return false;

    });
    $(".mobileupdatezip").click(function () {
        try {
            var $this = $(this);
            var url = $this[0].dataset.url;
            $('#zipCodeModal').data('url', url);
            var currentZip = getZipCodeForSection();
            if (!currentZip || currentZip.length !== 5) {
                showZipModal($this);
            } else {
                navAfterZipcode();
            }      
        } catch (err) {
            console.log(err);
            return false;
        }
        return false;

    });
    $(".navbtnmodal").click(function () {
        if (!Page_ClientValidate('NavZipInfoModal')) {
            return false;
        }
        var zipcode = $('.zipcodenavmodal').val().substr(0, 5);
        opentracker('r=changezipcode&p=' + zipcode);
        wait_InitializeRequest();
        $('.zip-input').val(zipcode);
        $('.currentzipcode').html(zipcode);
        saveZipCode(zipcode, navAfterZipcode);
        $(".btn-updatezip").text(zipcode != "" ? "Update" : "Submit");
        return false;
    });

    $(".zipcodenavmodal").on("keypress", function (e) {
        if (e.which == 13) {
            if (!Page_ClientValidate('NavZipInfoModal')) {
                return false;
            }
            var zipcode = $('.zipcodenavmodal').val().substr(0, 5);
            opentracker('r=changezipcode&p=' + zipcode);
            wait_InitializeRequest();
            $('.zip-input').val(zipcode);
            $('.currentzipcode').html(zipcode);
            saveZipCode(zipcode, navAfterZipcode);
            $(".btn-updatezip").text(zipcode != "" ? "Update" : "Submit");
            return false;
        }

    });

    $(".nav-zip-input").on("keypress", function (e) {
        if (e.which == 13) {
            if (!Page_ClientValidate('NavZipInfo')) {
                return false;
            }
            var zipcode = $('.nav-zip-input').val().substr(0, 5);
            opentracker('r=changezipcode&p=' + zipcode);
            wait_InitializeRequest();
            $('.currentzipcode').html(zipcode);
            saveZipCode(zipcode);
            if (document.getElementById("ZipCode")) {
                $("#ZipCode").val(zipcode).keyup();
            }
            $('.ps-zip-input').val(zipcode);
            return false;
        }

    });

    $(".btn-updatezip").click(function () {
        if (!Page_ClientValidate('NavZipInfo')) {
            return false;
        }
        var zipcode = $('.zip-input').val().substr(0, 5);
        opentracker('r=changezipcode&p=' + zipcode);
        wait_InitializeRequest();
        saveZipCode(zipcode);
        $(".btn-updatezip").text(zipcode !="" ? "Update" : "Submit");
        if (document.getElementById("ZipCode")) {
            $("#ZipCode").val(zipcode).keyup();
        }
        return false;
    });
    function showZipModal($this) {
        $('input,select').removeClass('ErrorHighlighted');
        $('.aspnetValidator').hide();
        $('#zipcodenavmodal').val('');
        var title = $this.data('title');
        if (!title || !title.length) //default copy
            title = $this.text();
        $('.zip-modal-title').html(title);
        var copy = $this.data('copy');
        if (!copy || !copy.length) {
            copy = 'Enter your zip code to view ' + title;
            if (title.trim().toLowerCase() == "change your zip code") {
                copy = 'Enter your zip code';
            }
        }  
        $('.zip-modal-copy').html(copy);
        $('#zipCodeModal').modal('show');
        var url = $('#zipCodeModal').data('url');
        opentracker('r=zipcodemodalnavopen&p=' + url);
    }
    function navAfterZipcode() {
        var url = $('#zipCodeModal').data('url');
        if (url == null) url = '';
        opentracker('r=afterzipcodenav&p=' + url);
        if (url.length) {            	
            if (url != "/rv/default.aspx") {
                window.location.href = url;
            } else {
                //Check RV availability
                if (isRVAvailable()) {
                    window.location.href = url;
                } else {
                    if (typeof showNotifyMe !== 'undefined') {
                        wait_EndRequest();
                        $('#zipCodeModal').modal('hide');
                        showNotifyMe('rv');
                    } else {
                        window.location.href = url;
                    }
                }
            }   
        } else {
            wait_EndRequest();
            $('#zipCodeModal').modal('hide');
        }
    }

});
function ScrollToFocus(ctrlselector, eleTopOffset, always) {
    var eltoscrollTo = $(ctrlselector);
    if (eltoscrollTo.length > 0) {
        if (eleTopOffset === 'undefined' || eleTopOffset === null || eleTopOffset === undefined)
            eleTopOffset = 50;
        var offset = eltoscrollTo.offset();
        if (offset !== null) {
            scrollTops = offset.top;
            scrollLefts = offset.left;

            if (always || $(window).scrollTop() > scrollTops) {
                $('html, body').animate({ scrollTop: scrollTops - eleTopOffset, scrollLeft: scrollLefts }, 500);
            }
        }
    }
}

function getZipCodeForSection() {
  let result = '';

  const targetUrl = '/api/member/getzipcode';

  $.ajax({
    url: targetUrl,
    type: 'POST',
    async: false,
    success: function (data) {
      result = data;
    },
    error: function (err) {
      console.log(`ERROR: getZipCode - ${err}`);
    }
  });

  return result;
}
;
