//start jquery hoverIntent function
(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 p=(e.type=="mouseover"?e.fromElement:e.toElement)||e.relatedTarget;while(p&&p!=this){try{p=p.parentNode;}catch(e){p=this;}}if(p==this){return false;}var ev=jQuery.extend({},e);var ob=this;if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);}if(e.type=="mouseover"){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.mouseover(handleHover).mouseout(handleHover);};})(jQuery);
//end jquery hoverIntent function


//start jquery dropdown function
var ddsmoothmenu={

//Specify full URL to down and right arrow images (23 is padding-right added to top level LIs with drop downs):
arrowimages: {down:['downarrowclass', '/images/trans.gif', 0], right:['rightarrowclass', '/images/trans.gif']},

transition: {overtime:100, outtime:0}, //duration of slide in/ out animation, in milliseconds
shadow: {enable:false, offsetx:2, offsety:2},

///////Stop configuring beyond here///////////////////////////

detectwebkit: navigator.userAgent.toLowerCase().indexOf("applewebkit")!=-1, //detect WebKit browsers (Safari, Chrome etc)
detectie6: document.all && !window.XMLHttpRequest,

getajaxmenu:function($, setting){ //function to fetch external page containing the panel DIVs
	var $menucontainer=$('#'+setting.contentsource[0]) //reference empty div on page that will hold menu
	$menucontainer.html("Loading Menu...")
	$.ajax({
		url: setting.contentsource[1], //path to external menu file
		async: true,
		error:function(ajaxrequest){
			$menucontainer.html('Error fetching content. Server Response: '+ajaxrequest.responseText)
		},
		success:function(content){
			$menucontainer.html(content)
			ddsmoothmenu.buildmenu($, setting)
		}
	})
},


buildmenu:function($, setting){
	var smoothmenu=ddsmoothmenu
	var $mainmenu=$("#"+setting.mainmenuid+">ul") //reference main menu UL
	$mainmenu.parent().get(0).className=setting.classname || "ddsmoothmenu"
	var $headers=$mainmenu.find("ul").parent()
	$headers.hover(
		function(e){
			$(this).children('a:eq(0)').addClass('selected')
		},
		function(e){
			$(this).children('a:eq(0)').removeClass('selected')
		}
	)
	$headers.each(function(i){ //loop through each LI header
		var $curobj=$(this).css({zIndex: 100-i}) //reference current LI header
		var $subul=$(this).find('ul:eq(0)').css({display:'block'})
		this._dimensions={w:this.offsetWidth, h:this.offsetHeight, subulw:$subul.outerWidth(), subulh:$subul.outerHeight()}
		this.istopheader=$curobj.parents("ul").length==1? true : false //is top level header?
		$subul.css({top:this.istopheader && setting.orientation!='v'? this._dimensions.h+"px" : 0})
		//$c//'<img src="'+ (this.istopheader && setting.orientation!='v'? smoothmenu.arrowimages.down[1] : smoothmenu.arrowimages.right[1])
			//+'" class="' + (this.istopheader && setting.orientation!='v'? smoothmenu.arrowimages.down[0] : smoothmenu.arrowimages.right[0])
			//+ '" style="border:0;" />'
		//)
		if (smoothmenu.shadow.enable){
			this._shadowoffset={x:(this.istopheader?$subul.offset().left+smoothmenu.shadow.offsetx : this._dimensions.w), y:(this.istopheader? $subul.offset().top+smoothmenu.shadow.offsety : $curobj.position().top)} //store this shadow's offsets
			if (this.istopheader)
				$parentshadow=$(document.body)
			else{
				var $parentLi=$curobj.parents("li:eq(0)")
				$parentshadow=$parentLi.get(0).$shadow
			}
			this.$shadow=$('<div class="ddshadow'+(this.istopheader? ' toplevelshadow' : '')+'"></div>').prependTo($parentshadow).css({left:this._shadowoffset.x+'px', top:this._shadowoffset.y+'px'})  //insert shadow DIV and set it to parent node for the next shadow div
		}
		$curobj.hover(
			function(e){
				var $targetul=$(this).children("ul:eq(0)")
				this._offsets={left:$(this).offset().left, top:$(this).offset().top}
				var menuleft=this.istopheader && setting.orientation!='v'? 0 : this._dimensions.w
				menuleft=(this._offsets.left+menuleft+this._dimensions.subulw>$(window).width())? (this.istopheader && setting.orientation!='v'? -this._dimensions.subulw+this._dimensions.w : -this._dimensions.w) : menuleft //calculate this sub menu's offsets from its parent
				if ($targetul.queue().length<=1){ //if 1 or less queued animations
					$targetul.css({left:menuleft+"px", width:this._dimensions.subulw+'px'}).animate({height:'show',opacity:'show'}, ddsmoothmenu.transition.overtime)
					if (smoothmenu.shadow.enable){
						var shadowleft=this.istopheader? $targetul.offset().left+ddsmoothmenu.shadow.offsetx : menuleft
						var shadowtop=this.istopheader?$targetul.offset().top+smoothmenu.shadow.offsety : this._shadowoffset.y
						if (!this.istopheader && ddsmoothmenu.detectwebkit){ //in WebKit browsers, restore shadow's opacity to full
							this.$shadow.css({opacity:1})
						}
						this.$shadow.css({overflow:'', width:this._dimensions.subulw+'px', left:shadowleft+'px', top:shadowtop+'px'}).animate({height:this._dimensions.subulh+'px'}, ddsmoothmenu.transition.overtime)
					}
				}
			},
			function(e){
				var $targetul=$(this).children("ul:eq(0)")
				$targetul.animate({height:'hide', opacity:'hide'}, ddsmoothmenu.transition.outtime)
				if (smoothmenu.shadow.enable){
					if (ddsmoothmenu.detectwebkit){ //in WebKit browsers, set first child shadow's opacity to 0, as "overflow:hidden" doesn't work in them
						this.$shadow.children('div:eq(0)').css({opacity:0})
					}
					this.$shadow.css({overflow:'hidden'}).animate({height:0}, ddsmoothmenu.transition.outtime)
				}
			}
		) //end hover
	}) //end $headers.each()
	$mainmenu.find("ul").css({display:'none', visibility:'visible'})
},

init:function(setting){
	if (typeof setting.customtheme=="object" && setting.customtheme.length==2){ //override default menu colors (default/hover) with custom set?
		var mainmenuid='#'+setting.mainmenuid
		var mainselector=(setting.orientation=="v")? mainmenuid : mainmenuid+', '+mainmenuid
		document.write('<style type="text/css">\n'
			+mainselector+' ul li a {background:'+setting.customtheme[0]+';}\n'
			+mainmenuid+' ul li a:hover {background:'+setting.customtheme[1]+';}\n'
		+'</style>')
	}
	this.shadow.enable=(document.all && !window.XMLHttpRequest)? false : this.shadow.enable //in IE6, always disable shadow
	jQuery(document).ready(function($){ //ajax menu?
		if (typeof setting.contentsource=="object"){ //if external ajax menu
			ddsmoothmenu.getajaxmenu($, setting)
		}
		else{ //else if markup menu
			ddsmoothmenu.buildmenu($, setting)
		}
	})
}

} //end ddsmoothmenu variable

//Initialize Menu instance(s):
//end jquery dropdown function



//start jquery cookie function
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
//end jquery cookie function

function init_menus() {
	ddsmoothmenu.init({		  
		mainmenuid: "global-nav", 
		orientation: 'h', 
		classname: 'menu', 
		contentsource: "markup"  
	})
};
var timeout    = 300; //how long before mouseout triggers
var closetimer = 0;
var ddmenuitem = 0;

function jsddm_open()
{  jsddm_canceltimer();
   jsddm_close();
   ddmenuitem = $(this).find('div').css('visibility', 'visible');}

function jsddm_close()
{  if(ddmenuitem) ddmenuitem.css('visibility', 'hidden');}

function jsddm_timer()
{  closetimer = window.setTimeout(jsddm_close, timeout);}

function jsddm_canceltimer()
{  if(closetimer)
   {  window.clearTimeout(closetimer);
      closetimer = null;}}
    
function livechat(theurl) 
{
	var width  = 550;
	var height = 400;
	var left   = (screen.width  - width)/2;
	var top    = (screen.height - height)/2;
	var params = 'width='+width+', height='+height;
		params += ', top='+top+', left='+left;
		params += ', resizable=yes';
		params += ', scrollbars=no';
	chatwin=window.open(theurl,'chatwindow', params);
	trackPageClick('/FindADoc/LiveChat');
	return false;
}
function callmeback(theurl) 
{
	var width  = 550;
	var height = 495;
	var left   = (screen.width  - width)/2;
	var top    = (screen.height - height)/2;
	var params = 'width='+width+', height='+height;
		params += ', top='+top+', left='+left;
		params += ', resizable=yes';
		params += ', scrollbars=no';
	cmbwin=window.open(theurl,'cmbwindow', params);
	trackPageClick('/FindADoc/CallMeBack');
	return false;
}
function addEvent(D,C,B,A){
	if(D.addEventListener){
		D.addEventListener(C,B,A);
		return true
	}
	if(D.attachEvent){return D.attachEvent("on"+C,B)}
	D["on"+C]=B;
	return false
};
function readQS(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i=0;i<vars.length;i++) {
        var pair = vars[i].split("=");
        if (pair[0] == variable) return pair[1];
    }
    return null; // not found
};
function buildCampaignString() {
    var campaignString = "?";
	campaignString += ((readQS("utm_campaign")!=null)?"utm_campaign="+readQS("utm_campaign")+"&":""); 
	campaignString += ((readQS("utm_source")!=null)?"utm_source="+readQS("utm_source")+"&":""); 
	campaignString += ((readQS("utm_medium")!=null)?"utm_medium="+readQS("utm_medium")+"&":""); 
	campaignString += ((readQS("utm_content")!=null)?"utm_content="+readQS("utm_content")+"&":""); 
	campaignString += ((readQS("utm_term")!=null)?"utm_term="+readQS("utm_term")+"&":""); 
	if (campaignString.length<10) return null;
	return campaignString;
};
function trackPageClick(sstr){
    if(sstr.length<5)return;
	if (window.location.search.length>10) sstr += buildCampaignString();
    try{pageTracker._trackPageview(sstr)} catch(err){}
};

(function($) {
  var cache = [];
  // Arguments are image paths relative to the current page.
  $.preLoadImages = function() {
    var args_len = arguments.length;
    for (var i = args_len; i--;) {
      var cacheImage = document.createElement('img');
      cacheImage.src = arguments[i];
      cache.push(cacheImage);
    }
  }
})(jQuery)
$("li.resize").show();
var sitefunctions = {
	textresize : function(){
	
		// show text resizing links
		var $cookie_name = "emersonFontSize";
		var originalFontSize = $(".col3").css("font-size");
		//alert(originalFontSize);
		// if exists load saved value, otherwise store it
		if($.cookie($cookie_name)) {
			var $getSize = $.cookie($cookie_name);
			$(".col3").css({fontSize : $getSize + ($getSize.indexOf("px")!=-1 ? "" : "px")}); // IE fix for double "pxpx" error
		} else {
			$.cookie($cookie_name, originalFontSize);
		}
		// text "-" link
		 $("a.small").click(function(){
			    $(".col3").css("font-size", originalFontSize);
			    $.cookie($cookie_name, originalFontSize);
			return false;
		  });
		// reset link
		$("a.medium").bind("click", function() {
			    var currentFontSize = $('.col3').css('font-size');
			    var newFontSize = 16;
			    $(".col3").css("font-size", newFontSize);
			    $.cookie($cookie_name, newFontSize);
			return false;
		});
		// text "+" link
		$("a.large").bind("click", function() {
			    var newFontSize = 20;
				$(".col3").css("font-size", newFontSize);
				$.cookie($cookie_name, newFontSize);			
			return false;	
		});
		
	}
}
$(document).ready(function(){
  sitefunctions.textresize();
  $('#search-field').focus(function() {
            $(this).val('')         
    }
  )
   $('#search-field').blur(function() {
   if ($(this).val()=='') { 
                $(this).val('Search')
    }
  })
  //$('.story-content').ThreeDots({ max_rows:8 }) //deferred truncation for tab story content
  
  $('a:not([href])').addClass('named-anchor');  
  $('#example').hide();
  
  $('a.disabled').click(function(){return false})
  $('a.more-options').click(function(){
    $(this).text($(this).text() == 'More Search Options' ? 'Fewer Search Options' : 'More Search Options');
    $('a.more-options').toggleClass('collapse');
    $('.search-options').slideToggle('medium'); 
    return false;
 
   });
  
  $('.button').hover(function() {
    $(this).addClass('hover');
        }, function() {
	    $(this).removeClass('hover');  
	})
	var config = {    
     sensitivity: 7, // number = sensitivity threshold (must be 1 or higher)    
     interval: 200, // number = milliseconds for onMouseOver polling interval    
     over: jsddm_open, // function = onMouseOver callback (REQUIRED)    
     //timeout: 500, // number = milliseconds delay before onMouseOut    
     out: jsddm_timer // function = onMouseOut callback (REQUIRED)    
    }
	$("#global-nav > li").hoverIntent(config); 

    document.onclick = jsddm_close;

//tabs function

//When page loads...
	$(".tab-contents").hide(); //Hide all content
	$("ul.tabs li:first").addClass("current").show(); //Activate first tab
	$(".tab-contents:first").show(); //Show first tab content

	//On Click Event
	$("ul.tabs li").click(function() {

		$("ul.tabs li").removeClass("current"); //Remove any "active" class
		$(this).addClass("current"); //Add "active" class to selected tab
		$(".tab-contents").hide(); //Hide all tab content

		var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
		$(activeTab).fadeIn(960); //Fade in the active ID content
		return false;
	});
    $("ul.tabs li").dblclick(function(){return false;})
	$('a.nyroModal').nyroModal({width: 552});
    $('a.nyroModal.textme').nyroModal({width: 374});
    $('a.nyroModal.email').nyroModal({width: 475, height:375});
    $('a.nyroModal.story-modal').nyroModal({width: 690});
    $('a.nyroModal.video-modal').nyroModal({width: 552, height: 440});
    $('div.survey a.nyroModal').nyroModal({width: 552, height: 500});
    
    $('.alpha-list a[href*=#]').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
    && location.hostname == this.hostname) {
      var $target = $(this.hash);
      $target = $target.length && $target || $('[name=' + this.hash.slice(1) +']');
      if ($target.length) {
        var targetOffset = $target.offset().top;
        $('html,body')
        .animate({scrollTop: targetOffset}, 1000);
       return false;
      }
    }
  });
});
