$j(document).ready(function () {

    //equalize heights of two column verticals

    function EqualizeButtons() {
        var offset1 = $j('.col:nth-child(1)', '.twocolumnvertical').children('.list-menu').offset();
        var offset2 = $j('.col:nth-child(2)', '.twocolumnvertical').children('.list-menu').offset();

        var difference = (offset1.top - offset2.top < 0) ? offset2.top - offset1.top : offset1.top - offset2.top;

        if (offset1.top > offset2.top) {
            var currentMargin = $j('.col:nth-child(1) .list-menu', '.twocolumnvertical').css('margin-top').replace('px', '');
            var newMargin = currentMargin - difference;
            var formattedDifference = newMargin + 'px';
            console.log(formattedDifference);
            $j('.col:nth-child(1) .list-menu', '.twocolumnvertical').css('margin-top', formattedDifference);
        }
        else {
            var currentMargin = $j('.col:nth-child(2) .list-menu', '.twocolumnvertical').css('margin-top').replace('px', '');
            var newMargin = currentMargin - difference;
            var formattedDifference = newMargin + 'px';
            $j('.col:nth-child(2) .list-menu', '.twocolumnvertical').css('margin-top', formattedDifference);
        }
    }

    var maxHeight = 0;

    $j('.col', '.twocolumnvertical').each(
        function () {
            var thisHeight = 0;
            var col = $j(this);
            $j(this).children().each(
                function () {
                    if (col.data('height') != null)
                        col.data('height', $j(this).outerHeight() + col.data('height'));
                    else
                        col.data('height', $j(this).outerHeight());
                }
            );
        }
    );

    if ($j('.col', '.twocolumnvertical').length == 2) {
        var col1 = $j('.col:nth-child(1)', '.twocolumnvertical');
        var col2 = $j('.col:nth-child(2)', '.twocolumnvertical');

        var difference = (col1.data('height') - col2.data('height') < 0) ? col2.data('height') - col1.data('height') : col1.data('height') - col2.data('height');

        if (col1.data('height') < col2.data('height')) {
            col1.children().last().prev().after('<div style="height: ' + difference + 'px;"></div>');
            EqualizeButtons();
        }
        else {
            col2.children().last().prev().after('<div style="height: ' + difference + 'px;"></div>');
            EqualizeButtons();
        }
    }

    //ShareThis button implementation

    $j.fn.AddShareThis = function (AddAfter) {
        var html = "<div class='sharethisstuff-outter'><div class='sharethisstuff-inner'><span  class='st_twitter_large' ></span><span  class='st_facebook_large' ></span><span  class='st_email_large' ></span><span  class='st_sharethis_large' ></span></div></div>";
        if (AddAfter) {
            $j(this).after(html);
        }
        else {
            $j(this).prepend(html);
        }
    }

    //if left column
    if ($j('.split-right', '.content-container').length > 0) {
        //if has navigation
        if ($j('.sub-section-menu', '.sidebar').length > 0) {
            $j('.sidebar .sub-section-menu:first-child').AddShareThis(true);
        }
        //else
        else {
            $j('.sidebar:first-child').AddShareThis(false);
        }
    }

    //else if right column
    else if ($j('.split-left', '.content-container').length > 0) {
        $j('.sidebar', '.content-container').AddShareThis(false);
    }

    //else if hero image
    else if ($j('.hero', '.content-container').length > 0) {
        $j('.section-content.full .main-column').AddShareThis(false);
        $j('.sharethisstuff-outter').css('text-align', 'right');
    }

    $j('.open-button', '.list-menu').next('.thirdtierchildren').css('display', 'none');
    $j('.current-open', '.list-menu').next('.thirdtierchildren').css('display', 'block');

    $j('.open-button', '.list-menu').bind('click',
        function () {
            var ChildMenu = $j(this).next('.thirdtierchildren');
            var DisplayProp = ChildMenu.css('display');
            if (DisplayProp == 'block') {
                ChildMenu.css('display', 'none');
                $j(this).removeClass('current-open');
            }
            else {
                ChildMenu.css('display', 'block');
                $j(this).addClass('current-open');
            }
        }
    );


    $j('.section-menu li').hover(
        function () {
            $j(this).children('.subnavchildrencontainer').css('display', 'block');
        },
        function () {
            $j(this).children('.subnavchildrencontainer').css('display', 'none');
        }
    );

    //Set correct active state on seconday menu

    var activeCount = $j('.section-menu-container .section-menu li.active', '.content-container').size();

    if (activeCount > 1) {
        var lastElement = $j('.section-menu-container .section-menu li.active:last', '.content-container');
        $j('.section-menu-container .section-menu li.active', '.content-container').removeClass('active');
        lastElement.addClass('active');
    }

    $j('.header .search .button, .sidebar .search .button, .search-bar .button').val('');
    $j('.tabs').not('.clinics .tabs, .hospitals .tabs').tabs();

    $j('.box-tabs').each(function () {
        $j(this).find('.content').prepend($j(this).find('.ui-tabs-nav'));
    });

    $j('.big-num-list li.big-num-item').each(function () {
        $j(this).prepend(
										 $j('<div/>')
													 .addClass('num')
													 .text($j(this).index() + 1)
							);
    });

    $j('.teaser .meta-data').each(function () {
        $j(this).find('li').not(':last')
										 .append(
													 $j('<strong/>')
																	.addClass('divider')
																	.text('/')
										 );
    });

    // set default value for search
    SetText();

    $j('.search-results-bar:eq(1)').css('background-position', 'top').css('margin-bottom', '0');

    $j('.radio').dgStyle();
    $j('.checkbox').dgStyle();

    // Pairs of functions that work together

    $j('.find-location-search input[type="text"]').change(function () {
        $j('.find-location-search select.city').val('Search By City');
        if ($j(this).val() == '')
            SetText();
    });
    $j('.find-location-search select.city').change(function () {
        $j('.find-location-search input[type="text"]').val('');
        SetText();
    });

    $j('.find-location-search .button-container input').click(
        function () {
            SetText();
        }
    );



    $j('.find-doctor-search input.zip-code').change(function () { $j('.find-doctor-search select.city').val(''); });
    $j('.find-doctor-search select.city').change(function () { $j('.find-doctor-search input.zip-code').val(''); SetText(); });


    $j('.clear-the-text').click(function () { $j('.find-doctor-search input.specialist-type').val(''); SetText(); });

    function SetText() {
        $j('.search input[type="text"], .find-location-search input[type="text"],  .find-doctor-search input[type="text"], #share-your-story input[type="text"], #share-your-story textarea').each(function () {
            if ($j(this).attr('title') == $j(this).val() || $j(this).val() == '')
                $j(this).defaultvalue($j(this).attr('title'));
        });
    }

    $j('.doctor-card:odd').addClass('odd');

    $j('div.dialog').dialog({
        autoOpen: false,
        modal: true,
        width: 656
    });
    $j('a.dialog').click(function () {
        if ($j(this).hasClass('external-link')) {
            $j('#leaving-thedacare-dialog').dialog('open');
            var target = $j(this).attr('target') ? $j(this).attr('target') : '_self';
            $j('#leaving-thedacare-dialog .btn_leaving')
													 .attr('href', $j(this).attr('href'))
													 .attr('target', target)
													 .click(function () {
													     $j('#leaving-thedacare-dialog').dialog('close');
													 });
            $j('#leaving-thedacare-dialog .btn_stay').click(function () {
                $j('#leaving-thedacare-dialog').dialog('close');
            });
        } else if ($j(this).hasClass('video-link')) {
            $j('#video-dialog').dialog({
                title: $j(this).attr('title'),
                width: 860,
                open: loadVideoPlayer($j(this).attr('playerid'), $j(this).attr('videoid')),
                close: function () { $j('#video-player').html(''); }
            });
            $j('#video-dialog').dialog('open');
        }
        else if ($j(this).hasClass('short-article')) {

            var divid = $j(this).attr('divid') ? $j(this).attr('divid') : '';
            $j('#' + divid).dialog({
                title: $j(this).attr('title'),
                width: 610
            });
            $j('#' + divid).dialog('open');
        } else {
            $j($j(this).attr('href')).dialog('open');
        }
        return false;
    });

    /* fix drop downs */
    $j('.field-row').each(function () {
        $j(this).css('z-index', ($j('.field-row').length + 100) - $j(this).index());
    });

    var sizeChange = 45;

    var textSizeCookie = readCookie('textsizestyle');
    textsize = textSizeCookie ? textSizeCookie : 1.0;
    if (textsize < 1) {
        $j('.hospitals .box .teaser').ChangeSize(-sizeChange, textsize);
        $j('.clinics .box .tabs .ui-tabs-panel .clinic-col li').ChangeSize(-sizeChange + 10, textsize);
    }
    else if (textsize > 1) {
        $j('.hospitals .box .teaser').ChangeSize(sizeChange, textsize);
        $j('.clinics .box .tabs .ui-tabs-panel .clinic-col li').ChangeSize(sizeChange - 10, textsize);
    }
    fsize(textsize, 'em', '.content-container');

    $j('.text-size a').click(function () {
        if ($j(this).hasClass('larger')) {
            var changed = changetextsize(true);
            fsize(textsize, 'em', '.content-container');
            if (changed) {
                $j('.hospitals .box .teaser').ChangeSize(sizeChange, textsize);
                $j('.clinics .box .tabs .ui-tabs-panel .clinic-col li').ChangeSize(sizeChange - 10, textsize);
            }
        } else {
            var changed = changetextsize(false);
            fsize(textsize, 'em', '.content-container');
            if (changed) {
                $j('.hospitals .box .teaser').ChangeSize(-sizeChange, textsize);
                $j('.clinics .box .tabs .ui-tabs-panel .clinic-col li').ChangeSize(-sizeChange + 10, textsize);
            }
        }

        return false;
    });

    if ($j('ul.foundations').length <= 0) {
        $j('ul.section-menu').css('padding-right', '0');
    }
    $j('ul.section-menu').css('visibility', 'visible');

    $j('p.box-image').each(function () {
        if ($j(this).find('img').length <= 0)
            $j(this).hide();
        else
            $j(this).show();
    });
});

$j(document).ready(function () {
    //see if the freeze hash exists
    var FreezeLooping = false;
    if ($j('input[id$=CaptureHidden]').length > 0) {
        if ($j('input[id$=CaptureHidden]').val() == 'true')
            FreezeLooping = true;
    }

    $j('.carousel').anythingSlider({
        easing: "easeInOutExpo", 	// Anything other than "linear" or "swing" requires the easing plugin
        autoPlay: true, 				// This turns off the entire FUNCTIONALY, not just if it starts running or not.
        delay: 7000, 				// How long between slide transitions in AutoPlay mode
        startStopped: FreezeLooping, 			// If autoPlay is on, this can force it to start stopped
        animationTime: 1000, 		// How long the slide transition takes
        hashTags: true, 				// Should links change the hashtag in the URL?
        buildNavigation: true, 		// If true, builds and list of anchor links to link to each slide
        pauseOnHover: true, 			// If true, and autoPlay is enabled, the show will pause on hover
        startText: "Go", 			// Start text
        stopText: "Stop", 			// Stop text
        navigationFormatter: formatText	// Details at the top of the file on this use (advanced use)
    });

    $j('#thumbNav a').wrapInner('<span/>');
    function formatText(index, panel) {
        return index + "";
    }
    $j('.hero-slide').css('visibility', 'visible');
    Cufon.replace('.hero-slide h1, .hero-slide h4, .hero-slide h5', { fontFamily: 'Gotham Rounded Book' });
    $j('.hero-home .loading-animation').remove();


    if ($j('.toggle-search').length > 0) {
        $j('.search-box').css('padding-bottom', '29px');
    }

    $j('.toggle-search').live('click', function () {
        if ($j(this).find('span').text() == 'Minimize Search') {
            $j('.search-box .content').slideUp();
            $j(this).find('span').text('Search Again');
            $j(this).find('span').css('background-position', 'right -35px');
        } else {
            $j('.search-box .content').slideDown();
            $j(this).find('span').text('Minimize Search');
            $j(this).find('span').css('background-position', 'right 13px');
        }
        return false;
    });

});

$j(window).load(function () {
    
    $j('.video-link').each(function () {
        $j(this).prepend('<span/>');
    });
});

var loadVideoPlayer = function (pid, vid) {
    var playerHtml = '<object id="myExperience' + vid + '" class="BrightcoveExperience">' +
					 ' <param name="bgcolor" value="#000" />' +
					 ' <param name="width" value="860" />' +
					 ' <param name="height" value="484" />' +
					 ' <param name="playerID" value="' + pid + '" />' +
					 ' <param name="playerKey" value="AQ~~,AAAA1L6V3Bk~,-xnwAi7opVkvax-bynsIGI1YY6VQ7i--" />' +
					 ' <param name="isVid" value="true" />' +
					 ' <param name="isUI" value="true" />' +
					 ' <param name="dynamicStreaming" value="true" />' +
					 ' <param name="@videoPlayer" value="' + vid + '" />' +
					'</object>';
    $j('#video-player').prepend($j('<div/>'));
    $j('#video-player').append(playerHtml);

    //runMobileCompatibilityScript('flashObj');
    brightcove.createExperiences();
}

$j.fn.ChangeSize = function (sizeChange, textsize) {
    $j(this).height($j(this).height() + sizeChange);

    //change hero size, it's absolutely positioned so we need to do some adjusting
    if(textsize <= 1)
        $j('.hero').height('');
    else if (textsize > 1)
    {
        $j('.hero').height($j('.hero').height() + sizeChange);
    }
}
