﻿/* variables
=====================================*/
var $j = jQuery.noConflict();
var i = 0;

/* document ready 
=====================================*/
$j(document).ready(function () {
    if ($j("#dialog").length != 0) {
        //console.log("dialog exists");
        $j(function () {
            $j("#dialog").dialog();
        });
        $j("#dialogTrigger").click(function () {
            //console.log("clicked");
            $j("#dialog").dialog("open");
            return false;
        });
    }

    //Gets rid of any elements of class "nojs-alt"
    $j('.nojs-alt').remove();

    if ($j.isFunction($j("#ctl15_txtHeaderSearch").autocomplete)) {
        $j("#ctl15_txtHeaderSearch").autocomplete("/autosuggest.aspx", { minChars: 3 });
    }

    //I am not sure what this id is supposed to be.
    if ($j.isFunction($j("#ctl13_txtHeaderSearch").autocomplete)) {
        $j("#ctl13_txtHeaderSearch").autocomplete("/autosuggest.aspx", { minChars: 3 });
    }

    if ($j.isFunction($j("#txtHeaderSearch").autocomplete)) {
        $j("#txtHeaderSearch").autocomplete("/autosuggestkit.aspx", { minChars: 3 });
    }

    if ($j.isFunction($j("#phcontent_0_txtBlogHeaderSearch").autocomplete)) {
        $j("#phcontent_0_txtBlogHeaderSearch").autocomplete("/autosuggestblog.aspx", { minChars: 3 });
    }

    $j("#sitemap").css("display", "none");

    $j("#link-site-map").click(function () {
        $j("#sitemap").slideToggle("slow");
    });

    if ($j("#navLearn .trigger").length != 0) {
        $j("#navLearn .trigger").click(function () {
            if ($j("#navLearn .trigger").text() == "More...") {
                $j("#navLearn .island .morePubs").slideDown("slow",
    function () {
        $j("#navLearn .trigger").attr("title", "Less...");
        $j("#navLearn .trigger").text("Less...");
    });
            } else {
                $j("#navLearn .island .morePubs").slideUp("slow",
    function () {
        $j("#navLearn .trigger").attr("title", "More...");
        $j("#navLearn .trigger").text("More...");
    });
            }

            return false;
        });
    }
    //Related News - more news slider effect. 
    if ($j(".finddoctor .island a.trigger").length != 0) {
        $j(".finddoctor .island .more").hide();
        $j(".finddoctor .island a.trigger").click(function () {
            if ($j(".finddoctor .island a.trigger").text() == "More...") {
                if ($j(".finddoctor .island .more").children().length % 2 != 0) {
                    //                            $j(".finddoctor .island a.trigger").animate({ 
                    //                                backgroundColor: "#F7F6F2" //#FFFFFF
                    //                            }, 1500 );

                    $j(".finddoctor .island a.trigger").parent().parent().removeClass("row3")
                    $j(".finddoctor .island a.trigger").parent().parent().addClass("row2")
                }
                $j(".finddoctor .island .more").slideDown("slow",
    function () {
        $j(".finddoctor .island a.trigger").attr("title", "Less...");
        $j(".finddoctor .island a.trigger").text("Less...");
    });
            } else {
                if ($j(".finddoctor .island .more").children().length % 2 != 0) {
                    //                            $j(".finddoctor .island a.trigger").animate({ 
                    //                                backgroundColor: "#FFFFFF"
                    //                            }, 1500 );
                    //                        
                    $j(".finddoctor .island a.trigger").parent().parent().removeClass("row2")
                    $j(".finddoctor .island a.trigger").parent().parent().addClass("row3")
                }
                $j(".finddoctor .island .more").slideUp("slow",
    function () {
        $j(".finddoctor .island a.trigger").attr("title", "More...");
        $j(".finddoctor .island a.trigger").text("More...");
    });
            }

            return false;
        });
    }

    if ($j('.infofor select').length != 0) {
        $j('.infofor select').templatedSelect({
            getOption: function (v, t) {
                return "" + t;
            }
        });
    }

    $j('.iwantnav input').remove();
    $j('.infofor input').remove();

    if ($j('.iwantnav .navdrop').length != 0) {
        $j('.iwantnav .navdrop').templatedSelect({
            getOption: function (v, t) {
                return "" + t;
            }
        });
    }

    /**** Health Tools Quiz Pop-Ups ****/
    $j(".ht_quiz_popup").each(function (index, item) {
        //switch href to "#"

        var newLink = $j(item).clone();
        var url = newLink.attr("href");
        newLink.attr("href", "#");
        newLink.attr("target", "");
        newLink.insertBefore($j(item));
        $j(item).remove();

        //add click event to open popup
        newLink.click(function () {
            window.open(url, "Quiz", "height=480,width=400");
            return false;
        });
    });

    /**** All tabs control ****/
    if ($j("#maincontent .finddoctor .island .tabs").length != 0 && $j("#maincontent .healthcarepro").length == 0) {
        $j("#maincontent .finddoctor .tabs li a").click(function () {
            //Remove the active class from all tabs.
            $j("#maincontent .finddoctor .tabs li a").removeClass("active");
            //removes "by" returns the rest. 
            tab = $j(this).attr("class").substring(2).toLowerCase();
            //Hide all tab/options
            $j("#maincontent .finddoctor .tabs li a").each(function (index, item) {
                tempTab = $j(item).attr("class").substring(2).toLowerCase();
                if (tempTab != tab) {
                    $j("#maincontent .finddoctor .island div[class='" + tempTab + "']").hide();
                }
            });
            //make the clicked tab active. 
            $j(this).addClass("active");
            //Show the one clicked. 
            $j("#maincontent .finddoctor .island div[class='" + tab + "']").show();
            //Set the SpecialtySearchType ** May not be needed. 
            $j("#specialtySearchType input").attr("value", tab);

            var isFindDoctor = false;
            if ($j("#maincontent .healthcarepro").length > 0)
                isFindDoctor = true;

            var isRelated = $j(this).parents().hasClass("AZIndex");

            //D+S,D+C,T+T, FD
            if (tab == "other") {
                //attach event change dropdown              
                //$("#developer").change(onSelectChange); 

                $j("#maincontent .finddoctor .rowList").hide();
                $j("#maincontent .finddoctor .rowList2").hide();
                $j("#maincontent .finddoctor .rowList3").show();
                //get all others

            } else if (tab == "keyword") {
                //ajax button
                $j("#maincontent .finddoctor .keyword .goContainer").html("<input type=\"button\" class=\"go\" onclick=\"javascript:GetDataFromKeyword(null);\" />");
                //bind enter key to ajax button                
                $j("#maincontent .finddoctor .keyword .search input").bind("keydown", function (event) {
                    // track enter key
                    var keycode = (event.keyCode ? event.keyCode : (event.which ? event.which : event.charCode));
                    if (keycode == 13) { // keycode for enter key
                        // force the 'Enter Key' to implicitly click the Update button
                        $j("#maincontent .finddoctor .keyword .go").click();
                        return false;
                    } else {
                        return true;
                    }
                }); // end of bind function

                //reset value field
                $j("#maincontent .finddoctor .keyword input").attr("value", "Search...");

                //if D&S clear keyword results
                if ($j("#maincontent .departmentsandservices").length > 0)
                    $j("#maincontent .finddoctor .rowList2").html("");

                if (isFindDoctor) {
                    $j("#maincontent .finddoctor .rowList2").html("");
                    $j("#maincontent .finddoctor .rowList3").hide();
                }

                $j("#maincontent .finddoctor .rowList").hide();
                $j("#maincontent .finddoctor .rowList2").show();

            }
            else if (tab == "showall") {
                $j("#maincontent .finddoctor .rowList").show();
                //get all data                    
                if (isRelated) {
                    GetRelatedData("all", null);
                }
                else {
                    GetDataFromCategory("all", null);
                }
            }
            else {
                if ($j(".index-list li a").length > 0) {
                    $j(".index-list li a").each(function (index, item) {
                        $j(item).removeClass("active");
                    });
                    //get all data                    
                    if (isRelated) {
                        GetRelatedData("all", null);
                    }
                    else {
                        GetDataFromCategory("all", null);
                    }
                } else if ($j("#maincontent .departmentsandservices").length > 0) {
                    //reset dropdown
                    $j("#maincontent .finddoctor .health-box .select-current-val").html("- Any Healthcare Service -");
                    //get all data
                    if (isRelated) {
                        GetRelatedData("all", null);
                    }
                    else {
                        GetDataFromCategory("all", null);
                    }
                }

                if (isFindDoctor) {
                    //attach event change dropdown              
                    //$("#developer").change(onSelectChange); 
                    $j("#maincontent .finddoctor .rowList3").hide();
                }

                $j("#maincontent .finddoctor .rowList").show();
                $j("#maincontent .finddoctor .rowList2").hide();
            }

            return false;
        });
    }

    //Departments and Services. 
    if ($j('.specialty .options .select-health').length != 0) {
        $j('.specialty .options .select-health').templatedSelect({
            getOption: function (v, t) {
                return "" + t;
            }
        });
    }

    /****  Find a doctor select boxes. ****/
    //Specialty 
    if ($j('.specialty .options .select-specialty').length != 0) {
        $j('.specialty .options .select-specialty').templatedSelect({
            getOption: function (v, t) {
                return "" + t;
            }
        });
    }

    //Other healthcare professionals 
    if ($j('.other .options .select-other-specialty').length != 0) {
        $j('.other .options .select-other-specialty').templatedSelect({
            getOption: function (v, t) {
                return "" + t;
            }
        });
    }
    if ($j('.focus .select-affiliation').length != 0) {
        $j(".focus select").each(function (index, item) {
            if (!$j(item).hasClass("select-subspecialty")) {
                $j(item).templatedSelect({ getOption: function (v, t) { return "" + t; } });
            } else if ($j(item).hasClass("select-subspecialty") &&
                    !$j(item).parent().hasClass("hide")) {
                $j(item).templatedSelect({ getOption: function (v, t) { return "" + t; } });
            }
        });
    }
    /*
    //Other Specialty 
    if ($j('.other .select-specialty').length != 0) {
    $j('.other .select-specialty').templatedSelect({
    getOption: function(v, t) {
    return "" + t;
    }
    });
    }

    //Other Area of Focus
    if ($j('.otherfocus .select-focus').length != 0) {
    $j('.otherfocus .select-focus').templatedSelect({
    margin: "8px 0 8px 84px",
    getOption: function(v, t) {
    return "" + t;
    }
    });
    }
    */

    //Clear Search... from keyword search. 
    if ($j("#maincontent .finddoctor .keyword .search input").length != 0) {
        $j("#maincontent .finddoctor .keyword input").bind("blur", function () { resetKeyword(); });
        $j("#maincontent .finddoctor .keyword input").bind("focus", function () { clearKeyword(); });
    }

    //Reset keyword
    function resetKeyword() {
        var keywordInput = $j("#maincontent .finddoctor .keyword input");
        if ((keywordInput.attr("value").length == 0) | (keywordInput.attr("value") == "Search...")) {
            keywordInput.attr("value", "Search...");
        }
    }

    //clear keyword
    function clearKeyword() {
        var keywordInput = $j("#maincontent .finddoctor .keyword input");
        if (keywordInput.attr("value") == "Search...") {
            keywordInput.attr("value", "");
        }
    }

    //Clear Search... from site search
    if ($j(".main #header .search input").length != 0) {
        $j(".main #header input").bind("blur", function () { resetKeyword1(); });
        $j(".main #header input").bind("focus", function () { clearKeyword1(); });
    }

    //Reset keyword
    function resetKeyword1() {
        var keywordInput = $j(".main #header .search input");
        if ((keywordInput.attr("value").length == 0) | (keywordInput.attr("value") == "Search")) {
            keywordInput.attr("value", "Search");
        }
    }

    //clear keyword
    function clearKeyword1() {
        var keywordInput = $j(".main #header .search input");
        if (keywordInput.attr("value") == "Search") {
            keywordInput.attr("value", "");
        }
    }


    /**** End of Find a doctor scripts *****/

    expandCollapse();

    if ($j("#maincontent .finddoctor").length > 0 && $j("#maincontent .healthcarepro").length == 0) {
        //startup pagination
        SetPaginationAjax("all", 0);
    }

    //enable all ajax compare button
    if ($j("#maincontent .finddoctor .btnCompareAjax").length > 0) {
        //display compare button
        $j("#maincontent .finddoctor .btnCompareAjax").each(function (index, item) {
            $j(item).show();
        });

        //display Name sort button
        $j("#content_0_threecolumncontent_0_btnSortName").show();
        $j("#content_0_threecolumncontent_0_btnSortNameOther").show();


        //remove padding from results title
        $j("#maincontent .healthcarepro .rowList .row1 .name").css("padding-bottom", "0");
        $j("#maincontent .healthcarepro .rowList3 .row1 .name").css("padding-bottom", "0");
    }

    //startup A-Z list
    $j(".index-list li a").attr("href", "javascript:void(0);");

    $j(".index-list li a").click(function () {
        if ($j(this).hasClass("emptyletter")) {
            return false;
        }

        var isRelated = $j(this).parents().hasClass("AZIndex");

        if (!$j(this).hasClass("active")) {
            $j(".index-list li a").each(function (index, item) {
                $j(item).removeClass("active");
            });
            $j(this).addClass("active");
            if (isRelated)
                GetRelatedData($j(this).html(), null);
            else
                GetDataFromCategory($j(this).html(), null);
        } else {
            $j(this).removeClass("active");
            if (isRelated)
                GetRelatedData("all", null);
            else
                GetDataFromCategory("all", null);
        }
    });

    //Error handling for Forms
    $j(".contactForm .submit").click(function () {
        var summary = "";

        $j(".contactForm input.req").each(function (index, item) {
            //console.log($j(item));            
            if ($j(item).attr("value") == "" || $j(item).attr("value").length == 0)
                summary = "Required fields can not be blank.\n";
        });

        $j(".contactForm select.req").each(function (index, item) {
            if ($j(item).val() == "Any State" ||
                $j(item).val() == "Please Select" ||
                $j(item).val() == "Month" ||
                $j(item).val() == "Day" ||
                $j(item).val() == "Year") {
                summary = "Required fields can not be blank.\n";
            }
        });

        if ($j(".contactForm .reqemail").attr("value") != "" &&
            $j(".contactForm .reqemail").attr("value").length != 0) {
            if (!isEmail($j(".contactForm .reqemail").attr("value")))
                summary += "Please verify the email address.\n";
        }

        if ($j(".contactForm .reqradio").length != 0) {
            var ischecked = false;
            $j(".contactForm .reqradio .radio").each(function (index, item) {
                if ($j(item).attr("checked"))
                    ischecked = true;
            });
            if (!ischecked)
                summary = "Required fields can not be blank.\n";
        }

        if (summary == "") {
            return true;
        } else {
            window.scrollTo(0, 0);
            alert(summary);
            return false;
        }
    });

    //Modal start up 
    $j('.defaultDOMWindow').openDOMWindow({ eventType: 'click' });
    $j('.DOMWindow820').openDOMWindow({ eventType: 'click', height: 640, width: 820 });
    $j('.patientStoryDOMWindow').openDOMWindow({ eventType: 'click', height: 680, width: 620 });
    $j('.doubleWideDOMWindow').openDOMWindow({ eventType: 'click', height: 680, width: 720 });

    /* select click out */
    $j("body").click(function () {
        if (i == 0) {
            if ($j("div .select-options:visible").length != 0)
                i++;
        }
        else {
            $j("div .select-options").hide();
            i = 0;
        }
    });

    //attach even keyword search finddoctor
    $j(".finddoctor .search input").keypress(function (e) {
        if (e.which == 13) {
            $j(".goContainer input").click();
        }
    });

    /* Auto-rotator */
    // Shows only the first item of all the rotators
    $j('.auto-rotator ul.rotating li').hide();
    $j('.auto-rotator ul.rotating li:first-child').show().addClass('showing');
    // Set up navigation if needed
    $j('#coe-rotator .rotator-nav').each(function () {
        var navString = "";
        var thisNav = $j(this);
        var thisRotator = $j(this).parent('.auto-rotator');
        // Adds the "pagination" class to the rotator nav -- for styling
        thisNav.addClass('pagination');
        // Use the number of elements to set the position of the nav
        var count = thisRotator.find('ul.rotating li').size();
        var offset = 420 - count * 11;
        navString = navString + '<ul><li class="arrow prev" style="margin-right:' + offset + 'px;"><a><img src="http://www.jeffersonhospital.org/images/arrow-prev.gif"></a></li>';
        thisRotator.find('ul.rotating li').each(function () {
            var itemIndex = thisRotator.find('ul.rotating li').index($j(this));
            navString = navString + '<li class="number"><a>&bull;</a></li>';
            //navString = navString + '<li class="number"><a>' + (itemIndex + 1) + '</a></li>';
        });
        navString = navString + '<li class="arrow next"><a><img src="http://www.jeffersonhospital.org/images/arrow01.gif"></a></li></ul>';
        thisNav.append(navString);
    });
    $j('.auto-rotator .rotator-nav').each(function () {
        var thisNav = $j(this);
        // Make the nav show the first one is current.
        thisNav.find('li.number:first').addClass('current');
        thisNav.find('li.number').show();
    });
    // Wrap the navigation in an a to activate it.
    $j('.rotator-nav li.number').wrapInner('<a>');
    // When you click a number, it goes to that item
    $j('.rotator-nav li.number a').click(function () {
        // Removes the class "current" from whatever number has it. Then gets the index of the one that's been clicked.
        var i = $j(this).parents('.rotator-nav').find('li.number').removeClass('current').index($j(this).parents('li.number').addClass('current'));
        // Stops the rotation, then gets the corresponding item in the rotating list. Sets this class to current, the corresponding item to showing, hides and removes class from the one that's already showing.
        $j(this).parents('.auto-rotator').unbind().find('ul.rotating li.showing').removeClass('showing').hide().parents('.auto-rotator').find('ul.rotating li:eq(' + i + ')').addClass('showing').fadeIn('fast');
    });
    // Arrows go back and forth
    $j('.rotator-nav li.arrow, .intro-rotator-nav li.arrow').show().click(function () {
        var theNav = $j(this).parent('.rotator-nav ul');
        var theRotator = $j(this).parents('.auto-rotator').unbind('auto-rotate');
        var nextItem;
        var nextNav;
        if ($j(this).hasClass('next')) {
            nextItem = theRotator.find('ul.rotating li:last-child').hasClass('showing') ? theRotator.find('ul.rotating li:first-child') : theRotator.find('ul.rotating li.showing').next();
            nextNav = theNav.find('li.number:last').hasClass('current') ? theRotator.find('li.number:first') : theRotator.find('li.current').next('.number');
        } else {
            nextItem = theRotator.find('ul.rotating li:first-child').hasClass('showing') ? theRotator.find('ul.rotating li:last-child') : theRotator.find('ul.rotating li.showing').prev();
            nextNav = theNav.find('li.number:first').hasClass('current') ? theRotator.find('li.number:last') : theRotator.find('li.current').prev('.number');
        }
        theNav.find('li.current').removeClass('current');
        nextNav.addClass('current');
        theRotator.find('ul.rotating li.showing').removeClass('showing').fadeOut('slow');
        nextItem.addClass('showing').fadeIn('fast');
    });
    // Binds the rotate event to the rotators
    $j('.auto-rotator').bind('auto-rotate', function () {
        var nextItem = $j(this).find('ul.rotating li:last-child').hasClass('showing') ? $j(this).find('ul.rotating li:first-child') : $j(this).find('ul.rotating li.showing').next();
        var i = $j(this).find('ul.rotating li').index(nextItem);
        $j(this).find('.rotator-nav li.number').removeClass('current');
        $j(this).find('.rotator-nav li.number:eq(' + i + ')').addClass('current');
        $j(this).find('ul.rotating li.showing').removeClass('showing').fadeOut('slow');
        nextItem.addClass('showing').fadeIn('fast');
        if ($j(this).is('#kit-rotator')) {
            // For KIT, makes the TOC scroll too.
            selectItemFromList(i - 1);
        }
    });

    // Sets the US News logo to rotate (seconds * 1000)
    var usnewsint = setInterval(function () { $j('#usnews-rotator').trigger('auto-rotate'); }, 2000);
    // Sets the promos on the home page to rotate (seconds * 1000)
    var promoint = setInterval(function () { $j('#promo-rotator').trigger('auto-rotate'); }, 4500);
    // Sets the article rotator on the KIT home page
    var kitint = setInterval(function () { $j('#kit-rotator').trigger('auto-rotate'); }, 4000);
    // Sets the intro rotator on the home page to rotate (seconds * 1000)
    var introint = setInterval(function () { $j('#intro-rotator').trigger('auto-rotate'); }, 4000);
    // Sets the COE rotator to rotate (seconds * 1000)
    var coeint = setInterval(function () { $j('#coe-rotator').trigger('auto-rotate') }, 4000);
    // Sets the microsite/knowledge portal rotator to rotate (seconds * 1000)
    var microint = setInterval(function () { $j('#micro-rotator').trigger('auto-rotate') }, 4000);

    // Sets up Staywell tracking (cross domain issue)
    $j('a[href*="staywellsolutionsonline.com"]').attr('onclick', 'return gaOpenWindow(this);');

    // Accordion
    $j("div.accordion-element").hide();
    $j(".accordion-toggler.open").removeClass("open");
    $j(".accordion-toggler").click(function () {
        $j(".accordion-toggler.open").removeClass("open").filter('a:contains("Read less")').text('Read more');
        $j("div.accordion-element").slideUp("400");
        if ($j(this).next().is(":hidden")) {
            $j(this).next().slideDown("400");
            $j(this).addClass("open");
            $j(this).filter('a:contains("Read more")').text('Read less');
        }
    });
    // If the accordion contains a form error warning, load page with accordion already open.
    $j("div.accordion-element:has(.scfValidationSummary:has(ul))").show().parent().children(".accordion-toggler").addClass("open");
    // If the accordion contains a form success/failure message, load page with accordion already open.
    $j("div.accordion-element:has(.scfForm:has(.postback))").show().parent().children(".accordion-toggler").addClass("open");

    // Fancybox settings for Event Calendar
    $j('a.colorbox').fancybox({
        'width': 787,
        'height': '140%',
        'autoScale': false,
        'scrolling': 'no',
        'transitionIn': 'elastic',
        'transitionOut': 'none',
        'type': 'iframe',
        'padding': 0,
        'margin': 0,
        'overlayColor': '#fff',
        'overlayShow': false,
        'hideOnOverlayClick': false,
        'showCloseButton': false,
        'titleShow': false,
        'onComplete': function () {
            $j("#fancybox-wrap").removeClass("notch");
        }
    });
    $j('a.colorbox-related').fancybox({
        'width': 787,
        'height': '140%',
        'autoScale': false,
        'scrolling': 'no',
        'transitionIn': 'elastic',
        'transitionOut': 'none',
        'type': 'iframe',
        'padding': 0,
        'margin': 0,
        'overlayColor': '#fff',
        'overlayShow': false,
        'hideOnOverlayClick': false,
        'showCloseButton': false,
        'titleShow': false,
        'onComplete': function () {
            $j("#fancybox-wrap").addClass("notch");
        }
    });
});


/* GLOBAL FUNCTIONS 
=====================================*/

/* email validation */
function isEmail(str)
{
var regex = /^[-_.a-z0-9]+@(([-_a-z0-9]+\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i;
return regex.test(str);
}


/* stop events */
function stopEvent(e) {
    if (e.stopPropagation) 
        e.stopPropagation();
    else 
        e.cancelBubble = true;

    if (e.preventDefault) 
        e.preventDefault();
    else 
        e.returnValue = false;
} 
 
function AttachToInput () {
    $j(".pagination ul li input").click(function() {
        if ($j(".index-list li a.active").length > 0)
            param = $j(".index-list li a.active").html();
        else if ($j("#specialtySearchType input").val() == 'specialty')
            param = $j('.specialty .select-health').val();
        else
            param = "all";
        
        var isRelated = $j(this).parents().hasClass("AZIndex");

        if (isRelated) {
            GetRelatedData(param, $j(this).val());
        }
        else {
            GetDataFromCategory(param, $j(this).val());
        }
        return false;
    });
}

function expandCollapse() {
    //expandable items
    $j(".expandable li").each(function(index, item) {
        //initialize   
        var title = $j(item).children(":first").attr("title");
        if (title != "" && title != null)
            title = title.toLowerCase();
        if (title != "collapse") {
            $j(item).children(".collapse").removeClass("collapse").addClass("expand");
            $j(item).children("ul").css("display", "none");
        }
        if (title == "expand") {
            $j(item).children(".expand").removeClass("expand").addClass("collapse");
            $j(item).children("ul").css("display", "block");
        }


        //if D+S
        if ($j(".departmentsandservices").length > 0) {
            $j(item).children("span").children(".collapse").removeClass("collapse").addClass("expand");
            $j(item).children("span").children("ul").css("display", "none");

            $j(item).children("span").children(":first").click(function() {
                if ($j(this).hasClass("expand")) {
                    $j(this).next().next().slideDown();
                    $j(this).removeClass("expand").addClass("collapse");
                } else if ($j(this).hasClass("collapse")) {
                    $j(this).next().next().slideUp();
                    $j(this).removeClass("collapse").addClass("expand");
                }
            });
        }

        //attach events
        $j(item).children(":first").click(function() {
            if ($j(this).hasClass("expand")) {
                $j(this).next().next().slideDown();
                $j(this).removeClass("expand").addClass("collapse");
            } else if ($j(this).hasClass("collapse")) {
                $j(this).next().next().slideUp();
                $j(this).removeClass("collapse").addClass("expand");
            }
        });
        $j(item).children(".folder").click(function() {
            $j(item).children(":first").trigger("click");
        });
        $j(item).children(".year").click(function() {
            $j(item).children(":first").trigger("click");
        })
        .attr("href", "javascript:void(0);");
    });
}


function GetDataFromCategory(param, page){
   //param = selected letter   
   //page = current page number    
   
   if($j("#maincontent .finddoctor .rowList").css('display')=='block'){
    
        searchType = "diseasesandconditions";
        if(page == null){
            page = "1";
        }

        var page_size = 20;   
        
       if($j("#maincontent .departmentsandservices").length>0){
            if($j("#maincontent .departmentsandservices .byIndex").hasClass("active")){
                searchType = "departmentsandserviceslist";
            }else{
                searchType = "departmentsandservices";
            }
            if ($j("#maincontent .departmentsandservices .byShowAll").hasClass("active")) {
                page_size = -1;
                param = "all"
            }
       }else if($j("#maincontent .testsandtreatments").length>0){
            searchType = "testsandtreatments";
       }
       
       //remove search results
       $j('.listSearchResults').each(function(i, item){
            $j(item).remove();
       });   
       $j('.pagination').each(function(i, item){
            $j(item).remove();
       });
       //show loader
       $j('#loading').show();
       //hide list
       $j('.rowList').hide();
       
       var urlString = "/utilities/AjaxServices.asmx/CategorySearchPagination";              
       
       if (typeof(param) == 'undefined')
           param = "all";
          
       jQuery.ajax({
          type: "POST",
          url: urlString,
           data: '{"param":"' + param + '","searchType":"' + searchType + '", "ajax":1, "page":' + page + ', "page_size":' + page_size + '}',
           contentType: "application/json; charset=utf-8",
          dataType: "json",
          success: function(result) {
            //var options = "";            
            if(searchType == "departmentsandservices"){            
                //Set the pagination title to the selected item. 
                title = $j(".health-box .select-current-val").text();
                if(title == "- Any Healthcare Service -"){
                    title = "All Departments &amp; Services"; 
                }
                $j(".pagination .page-title").text(title);                       
            }       
            $j(".rowList").html(result.d); 
                
            //hide loader
            $j('#loading').hide();
            //show results
            $j('.rowList').show();
            //collapse
            expandCollapse();
            //AttachToInput();      
            //pagination ajax
            SetPaginationAjax(param, 0);
        }
      });
   }
}


function GetDataFromKeyword(page){
   //page = current page number
   
   searchType = "diseasesandconditions";    
   if($j("#maincontent .healthcarepro").length>0){
        searchType = "healthcareprofessionals";
   }else if($j("#maincontent .departmentsandservices").length>0){
        searchType = "departmentsandservices";
   }else if($j("#maincontent .testsandtreatments").length>0){
        searchType = "testsandtreatments";
   }
   
    if(page == null){
        page = "1";
    }
    
   //remove search results
   $j('.rowList2 .listSearchResults').each(function(i, item){
        $j(item).remove();
   });   
   $j('.rowList2 .pagination').each(function(i, item){
        $j(item).remove();
   });
   
   //show loader
   $j('#loading').show();
   //hide list
   $j('.rowList2').hide();
   
   var urlString = "/utilities/AjaxServices.asmx/GetDataKeyword";   
   var page_size = 20; 
   
   if (typeof(param) == 'undefined')
    param = "";
         
   jQuery.ajax({
      type: "POST",
      url: urlString,
       data: '{"keyword":"' + $j("#maincontent .finddoctor .keyword input").val() + '","searchType":"' + searchType + '", "page":' + page + ', "pageSize":' + page_size + '}',
       contentType: "application/json; charset=utf-8",
      dataType: "json",
      success: function(result) {
        $j(".rowList2").html(result.d);        
            
        //hide loader
        $j('#loading').hide();
        //show results
        $j('.rowList2').show();
        //collapse
        expandCollapse();
        //AttachToInput();        
        //pagination ajax
        SetPaginationAjax(param, 1);
      }
    });
}

function SetPaginationAjax(param, type){
    // 0 = category, 1 = keyword, 2 = other, 3 = related_list   
    
    paginationType = "rowList";
    if (type == 1)
        paginationType = "rowList2";
    else if (type == 2)
        paginationType = "rowList3";
    else if (type == 3)
        paginationType = "related_list";
    
    var isRelated = ($j(".AZIndex").length != 0);

    $j("#maincontent .finddoctor ." + paginationType + " .pagination ul li").each(function(index, item) {
        if ($j(item).children("input").length > 0) {

            if (isRelated) {
                var oldButton = $j(item).children("input");
                var value = oldButton.attr("value");
                
                $j(item).html("<input type='button' name='" + oldButton.attr("name") + "' class='" + oldButton.attr("class") + "' value='" + oldButton.attr("value") + "' />");
                
                //attach event
                var newButton = $j(item).children("input");
                newButton.click(function() {
                    if ($j(".index-list li a.active").length > 0) {
                        var letter = $j(".index-list li a.active").html();
                    }
                    else {
                        var letter = "all";
                    }
                    GetRelatedData(letter, value);
                });

            }
            else {
                //attach event            
                $j(item).children("input").click(function() {

                    if (type == 1) {
                        GetDataFromKeyword($j(item).children("input").attr("value"));
                    } else {
                        GetDataFromCategory(param, $j(item).children("input").attr("value"));
                    }
                });
            }
        }
    });
}

function onChangeHealthSelect(){
    //show loading
    $j(".options .subloading").show();
    
    //populate filter ajax    
    jQuery.ajax({
      type: "POST",
      url: "/utilities/AjaxServices.asmx/GetSpecialtySubspecialty",
       data: '{"param":"' + $j('.specialty-box .select-specialty').val() + '"}',
       contentType: "application/json; charset=utf-8",
      dataType: "json",
      success: function(result) {
        if(result.d!=""){
            
            if($j(".subspecialty div.select-container").length > 0){
                //remove custom select
                $j(".subspecialty div.select-container").remove();
                //clean select
                $j(".subspecialty div select option").remove();
            }
                    
            //add option
            for(i=0;i<result.d.length;i++){
                $j(".subspecialty div select").append(result.d[i]);
            }
            //select first index
            $j(".subspecialty div select")[0].selected = true;
            
            //format select
            $j('.focus .select-subspecialty').templatedSelect({getOption: function(v, t) {return "" + t;}});            
            //show area of focus
            $j(".subspecialty div").removeClass("hide");
        }else{
            //hide area of focus
            $j(".subspecialty div").addClass("hide");
        }
        $j(".options .subloading").hide();
      }
    });
}

function GetRelatedData(param, page) {
    //param = selected letter   
    //page = current page number
    
    searchType = $j("#searchType").attr("value");
    source_id = $j("#source_id").attr("value");
            
    if (page == null) {
        page = "1";
    }

    var page_size = 10;        
    
    //show loader
    $j('#loading').show();

    //hide list
    $j('.related_list').hide();


    var urlString = "/utilities/AjaxServices.asmx/RelatedIndexPagination";

    if (typeof (param) == 'undefined')
        param = "all";

    jQuery.ajax({
        type: "POST",
        url: urlString,
        data: '{"letter":"' + param + '","searchType":"' + searchType + '", "ajax":1, "page":' + page + ', "page_size":' + page_size + ', "source_id":"' + source_id + '"}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(result) {
            $j('.related_list').html(result.d);
            //hide loader
            $j('#loading').hide();
            //show results
            $j('.related_list').show();
            //collapse
            expandCollapse();
            //pagination
            SetPaginationAjax(param, 3);
        }
    });
}
// For tracking cross-domain links
function gaOpenWindow(link) {
    _gaq.push(function() {
        var tracker = _gaq._getAsyncTracker();
        window.open(tracker._getLinkerUrl(link.href));
    });
    return false;
}
// Limelight event tracking
var currentVideoTitle;
var alreadyPlayed = false;
function delvePlayerCallback(playerId, eventName, data) {
    var id = "limelight_player";
    if (eventName == 'onPlayerLoad' && (DelvePlayer.getPlayers() == null || DelvePlayer.getPlayers().length == 0)) {
        DelvePlayer.registerPlayer(id);
    }

    switch (eventName) {
        case 'onMediaLoad':
            currentVideoTitle = data.title;
            break;
        case 'onPlayStateChanged':
            if (data.isPlaying) {
                if (!alreadyPlayed) {
                    alreadyPlayed = true;
                    _gaq.push(['_trackEvent', 'Videos', 'Play', currentVideoTitle]);
                }
            }
            break;
        case 'onMediaComplete':
            _gaq.push(['_trackEvent', 'Videos', 'Completed', data.title]);
            break;
    }
}

// Get query string variable
urlParam = function (name) {
    var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
    if (!results) { return 0; }
    return results[1] || 0;
}

function openApptForm() {
    var refpage = urlParam("refpage");
    var docpage = urlParam("docpage");
    var refstring = '';
    if (refpage != 0) {
        refstring = "?refpage=" + refpage;
        if (docpage != 0) {
            refstring = refstring + "&docpage=" + docpage;
        }
    } else if (docpage != 0) {
        refstring = "?docpage=" + docpage;
    }
    apptwinObj = window.open(
        '/forms/AppointmentRequestForm.aspx' + refstring,
        'apptwin', 
        'height=840,width=840,directories=0,menubar=0,resizable=1,scrollbars=1,status=1,location=0,toolbar=0'
        );
    if (apptformwin == null || apptformwin.closed) {
        apptformwin = openFormWindow();
    } else {
        apptformwin.focus(); 
    }
}

function openIntApptForm() {
    apptwinObj = window.open(
        'https://apps.jeffersonhospital.org/jeffnow_appointment_form/apptfrm_int.cfm?tjuh++++0',
        'apptwin',
        'height=840,width=650,directories=0,menubar=0,resizable=1,scrollbars=1,status=1,location=0,toolbar=0'
        );
    if (apptformwin == null || apptformwin.closed) {
        apptformwin = openFormWindow();
    } else {
        apptformwin.focus();
    } 
}
