// Add Page Tools
function addPageTools() {
    var urlToUse = (('https:' == document.location.protocol) ? 'https://secure.addthis.com/js/250/addthis_widget.js?pub=averaaddthis' : 'http://s7.addthis.com/js/250/addthis_widget.js?pub=averaaddthis')
    var imgPath = '/imgs/icons/';
    $('#PageToolsWrapper').append('<div id="PageTools"><ul>' +
		    '<li class="AddThis">' +
			    '<!-- AddThis Button BEGIN -->' +
		        '<script type="text/javascript">var addthis_pub = "averaaddthis";</script>' +
		        '<a href="http://www.addthis.com/bookmark.php?v=250&pub=averaaddthis" onclick="return addthis_open(this, \'\', \'[URL]\', \'[TITLE]\')" onmouseout="addthis_close();" onclick="return addthis_sendto();">Share This Page</a>' +
		        '<script type="text/javascript" src="' + urlToUse + '"></script>' +
		        '<!-- AddThis Button END -->' +
			'</li>' +
			'<li class="Email"><a href="#">Email</a></li>' +
			'<li class="Print"><a href="#">Print</a></li>' +
		'</ul></div>');
    var clientDomainName = 'avera.org';
    var clientSiteName = 'Avera';
    var titleEl = document.getElementsByTagName('title')[0];
    var currentPageTitle = '';
    if (titleEl.text) { currentPageTitle = titleEl.text; } else { currentPageTitle = title.data; }
    currentPageTitle = escape(currentPageTitle);
    var currentPageUrl = document.location;
    var emailSubject = clientDomainName + ': ' + currentPageTitle;
    var emailHref = 'mailto:?subject=' + emailSubject + '&body=I thought you would be interested in a page on the ' + clientSiteName + ' Web site: ' + currentPageTitle + ' - ' + currentPageUrl;
    $('li.Email a').attr({ href: emailHref });
    $('li.Print a').click(function() { print(); return false; });
}

//TEXT SIZER
function addTextSizer() {
    $('#PageTools').before('<div id="TextSizer"><p>Change Font Size</p><ul>' +
				'<li><a class="NormalFont" href="javascript:;" title="Small Font Size">Normal</a></li>' +
				'<li><a class="LargeFont" href="javascript:;" title="Medium Font Size">Large</a></li>' +
				'<li><a class="X-LargeFont" href="javascript:;" title="Large Font Size">X-Large</a></li>' +
			"</ul></div>");
	$('a.NormalFont').click(function() {$('#Content').removeClass('textLarge').removeClass('textXLarge');$.cookie('text_sizer', null, { path: '/' });});
	$('a.LargeFont').click(function() {$('#Content').addClass('textLarge').removeClass('textXLarge');$.cookie('text_sizer', 'large', { path: '/' });});
	$('a.X-LargeFont').click(function() {$('#Content').removeClass('textLarge').addClass('textXLarge');$.cookie('text_sizer', 'xlarge', { path: '/' });});
	$('#TextSizer a').click(function() {$('#TextSizer a').removeClass('active');$(this).addClass('active');});
}

function text_size_checker() {
	var text_sizer_cookie = $.cookie('text_sizer');
	if (text_sizer_cookie==null){$('a.NormalFont').addClass('active')};
	if (text_sizer_cookie=='large'){ $('#Content').addClass('textLarge');$('a.LargeFont').addClass('active') };
	if (text_sizer_cookie=='xlarge'){ $('#Content').addClass('textXLarge');$('a.X-LargeFont').addClass('active') };
}

function dynamicVideoPlayer(){
// markup to use: <a class="VideoLink" href="video/widescreen.mp4" title="height=288;width=512;aspect=16x9;hideControls=true;imageFilename=video/widescreen.jpg;">Video</a>
	String.prototype.startsWith = function(str) {return (this.match("^"+str)==str);}; // this creates a function that can be used to check if a string starts with a value
	// for each a.VideoLink, put a player in place
	$('a.VideoLink').each(function(n){
		var divID = 'videoID'+n;
			$(this).wrap('<div class="DynamicVideoPlayer" id="' + divID + '"></div>');
		var filename = $(this).attr('href');
		var vars = $(this).attr('title').replace(/\s+/g,'');
		var varArray = vars.split(';');
		var height, width, aspect, hideControls, imageFilename, theImage;
		height = width = aspect = hideControls = imageFilename = theImage = '';
		
		var cnt = 0;
		while (cnt < varArray.length) {
			if (varArray[cnt].toLowerCase().startsWith('height=')) { height = varArray[cnt].toLowerCase().replace(/height=/g,''); }
			if (varArray[cnt].toLowerCase().startsWith('width=')) { width = varArray[cnt].toLowerCase().replace(/width=/g,''); }
			if (varArray[cnt].toLowerCase().startsWith('aspect=')) { aspect = '_' + varArray[cnt].toLowerCase().replace(/aspect=/g,''); }
			if (varArray[cnt].toLowerCase().startsWith('hidecontrols=')) { hideControls = varArray[cnt].toLowerCase().replace(/hidecontrols=/g,''); }
			if (varArray[cnt].toLowerCase().startsWith('imagefilename=')) { imageFilename = varArray[cnt].toLowerCase().replace(/imagefilename=/g,''); }
			cnt+=1;
		}
		if (height < 0 || height > 600) { height = '240'; }
		if (width < 0 || width > 800) { width = '360'; }
		if ( aspect.length && !(aspect == '_4x3' || aspect == '_16x9' || aspect == '_1x1') ) { aspect = '_4x3'; }
		if (hideControls !== 'true' && hideControls !== 'false') { hideControls = 'false'; }
		if (imageFilename.length > 0 ) { theImage = 'imageFilename=' + imageFilename + '&'; }
			
		var so = new SWFObject('/video/videoPlayer' + aspect + '.swf?videoURL=' + filename, 'swf', width, height, '7' );
		so.addParam('wmode', 'transparent');
		so.addParam('FlashVars', theImage + 'hideControls=' + hideControls);
		so.addParam('allowscriptaccess', 'always');
		so.addParam('allowfullscreen', 'true');	
		so.write(divID);
	});
}

	
function dynamicWMVVideoPlayer(){
	// Like the above player, but instead will allow for WMV instead.
	// <a class="WMVVideoLink" href="video/filename.wmv" name="height=288;width=512;hideControls=true;autoStart=true">Any Text You Like</a>
		$('a.WMVVideoLink').each(function(n){
	
		var divID = 'WMVid'+n;
		$(this).wrap('<div class="WMVVideoPlayer" id="' + divID + '"></div>');
		$(this).hide();
		
		var filename = $(this).attr('href');
		var vars = $(this).attr('name').replace(/\s+/g,'');
		var varArray = vars.split(";");
		
		var height, width, hideControls, autoStart;
		height = width = hideControls = autoStart = '';
		
		var cnt = 0
		while (cnt < varArray.length) {
			if (varArray[cnt].toLowerCase().startsWith('height=')) { var height = varArray[cnt].toLowerCase().replace(/height=/g,''); };
			if (varArray[cnt].toLowerCase().startsWith('width=')) { var width = varArray[cnt].toLowerCase().replace(/width=/g,''); };
			if (varArray[cnt].toLowerCase().startsWith('hidecontrols=')) { var hideControls = varArray[cnt].toLowerCase().replace(/hidecontrols=/g,''); };
			if (varArray[cnt].toLowerCase().startsWith('autoStart=')) { var autoStart = varArray[cnt].toLowerCase().replace(/autoStart=/g,''); };
			cnt+=1;
		};

		if (height < 0 || height > 600) { var height = "240" };
		if (width < 0 || width > 800) { var width = "360" };
		if (hideControls == 'true') { hideControls = 'false' } else if (hideControls == 'false') { hideControls = 'true' };
		if (hideControls !== 'true' || hideControls !== 'false') { var hideControls = 'true' };
		
		
		if (hideControls == 'false') { autoStart = 'true' };
			
		$('#'+divID)
		.append('<OBJECT ID="MediaPlayer" WIDTH="' + width +'" HEIGHT="' + height +'" CLASSID="CLSID:22D6F312-B0F6-11D0-94AB-0080C74C7E95" STANDBY="Loading Windows Media Player components..." TYPE="application/x-oleobject">'
				+ '<PARAM NAME="FileName" VALUE="' + filename + '">'
				+ '<PARAM name="autostart" VALUE="' + autoStart + '">'
				+ '<PARAM name="ShowControls" VALUE="' + hideControls + '">'
				+ '<param name="ShowStatusBar" value="false">'
				+ '<PARAM name="ShowDisplay" VALUE="false">'
				+ '<EMBED TYPE="application/x-mplayer2" SRC="' + filename + '" NAME="MediaPlayer" WIDTH="' + width +'" HEIGHT="' + height +'" ShowControls="1" ShowStatusBar="0" ShowDisplay="0" autostart="0"> </EMBED>'
				+ '</OBJECT>');
		
	});
	}

$(document).ready(function(){
	addPageTools();	
	addTextSizer();
	text_size_checker();
	dynamicVideoPlayer();
	dynamicWMVVideoPlayer();
});

//Extras
$(document).ready(function() {

    // ----------- TEMPLATE EXTRAS ------------------//

    //adding active class to hard coded main nav
    var sectionName = $.url.segment(0);
    if (sectionName != null) {
        if (sectionName.toLowerCase() == 'services') {
            $('#CorpMainNav li.First').addClass('Active');
        }
        if (sectionName.toLowerCase() == 'locations') {
            $('#CorpMainNav li.Second').addClass('Active');
        }
        if (sectionName.toLowerCase() == 'doctors') {
            $('#CorpMainNav li.Third').addClass('Active');
        }
        if (sectionName.toLowerCase() == 'eventscalendar') {
            $('#CorpMainNav li.Fourth').addClass('Active');
        }
        if (sectionName.toLowerCase() == 'health-info') {
            $('#CorpMainNav li.Fifth').addClass('Active');
        }
        if (sectionName.toLowerCase() == 'careers') {
            $('#CorpMainNav li.Sixth').addClass('Active');
        }
        if (sectionName.toLowerCase() == 'avera') {
            $('#CorpMainNav li.Seventh').addClass('Active');
        }
    }
    $('#CorpMainNav li.Active a').addClass('Active');

    /* adding padding to the last main nav link to span across entire container 
    so that background spans all the way to the right.*/
    $('#CorpMainNav span').each(function(i) {
        var ah = $('#CorpMainNav ul').eq(i).width();
        var mh = (950 - ah - 1); //need -1 to fix wrapping on Mac
        $('#CorpMainNav li.Seventh a').eq(i).css('padding-right', mh);
        $('#CorpMainNav li.Seventh strong').eq(i).css('padding-right', mh);
    });

    // For Tri-State templates - moving prox nav within main nav
    $('body.TriStateLeftCol #ProximityNav').appendTo('#MainNav li.Active');
    $('body.LeftCol #ProximityNav').appendTo('#MainNav li.Active');
    $('body.Interior #ProximityNav').appendTo('#MainNav li.Active');
    $('body.Landing #ProximityNav').appendTo('#MainNav li.Active');
    // Removing Proximity Nav h2 if on page not in subsection.
    if ($('#Breadcrumbs p a[href]').length < 3) {
        $('#ProximityNav').addClass('RemoveH2');
    }
    else {
        $('#ProximityNav').addClass('KeepH2');
    }

    //Drop Down Styles
    // adds a width to the .Flyout .Dec div if it is shorter than Toggle anchor
    $('.DropDown').not('.Dropdown-Small').each(function() {
        var tw = $(this).find('a.Toggle').width();
        var fw = $(this).find('.Flyout').width();
        var mw = (tw - 22);
        if (fw < tw) {
            $(this).find('.Dec').css('width', mw);
        }
    });
    //Creates DropDown style function
    $('.Toggle').live('click', function() {
        var trigger = $(this);
        var triggerHeight = trigger.outerHeight();
        var triggerPosition = trigger.offset();
        var thePop = $(this).siblings('.Flyout');
        var popHeight = thePop.height();
        var docHeight = $(document).height();
        var winHeight = $(window).height();
        var scrolledHeight = $(window).scrollTop();

        var heightAboveTrigger = (triggerPosition.top - scrolledHeight);
        var heightBelowTrigger = winHeight - heightAboveTrigger - triggerHeight;

        //        alert('height above trigger:' + heightAboveTrigger
        //        		+ '\n height below trigger: ' + heightBelowTrigger
        //        		+ '\n height of popup: ' + (popHeight)
        //        		);

        var offset = 0;

        // if there's not enough room below, then set postion to be above trigger
        if (heightBelowTrigger < popHeight) {
            offset = -popHeight;
            // unless there's not enough room above it, then show below
            if (heightAboveTrigger < popHeight) {
                offset = $(this).outerHeight();
            }
            // except when we're at the end of the document, and there's not enough room below but there is above then show it above
            if ((docHeight - (winHeight + scrolledHeight) < popHeight) && (heightBelowTrigger < popHeight) && ((heightAboveTrigger + scrolledHeight) > popHeight)) {
                offset = -popHeight;
            }
        }
        // if there is enough room to show below, then do it
        else {
            offset = $(this).outerHeight();
        }

        // set z-index for dropdown then show the popup
        trigger.closest('.DropDown').css({ 'z-index': '3000' });
        //        thePop.css({ 'top': offset }).show();
        thePop.css({ 'top': offset, visibility: 'visible' });

    });

    // on mouseout, hide the popup
    $('.DropDown').mouseleave(function() {
        //        $(this).find('.Flyout').hide();
        $(this).find('.Flyout').css({ visibility: 'hidden' });
        $(this).css({ 'z-index': '0' });
    });

    //remove col3 if empty
    $('#Col3:empty').remove();

    //only show banner curve if panel exists within space
    $('#BannerCurve').hide();
    if ($('#Banner .cmspanel').length > 0) {
        $('#BannerCurve').show();
    }

    // img embelished style
    $('.ImageEmbellished').each(function() {
        var ih = $(this).find('img').height();
        var iw = $(this).find('img').width();
        $(this).find('.ImageEmbellishedOverlay').css('height', ih);
        $(this).find('.ImageEmbellishedOverlay').css('width', iw);
    });

    // img embelished doesn't work with hidden elements... so we'll re-activate it when you click on a tab or accordion to update the images that were hidden.
    $('.Tabnav li').live('click', function() {
        $(this).closest('.TabContainerlive').find('.ImageEmbellished:visible').each(function() {
            var ih = $(this).find('img').height();
            var iw = $(this).find('img').width();
            $(this).find('.ImageEmbellishedOverlay').css('height', ih);
            $(this).find('.ImageEmbellishedOverlay').css('width', iw);
        });
    });

    $('.Accordion .Trigger').live('click', function() {
        $(this).closest('.Accordion').find('.ImageEmbellished:visible').each(function() {
            var ih = $(this).find('img').height();
            var iw = $(this).find('img').width();
            $(this).find('.ImageEmbellishedOverlay').css('height', ih);
            $(this).find('.ImageEmbellishedOverlay').css('width', iw);
        });
    });

    // Avera Medical Group style
    $('.DrList li strong').text('Avera Medical Group').parent().parent().parent().parent().addClass('AMG');
    $('.DrList li strong').text('Avera Medical Group').prepend('<div id="HelpOverlay"><img src="/imgs/icons/help.gif" alt="What\'s this?" /><div class="Overlay"><p>Avera Medical Group physicians maintain their own practices and are backed by the resources of Avera.</p></div></div>');
    $('#DrDetail ul.Promotions li strong').text('Avera Medical Group').append('<div id="HelpOverlay"><img src="/imgs/icons/help.gif" alt="What\'s this?" /><div class="Overlay"><p>Avera Medical Group physicians maintain their own practices and are backed by the resources of Avera.</p></div></div>');
	
	// Hide the results list on the locations index page
    var thisDir = $.url.attr('directory')
    if (thisDir.indexOf('locations/index.aspx') > 0) {  // if the word 'locations/index.aspx' exists in the url path anywhere, then do this
        $('.Paging').remove();
		$('.LocationsList').remove();
    }

    // ----------- HACK LIST START ------------------//

    //removing padding from empty table cells from calendar event detail header
    $('.CalendarEventDetailHeader td:empty').addClass('Empty');

    //adding hack to be fixed after 5.2.7
    $('.TabContainer').addClass('TabContainerlive');

    //adding ClearFix class on div directly outside of the client cmspanel content.
    $('.cmsPanelContent').addClass('ClearFix');

    // ----------- HACK LIST END ------------------//

});
