﻿jQuery.fn.preload = function () {
    this.each(function () {
        jQuery('<img/>')[0].src = this;
    });
}

var hraWindow = '';

function InitPopup(url, features) {
    //checks to see if the popup is already open, if so, close
    if (!hraWindow.closed && hraWindow.location) {
        hraWindow.close();
    }

    hraWindow = window.open(url, 'mypopup', features);
    if (!hraWindow.opener) hraWindow.opener = self;
    if (hraWindow.closed) alert("It appears the page you requested is being blocked by pop-up blocking software. Please disable any pop-up blockers to view the page.");

    hraWindow.focus();

    return false;
}

function initializeMap() {
    var markers = new Array();

    var myOptions = {
        zoom: 14,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        mapTypeControl: false,
        streetViewControl: false,
        zoomControl: false
    }

    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

    if (mapData != null && mapData.Locations != null && mapData.Locations.length > 0) {

        jQuery.each(mapData.Locations, function (i) {
            var marker = new google.maps.Marker({
                position: new google.maps.LatLng(this.Latitude, this.Longitude),
                title: this.LocationName
            });

            if (mapData.ShowMultipleLocations) {
                var popup = jQuery('<div></div>');

                jQuery(popup).append('<div class="SubHeading"><a href="' + this.WellStarUrl + '">' + this.LocationName + '</a></div>');
                jQuery(popup).append('<div class="SpotBodyPurple">' + this.Address + '<div class="DirectionsBox">Get Directions from:<div class="AddressBoxWrapper"><input type="text" value="Address, City, Zip" class="AddressField" /></div></div></div>');
                jQuery(popup).append('<div style="margin-top:-5px;"><a class="MapDirectionsLink" href="#">Get Directions</a></div>');
                jQuery(popup).append('<span class="Url" style="display:none;">' + this.DirectionsUrl + '</span>');

                var ibOptions = {
                    content: jQuery(popup).html(),
                    pixelOffset: new google.maps.Size(15, -50),
                    boxStyle: {
                        width: "268px"
                    },
                    closeBoxURL: "/_layouts/images/WellStar/shared/btn_Close.gif",
                    infoBoxClearance: new google.maps.Size(1, 1)
                    ,
                    enableEventPropagation: true
                };

                var ib = new InfoBox(ibOptions);

                google.maps.event.addListener(marker, "click", function (e) {
                    ib.open(map, this);
                });
            }
            else {
                jQuery('#FooterDirectionsBox').append('<span class="Url" style="display:none;">' + this.DirectionsUrl + '</span>');
            }

            markers.push(marker);
        });

        if (mapData.ShowMultipleLocations) {
            jQuery(['/_layouts/images/WellStar/shared/bg_MapPopup.png', '/_layouts/images/WellStar/shared/btn_Close.gif']).preload();

            var bounds = new google.maps.LatLngBounds();

            jQuery.each(markers, function (i) {
                this.setMap(map);
                bounds.extend(this.position);
            });

            map.setCenter(bounds.getCenter());
            map.fitBounds(bounds);

            jQuery('#map_canvas').addClass('MultiLocationMap');
        }
        else {
            markers[0].setMap(map);
            map.setCenter(markers[0].position);
            jQuery('#map_canvas').addClass('SingleLocationMap');
            jQuery('#FooterDirectionsBox').show();
        }
    }
}

function WireUpMaps() {
    jQuery('a.MapDirectionsLink').live('click', function () {
        var directionContainer = jQuery(this).parents('div.MapDirectionsContainer,div.infoBox');
        if (directionContainer.length > 0) {
            var fromBox = jQuery(directionContainer).find('input.AddressField');
            var spnUrl = jQuery(directionContainer).find('span.Url');

            if (fromBox.length > 0 && spnUrl.length > 0) {
                var url = jQuery(spnUrl[0]).text().replace('XXX', jQuery(fromBox).val());
                window.location = url;
            }
        }
        return false;
    });

    jQuery('.DirectionsBox').live('click', function () {
        var tbMatches = jQuery(this).find('input');
        if (tbMatches.length > 0) {
            var tb = tbMatches[0];
            if (jQuery(tb).val() == 'Address, City, Zip') {
                jQuery(tb).val('');
            }
            jQuery(tb).focus();
        }
    });

    jQuery('input.AddressField').live('keydown', function (e) {
        var key = e.which;
        if (key == 13) {
            e.preventDefault();

            var directionContainer = jQuery(this).parents('div.MapDirectionsContainer,div.infoBox');
            if (directionContainer.length > 0) {
                var spnUrl = jQuery(directionContainer).find('span.Url');

                if (spnUrl.length > 0) {
                    var url = jQuery(spnUrl[0]).text().replace('XXX', jQuery(this).val());
                    window.location = url;
                }
            }

            return false;
        }
    });
}

function SetVideo(dataIslandName) {
    var dataIsland = eval(dataIslandName);

    var videoPanel = jQuery('#' + dataIsland.Container);
    var parent = jQuery(videoPanel).parent('div.WS_InlineVideo');
    jQuery(parent).find('div.pnlVideoDescription').html(dataIsland.Videos[dataIsland.Index].DescriptionHtml);

    jQuery(videoPanel).html('<img src="' + dataIsland.Videos[dataIsland.Index].PreviewImage + '" />');

    var play = videoPanel.siblings('div.VideoPlay')
    jQuery(play).show();

    var imgAction = jQuery(videoPanel).children('img');

    jQuery(play).one('click', function () {
        jQuery(this).hide();
        jQuery(imgAction).trigger('click');
    });

    jQuery(imgAction).one('click', function () {
        jQuery(this).remove();

        if (play != null) {
            jQuery(play).fadeOut('2000');
        }

        var prev = videoPanel.siblings('div.VideoPrevious')
        if (prev != null) {
            jQuery(prev).fadeOut('2000');
        }

        var next = videoPanel.siblings('div.VideoNext')
        if (next != null) {
            jQuery(next).fadeOut('2000');
        }

        jQuery(videoPanel).attr('href', dataIsland.Videos[dataIsland.Index].VideoUrl);

        flowplayer(dataIsland.Container, { src: "/_layouts/WellStar/flash/flowplayer.commercial-3.2.7.swf", wmode: 'opaque', logo: 'null' },
		{ 
			key: '$d5ebb8312f70ab9e549',
            clip: 
				{ url: dataIsland.Videos[dataIsland.Index].VideoUrl, provider: 'rtmp', autoPlay: 'true' },
            
			plugins: { 
					rtmp: { 
						url: '/_layouts/WellStar/flash/flowplayer.rtmp-3.2.3.swf', 
						netConnectionUrl: 'rtmp://media.wellstar.org/public/'
						}
					}
		});	
     });
}

function WireUpSocialVideo(hlVideoContainer, videoUrl) {
    var videoPanel = jQuery('#' + hlVideoContainer);
    jQuery(videoPanel).attr('href', videoUrl);

    flowplayer(hlVideoContainer, { src: "/_layouts/WellStar/flash/flowplayer.commercial-3.2.7.swf", wmode: 'opaque', logo:'null' },
    { 
		key: '$d5ebb8312f70ab9e549',
        clip: { url: videoUrl, provider: 'rtmp', autoPlay: 'true' },
        plugins: { rtmp: { url: '/_layouts/WellStar/flash/flowplayer.rtmp-3.2.3.swf', netConnectionUrl: 'rtmp://media.wellstar.org/public/'} }
    });
}

function WireUpFlowPlayerVideos(hlVideos, videoUrl) {
    var videoPanel = jQuery('#' + hlVideos);
    jQuery(videoPanel).attr('href', videoUrl);

    flowplayer(hlVideos, { src: "/_layouts/WellStar/flash/flowplayer.commercial-3.2.7.swf", wmode: 'opaque', logo: 'null' },
    {
		key: '$d5ebb8312f70ab9e549',
        clip: {
            url: videoUrl, provider: 'rtmp', autoPlay: 'false'
        },
        plugins: {
            rtmp: {
                url: '/_layouts/WellStar/flash/flowplayer.rtmp-3.2.3.swf', netConnectionUrl: 'rtmp://media.wellstar.org/public/'
            },
            controls: {
                progressGradient: 'none',
                backgroundGradient: [0.5, 0, 0.3],
                sliderBorder: '1px solid rgba(128, 128, 128, 0.7)',
                durationColor: '#a3a3a3',
                timeSeparator: ' ',
                buttonOffColor: 'rgba(130,130,130,1)',
                timeColor: '#ffffff',
                bufferColor: '#445566',
                autoHide: 'never',
                sliderGradient: 'none',
                timeBorder: '0px solid rgba(0, 0, 0, 0.3)',
                progressColor: '#112233',
                buttonOverColor: '#ffffff',
                buttonColor: '#ffffff',
                tooltipTextColor: '#ffffff',
                volumeSliderGradient: 'none',
                volumeColor: '#ffffff',
                sliderColor: '#000000',
                tooltipColor: '#000000',
                volumeSliderColor: '#ffffff',
                borderRadius: '0px',
                timeBgColor: 'rgb(0, 0, 0, 0)',
                bufferGradient: 'none',
                volumeBorder: '1px solid rgba(128, 128, 128, 0.7)',
                backgroundColor: '#222222',
                height: 24,
                opacity: 1.0
            }
        }
    });
  }


function WireUpFeaturedVideo(hlVideo, videoUrl) {
    var videoPanel = jQuery('#' + hlVideo);
    var imgAction = jQuery(videoPanel).children('img');

    var play = videoPanel.siblings('div.VideoPlay')
    jQuery(play).show();

    jQuery(play).one('click', function () {
        jQuery(this).hide();
        jQuery(imgAction).trigger('click');
    });

    jQuery(imgAction).one('click', function () {
        jQuery(this).remove();

        if (play != null) {
            jQuery(play).fadeOut('2000');
        }

        jQuery(videoPanel).attr('href', videoUrl);

        flowplayer(hlVideo, { src: "/_layouts/WellStar/flash/flowplayer.commercial-3.2.7.swf", wmode: 'opaque', logo: 'null' },
        {
			key: '$d5ebb8312f70ab9e549',
            clip: { url: videoUrl, provider: 'rtmp', autoPlay: 'false' },
            plugins: { rtmp: { url: '/_layouts/WellStar/flash/flowplayer.rtmp-3.2.3.swf', netConnectionUrl: 'rtmp://media.wellstar.org/public/'} }
        });
    });
}

function LoadTaskUrl() {
    var selected = jQuery(this).getSetSSValue();
    if (selected && selected.length > 0) {
        window.location = selected;
    }
}

function WireUpMenu() {
    jQuery(".WS_TopNav ul.mainNav li.topTab").mouseenter(function () {
        jQuery(this).children("div").stop(true, true).show();
    });
    jQuery(".WS_TopNav ul.mainNav li.topTab").mouseleave(function () {
        jQuery(this).children("div").stop(true, true).hide();
    });

    jQuery("#medicalTab").parent().mouseenter(function () {
        jQuery(this).children("a").stop(true, true).css('background-position', '0px 0px');
    });
    jQuery("#medicalTab").parent().mouseleave(function () {
        jQuery(this).children("a").stop(true, true).css('background-position', '0px -33px');
    });

    jQuery("#physiciansTab").parent().mouseenter(function () {
        jQuery(this).children("a").stop(true, true).css('background-position', '-157px 0px');
    });
    jQuery("#physiciansTab").parent().mouseleave(function () {
        jQuery(this).children("a").stop(true, true).css('background-position', '-157px -33px');
    });

    jQuery("#locationsTab").parent().mouseenter(function () {
        jQuery(this).children("a").stop(true, true).css('background-position', '-314px 0px');
    });
    jQuery("#locationsTab").parent().mouseleave(function () {
        jQuery(this).children("a").stop(true, true).css('background-position', '-314px -33px');
    });

    jQuery("#eventsTab").parent().mouseenter(function () {
        jQuery(this).children("a").stop(true, true).css('background-position', '-471px 0px');
    });
    jQuery("#eventsTab").parent().mouseleave(function () {
        jQuery(this).children("a").stop(true, true).css('background-position', '-471px -33px');
    });

    jQuery("#infoTab").parent().mouseenter(function () {
        jQuery(this).children("a").stop(true, true).css('background-position', '-726px 0px');
    });
    jQuery("#infoTab").parent().mouseleave(function () {
        jQuery(this).children("a").stop(true, true).css('background-position', '-726px -33px');
    });

    jQuery("ul.mainNav li.topTab").each(function (i) {
        var columnClass = '';

        var subNavHeaderCount = jQuery(this).find("li.subNavHeader").length;
        switch (subNavHeaderCount) {
            case 1:
                columnClass = 'oneColumn';
                break;
            case 2:
                columnClass = 'twoColumn';
                break;
            case 3:
                columnClass = 'threeColumn';
                break;
            case 4:
                columnClass = 'fourColumn';
                break;
            case 5:
                columnClass = 'fiveColumn';
                break;
        }

        jQuery(this).children('div.subNav').addClass(columnClass);
    });
}

function WireUpAccordions() {
    jQuery('.AccordionContainer').hide();
    jQuery('.AccordionTrigger:first').addClass('AccordionActive').next().show();

    jQuery('.AccordionTrigger').click(function () {
        if (jQuery(this).next().is(':hidden')) {
            var fxRegion;

            if (jQuery('#MSOSPWebPartManager_DisplayModeName').val() == 'Browse') {
                var children = jQuery(this).next().children();
                if (children != null && children.length > 0) {
                    fxRegion = jQuery(children[0]).attr('id');
                }
            }

            jQuery(this).parent().parent().find('.AccordionTrigger').removeClass('AccordionActive').next().slideUp('slow');
            jQuery(this).toggleClass('AccordionActive').next().slideDown('slow');

            if (fxRegion != "") {
                fleXenv.fleXcrollMain(fxRegion);
            }
        }
        return false;
    });
}

function WireUpVideoPlayer() {
    jQuery('div.VideoPrevious').click(function () {
        var dataIslandName = jQuery(this).siblings('span.hidDataIslandName').text();
        var dataIsland = eval(dataIslandName);
        dataIsland.Index--;

        if (dataIsland.Index == 0) {
            jQuery(this).fadeOut('2000');
        }

        jQuery(this).siblings('div.SpotTitle').css('background-position', dataIsland.Index * -320 + 'px  0');
        jQuery(this).siblings('div.VideoNext').show();

        SetVideo(dataIslandName);
    });

    jQuery('div.VideoNext').click(function () {
        var dataIslandName = jQuery(this).siblings('span.hidDataIslandName').text();
        var dataIsland = eval(dataIslandName);
        dataIsland.Index++;

        if (dataIsland.Index == 2) {
            jQuery(this).fadeOut('2000');
        }

        jQuery(this).siblings('div.SpotTitle').css('background-position', dataIsland.Index * -320 + 'px  0');
        jQuery(this).siblings('div.VideoPrevious').show();

        SetVideo(dataIslandName);
    });
    //The function below was throwing errors - so I will comment it out for now MQ
    //  jQuery('div.WS_InlineVideo, a.IVContent').hover(
    //     function () {
    //        var dataIslandName = jQuery(this).find('span.hidDataIslandName').text();
    //         var dataIsland = eval(dataIslandName);


    //        var prev = jQuery(this).find('div.VideoPrevious');

    //        if (prev != null) {
    //             if (dataIsland.Index > 0) {
    //                 jQuery(prev).show();
    //             }
    //          }

    //          var next = jQuery(this).find('div.VideoNext');
    //           if (next != null) {
    //              if (dataIsland.Index < 2) {
    //                   jQuery(next).show();
    //            }
    //         }
    //      });	  


    jQuery('a.IVContent').click(function (e) {
        e.preventDefault();
        return false;
    });

    jQuery('.VideoLink').click(function () {
        jQuery(this).unbind('click');

        var videoLink = jQuery(this).find('a.VideoTitle')[0];


        var title = jQuery(videoLink).html();
        var lightBox = jQuery(videoLink).attr('href');

        var spnVideoTitle = jQuery(lightBox).find('span.spnVideoTitle');
        if (spnVideoTitle.length > 0) {
            jQuery(spnVideoTitle[0]).html(title);
        }

        var videoUrl;
        var videoContainer;

        var FP_VideoUrl = jQuery(videoLink).siblings('span.FP_VideoUrl');
        if (FP_VideoUrl) {
            videoUrl = jQuery(FP_VideoUrl).html();
        }

        var FP_VideoId = jQuery(videoLink).siblings('span.FP_VideoId');
        if (FP_VideoId) {
            videoContainer = jQuery(FP_VideoId).html();
        }

        if (videoUrl && videoUrl != "" && videoContainer && videoContainer != "") {
            jQuery('#' + videoContainer).attr('href', videoUrl);
            //flowplayer(videoContainer, '/_layouts/WellStar/flash/flowplayer-3.2.5.swf');
            //  flowplayer(videoContainer, { src: "/_layouts/WellStar/flash/flowplayer-3.2.5.swf", wmode: 'opaque' },
            // Added by MQ 112611
            flowplayer(videoContainer, { src: "/_layouts/WellStar/flash/flowplayer.commercial-3.2.7.swf", wmode: 'opaque', logo:'null' },
        	{
				key: '$d5ebb8312f70ab9e549',
        	    clip: { url: videoUrl, provider: 'rtmp', autoPlay: 'false' },
        	    plugins: { rtmp: { url: '/_layouts/WellStar/flash/flowplayer.rtmp-3.2.3.swf', netConnectionUrl: 'rtmp://media.wellstar.org/public/'} }
        	});
        }

        jQuery(videoLink).fancybox({ 'showCloseButton': false });
        jQuery(videoLink).trigger('click');
        return false;
    });
}

function toggleTab(entity, div) {
    jQuery(entity).toggleClass('SelectedSubNav');
    jQuery(entity).siblings().removeClass('SelectedSubNav');

    jQuery(div).siblings().hide();
    jQuery(div).show();
}

function WireUpTooltips() {
    if (jQuery('#MSOSPWebPartManager_DisplayModeName').val() == 'Browse') {
        if (jQuery('.ToolTip').tipsy) {
            jQuery('span.ToolTip').tipsy({ gravity: 's', title: 'tip', opacity: 1 });
            jQuery('a.ToolTip').tipsy({ gravity: 's', opacity: 1 });

            jQuery('.LeftToolTip').attr('src', '/SiteCollectionImages/Spots/info.gif');
            jQuery('.LeftToolTip').tipsy({ gravity: 'e', title: 'tip', opacity: 1 });
            jQuery('.LeftToolTip').live("mouseover mouseout", function (e) {
                if (e.type == 'mouseover') {
                    jQuery(this).attr('src', '/SiteCollectionImages/Spots/infohover.gif');
                } else {
                    jQuery(this).attr('src', '/SiteCollectionImages/Spots/info.gif');
                }
            });
        }
    }
}

function WireUpGalleries() {
    if (jQuery('.ad-gallery').adGallery) {
        var galleries = jQuery('.ad-gallery').adGallery({
            loader_image: '/_layouts/images/WellStar/Shared/loader.gif',
            width: 660
        });
    }
}

function HandleLetterSelector() {
    var letterSelected = jQuery(this).html().toUpperCase();
    var offsetTop = 0;

    var divDoctors = jQuery('#fxDoctors');
    if (divDoctors) {
        var doctors = jQuery(divDoctors).find('a');
        if (doctors) {
            var lastLetterChecked;

            for (i = 0; i < doctors.length; i++) {
                var doctorName = jQuery(doctors[i]).html();
                var nameParts = doctorName.split(" ");

                if (nameParts && nameParts.length > 1) {
                    var lastName = nameParts[2];
                    var currentLetter = lastName.charAt(0);

                    if (currentLetter == lastLetterChecked) {
                        continue;
                    }
                    else if (currentLetter <= letterSelected) {
                        lastLetterChecked = currentLetter;
                        offsetTop = doctors[i].offsetTop;
                    } else {
                        break;
                    }
                }
            }
        }
    }

    var d = document.getElementById(jQuery(divDoctors).attr('id'));
    d.fleXcroll.setScrollPos(false, offsetTop - 14);
}

function GetImageHoverClass(rawClasses) {
    var match = '';

    if (rawClasses) {
        var classes = rawClasses.split(' ');

        for (i = 0; i < rawClasses.length; i++) {
            if (classes[i] !== 'ImageHover' && classes[i].indexOf('Hover') == -1) {
                match = classes[i];
                break;
            }
        }
    }

    return match;
}

function WireUpGenericButtonHovers() {
    jQuery('a.ImageHover').hover(
		function () {
		    var match = GetImageHoverClass(jQuery(this).attr('class'));
		    jQuery(this).addClass(match + 'Hover');
		},
		function () {
		    var match = GetImageHoverClass(jQuery(this).attr('class'));
		    jQuery(this).removeClass(match + 'Hover');
		}
	);
}

function WireUpCitations() {
    jQuery("a.Citation").click(function () {
        var targetId = jQuery(this).attr("name");
        var target = jQuery('#' + targetId);
        if (target) {
            target.toggle();
        }
    });
    jQuery("a.CitationClose").click(function () {
        var target = jQuery(this).parents("div.InlineCitation");
        if (target) {
            target.toggle();
        }
    });
}

function WireUpLetterSelectors() {
    jQuery('.DoctorList .LetterSelector a').live('click', HandleLetterSelector);

    jQuery('.LetterSelector a').each(function (i) {
        var letter = jQuery(this).html().toUpperCase();
        if (letter && letter != "") {
            var anchorMatch = jQuery('a[name="' + letter + '"]');
            if (anchorMatch.length == 0) {
                jQuery(this).addClass("DisabledLink");
            }
        }
    });
}

function WireUpTableActions() {
    jQuery('tr.ClickableRow').hover(
        function () {
            jQuery(this).addClass('HoverRow');
        },
        function () {
            jQuery(this).removeClass('HoverRow');
        }
    );

    jQuery('tr.ClickableRow').live("click", function (e) {
        var lnkProfile = jQuery(this).find("a.lnkProfile");
        if (lnkProfile.length > 0) {
            var url = jQuery(lnkProfile[0]).attr('href');
            window.location = url;
        }
    });
}

//maybe for mini event it should be the first date >= today?
function selectFirstEvent() {
    if (miniEventMode) {
        if (events.length > 0) {
            eventIndex = 0;
            selectDate(eventIndex);
        };
    } else {
        jQuery('#dpEvents a.ui-state-active').removeClass('ui-state-active');
        jQuery('#dpEvents td.ui-datepicker-current-day').removeClass('ui-datepicker-current-day');
    }
}

function highlightDays(date) {
    var dates = [];
    for (var i = 0; i < events.length; i++) {
        dates.push(new Date(events[i].StartDate));
    }

    for (var i = 0; i < dates.length; i++) {
        if (dates[i].getMonth() == date.getMonth() && dates[i].getDate() == date.getDate() && dates[i].getFullYear() == date.getFullYear()) {
            return [true, 'ui-state-active'];
        }
    }
    return [false, ''];
}

function eventSelected(strDate) {
    for (var i = 0; i < events.length; i++) {
        if (events[i].StartDate == strDate) {
            eventIndex = i;
            selectDate(i);
            break;
        }
    }
}

function UpdateEventNavigation() {
    if (events.length > eventIndex + 1) {
        jQuery('#nextEvent').show();
    } else {
        jQuery('#nextEvent').hide();
    }

    if (eventIndex > 0) {
        jQuery('#previousEvent').show();
    } else {
        jQuery('#previousEvent').hide();
    }
}

function PopulateFullEventDetails() {
    var posX = 0;
    var posY = 0;
    var selectedDays = jQuery('#dpEvents').find('td.ui-datepicker-current-day a');

    if (selectedDays.length > 0) {
        var position = jQuery(selectedDays[0]).offset();
        posX = position.left + 95;
        posY = position.top + 30

        var selectedDate = new Date(events[eventIndex].StartDate);
        if (selectedDate.getDay() > 3) {
            posX = posX - 400;
        }
    }

    var qtipContent = '';
    qtipContent = qtipContent + '<div class="cancelqtip"><a href="#"><img style="border:0;" src="/_layouts/images/WellStar/Shared/btn_PurpleClose.gif" alt="Close" /></a></div>';
    qtipContent = qtipContent + '<div class="InnerContent">';
    qtipContent = qtipContent + '<div class="SpotBodyPurple"><a class="PurpleLink" href="/Classes-Community-Outreach/Pages/Class-Details.aspx?eid=' + events[eventIndex].EventId + '" id="spanEventTitle">' + events[eventIndex].EventTitle + '</a></div>';
    qtipContent = qtipContent + '<div class="SpotBodyGray"><div>' + events[eventIndex].TimeSpan + '</div><div>' + events[eventIndex].Location + '</div></div>';
    qtipContent = qtipContent + '<div class="CalendarNav"><div><a href="#" id="nextEvent" style="display: inline;"><img title="Next Event" alt="Next Event" src="/SiteCollectionImages/MiniEvents/btn_Next.gif"></a></div><div><a href="#" id="previousEvent" style="display: inline;"><img title="Previous Event" alt="Previous Event" src="/SiteCollectionImages/MiniEvents/btn_Previous.gif"></a></div></div></div>';

    var existingToolTip = jQuery('.ui-tooltip-content');
    if (existingToolTip != null && existingToolTip.length > 0) {
        jQuery(existingToolTip[0]).html(qtipContent);
        posY = posY - 89.5; //qtip does some manipulation of the offset, and this is the factor it used
        jQuery('.qtip').css('top', '' + posY + 'px');
        jQuery('.qtip').css('left', '' + posX + 'px');
    }
    else {
        jQuery(document.body).qtip({
            overwrite: true,
            content: {
                prerender: true,
                text: qtipContent
            },
            position: {
                my: 'left center',
                at: 'top left',
                adjust: {
                    x: posX,
                    y: posY
                }
            },
            style: {
                classes: 'ui-tooltip-light',
                tip: true
            },
            show: false,
            hide: false
        });

        jQuery(document.body).qtip("show");
    }

    UpdateEventNavigation();
}

function selectDate(eventIndex) {
    var selectedEvent = events[eventIndex];
    var date = new Date(selectedEvent.StartDate);

    jQuery('#dpEvents').datepicker("setDate", date);

    if (miniEventMode) {
        PopulateMiniEventDetails(selectedEvent, date);
    } else {
        PopulateFullEventDetails();
    }
}

function PopulateMiniEventDetails(selectedEvent, date) {
    jQuery('#pnlEventMonthNumber').css('background-position', ((date.getMonth() + 1) * -45 + 45) + 'px 0');
    jQuery('#pnlEventDayNumber').css('background-position', (date.getDate() * -45 + 45) + 'px 0');
    jQuery('#pnlEventDay').css('background-position', (date.getDay() * -128) + 'px 0');

    jQuery('#spanEventTitle').html(selectedEvent.EventTitle);
    //jQuery('#pnlEventSubTitle').html(selectedEvent.SubTitle);
    jQuery('#spanEventTitle').attr('href', '/Classes-Community-Outreach/Pages/Class-Details.aspx?eid=' + selectedEvent.EventId);
    jQuery('#pnlEventTime').text(selectedEvent.TimeSpan);
    jQuery('#pnlEventLocation').text(selectedEvent.Location);

    UpdateEventNavigation();
}

function CalendarMonthChange(year, month, inst) {
    var url = '/events.axd?m=' + month + '&y=' + year;

    var selected = jQuery('#ddlEventCategories').getSetSSValue();
    if (selected != "") {
        url = url + '&ecid=' + selected;
    }

    currentYear = year;
    currentMonth = month;

    jQuery.ajax({
        url: url,
        dataType: 'json',
        success: function (data) {
            events = data;
            jQuery('#dpEvents').datepicker('refresh');
            selectFirstEvent();
        }
    });
}

var currentYear;
var currentMonth;

function WireUpCalendar() {
    jQuery(['/SiteCollectionImages/WebParts/bg_ViewEvents.gif', '/SiteCollectionImages/WebParts/bg_ViewEventsHover.gif']).preload();
    if (events != null) {
        var firstOfMonth = new Date();
        firstOfMonth.setDate(1);

        currentYear = firstOfMonth.getFullYear();
        currentMonth = firstOfMonth.getMonth() + 1;

        jQuery('#dpEvents').datepicker({
            dayNamesMin: ['Sun', 'Mon', 'Tues', 'Wed', 'Thur', 'Fri', 'Sat'],
            showOtherMonths: true,
            minDate: firstOfMonth,
            beforeShowDay: highlightDays,
            onSelect: eventSelected,
            onChangeMonthYear: CalendarMonthChange
        });

        selectFirstEvent();
    }

    jQuery('#nextEvent').live('click', function () {
        if (events != null && events.length > eventIndex + 1) {
            eventIndex++;
            selectDate(eventIndex);
        }
        return false;
    });

    jQuery('#previousEvent').live('click', function () {
        if (events != null && eventIndex > 0) {
            eventIndex--;
            selectDate(eventIndex);
        }
        return false;
    });

    jQuery('div.cancelqtip a').live('click', function () {
        jQuery('.qtip').qtip("destroy");
        return false;
    });
}

function FilterCalendar() {
    jQuery('.qtip').qtip("destroy");
    var selected = jQuery('#ddlEventCategories').getSetSSValue();
    CalendarMonthChange(currentYear, currentMonth, null);
}

function WireUpMyPhysicians(ddlLocationsId) {
    jQuery('.fbRemovePhysician, a.fbRemovePhysician').click(function () {
        var allEvents = jQuery(this).data("events");
        var clickEvent = allEvents.click[0];

        jQuery(this).unbind('click');

        var lightBox = jQuery(this).attr('href');

        var lastName;
        var physicianId;
        var spnRPImageUrl;

        var spnRPId = jQuery(this).siblings('span.spnRPId');
        if (spnRPId) {
            physicianId = jQuery(spnRPId).html();
        }

        var spnRPLastName = jQuery(this).siblings('span.spnRPLastName');
        if (spnRPLastName) {
            lastName = jQuery(spnRPLastName).html();
        }

        var spnRPImageUrl = jQuery(this).siblings('span.spnRPImageUrl');
        if (spnRPImageUrl) {
            spnRPImageUrl = jQuery(spnRPImageUrl).html();
        }

        var hfRemovePhysicianId = jQuery(lightBox).find('input[name="hfRemovePhysicianId"]');
        if (hfRemovePhysicianId.length > 0) {
            jQuery(hfRemovePhysicianId[0]).val(physicianId);
        }

        var spnRPLB_LastName = jQuery(lightBox).find('span.spnRPLB_LastName');
        if (spnRPLB_LastName.length > 0) {
            jQuery(spnRPLB_LastName[0]).html(lastName);
        }

        var spnRPLB_ImageUrl = jQuery(lightBox).find('img.spnRPLB_ImageUrl');
        if (spnRPLB_ImageUrl.length > 0) {
            jQuery(spnRPLB_ImageUrl[0]).attr('src', spnRPImageUrl);
        }

        jQuery(this).fancybox({ 'showCloseButton': false });
        jQuery(this).trigger('click');

        jQuery(this).unbind('click');
        jQuery(this).click(clickEvent);
        return false;
    });

    jQuery('a#ibPhysicianLB').fancybox({ 'showCloseButton': false });
}

function RunQuickSearch() {
    var url = '/Pages/search.aspx?q=' + jQuery('#txtSearch').val();
    window.location = url;
}

function WireUpQuickSearch() {
    jQuery("li.flyout").mouseenter(function () {
        jQuery('.pnlSearch .SearchBox input').blur();
    });

    jQuery('#txtSearch').keydown(function (e) {
        var key = e.which;
        if (key == 13) {
            e.preventDefault();
            RunQuickSearch();
            return false;
        }
    });

    jQuery("#imgSearch").click(function () {
        RunQuickSearch();
    });
}

//function SelectLocation(n, id) {
//    jQuery('#' + searchFields['hfLocationId']).val(id);
//    jQuery('#' + searchFields['txtLocation']).val(n);
//    jQuery('#' + searchFields['txtPostalCode']).val(searchFields['DefaultPostalCodeText']);
//    CheckSearchFields();
//    jQuery.fancybox.close();
//}

function CheckSearchFields() {
    var criteriaSelected = 0;
    var isValid = true;
    var firstName = jQuery('#' + searchFields['txtFirstName']).val();
    var lastName = jQuery('#' + searchFields['txtLastName']).val();
    var gender = jQuery('#' + searchFields['ddlGender']).val();
    var specialty = jQuery('#' + searchFields['ddlSpecialty']).val();
    var language = jQuery('#' + searchFields['ddlLanguages']).val();
    //var location = jQuery('#' + searchFields['txtLocation']).val();
    var city = jQuery('#' + searchFields['txtCity']).val();
    //var locationId = jQuery('#' + searchFields['hfLocationId']).val();
    var postalCode = jQuery('#' + searchFields['txtPostalCode']).val();
    //var spnInvalidLocation = jQuery('#spnInvalidLocation');

    //spnInvalidLocation.hide();

    if (firstName != '') { criteriaSelected++; }
    if (lastName != '') { criteriaSelected++; }
    if (gender != '') { criteriaSelected++; }
    if (specialty != '') { criteriaSelected++; }
    if (language != '') { criteriaSelected++; }
    //    if (location != '') {
    //        if (locationId != '') {
    //            criteriaSelected++;
    //        }
    //        else if (location !== 'Enter Practice or Hospital Name') {
    //            spnInvalidLocation.show(); isValid = false;
    //        }
    //    }
    if (city != '' && city != searchFields['DefaultCityText']) { criteriaSelected++; }
    if (postalCode != '' && postalCode != searchFields['DefaultPostalCodeText']) { criteriaSelected++; }

    var ibSearch = jQuery('#' + searchFields['ibSearch']);

    if (criteriaSelected > 0 && isValid) {
        ibSearch.attr('src', '/SiteCollectionImages/PhysicianSearch/btn_SearchPhysicians_Active.gif');
        ibSearch.removeAttr('disabled');
        ibSearch.removeAttr('style');
    }
    else {
        ibSearch.attr('src', '/SiteCollectionImages/PhysicianSearch/btn_SearchPhysicians_Inactive.gif');
        ibSearch.attr('disabled', 'true');
        jQuery(ibSearch).attr('style', 'cursor:pointer;');
    }
}

//function WireUpAutoComplete() {
//    jQuery('input.LocationAutoComplete').focus(function () {
//        if (jQuery(this).val() === 'Enter Practice or Hospital Name') {
//            jQuery(this).val('');
//        } else {
//            jQuery(this).select();
//        }
//    });

//    if (jQuery('input.LocationAutoComplete').autocomplete) {
//        jQuery('input.LocationAutoComplete').autocomplete({
//            source: function (request, response) {
//                jQuery.ajax({
//                    url: "locations.ac?q=" + request.term,
//                    dataType: "json",
//                    success: function (data) {
//                        response(data);
//                    }
//                });
//            },
//            select: function (event, ui) {
//                jQuery(this).val(ui.item.label);
//                jQuery('#' + searchFields['hfLocationId']).val(ui.item.value);
//                jQuery('#' + searchFields['txtPostalCode']).val(searchFields['DefaultPostalCodeText']);
//                CheckSearchFields();
//                return false;
//            },
//            autoFill: false,
//            minLength: 2
//        });
//    }
//}


//searchFields['']
function WireUpPhysicianSearch() {
    //jQuery('a#ibSearchLB').fancybox({ 'showCloseButton': false });

    jQuery('#' + searchFields['txtFirstName']).bind('hastext notext', function () { CheckSearchFields(); });
    jQuery('#' + searchFields['txtLastName']).bind('hastext notext', function () { CheckSearchFields(); });

    jQuery('#' + searchFields['ddlGender']).sSelect({ containerClass: 'SearchGenderList' }).change(function () { CheckSearchFields(); });
    jQuery('#' + searchFields['ddlSpecialty']).sSelect({ containerClass: 'SearchSpecialtyList', ddMaxHeight: '300px' }).change(function () { CheckSearchFields(); });
    jQuery('#' + searchFields['ddlLanguages']).sSelect({ containerClass: 'SearchLanguagesList', ddMaxHeight: '300px' }).change(function () { CheckSearchFields(); });

    jQuery('#' + searchFields['txtPostalCode']).focus(function () {
        if (jQuery(this).val() === searchFields['DefaultPostalCodeText']) {
            jQuery(this).val('');
            jQuery('#' + searchFields['txtPostalCode']).bind('notext', function () { CheckSearchFields(); }); //only bind this event after we've clicked there once
            jQuery('#' + searchFields['txtPostalCode']).bind('hastext', function () { //only bind this event after we've clicked there once
                //jQuery('#' + searchFields['txtLocation']).val(searchFields['DefaultPracticeText']);
                //jQuery('#' + searchFields['hfLocationId']).val('');
                CheckSearchFields();
            });
        }
        else {
            jQuery(this).select();
        }
    });

    jQuery('#' + searchFields['ibSearch']).attr('disabled', 'true');
    jQuery('#' + searchFields['ibSearch']).attr('style', 'cursor:default;');

    jQuery('.SearchFields').live('change', CheckSearchFields);
    jQuery('.SearchFields').live('blur', CheckSearchFields);

    //    jQuery('#' + searchFields['txtLocation']).bind('notext', function () {
    //        jQuery('#' + searchFields['hfLocationId']).val('');
    //        CheckSearchFields();
    //    });

    //    jQuery('#tabHospitals').click(function () {
    //        toggleTab(jQuery(this), '#divHospitals');
    //    });
    //    jQuery('#tabPractices').click(function () {
    //        toggleTab(jQuery(this), '#divPractices');
    //        fleXenv.fleXcrollMain('divPractices');
    //    });

    jQuery('.hlSelectCity').live('click', function () {
        var city = jQuery(this).html();
        jQuery('#' + searchFields['txtCity']).val(city);
        jQuery.fancybox.close();
        CheckSearchFields();
        return false;
    });

    jQuery('a#ibSearchLB').one('click', function () {
        jQuery(this).fancybox({ 'showCloseButton': false });
        jQuery(this).trigger('click');
        fleXenv.fleXcrollMain('divCities');
        return false;
    });

    CheckSearchFields();
}

function WireUpPhysicianSearchResults(ddlSort) {
    jQuery('#' + ddlSort).sSelect({ containerClass: 'SearchSortList' });
}

function ResetCalc(calc) {
    jQuery(calc + ' .calculator').show();
    jQuery(calc + ' .calc-footer').show();
    jQuery(calc + ' .calc-result').hide();

    jQuery(calc + ' .calc-reset').trigger('click')
}

function LoadCalculator(button, calc) {
    var allEvents = jQuery(button).data("events");
    var clickEvent = allEvents.click[0];

    jQuery(button).unbind('click');

    ResetCalc(calc);

    jQuery('#hfCurrentCalc').val(calc);
    jQuery(button).fancybox({
        'showCloseButton': false,
        'onComplete': function () {
            replaceMe();
            getMonthly();
        }
    });
    jQuery(button).trigger('click');

    jQuery(button).unbind('click');
    jQuery(button).click(clickEvent);
}

function WireUpFoundationCalculators() {
    var status = "closed";

    jQuery(".styledselect").click(function () {
        if (status == "closed") {
            jQuery(".dropdown").fadeIn(100);
            status = "open";
        }
        else {
            jQuery(".dropdown").fadeOut(100);
            status = "closed";
        }

        return false;
    });

    jQuery('.styledselect ul li a').click(function () {
        var btn = jQuery(this).attr('btn');
        var calc = jQuery(this).attr('calc');

        //jQuery.fancybox.close();
        jQuery(".dropdown").hide();
        status = "closed";

        LoadCalculator(btn, calc);

        return false;
    });

    jQuery('#hlcalcCharitableGifts').click(function () {
        LoadCalculator(this, '.calc-charitable');
        return false;
    });

    jQuery('#hlcalcDeferredGifts').click(function () {
        LoadCalculator(this, '.calc-deferred');
        return false;
    });

    jQuery('#hlcalcRemainderUnitrust').click(function () {
        LoadCalculator(this, '.calc-remainder-unitrust');
        return false;
    });

    jQuery('#hlcalcRemainderUnitrustTerm').click(function () {
        LoadCalculator(this, '.calc-remainder-unitrust-term');
        return false;
    });

    jQuery('#hlcalcRemainderAnnuityTrust').click(function () {
        LoadCalculator(this, '.calc-remainder-annuity');
        return false;
    });

    jQuery('#hlcalcRemainderAnnuityTrustTerm').click(function () {
        LoadCalculator(this, '.calc-remainder-term');
        return false;
    });

    jQuery('#hlcalcLeadUnitrustTerm').click(function () {
        LoadCalculator(this, '.calc-lead-unitrust');
        return false;
    });

    jQuery('#hlcalcLeadAnnuityTrustTerm').click(function () {
        LoadCalculator(this, '.calc-lead-annuity');
        return false;
    });
}

function WireUpFoundationControls() {
    jQuery('.paginate_enabled_previous, .paginate_enabled_next').hover(
        function () {
            jQuery(this).addClass('hover');
        },
        function () {
            jQuery(this).removeClass('hover');
        }
    );

    WireUpFoundationCalculators();

    jQuery('#hlFoundationPlaque').click(function () {
        jQuery(this).unbind('click');
        jQuery(this).fancybox({ 'showCloseButton': false });

        var flashvars = {};
        var params = {
            menu: "false",
            scale: "noScale",
            allowFullscreen: "true",
            allowScriptAccess: "always",
            bgcolor: "#FFFFFF"
        };
        var attributes = {
            id: "InteractiveHero"
        };
        swfobject.embedSWF("/Heroes/Foundation/Wellstar_Plaque.swf", "foundationFlash", "420px", "500px", "9.0.0", "/Heroes/expressInstall.swf", flashvars, params, attributes);

        jQuery(this).trigger('click')

        return false;
    });

    jQuery('#ddlHospitalName').sSelect();

    jQuery("#btnViewWishList").click(function () {
        var selected = jQuery('#ddlHospitalName').getSetSSValue();
        var facilityId = parseInt(selected);

        if (facilityId > 0) {
            window.location = 'https://ssl.4agoodcause.com/wellstar/wish_list.aspx?Facility_ID=' + facilityId;
        };

        return false;
    });
}

function ValidateEmail(email) {
    var isValid = true;

    var rgxEmail = new RegExp(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/gi);
    if (email == "" || !rgxEmail.test(email)) //isn't formatted like an email address
    {
        isValid = false;
    }

    return isValid;
}

function SignUpForNewsletter(Signup) {
    //validation, make sure it's not blank, the default value, and is formatted like an email address

    var email = Signup.EmailField.val().replace(" ", "");
    if (!ValidateEmail(email) || email == Signup.DefaultEmailValue) {
        alert("Please enter a properly formatted email address.");
        return false;
    }

    //passed validation, let's process it
    jQuery.ajax({
        success: function (data) {
            switch (data.status) {
                case 0:
                    alert("You've been successfully added to our newsletter!");
                    break;
                case 1:
                    alert("There was a validation error with your email address.");
                    break;
                case 2:
                    alert("There was an error adding you to our newsletter, please try again.");
                    break;
                case 3:
                    alert("That email address has already subscribed to the newsletter.");
                    break;
                default:
                    alert("Unexpected response from server, please try again.");
                    break;
            }
        },
        error: function (ajax, status, err) {
            console.log(status);
            console.log(err);
        },
        dataType: "json",
        type: "POST",
        url: "/Service.axd",
        data: { func: "Newsletter_Signup", emailAddress: email }
    });
}

function WireUpNewsletterSignup() {
    var Signup = new Object();
    Signup.Button = jQuery(".btnNewsletterSignup");
    Signup.EmailField = jQuery("input.txtNewsletterEmail");
    Signup.DefaultEmailValue = Signup.EmailField.val();

    Signup.EmailField.blur(function () {
        if (jQuery(this).val().replace(" ", "") == "") {
            jQuery(this).val(Signup.DefaultEmailValue);
        }
    });

    Signup.EmailField.focus(function () {
        if (jQuery(this).val() == Signup.DefaultEmailValue) {
            jQuery(this).val("");
        }
    });

    Signup.EmailField.keyup(function () {
        if (jQuery(this).val().replace(" ", "") != "") {
            Signup.Button.attr("disabled", false);
        } else {
            Signup.Button.attr("disabled", true);
        }
    });

    Signup.EmailField.keydown(function (e) {
        var key = e.which;
        if (key == 13) {
            e.preventDefault();

            SignUpForNewsletter(Signup);

            return false;
        }
    });

    Signup.Button.click(function () {
        SignUpForNewsletter(Signup);
        return false;
    });
}

function RegisterForClass() {
    var firstName = jQuery('#txtRegisterFirstName').val();
    var lastName = jQuery('#txtRegisterLastName').val();
    var email = jQuery('#txtRegisterEmail').val();
    var emailConfirm = jQuery('#txtRegisterEmailConfirm').val();
    var attending = jQuery('#txtRegisterAttending').val();
    var notes = jQuery('#txtRegisterComments').val();
    var eventId = jQuery('#spnTargetEventId').html();
    var eventName = jQuery('#targetEventName').html();
    var confirmationId = jQuery('#spnConfirmationId').html();

    if (firstName == "") {
        alert("Please enter your first name.");
        return;
    }

    if (lastName == "") {
        alert("Please enter your last name.");
        return;
    }

    if (email !== emailConfirm) {
        alert("Please verify the email addresses you entered match.");
        return;
    }

    if (!ValidateEmail(email)) {
        alert("Please enter a properly formatted email address.");
        return;
    }

    if (attending == "" || isNaN(attending)) {
        alert("Please enter the number of people who will be attending.");
        return;
    }

    jQuery('#pnlRegistrationForm').hide();
    jQuery('#pnlRegistrationFormWaiting').show();

    jQuery.ajax({
        success: function (data) {
            jQuery('#confirmationEventName').html(jQuery('#targetEventName').html());
            jQuery('#confirmationEventDetails').html(jQuery('#targetEventDetails').html());

            jQuery('#spnConfirmedName').html(jQuery('#txtRegisterFirstName').val() + ' ' + jQuery('#txtRegisterLastName').val());
            jQuery('#spnConfirmedEmail').html(jQuery('#txtRegisterEmail').val());
            jQuery('#spnConfirmedAttending').html(jQuery('#txtRegisterAttending').val());
            jQuery('#spnConfirmedNotes').html(jQuery('#txtRegisterComments').val());

            jQuery('#spnConfirmationId').html(data.confirmationId);

            jQuery('#pnlRegister').hide();
            jQuery('#pnlConfirmation').show();
        },
        error: function (ajax, status, err) {
            console.log(status);
            console.log(err);
        },
        dataType: "json",
        type: "POST",
        url: "/Service.axd",
        data: { func: "FoundationEvent_Register", confirmationId: confirmationId, firstName: firstName, lastName: lastName, emailAddress: email, attending: attending, notes: notes, eventId: eventId, eventName: eventName }
    });
}

function WireUpFoundationEvents() {
    jQuery('#hlRegister').click(function () {
        RegisterForClass();
        return false;
    });

    jQuery('#hlEditRegistration').click(function () {
        jQuery('#pnlRegistrationFormWaiting').hide();
        jQuery('#pnlRegistrationForm').show();

        jQuery('#pnlConfirmation').hide();
        jQuery('#pnlRegister').show();
        e.preventDefault();
        return false;
    });

    jQuery('#hlPrintConfirmation').click(function () {
        var cid = jQuery('#spnConfirmationId').html();
        window.open('/Foundation/Events/Pages/Confirmation.aspx?cid=' + cid);
        e.preventDefault();
        return false;
    });

    WireUpFoundationLightbox();
}

function WireUpFoundationLightbox() {
    jQuery('a.ibEventRegistrationLB').click(function () {
        jQuery(this).unbind('click');

        jQuery('#txtRegisterFirstName').val('');
        jQuery('#txtRegisterLastName').val('');
        jQuery('#txtRegisterEmail').val('');
        jQuery('#txtRegisterEmailConfirm').val('');
        jQuery('#txtRegisterAttending').val('');
        jQuery('#txtRegisterComments').val('');
        jQuery('#spnTargetEventId').html('');
        jQuery('#targetEventName').html('');
        jQuery('#spnConfirmationId').html('');

        var spnEventId = jQuery(this).siblings('span.spnEventId');
        if (spnEventId != null) {
            jQuery('#spnTargetEventId').html(spnEventId.html());
        }

        var spnEventName = jQuery(this).siblings('span.spnEventName');
        if (spnEventName != null) {
            jQuery('#targetEventName').html(spnEventName.html());
        }

        var spnEventDescription = jQuery(this).siblings('span.spnEventDescription');
        if (spnEventDescription != null) {
            jQuery('#targetEventDescription').html(spnEventDescription.html());
        }

        var trDataRow = jQuery(this).parents('.trDataRow');
        if (trDataRow.length > 0) {
            var tdEventTimeLocation = jQuery(trDataRow).find('td.tdEventTimeLocation');
            if (tdEventTimeLocation.length > 0) {
                jQuery('#targetEventDetails').html(jQuery(tdEventTimeLocation[0]).html());
            }
        }

        jQuery('#pnlConfirmation').hide();
        jQuery('#pnlRegister').show();

        jQuery(this).fancybox({ 'showCloseButton': false });
        jQuery(this).trigger('click');

        jQuery('#txtRegisterFirstName').focus();
        jQuery('#eventRegistrationLB').scrollTop(0);

        jQuery(this).unbind('click');
        WireUpFoundationLightbox();
        return false;
    });
}

var CommentFields = new Object();

function ValidateEventCommenterName(sender, args) {
    args.IsValid = !(CommentFields.CommenterName.val() == CommentFields.CommenterNameDefaultValue ||
        CommentFields.CommenterName.val() == "");
}

function ValidateEventComment(sender, args) {
    args.IsValid = !(CommentFields.Comment.val() == CommentFields.CommentDefaultValue ||
        CommentFields.Comment.val() == "");
}

function WireUpEventDetails() {
    jQuery('#hlPostCommentToggle').click(function () {
        if (jQuery('.pnlAddComment').is(":visible")) {
            jQuery('#hlPostCommentToggle img').attr('src', '/_layouts/images/WellStar/DataTables/forward_enabled.jpg');
        }
        else {
            jQuery('#hlPostCommentToggle img').attr('src', '/_layouts/images/WellStar/DataTables/sort_desc.png');
        }

        jQuery('.pnlAddComment').toggle();
        return false;
    });

    CommentFields.CommenterName = jQuery("input.txtCommenterName");
    CommentFields.Comment = jQuery('textarea.txtComment');
    CommentFields.CommenterNameDefaultValue = CommentFields.CommenterName.val();
    CommentFields.CommentDefaultValue = CommentFields.Comment.val();

    CommentFields.CommenterName.focus(function () {
        if (jQuery(this).val() == CommentFields.CommenterNameDefaultValue) {
            jQuery(this).val("");
        }
    });

    CommentFields.CommenterName.blur(function () {
        if (jQuery(this).val().replace(" ", "") == "") {
            jQuery(this).val(CommentFields.CommenterNameDefaultValue);
        }
    });

    CommentFields.Comment.focus(function () {
        if (jQuery(this).val() == CommentFields.CommentDefaultValue) {
            jQuery(this).val("");
        }
    });

    CommentFields.Comment.blur(function () {
        if (jQuery(this).val().replace(" ", "") == "") {
            jQuery(this).val(CommentFields.CommentDefaultValue);
        }
    });
}

jQuery(document).ready(function () {
    WireUpMenu();
    WireUpQuickSearch();
    WireUpAccordions();
    WireUpVideoPlayer();
    WireUpTooltips();
    WireUpGalleries();
    WireUpGenericButtonHovers();
    WireUpCitations();
    WireUpLetterSelectors();
    WireUpTableActions();

    jQuery('ul.EmergencyNavList li a').live("click", function (e) {
        var detailsPaneName = jQuery(this).attr('details');
        if (detailsPaneName != null && detailsPaneName != '') {
            var detailsPane = jQuery('#' + detailsPaneName);
            if (detailsPane) {
                jQuery(detailsPane).siblings().hide();
                jQuery(detailsPane).show();
            }
        }
    });
});
