String.prototype.startsWith = function (str) {
    return (this.indexOf(str) === 0);
}
jQuery(document).ready(function () {

    //Start Image Carousel code
    var ic = $('#banners'),
	 items = null,
	 insertBuffer = [],
	 item = null;

    function emptyCarouselBuffer() {
        insertBuffer.sort(function () { return 0.5 - Math.random(); });
        while (insertBuffer.length > 0) {
            $('#banners').append(insertBuffer.pop());
        }
    }

    if (ic) {
        items = $('.BannerOuterContent', ic).detach().toArray();

        while (items.length > 0) {
            item = items.shift(); //Take first item off array

            //Does item match insert buffer?
            if (insertBuffer && insertBuffer[0]) {
                if ($(item).attr('title') === $(insertBuffer[0]).attr('title')) {
                    //Match - add it to the buffer
                    insertBuffer[insertBuffer.length] = item;
                }
                else {
                    //No match. Dump the buffer
                    emptyCarouselBuffer();

                    //Add the item as the first entry in the new buffer.
                    insertBuffer[insertBuffer.length] = item;
                }
            }
            else {
                insertBuffer[insertBuffer.length] = item;
            }
        }
        emptyCarouselBuffer();
        var imageCarousel = document.getElementById("banners");
        if (imageCarousel != null) {
            if (navigator.userAgent != "SITEARCHIVER") {
                $('#banners').scroller({ transition: 'fade', perPage: 1, itemClass: 'BannerOuterContent', leftButton: '<div id="left-button"><span>&laquo;</span></div>', rightButton: '<div id="right-button"><span>&raquo;</span></div>', dotCounter: true, auto: true, animateSpeed: SLIDE_SPEED, autoSpeed: SLIDE_DELAY });
            }
        }
    }
    //End Image Carousel code
    //Start design element changes
    $("#topNav ul li:last-child").addClass("last");
    $("#bottomNav ul li:last").addClass("last");
    $("#bottomNav2 ul li:last").addClass("last");
    $("#breadcrumbs ul li:last").addClass("active");

    $("#topNav .loginDropDown").hide();
    $("#login .loginDropDown").hide();
    $("#login .loginAssistanceDropDown").hide();
    if ($("#topNav li:contains('Login')")) {
        $("#topNav li:contains('Login')").click(function (e) {
            e.preventDefault();
            $("#topNav .loginDropDown").slideToggle();
        });
    }
    else {
        $("#topNav .loginDropDown").remove();
    }

    if ($("#login div").hasClass("loginDropDown")) {

        $("#loginButton a").click(function (e) {
            e.preventDefault();
            $("#login .loginDropDown").slideToggle();
        });
    }
    if ($("#login div").hasClass("loginAssistanceDropDown")) {

        $("#loginAssist a").click(function (e) {
            e.preventDefault();
            $("#login .loginAssistanceDropDown").slideToggle();
        });
    }
    $('a.videoPlayer').colorbox({
        onCleanup: function () { $("#myExperience").remove(); },
        //onComplete: function(){ brightcove.createExperiences(); }
        opacity: 0.8,
        innerWidth: "830px",
        innerHeight: "640px",
        iframe: "true"
    });
   /* $("a#ASYMCADemoLink").colorbox({
        onCleanup: function () { $("#ASYMCADemo").remove(); },
        innerWidth: "825px",
        innerHeight: "640px",
        iframe: "true"

        //onClosed: function(){ stopTheDemo(); }
    });
    $("a#USODemoLink").colorbox({
        onCleanup: function () { $("#military_pro").remove(); },
        innerWidth: "870px",
        innerHeight: "780px",
        iframe: "true"
        //onClosed: function(){ stopTheDemo(); }
    });*/
    if (window.location.pathname != "/en/beneficiary/" && window.location.pathname != "/en/provider/" && window.location.pathname != "/en/about-triwest/" && window.location.pathname != "/en/" && !window.location.pathname.toLowerCase().startsWith("/search/") && !window.location.pathname.toLowerCase().startsWith("/provider/onlineforms/") && !window.location.pathname.toLowerCase().startsWith("/beneficiary/onlineforms") && !window.location.pathname.toLowerCase().startsWith("/provider/procedurepricing/") && !window.location.pathname.toLowerCase().startsWith("/provider/providerenewsregistration/")) {
        $("#content").addClass("subPage");
        //End design element changes
    }
    if (window.location.pathname.toLowerCase().startsWith("/onlineproviderdirectory/") || window.location.pathname.toLowerCase().startsWith("/beneficiary/mtflocator/")) {
        $("#content").removeClass("subPage");
        $("#content").addClass("subPageNoLeftApp");
        $("#appLogin").hide();
    }
    if (window.location.pathname.toLowerCase().startsWith("/beneficiary/")) {
        $("#content").removeClass("subPage");
    }
    if (window.location.pathname.startsWith("/en/beneficiary/")) {
        $("#topNav li:contains('Beneficiary')").addClass("active");
    }
    if (window.location.pathname.startsWith("/en/provider/")) {
        $("#topNav li:contains('Provider Connection')").addClass("active");
    }
    if (window.location.pathname.startsWith("/en/about-triwest/")) {
        $("#topNav li:contains('About TriWest')").addClass("active");
    }
    if (window.location.pathname == "/en/" || window.location.pathname.startsWith("/en/about-triwest/")) {
        $("#RegButton a, #popularLinks li:contains('Registration')").click(function (e) {
            e.preventDefault();
            $("#TCAlert").modal({
                overlayCss: { background: "#000000" },
                opacity: 70,
                onOpen: function (dialog) {
                    dialog.overlay.fadeIn('normal', function () {
                        dialog.container.slideDown('normal', function () {
                            dialog.data.fadeIn('normal');
                        });
                    });
                },
                onClose: function (dialog) {
                    dialog.data.fadeOut('normal', function () {
                        dialog.container.slideUp('normal', function () {
                            dialog.overlay.fadeOut('normal', function () {
                                $.modal.close(); // must call this!
                            });
                        });
                    });
                }
            });
        });
    }
    else {
        $("#TCAlert").remove();
    }
    //FAQ
    $(".content").hide();
    //toggle the componenet with class msg_body
    $(".heading").click(function () {
        $(this).next(".content").slideToggle(450);
    }),
        $("#faq").find("td").removeAttr("style");
    //End FAQ
    //Start Bene Form Listing
    $(function () {

        // hide the element with class categoryQuestionList by writing inline style="display: none" to it
        $(".formListing").hide();
        $(".EnrollmentListing").show();
        $(".categoryQuestionList").hide();
        $(".CIForms").hide();

        // assign toggle function to element with class categoryTitle
        $(".categoryTitle").click(function () {

            // on toggle un-hide the element with class categoryQuestionList by writing inline style="display: block" to it
            if ($(this).next().is('.formListing')) {
                $(this).next(".formListing").toggle();
                $(this).toggleClass('open');
            }
            else {
                $(this).next(".EnrollmentListing").toggle();
                $(this).toggleClass('open');
            }
            return false;
        });
        // assign toggle function to element with class categoryTitle
        $(".categoryTitle").click(function () {

            // on toggle un-hide the element with class categoryQuestionList by writing inline style="display: block" to it
            $(this).parent().parent().nextAll().toggle();
        });
    });
    //END Bene Form Listing
    //Start stitemap changes
    $("#siteMap ul li ul").hide();
    $(".HasChildren").unbind('toggle').toggle(
    function () {
        $(this).children("ul").slideDown();
        $(this).addClass("HasChildrenCollapse");
    },
    function () {
        $(this).children("ul").slideUp();
        $(this).removeClass("HasChildrenCollapse");
    });
    //End sitemap changes

    $('#siteNav #SectionNav ul:first li').has('ul').click(function (evt) {
        var ul = $(this).find('ul');

        var onClass = 'downArrow';
        var offClass = 'overArrow';

        $(this).parent().find('li a .' + onClass).removeClass(onClass).addClass(offClass).parent().parent().find('ul').slideUp().addClass('current');

        evt.preventDefault();

        var toggler = $(this).find('a span');

        var isOn = toggler.hasClass(offClass);

        $(this).find('ul li').each(function (i) {
            $(this).find('a').click(function (e) {
                e.preventDefault();

                var target = $(this).attr('target');
                if (target != '_blank') {

                    window.location = $(this).attr('href');

                }
                else {
                    window.open($(this).attr('href'));
                }


                return false;
            });

        });


        if (isOn) {
            if (!ul.hasClass('current')) {
                toggler.removeClass(offClass);
                toggler.addClass(onClass);

                ul.slideToggle();
            }
        }
        else {
            toggler.removeClass(onClass);
            toggler.addClass(offClass);
        }

        $(this).parent().find('li .current').removeClass('current');
    });


    $('#siteNav #SectionNav ul:first li ul').hide();
    $('#siteNav #SectionNav ul:first li').has('ul').each(function (j) {
        var li = $(this);
        var found = false;

        $(this).find("ul li a").each(function (xs) {
            if (window.location.pathname.toLowerCase().startsWith($(this).attr("href").toLowerCase())) {
                if (!found) {
                    li.find('a:first').click();
                    found = true;

                }
            }
        });
    });


    //Start external link check

    $('a').each(function (index) {
        var TWsites = [
                '/',
                '#',
                '?',
                'mailto:',
                'javascript:',
                'triwest-dev.triwps.com',
                'triwest-qa.triwps.com',
                'triwestqa.triwps.com',
                'staging.triwest.com',
                'triwest.qualtrics.com',
                'www.triwest.com',
                'recruiter.triwest.com',
                'triwest.com',
                'triwest-dev',
                'triwest-qa',
                'netsub.triwest.com',
                'eSeminarList.aspx',
                'WebinarRegistration.aspx',
                'netsub-qa',
                'govt-qa',
                'govt.triwest.com',
                'searchresults.aspx',
                'secure.triwest.com',
                'SearchProvider.aspx',
                'triwest.server.tracorp.com',
                'DirectoryHelp.aspx',
                'Default.aspx',
                'ProviderDetails.aspx',
                'MakePayment.aspx',
                'AuthRefDetaill.aspx',
                'PaperlessPreferences.aspx',
                '../twmap',
                'inbox.aspx'
                ];

        if ($(this).attr("href") != undefined) {

            var fullLink = $(this).attr("href");
            var linkIs = $(this).attr("href");
            if (linkIs.startsWith("http://")) {
                var temp1 = linkIs.substring(7);
                if (temp1.indexOf("/") != -1) {

                    linkIs = temp1.substring(0, temp1.indexOf("/"));
                }
                else {
                    linkIs = temp1;
                }
            }
            else if (linkIs.startsWith("https://")) {
                var temp2 = linkIs.substring(8);
                if (temp2.indexOf("/") != -1) {
                    linkIs = temp2.substring(0, temp2.indexOf("/"));
                }
                else {
                    linkIs = temp2;
                }
            }
            else if (linkIs.startsWith("/")) {
                linkIs = linkIs.substring(0, 1);
            }
            else if (linkIs.startsWith("?")) {
                linkIs = linkIs.substring(0, 1);
            }
            else if (linkIs.startsWith("#")) {
                linkIs = linkIs.substring(0, 1);
            }
            else if (linkIs.startsWith("mailto:")) {
                linkIs = linkIs.substring(0, 7);
            }
            else if (linkIs.startsWith("javascript:")) {
                linkIs = linkIs.substring(0, 11);
            }
            else if (linkIs.startsWith("searchresults.aspx")) {
                linkIs = linkIs.substring(0, 18);
            }
            else if (linkIs.startsWith("eSeminarList.aspx")) {
                linkIs = linkIs.substring(0, 17);
            }
            else if (linkIs.startsWith("WebinarRegistration.aspx")) {
                linkIs = linkIs.substring(0, 24);
            }
            else if (linkIs.startsWith("SearchProvider.aspx")) {
                linkIs = linkIs.substring(0, 19);
            }
            else if (linkIs.startsWith("DirectoryHelp.aspx")) {
                linkIs = linkIs.substring(0, 19);
            }
            else if (linkIs.startsWith("Default.aspx")) {
                linkIs = linkIs.substring(0, 12);
            }
            else if (linkIs.startsWith("ProviderDetails.aspx")) {
                linkIs = linkIs.substring(0, 20);
            }
            else if (linkIs.startsWith("AuthRefDetaill.aspx")) {
                linkIs = linkIs.substring(0, 19);
            }
            else if (linkIs.startsWith("../twmap")) {
                linkIs = linkIs.substring(0, 8);
            }
            var baseUrl = linkIs;

            function objConv(a) {
                var o = {};
                for (var i = 0; i < a.length; i++) {
                    o[a[i]] = '';
                }
                return o;
            }

            if (baseUrl in objConv(TWsites)) {
            } else {
                $(this).click(function (e) {
                    e.preventDefault();
                    document.getElementById('buttons').innerHTML = "<a class=\"btnBack\" href=\"" + fullLink + "\" id=\"btn_proceed\" title=\"Proceed\" target=\"_blank\" onclick=\"javascript:$.modal.close();\" onkeypress=\"javascript:$.modal.close();\">Proceed</a> <a class=\"btnBack\" title=\"Cancel\" onclick=\"javascript:$.modal.close();\" onkeypress=\"javascript:$.modal.close();\">Cancel</a>";
                    //$("#btn_proceed").attr("href", fullLink);
                    $("#ExitWarning").modal({
                        overlayCss: { background: "#000000" },
                        opacity: 70,
                        onOpen: function (dialog) {
                            dialog.overlay.fadeIn('normal', function () {
                                dialog.container.slideDown('normal', function () {
                                    dialog.data.fadeIn('normal');
                                });
                            });
                        },
                        onClose: function (dialog) {
                            dialog.data.fadeOut('normal', function () {
                                dialog.container.slideUp('normal', function () {
                                    dialog.overlay.fadeOut('normal', function () {
                                        $.modal.close(); // must call this!
                                    });
                                });
                            });
                        }
                    });
                });
            }
        }
    });

});
