/**
* hoverIntent r6 // 2011.02.26 // jQuery 1.5.1+
* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
* 
* @param  f  onMouseOver function || An object with configuration options
* @param  g  onMouseOut function  || Nothing (use configuration options object)
* @author    Brian Cherne brian(at)cherne(dot)net
*/
(function ($) { $.fn.hoverIntent = function (f, g) { var cfg = { sensitivity: 7, interval: 100, timeout: 0 }; cfg = $.extend(cfg, g ? { over: f, out: g} : f); var cX, cY, pX, pY; var track = function (ev) { cX = ev.pageX; cY = ev.pageY }; var compare = function (ev, ob) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); if ((Math.abs(pX - cX) + Math.abs(pY - cY)) < cfg.sensitivity) { $(ob).unbind("mousemove", track); ob.hoverIntent_s = 1; return cfg.over.apply(ob, [ev]) } else { pX = cX; pY = cY; ob.hoverIntent_t = setTimeout(function () { compare(ev, ob) }, cfg.interval) } }; var delay = function (ev, ob) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); ob.hoverIntent_s = 0; return cfg.out.apply(ob, [ev]) }; var handleHover = function (e) { var ev = jQuery.extend({}, e); var ob = this; if (ob.hoverIntent_t) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t) } if (e.type == "mouseenter") { pX = ev.pageX; pY = ev.pageY; $(ob).bind("mousemove", track); if (ob.hoverIntent_s != 1) { ob.hoverIntent_t = setTimeout(function () { compare(ev, ob) }, cfg.interval) } } else { $(ob).unbind("mousemove", track); if (ob.hoverIntent_s == 1) { ob.hoverIntent_t = setTimeout(function () { delay(ev, ob) }, cfg.timeout) } } }; return this.bind('mouseenter', handleHover).bind('mouseleave', handleHover) } })(jQuery);



function addEmailLink() {
	var clientDomainName = 'http://www.uch.edu/',
		clientSiteName = 'University of Colorado Hospital',
		currentPageUrl = document.location,
		currentPageTitle = $.trim($('title').text()),
		emailSubject = clientDomainName + ': ' + currentPageTitle,
		emailHref = 'mailto:?subject=' + escape(emailSubject) + '&body=I thought you would be interested in a page on the ' + escape(clientSiteName) + ' Web site: ' + escape(currentPageTitle) + ' - ' + escape(currentPageUrl);

    $('#PageTools').prepend('<div id="EmailPrint"><ul>' +
			'<li class="Email"><a href="' + emailHref + '">Email Page</a></li>' +
            '<li class="Print"><a href="javscript:;" onclick="print();">Printer Friendly</a></li>' +
		'</ul></div>');
}

/***********************************************
* Bookmark site script- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/
function Save(title, url) {
    if (window.sidebar) // firefox
        window.sidebar.addPanel(title, url, '');
    else if (document.all)// ie
        window.external.AddFavorite(url, title);
    else {
        // other browsers - tell them to add a bookmark (adds current page, not target page)
        window.alert('Please use your browser\'s bookmarking facility to create a bookmark');
    }
}
function addTextSizer() {
    $('#PageTools').prepend('<div id="TextSizer" class="ClearFix"><dl>' +
				'<dt>Font Size</dt>' +
				'<dd><a class="NormalFont" href="javascript:;" title="Small Font Size"></a></dd>' +
				'<dd><a class="LargeFont" href="javascript:;" title="Medium Font Size"></a></dd>' +
				'<dd><a class="X-LargeFont" href="javascript:;" title="Large Font Size"></a></dd>' +
			'</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') };
}

// AUTO PHOTO ROTATOR
function theRotator() {
	//Set the opacity of all images to 0
	$('div.Rotator ul li').css({opacity: 0.0});
	
	//Get the first image and display it (gets set to full opacity)
	$('div.Rotator ul li:first').css({opacity: 1.0});
		
	//Call the Rotator function to run the slideshow, 6000 = change to next image after 6 seconds
	setInterval('rotate()',5400);
}

function rotate() {	
	//Get the first image
	var current = ($('div.Rotator ul li.show')?  $('div.Rotator ul li.show') : $('div.Rotator ul li:first'));

	//Get next image, when it reaches the end, rotate it back to the first image
	var next = ((current.next().length) ? ((current.next().hasClass('show')) ? $('div.Rotator ul li:first') :current.next()) : $('div.Rotator ul li:first'));	
	
	//Set the fade in effect for the next image, the show class has higher z-index
	next.css({opacity: 0.0})
	.addClass('show')
	.animate({opacity: 1.0}, 2500);

	//Hide the current image
	current.animate({opacity: 0.0}, 2500)
	.removeClass('show');
};

$(document).ready(function() {		
	//Load the slideshow
	theRotator();
});


// TABS
// Copyright (c) 2006 Patrick Fitzgerald
// http://www.barelyfitz.com/projects/tabber/
/* Optional: set an ID for each tab navigation link */
var tabberOptions = { 'addLinkId': true };
/* start minified tabs script*/
function tabberObj(argsObj)
{var arg;this.div=null;this.classMain="TabsContainer";this.classMainLive="TabsContainerlive";this.classTab="Tab";this.classTabDefault="Tabdefault";this.classNav="Tabnav ClearFix";this.classTabHide="Tabhide";this.classNavActive="Tabactive";this.summaryElements=['h2'];this.summaryElementsStripHTML=true;this.removeSummary=true;this.addLinkId=false;this.linkIdFormat='<tabberid>nav<tabnumberone>';for(arg in argsObj){this[arg]=argsObj[arg];}
this.REclassMain=new RegExp('\\b'+this.classMain+'\\b','gi');this.REclassMainLive=new RegExp('\\b'+this.classMainLive+'\\b','gi');this.REclassTab=new RegExp('\\b'+this.classTab+'\\b','gi');this.REclassTabDefault=new RegExp('\\b'+this.classTabDefault+'\\b','gi');this.REclassTabHide=new RegExp('\\b'+this.classTabHide+'\\b','gi');this.tabs=new Array();if(this.div){this.init(this.div);this.div=null;}}
tabberObj.prototype.init=function(e)
{var
childNodes,i,i2,t,defaultTab=0,DOM_ul,DOM_li,DOM_a,aId,headingElement;if(!document.getElementsByTagName){return false;}
if(e.id){this.id=e.id;}
this.tabs.length=0;childNodes=e.childNodes;for(i=0;i<childNodes.length;i++){if(childNodes[i].className&&childNodes[i].className.match(this.REclassTab)){t=new Object();t.div=childNodes[i];this.tabs[this.tabs.length]=t;if(childNodes[i].className.match(this.REclassTabDefault)){defaultTab=this.tabs.length-1;}}}
DOM_ul=document.createElement("ul");DOM_ul.className=this.classNav;for(i=0;i<this.tabs.length;i++){t=this.tabs[i];t.headingText=t.div.summary;if(this.removeSummary){t.div.summary='';}
if(!t.headingText){for(i2=0;i2<this.summaryElements.length;i2++){headingElement=t.div.getElementsByTagName(this.summaryElements[i2])[0];if(headingElement){t.headingText=headingElement.innerHTML;if(this.summaryElementsStripHTML){t.headingText.replace(/<br>/gi," ");t.headingText=t.headingText.replace(/<[^>]+>/g,"");}
break;}}}
if(!t.headingText){t.headingText=i+1;}
DOM_li=document.createElement("li");t.li=DOM_li;DOM_a=document.createElement("a");DOM_a.innerHTML = t.headingText;DOM_a.href="javascript:void(null);";DOM_a.summary=t.headingText;DOM_a.onclick=this.navClick;DOM_a.tabber=this;DOM_a.tabberIndex=i;if(this.addLinkId&&this.linkIdFormat){aId=this.linkIdFormat;aId=aId.replace(/<tabberid>/gi,this.id);aId=aId.replace(/<tabnumberzero>/gi,i);aId=aId.replace(/<tabnumberone>/gi,i+1);aId=aId.replace(/<tabsummary>/gi,t.headingText.replace(/[^a-zA-Z0-9\-]/gi,''));DOM_a.id=aId;}
DOM_li.appendChild(DOM_a);DOM_ul.appendChild(DOM_li);}
e.insertBefore(DOM_ul,e.firstChild);e.className=e.className.replace(this.REclassMain,this.classMainLive);this.tabShow(defaultTab);if(typeof this.onLoad=='function'){this.onLoad({tabber:this});}
return this;};tabberObj.prototype.navClick=function(event)
{var
rVal,a,self,tabberIndex,onClickArgs;a=this;if(!a.tabber){return false;}
self=a.tabber;tabberIndex=a.tabberIndex;a.blur();if(typeof self.onClick=='function'){onClickArgs={'tabber':self,'index':tabberIndex,'event':event};if(!event){onClickArgs.event=window.event;}
rVal=self.onClick(onClickArgs);if(rVal===false){return false;}}
self.tabShow(tabberIndex);return false;};tabberObj.prototype.tabHideAll=function()
{var i;for(i=0;i<this.tabs.length;i++){this.tabHide(i);}};tabberObj.prototype.tabHide=function(tabberIndex)
{var div;if(!this.tabs[tabberIndex]){return false;}
div=this.tabs[tabberIndex].div;if(!div.className.match(this.REclassTabHide)){div.className+=' '+this.classTabHide;}
this.navClearActive(tabberIndex);return this;};tabberObj.prototype.tabShow=function(tabberIndex)
{var div;if(!this.tabs[tabberIndex]){return false;}
this.tabHideAll();div=this.tabs[tabberIndex].div;div.className=div.className.replace(this.REclassTabHide,'');this.navSetActive(tabberIndex);if(typeof this.onTabDisplay=='function'){this.onTabDisplay({'tabber':this,'index':tabberIndex});}
return this;};tabberObj.prototype.navSetActive=function(tabberIndex)
{this.tabs[tabberIndex].li.className=this.classNavActive;return this;};tabberObj.prototype.navClearActive=function(tabberIndex)
{this.tabs[tabberIndex].li.className='';return this;};function tabberAutomatic(tabberArgs)
{var
tempObj,divs,i;if(!tabberArgs){tabberArgs={};}
tempObj=new tabberObj(tabberArgs);divs=document.getElementsByTagName("div");for(i=0;i<divs.length;i++){if(divs[i].className&&divs[i].className.match(tempObj.REclassMain)){tabberArgs.div=divs[i];divs[i].tabber=new tabberObj(tabberArgs);}}
return this;}
function tabberAutomaticOnLoad(tabberArgs)
{var oldOnLoad;if(!tabberArgs){tabberArgs={};}
oldOnLoad=window.onload;if(typeof window.onload!='function'){window.onload=function(){tabberAutomatic(tabberArgs);};}else{window.onload=function(){oldOnLoad();tabberAutomatic(tabberArgs);};}}
if(typeof tabberOptions=='undefined'){tabberAutomaticOnLoad();}else{if(!tabberOptions['manualStartup']){tabberAutomaticOnLoad(tabberOptions);}}

// FIX DROP DOWN BOXES IN IE SO THEY ACT LIKE FIREFOX DROP DOWNS (<SELECT>)
(function($) {
    $.fn.IELongDropDown = function(cln) {
        if ($.browser.msie) { //only IE has problems with long select boxes
            var el = this;
            var previousWidth = el.width();
			if(previousWidth>0){
				var divWrapper = '<span style="padding:0;margin:0;overflow:hidden;width:'+ previousWidth +'px"></span>';
				el.wrap(divWrapper);
				var newWidth = el.width('auto').width();
				el.width(previousWidth);
				if(newWidth > previousWidth && $.browser.version!='6.0') {
					el.bind('mousedown', function(){ return el.width('auto').focus(); }); 
					el.bind('blur', function(){ return el.width(previousWidth); });
					el.bind('change', function(){ return el.width(previousWidth); });
				}
				else if(newWidth > previousWidth && $.browser.version=='6.0') {  
					el.bind('focusin',function(){el.width('auto').focus();});
					el.blur(function(){el.width(previousWidth);});
//					el.bind('mousedown', function(){ return el.width('auto').focus(); }); 
//					el.bind('blur', function(){ return el.width(previousWidth); });
//					el.bind('change', function(){ return el.width(previousWidth); });
				}
			} 
        } 
        return this;
    };
})(jQuery);

$(document).ready(function () {
    addEmailLink();
    addTextSizer();
    text_size_checker();

    // FIX DROP DOWNS IN IE
    $('select').each(function () {
        $(this).IELongDropDown();
    });


    // ----------- TEMPLATE EXTRAS ------------------//

    // Adding class of first to Clinical Trial results list first li
    $('#ClinicalTrialsResults .ResultsList li:first').addClass('First');

    //Remove quicklinks if empty
    $("#ContactInfo ul li:empty").remove();
    if ($.trim($("#ContactInfo ul li").text()) == "") {
        $("#ContactInfo ul li").remove();
    }
    $("#Col3Panels:empty").remove();
    if ($.trim($("#Col3Panels").text()) == "") {
        $("#Col3Panels").remove();
    }
    $(".Col3Inner1:empty").remove();
    if ($.trim($(".Col3Inner1").text()) == "") {
        $(".Col3Inner1").remove();
    }
    $(".RegDetails:empty").remove();
    if ($.trim($(".RegDetails").text()) == "") {
        $(".RegDetails").remove();
    }

    // remove last li on home page 
    $('#Home #MainNav ul').addClass('MainNav');
    $('#Home #MainNav ul ul').removeClass();
    $('#MainNav ul ul li').removeClass();
    $('#Home #MainNav ul.MainNav li.Last').remove();
    $('#Home #MainNav ul.MainNav li:last-child').addClass('Last').addClass('Block');

    $('#MainNav li:nth-child(1)').addClass('First');
    $('#MainNav li:nth-child(2)').addClass('Second');
    $('#MainNav li:nth-child(3)').addClass('Third');
    $('#MainNav li:nth-child(4)').addClass('Fourth');
    $('#MainNav li:nth-child(5)').addClass('Fifth');
    $('#MainNav li:nth-child(6)').addClass('Sixth');
    $('#MainNav li:nth-child(7)').addClass('Seventh');
    $('#MainNav li:nth-child(8)').addClass('Eighth');

    $('#Flyout1').appendTo('#MainNav li.First');
    $('#Flyout2').appendTo('#MainNav li.Second');
    $('#Flyout3').appendTo('#MainNav li.Third');
    $('#Flyout4').appendTo('#MainNav li.Fourth');
    $('#Flyout5').appendTo('#MainNav li.Fifth');
    $('#Flyout6').appendTo('#MainNav li.Sixth');

    // remove the main nav drop down if .cmspanel doesn't exist or is empty
    $('.Flyout .FlyoutInner:empty').parent().parent().parent().remove();
    $('.Flyout .FlyoutInner .cmspanel:empty').parent().parent().parent().parent().remove();

    $('#MainNav ul ul li').removeClass();

    $("#VisitorType a").hover(
      function () {
          $('#VisitorType li a').removeClass("Active");
          $(this).addClass("Active");
      },
      function () {
          $(this).removeClass("Active");
          $('#VisitorType li.First a').addClass("Active");
      }
    );

    //Making last nav item expand
    $('#MainNav span').each(function (i) {
        var ah = $('#MainNav ul').eq(i).width();
        var mh = (987 - ah);
        $('#MainNav li.Last a').eq(i).css('padding-right', mh);
        $('#MainNav li.Last strong').eq(i).css('padding-right', mh);
        $('#MainNav li.Last ul a').css('padding-right', '3px');
        $('#MainNav li.Last ul strong').css('padding-right', '3px');
    });

    $('#Mobile #MainNav span').each(function (i) {
        var mh = 0;
        $('#MainNav li.Last a').eq(i).css('padding-right', mh);
        $('#MainNav li.Last strong').eq(i).css('padding-right', mh);
        $('#MainNav li.Last ul a').css('padding-right', '0px');
        $('#MainNav li.Last ul strong').css('padding-right', '0px');
    });

    $('#Home #MainNav li.Last a').css('padding-right', '25px');

    $("#MainNav li.First").hover(
      function () {
          $('#MainNav li.Active').addClass("DeActive").delay(1000);
          $('#MainNav li.Active').removeClass("Active").delay(1000);
          $(this).addClass("Hover");
      },
      function () {
          $('#MainNav li.DeActive').addClass("Active").delay(1000);
          $('#MainNav li.DeActive').removeClass("DeActive").delay(1000);
          $(this).removeClass("Hover");
      }
    );
    $("#MainNav li.Second").hover(
      function () {
          $('#MainNav li.Active').addClass("DeActive").delay(1000);
          $('#MainNav li.Active').removeClass("Active").delay(1000);
          $(this).addClass("Hover");
      },
      function () {
          $('#MainNav li.DeActive').addClass("Active").delay(1000);
          $('#MainNav li.DeActive').removeClass("DeActive").delay(1000);
          $(this).removeClass("Hover");
      }
    );
    $("#MainNav li.Third").hover(
      function () {
          $('#MainNav li.Active').addClass("DeActive").delay(1000);
          $('#MainNav li.Active').removeClass("Active").delay(1000);
          $(this).addClass("Hover");
      },
      function () {
          $('#MainNav li.DeActive').addClass("Active").delay(1000);
          $('#MainNav li.DeActive').removeClass("DeActive").delay(1000);
          $(this).removeClass("Hover");
      }
    );
    $("#MainNav li.Fourth").hover(
      function () {
          $('#MainNav li.Active').addClass("DeActive").delay(1000);
          $('#MainNav li.Active').removeClass("Active").delay(1000);
          $(this).addClass("Hover");
      },
      function () {
          $('#MainNav li.DeActive').addClass("Active").delay(1000);
          $('#MainNav li.DeActive').removeClass("DeActive").delay(1000);
          $(this).removeClass("Hover");
      }
    );
    $("#MainNav li.Fifth").hover(
      function () {
          $('#MainNav li.Active').addClass("DeActive").delay(1000);
          $('#MainNav li.Active').removeClass("Active").delay(1000);
          $(this).addClass("Hover");
      },
      function () {
          $('#MainNav li.DeActive').addClass("Active").delay(1000);
          $('#MainNav li.DeActive').removeClass("DeActive").delay(1000);
          $(this).removeClass("Hover");
      }
    );
    $("#MainNav li.Sixth").hover(
      function () {
          $('#MainNav li.Active').addClass("DeActive").delay(1000);
          $('#MainNav li.Active').removeClass("Active").delay(1000);
          $(this).addClass("Hover");
      },
      function () {
          $('#MainNav li.DeActive').addClass("Active").delay(1000);
          $('#MainNav li.DeActive').removeClass("DeActive").delay(1000);
          $(this).removeClass("Hover");
      }
    );
    $("#MainNav li.Seventh").hover(
      function () {
          $('#MainNav li.Active').addClass("DeActive").delay(1000);
          $('#MainNav li.Active').removeClass("Active").delay(1000);
          $(this).addClass("Hover");
      },
      function () {
          $('#MainNav li.DeActive').addClass("Active").delay(1000);
          $('#MainNav li.DeActive').removeClass("DeActive").delay(1000);
          $(this).removeClass("Hover");
      }
    );
    $("#MainNav li.Eighth").hover(
      function () {
          $('#MainNav li.Active').addClass("DeActive").delay(1000);
          $('#MainNav li.Active').removeClass("Active").delay(1000);
          $(this).addClass("Hover");
      },
      function () {
          $('#MainNav li.DeActive').addClass("Active").delay(1000);
          $('#MainNav li.DeActive').removeClass("DeActive").delay(1000);
          $(this).removeClass("Hover");
      }
    );

    // Changing cmspanel class to NoMargin panel
    $('#Col3 .NoMargin').parent().parent().parent().parent().parent().parent().removeClass('cmspanel').addClass('cmspanel2');

    // Adding classes to col3 cmspanel
    $('#Col3 .Col3Inner1 .cmspanel:first-child').addClass('First');
    $('#Col3 .cmspanel:last-child').addClass('Last');


    // Making tabs have equal heights
    function equalHeight(group) {
        var tallest = 0;
        group.each(function () {
            var thisHeight = $(this).height();
            if (thisHeight > tallest) {
                tallest = thisHeight;
            }
        });
        group.height(tallest);
    }
    equalHeight($(".Tabnav li"));
    equalHeight($(".Tabnav li a"));

    // Add "First" to accordions
    $('.Accordion h3:first-child').addClass('First');


    // ----------- HACK LIST START ------------------//
    //replace legends with labels
    $('legend').each(function (index) {
        $(this).replaceWith('<label class="Block">' + $(this).html() + '</label>');
    });

    //
    if ($('#Nearby #BottomAds .Dec div').hasClass('cmspanel')) {
        $('#Nearby #BottomAds').addClass('Active');
    }
    if ($('#Nearby #BottomAds').hasClass('Active')) {
        $('#Nearby #BottomAds').removeClass('Hide');
    }

    //Replacing text on Services module
    $('#ServicesSearch label.Block').html('Search for a Service, Therapy, or Treatment');
    $('#ServicesSearch #BrowseTab ul.Tabnav li:first-child a').html('Services, Therapies, and Treatments');

    //Remove after 6.2 release
    $('#CalendarSearch .SearchBox label:contains("Search for a calendar events")').text('Search for calendar events');

    // ----------- HACK LIST END ------------------//

    // For Mobile Template: if any div.cmspage is empty, let's remove it -- avoids padding on empty pages.			
    $('#Mobile div').each(function (i, el) {
        // Remove white space
        var html = $(el).html().replace(/\s+/, '');
        // Check if element is :empty or length of html is zero
        if ($(el).is(':empty') || html.length == 0)
            $(el).remove();
    });

    // Mobile site - Reformat Locations  //
    // Loop through array //
    $('#Mobile .LocationsList > ul > li').each(function () {
        //Move phone number after location name
        $(this).find('.Headline').after($(this).find('.Phone'))
        //Move Minor Details after Major Details
        $(this).find('.MajorDetails').after($(this).find('.MinorDetails'))
    });
    // Move Prev and Next links to their own line
    $('#Mobile .Paging').each(function () {
        var BackNext = $(this).find('.BackNext');
        $(this).find('tr').after('<tr class="BackNextLink"><td class="BackNext">' + BackNext.html() + '</td></tr>');
        BackNext.remove();
    });

    // Event Details - Move td with class EventDetailTime to its own row
    $('#Mobile .CalendarEventDetailHeader').each(function () {
        var EventTime = $(this).find('.EventDetailTime');
        $(this).find('tr').before('<tr><td class="EventDetailTime">' + EventTime.html() + '</td></tr>');
        EventTime.remove();
    });
    // Event Detials - Add class of first to h3 and h4 in Tab container
    $('#Mobile .CalendarDetail .Tab h3:first').addClass('First');
    $('#Mobile .CalendarDetail .Tab h4:first').addClass('First');

    // Mobile Find a doctor - move photo
    $('#Mobile .DrList > li').each(function () {
        var Picture = $(this).find('.Picture');
        $(this).find('dl').before('<div class="MovePicture">' + Picture.html() + '</div>');
        Picture.remove();
        $('.Locations .MovePicture').remove();
    });

});               // End Document Ready
