var afsIndivScroller;
var tooltipTemplate = '<div class="tooptip blue" role="tooptip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>';

$(document).ready(function () {
    $("#progress").hide();
    $(document).on('invalid-form.validate', 'form', function () {
        setTimeout(function () {
            $("#progress").show();
        }, 1);
    });

    $(document).on('submit', 'form', function () {
        setTimeout(function () {
            $("#progress").show();

        }, 0);
    });
    if (navigator.userAgent.indexOf("MSIE") > 0) {
        $("html").addClass("ie");
    }

    //Apply Tooltop on the elements
    $('[data-toggle="tooltip"]').tooltip({ template: tooltipTemplate });

    //Nav Submenu hover to expand
    if ($(window).width() > 768) {
        //Removing Active class which creates black background.
        $(".nav-container li.custom-dropdown.active").removeClass("active");
        $(".nav-container li.custom-dropdown").click(function () {
            $(".nav-container li.custom-dropdown.active").removeClass("active");
        });

        $(".custom-dropdown").hover(
            function () {
                $('.dropdown-menu', this).not('.in .dropdown-menu').stop(true, true).slideDown("300");
                $(".nav-container li.custom-dropdown").removeClass("open");
                $(this).toggleClass('open');
            },
            function () {
                $('.dropdown-menu', this).not('.in .dropdown-menu').stop(true, true).hide();
                $(".nav-container li.custom-dropdown").removeClass("open");
            }
        );

        //Commenting the following event as it is causing issues for the dropdowns in pages with older layout - eg. NSLP
        //$('ul.nav li.dropdown').on('click', function (e) {
        //    e.stopPropagation();
        //});
    }

    //Top Language Boxes
    if ($('#lang, #lang-mobile').length > 0) {
        function languageToggle() {
            $('.overlay').toggle();
            $('.flex-parent').slideToggle();
            if ($('.overlay').is(":visible")) {
                $(this).find("img").attr("src", "/Compass.Web/Content/Icons/arrow-up.png");
            } else {
                $(this).find("img").attr("src", "/Compass.Web/Content/Icons/arrow-down.png");
            }
        }

        $('.overlay').click(function () {
            $('#lang').click();
        });

        $('#lang-mobile, #lang').bind('click', languageToggle);
        $('#languageClose').bind('click', languageToggle);
    }

    // Clicking on COMPASS Logo, display redirection popup.
    $("#CompassHomeImage").click(function (evt) {
        evt.preventDefault();

        var sessionTimoutexceptions = ["CMPHOME", "COMPASS.WEB", "LOGIN"],
            urlParts = window.location.href.replace("?", "/").split("/"),
            currentPage = urlParts[urlParts.length - 1].toUpperCase(),
            currentPage1 = urlParts[urlParts.length - 2].toUpperCase();
        if (sessionTimoutexceptions.indexOf(currentPage) === -1 && sessionTimoutexceptions.indexOf(currentPage1) === -1) {
            $('#modal-leave-Current').modal('show');
        }
    });

    /* Dashboard tabs code for horizontal tab section - MCA, CP Dashboard*/
    $(".dashboard-tabs ul#tabs li").click(function () {
        if (!$(this).hasClass("active")) {
            var tabNum = $(this).index(),
                nthChild = tabNum + 1;
            $(".dashboard-tabs ul#tabs li.active").removeClass("active");
            $(this).addClass("active");
            $(".dashboard-tabs ul#tab li.active").removeClass("active");
            $(".dashboard-tabs ul#tab li:nth-child(" + nthChild + ")").addClass("active");
            $(".cp-container ul#tab li.active input#org").prop("checked", "checked");
            $(".cp-container ul#tab li.active input#orgsubmitted").prop("checked", "checked");
            $(".cp-container ul#tab li.active input#org_consent").prop("checked", "checked");
        }
    });

    /* code below is used for hiding and showing hovering icons on the MCA Dashboard and CP dashboard hovering on the table rows*/
    var table_row = $('.grid-container > div:last-child table tr:not(:first-child)');
    gridHoverEventBinder(table_row);

    /* Functionality on Generic Basic Grid with hover event */
    $('.grid tr.hover-menu').hover(function () {
        //alert($(this).outerHeight() + " - " + $(this).innerHeight() + " - " + $(this).height());
        var rowHeight = $(this).outerHeight(),
            marginTop = parseInt((rowHeight / 2) - 10),
            paddingTop = parseInt((rowHeight / 2) - 16);
        
        var buttonBox = $(this).find(".buttons-container");
        buttonBox.css("margin-top", "-" + marginTop + "px").css("padding", paddingTop + "px 0");
        buttonBox.show();
        gridHoverEventTimeout(buttonBox);
    }, function () {
        var buttonBox = $(this).find(".buttons-container");
        buttonBox.removeAttr("style");
        buttonBox.removeClass("active");
        buttonBox.hide();
    });

    /*Code below will toggle between the toggle arrows for panels when they are collapsed*/
    $(".accordion-toggle").click(function () {
        if ($(this).find("i.fa").length > 0) {
            if ($(this).hasClass("collapsed")) {
                $(this).find("i")[0].className = $(this).find("i")[0].className.replace("up", "down");
            }
        }
    });

    //If multiple panels in group, then make sure it always keep one open.
    if ($(".panel-group .panel-heading").length > 1) {
        $(".panel-heading a").click(function (evt) {
            if ($(this).parents(".panel").children(".panel-collapse").hasClass("in")) {
                evt.preventDefault();
                evt.stopPropagation();
            }
        });
    }

    //Fix for the footer, when content height gets changed dynamically.
    onElementHeightChange(document.body, function () {
        moveFooterAtBottom();
    });
    moveFooterAtBottom();

    //Add Blue Arrow in dropdown menu.
    addDropdownArrowInCISControls();

    //Display Lightbox window on link click
    $(document).on("click", "[data-toggle='lightbox']", function (evt) {
        evt.preventDefault();
        $(this).ekkoLightbox();
    });

    /* AFS Flow Script - This aligns AFS Secondary Menu / Page Title heading somewhere in middle of the page, based on current active page. */
    if ($(".afs-page-title-list").length > 0) {
        var containerWidth = $(".afs-page-title-list").width(),
            totalWidth = 0,
            activeElement = $(".afs-page-title-list .tabs li.active");
        $(".afs-page-title-list .tabs li").each(function () {
            totalWidth = totalWidth + $(this).width();
        });

        //alert(containerWidth + " --- " + totalWidth);
        if (totalWidth > containerWidth) {
            var tabContainer = $(".afs-page-title-list .tabs"),
                elementWidth = activeElement.width(),
                activeElementPosition = elementWidth;

            $(activeElement).prevAll().each(function () { activeElementPosition += $(this).width(); });
            if (activeElementPosition >= (containerWidth - 200)) {
                var elementLeft = (totalWidth / 2) - elementWidth;
                //var leftPosition = (containerWidth - (elementWidth + elementLeft));
                tabContainer.css({ left: -(elementLeft+175), width: totalWidth + elementLeft });
            }
        }
    }

    /* AFS - Top Navigation for the Individual Names */
    if ($('#peopleNav').length > 0) {
        afsIndivScroller = $('#peopleNav').navigationScroller();
    }

    //Submit the form when clicked enter in Input
    if ($(".cp-landing input:text, .cp-landing input:password, .forgot-password input:text, .forgot-password input:password, #cpSearch input:text, #cpSearch input:password, #cpConsentSearch input:text, #cpConsentSearch input:password, .check-app-status input:text, #check-app-status input:password").length > 0) {
        $(".cp-landing input:text, .cp-landing input:password, .forgot-password input:text, .forgot-password input:password, #cpSearch input:text, #cpSearch input:password, #cpConsentSearch input:text, #cpConsentSearch input:password, .check-app-status input:text, #check-app-status input:password").keypress(function (keyEvent) {
            if (keyEvent.which === 13) {
                keyEvent.preventDefault();
                $("input:submit").click();
                //$("form").submit();
            }
        });
    }

    // Clicking on COMPASS Logo, display redirection popup.
    $("#mobileAlertReadMore").click(function () {
        $('#mobile-alert-readmore').modal('show');
    });
});

function gridHoverEventBinder(gridName) {
    $(gridName).hover(function () {
        var buttonBox = $(this).children().children().last();
        buttonBox.show();
        gridHoverEventTimeout(buttonBox);
    }, function () {
        var buttonBox = $(this).children().children().last();
        buttonBox.hide();
        buttonBox.removeClass("active");
    });
}

function gridHoverEventTimeout(element) {
    setTimeout(function () {
        element.addClass("active");
    }, 100);
};

function addDropdownArrowInCISControls() {
    if ($(".cis-control select").length > 0) {
        $(".cis-control select").each(function () {
            if ($(this).parent().find("i.fa-chevron-down").length <= 0) {
                $(this).after('<i class="fa fa-chevron-down"></i>');
            }
        });
    }
}

function moveFooterAtBottom() {
    var leftNav = $(".left-side-nav");
    if (leftNav.length > 0) {
        //alert("Left Nav: " + $(".left-side-nav ul.nav").height() + ", Content: " + $(".tab-content").height());
        if ($(".tab-content").height() > $(".left-side-nav ul.nav").height()) {
            leftNav.removeClass("relative").addClass("absolute");
        } else if ($(".tab-content").height() < $(".left-side-nav ul.nav").height()) {
            leftNav.removeClass("absolute").addClass("relative");
        }
    }
}

function onElementHeightChange(elm, callback) {
    var lastHeight = elm.clientHeight, newHeight;
    (function run() {
        newHeight = elm.clientHeight;
        if (lastHeight !== newHeight) {
            callback();
        }
        lastHeight = newHeight;

        if (elm.onElementHeightChangeTimer) {
            clearTimeout(elm.onElementHeightChangeTimer);
        }

        elm.onElementHeightChangeTimer = setTimeout(run, 100);
    })();
}
var $scrollingDiv = $("#scrollingDiv");

/* Generic Scroller Plugin to use in any page */
$.fn.navigationScroller = function () {
    var _this = this,
        wrapper = _this.find(".scroller-wrapper"),
        leftArrow = _this.find(".scroller.left"),
        rightArrow = _this.find(".scroller.right"),
        tabContainer = _this.find("ul.tabs"),
        scrollPadding = 50;

    scroller = $.extend({
        wrapperWidth: function () {
            return wrapper.outerWidth();
        },
        leftPosition: function () {
            return tabContainer.position().left;
        },
        hiddenWidth: function () {
            return (wrapper.outerWidth() - scroller.contentWidth() - scroller.leftPosition()) - scrollPadding;
        },
        contentWidth: function () {

            return tabContainer.outerWidth();
        },
        scrollWidth: function () {
            var slidesCount = Math.ceil(scroller.contentWidth() / wrapper.outerWidth());
            return (Math.round(scroller.contentWidth() / slidesCount) - scrollPadding);
        },
        positionScrollAtActiveElement: function (nextPrevious) {
            var element = $("#peopleNav ul.tabs > li div.active"),
                household = $("#peopleNav ul.tabs > li")[0],
                previousAll = element.parent().prevAll(),
                prevwidth = 0,
                currentPositionWidth = 0,
                householdWidth = 0,
                animationWidth = element.outerWidth(),
                positiveNegativeSign = "";
            previousAll.each(function () {
                var itemWidth = $(this).outerWidth();
                prevwidth += itemWidth;
            });
            if (nextPrevious === 'N' && element[0] !== undefined) {
                positiveNegativeSign = "-";
                currentPositionWidth = prevwidth + element[0].clientWidth;
            } else if (nextPrevious === 'P') {
                if (household.clientWidth > 0) {
                    householdWidth = household.clientWidth;
                }
                currentPositionWidth = prevwidth;
                positiveNegativeSign = "+";
            }
            if (element.length > 0 && currentPositionWidth > wrapper.outerWidth()) {
                tabContainer.animate({
                    left: positiveNegativeSign + "=" + animationWidth + "px"
                }, 'slow');
            }
        },
        initialize: function () {
            if (scroller.contentWidth() <= wrapper.outerWidth()) {
                rightArrow.hide();
                leftArrow.hide();
            } else {
                if (scroller.leftPosition() > 0) {
                    leftArrow.show();
                }
                if (scroller.contentWidth() >= wrapper.outerWidth()) {
                    rightArrow.show();
                }
            }
        },
        logDetails: function () {
            console.log("Content Width: " + scroller.contentWidth());
            console.log("Wrapper Width: " + wrapper.outerWidth());
            console.log("Hidden Width: " + scroller.hiddenWidth());
        }
    });

    rightArrow.click(function () {
        var remainingWidth = ((scroller.contentWidth() + scroller.leftPosition()) - scroller.scrollWidth());
        if (remainingWidth <= 0 || Math.abs(scroller.hiddenWidth()) < wrapper.width()) {
            rightArrow.fadeOut('slow');
        }
        if (!leftArrow.is(":visible")) {
            leftArrow.fadeIn('slow');
        }
        tabContainer.animate({
            left: "-=" + scroller.scrollWidth() + "px"
        }, 'slow');
    });

    leftArrow.click(function () {
        var remainingWidth = Math.abs(scroller.leftPosition() + scroller.scrollWidth()),
            scrollWidth = scroller.scrollWidth();
        if (remainingWidth <= 0 || remainingWidth <= scrollPadding) {
            scrollWidth += remainingWidth;
            leftArrow.fadeOut('slow');
        }
        if (!rightArrow.is(":visible")) {
            rightArrow.fadeIn('slow');
        }
        tabContainer.animate({
            left: "+=" + scrollWidth + "px"
        }, 'slow');
    });
    //$(window).on('resize', function (e) {
    //    scroller.initialize();
    //});
    return scroller;
};;
var PopoverBlueTemplate = "<div class='popover blue-popover' role='tooltip'><div class='arrow'></div><h3 class='popover-title'></h3><div class='popover-content'></div></div>";
var HelpIconTemplate = '<img src="/Compass.Web/Content/images/hhs/question_icon.png" alt="Help?" class="help-icon" aria-hidden="true" data-toggle="popover" data-placement="right" data-trigger="click" data-container="body" data-html="true" data-class="blue-popover" />';

$(document).ready(function () {    
    var inputTypes = [':input[type=text]', ':input[type=email]', ':input[type=password]'];
    $.each(inputTypes, function (index, value) { $(value).attr("autocomplete", "off"); });
    if ($(".modalLogin").length > 0) {
        $(".modalLogin").click(function () {
            $("#eFormPwdShow").show();
            $("#HowToStart").show();
            $("#hideLinks").hide();
            $("#showLinks").show();
        });
    }

    if ($("#moreLanguagesbtn").length > 0) {
        $("#moreLanguagesbtn").click(function () {
            $("#moreLanguagesform").modal({ show: true, backdrop: true });
            $(".modal-open").removeClass("modal-open");
        });
    }

    initializeHelpTextToolTip();
    AssignTargetToCompassHome();
    AssignTargetOnCOMPASSMainMaster();

    //Prevent post on Enter Key Pressed
    $('input').on("keypress", function (e) {
        if (e.keyCode === 13) {
            return false;
        }
    });
});

function initializeHelpTextToolTip() {
    //Default for the website.
    $("[data-toggle='popover']").popover({ container: 'body', html: true, template: PopoverBlueTemplate });
    $("[data-toggle='dqb-popover']").popover({ container: 'body', html: true, placement: 'bottom', trigger: 'hover' });

    /* Start - Display help icon and help text as tool-tip */
    $('input[data-help-visible]').each(function () {
        var displayHelp = $(this).attr('data-help-visible'),
            tooltipText = $(this).attr('data-help-text'),
            helpIcon = $(HelpIconTemplate);
        if (typeof displayHelp !== 'undefined' && displayHelp !== '' && displayHelp.toLowerCase() === "true" && tooltipText !== '' && $(this).parent().find('img.help-icon').length <= 0) {
            $(helpIcon).attr("data-content", tooltipText);
            $(helpIcon).popover({ template: PopoverBlueTemplate });
            $(this).after(helpIcon);
        }
    });

    $("body").on("click", function (e) {
        $('[data-toggle="popover"]').each(function () {
            $(this).is(e.target) || 0 !== $(this).has(e.target).length || 0 !== $(".popover").has(e.target).length || $(this).popover("hide");
            if (!$('.popover:visible').hasClass('in')) {
                $('.popover').remove();
            }
        });
    });
    /* End - Display help icon and help text as tool-tip */
}
function closeWindow() {
    window.close();
    return false;
}

function AssignTargetToCompassHome() {
    if ($('#HomeApplyForBenefit').length > 0) {
        $('#HomeApplyForBenefit').click(function () {
            location.href = '/Compass.Web/AFS/SystemCompatibility?Origin=Apply%20for%20Any%20Benefits';
        });
    }
    if ($('#HomeDoIQualify').length > 0) {
        $('#HomeDoIQualify').click(function () {
            location.href = '/Compass.Web/Screening/SystemCompatibility?Origin=DoIQualify';
        });
    }    
}

//This function is written to fix ADA/HTML5 issues on COMPASS Main.master hyper links.
function AssignTargetOnCOMPASSMainMaster() {
    if ($('#MCADashboardLink').length > 0) {
        $('#MCADashboardLink').click(function () {
            location.href = '/Compass.Web/MCA/Dashboard';
        });
    }
    if ($('#BenefitSearchLink').length > 0) {
        $('#BenefitSearchLink').click(function () {
            location.href = '/Compass.Web/VIPS/BenefitSearch';
        });
    }
    if ($('#NSLPDashboardLink').length > 0) {
        $('#NSLPDashboardLink').click(function () {
            location.href = '/Compass.Web/CP/NSLP/Dashboard';
        });
    }
    if ($('#AdminFindLink').length > 0) {
        $('#AdminFindLink').click(function () {
            location.href = '/Compass.Web/Admin/Find';
        });
    }
    if ($('#CPDashboardLink').length > 0) {
        $('#CPDashboardLink').click(function () {
            location.href = '/Compass.Web/CP/Dashboard';
        });
    }
}

$(".row.randrPage .btn-submit.printPage").click(function () {
    window.print();
    return false;
});

function Print_onclick() {
    window.print();
    return false;
}

navigator.IsBrowserSupported = (function () {
    var ua = navigator.userAgent, tem,
        M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];

    if (/trident/i.test(M[1])) {
        tem = /\brv[ :]+(\d+)/g.exec(ua) || [];
        if (tem[1] !== undefined && tem[1] < 9) {
            return false;
        }
    }

    M = M[2] ? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?'];

    if ((tem = ua.match(/version\/(\d+)/i)) != null) M.splice(1, 1, tem[1]);

    switch (M[0]) {
        case 'Chrome':
            if (M[1] < 35) {
                return false;
            }
            break;
        case 'Firefox':
            if (M[1] < 35) {
                return false;
            }
            break;
        case 'IE':
            if (M[1] < 9) {
                return false;
            }
            break;
        case 'MSIE':
            if (M[1] < 9) {
                return false;
            }
            break;
    }
    return true;
})();;
