/* stop IE6 flicker */
try { document.execCommand("BackgroundImageCache", false, true); } catch(err) {}

// Return true if browser is Internet Explorer and version 6 or earlier
$.IE6Below = function() {
	if ($.browser.msie) {
		try {
			if (ScriptEngineMajorVersion() <= 5 && ScriptEngineMinorVersion() < 7) { // ie 6- only
				return true;
			}
		} catch(err) { return false; };
		return false;
	} else {
		return false;
	};
};

// Return true if browser is Safari 2.0 or earlier
$.Safari2Below = function() {
	if ($.browser.safari) {
		var kitName = "applewebkit/";
		var tempStr = navigator.userAgent.toLowerCase();
		var pos		  = tempStr.indexOf(kitName);
		var isAppleWebkit = (pos != -1);
		var kitVersion = 0		
		var kitVersion = tempStr.substring(pos + kitName.length,tempStr.length);
				kitVersion = kitVersion.substring(0,kitVersion.indexOf(" "));
				kitVersion = kitVersion.substring(0,3);
		return (kitVersion < 420) ? true : false;
	};
};

// add default text functionality to input fields
$(function(){ // (executes when the dom is ready)
	$('.input-default-text').each(function(i) {
		var defaultValue = $(this).attr('value');
		$(this).focus(function () { if (this.value == defaultValue) this.value = ''; this.style.color = '#333333' });
		$(this).blur(function () { if (this.value == '') { this.value = defaultValue; this.style.color = '#666666' }});
	});
});


// ** Main navigation rollover functions **
// **                                    **
$(function(){ // (executes when the dom is ready)
	// variables for our mouseouts and mouseactions
	var hasOrginalActiveNav = false;
	var originalActiveNav;
	var originalActiveNavLink;
	var cuedOverEffect;
	var cuedOutEffect;
	var cuedRestoreEffect;
	var rolloverDelay = 350;
	
	// search for nav-something or snav-something in the body tag
	// this tells us if a link should be active by default
	// (this is because each of our nav links uses an id, e.g. nav-home, so we define
	//  active links by simply declaring this id in the body tag of each page as a class name)
	$("body[@class*=nav-]").each(function(i) {
		var bodyClasses = $(this).attr("class").split(" ");
		var regex1 = /\bnav-\b/;
		var regex2 = /\bsnav-\b/;
		$.each(bodyClasses, function(i, n) {
			if (regex1.test(n) || regex2.test(n)) {
				// add class "active" to the first link in the li#nav-something or li#snav-something
				$('#'+n+'>a').addClass("active");
				// see if we're dealing with a sub nav, if so set its parent's parent's first link to active as well
				if (regex2.test(n)) {
					$($('#'+n).parent().parent().children("a")[0]).addClass("active");
				};
			};
		 });
	});
	
	// functions which carryout the over/out effects
	$.navMouseOver = function(hoveredElement) {
		var hoveredElementID;
		clearTimeout(cuedRestoreEffect);
		// grab the id of the elment
		$("#navigation-list>li").each(function(i) {
			if (hoveredElement == this) hoveredElementID = i;
		});
		if ($(hoveredElement).is('.hover')) {
			clearTimeout(cuedOverEffect);
			clearTimeout(cuedOutEffect);
		} else {
			cuedOverEffect = setTimeout('$.navMouseOverEffect("' + hoveredElementID + '")',rolloverDelay);
		};
	};
	$.navMouseOut = function(hoveredElement) {		
		clearTimeout(cuedRestoreEffect);
		clearTimeout(cuedOverEffect);
		clearTimeout(cuedOutEffect);
		// only cue the mouse out effect if this element is not our original nav element
		// (or we'd just turn it off only to turn it on again when we call our restore effect)
		if (!$(originalActiveNav).is(".hover")) {
			cuedOutEffect = setTimeout('$.navMouseOutEffect()',rolloverDelay);
		};
	};
	$.navMouseOverEffect = function(hoveredElementID) {
		var hoveredElement = $("#navigation-list>li")[hoveredElementID];
		$(hoveredElement).addClass("hover");
		if (hasOrginalActiveNav) $(originalActiveNavLink).removeClass("active");
		$("#navigation-list>li").not(hoveredElement).each(function(i) {
			$(this).removeClass("hover");
			$(this).removeClass("active");
		});
	};
	$.navMouseOutEffect = function() {
		$("#navigation-list>li").removeClass("hover");
		if (hasOrginalActiveNav) cuedRestoreEffect = setTimeout('$.navRestoreOriginalState()',20);
	};
	$.navRestoreOriginalState = function() {
		var restore = true;
		// make sure no other navs are on the "hover" state before we restore
		$("#navigation-list>li.hover").each(function(i) { restore = false; });
		if (restore) {
			$(originalActiveNav).addClass("active");
			$(originalActiveNavLink).addClass("active");
		};		
	};
	
	// if a navigation link has the class of "active" then set it's parent LI to "active" as well
	// we also keep a reference of the link and parent LI so we can turn on/off the "active" state
	// while we mouseover other links in the navigation
	$("#navigation-list>li>a.active").each(function(i) {
		hasOrginalActiveNav = true;
		$(this).parent().addClass("active");
		originalActiveNavLink = $(this);		
		originalActiveNav = $(this).parent();
	});
	
	// finally, add mouseover/out functions to each nav element
	$("#navigation-list>li").each(function(i){
		$(this).mouseover(function() {
			$.navMouseOver(this);
		});
		$(this).mouseout(function() {
			$.navMouseOut(this);
		});
	});
	
});


// ** Rotating backgrounds on home page **
// **                                   **
$(function(){ // (executes when the dom is ready)
	
	var initialized = false;
	var current_image_number = 0;
	var rotating_images = new Array();
	var initial_rotation_delay = 5000;
	var rotation_delay = 5000;
	var animation_speed = 2000;

	$.rotateBgImages = function() {
		// if we haven't initialized let's do that now
		if (! initialized)
		{			
			// find ".background" images and add them to our array
			$("#flash-area .backgrounds").each(function(i) {
				rotating_images[i] = this;
				$(this).css("z-index",300-i);
				if (i>0) $(this).css("visibility","hidden");
			});
			initialized = true;
			setTimeout('$.rotateBgImages()', initial_rotation_delay);
			return;
		}
		// if the first image doesn't exist, just exit
		if (! rotating_images[0]) return;
		// if the first image has downloaded, continue
		if (rotating_images[0].complete || rotating_images[0].complete == undefined)
		{
			// set the next image we should load
			var next_image_number = current_image_number + 1;
			if (next_image_number >= rotating_images.length) next_image_number = 0;
			// has this image been loaded
			if (rotating_images[next_image_number].complete || rotating_images[next_image_number].complete == undefined)
			{
				// ok, switch to this new image
				$(rotating_images[current_image_number]).fadeOut(animation_speed);
				$(rotating_images[next_image_number]).css("visibility","visible").fadeIn(animation_speed);
				// set the Find More link to the rel attribute of the image (so images can link to different pages)				
				$("#flash-area .find-more").attr("href",$(rotating_images[next_image_number]).attr("rel"));
				// change the current image to this one
				current_image_number = next_image_number;
			};
			setTimeout('$.rotateBgImages()', rotation_delay);
		}
		else
		{
			// not downloaded yet, check back later
			setTimeout("$.rotateBgImages()", rotation_delay);
		};
	};
	
	// start rotation
	$.rotateBgImages();
});


// ** Rotating logos on home page **
// **                             **
$(function(){ // (executes when the dom is ready)
	
	var initialized = false;
	var current_image_number = 0;
	var rotating_images = new Array();
	var initial_rotation_delay = 2000;
	var rotation_delay = 5000;
	var animation_speed = 3000;

	$.rotateImages = function() {
		// if we haven't initialized let's do that now
		if (! initialized)
		{
			// find "image-collection" divs and add them to our array
			$(".image-collection").each(function(i) {
				rotating_images[i] = this;
				$(this).css("z-index",200-i);
				if (i>0) $(this).css("visibility","hidden");
			});
			initialized = true;
			setTimeout('$.rotateImages()', initial_rotation_delay);
			return;
		}
		// if the first image doesn't exist, just exit
		if (! rotating_images[0]) return;
		// set the next image we should load
		var next_image_number = current_image_number + 1;
		if (next_image_number >= rotating_images.length) next_image_number = 0;
		// ok, switch to this new image		
		$(rotating_images[current_image_number]).fadeOut(animation_speed);		
		$(rotating_images[next_image_number]).css("visibility","visible").fadeIn(animation_speed);
		// change the current image to this one
		current_image_number = next_image_number;
		setTimeout('$.rotateImages()', rotation_delay);	
	};
	
	// start rotation
	$.rotateImages();
	
});


// ** Load over state for images **
// **                                    **
$(function(){ // (executes when the dom is ready)
	
	var temp_bg_image_holder = new Array();
	var temp_bg_simage_holder = new Array();
	var temp_bg_image_folder = "/images/layout/navigation/";
	var temp_bg_simage_folder = "/images/layout/subnavigation/";
	
	if ($.IE6Below()) temp_bg_image_folder = "/images/layout/navigation-ie/"; // IE 6- only

	temp_bg_image_holder[0] = new Image();
	temp_bg_image_holder[0].src = temp_bg_image_folder + "about-us-o.png";
	temp_bg_image_holder[1] = new Image();
	temp_bg_image_holder[1].src = temp_bg_image_folder + "assessments-o.png";
	temp_bg_image_holder[2] = new Image();
	temp_bg_image_holder[2].src = temp_bg_image_folder + "biomarker-research-o.png";
	temp_bg_image_holder[3] = new Image();
	temp_bg_image_holder[3].src = temp_bg_image_folder + "for-physicians-o.png";
	temp_bg_image_holder[4] = new Image();
	temp_bg_image_holder[4].src = temp_bg_image_folder + "home-o.png";
	temp_bg_image_holder[5] = new Image();
	temp_bg_image_holder[5].src = temp_bg_image_folder + "news-o.png";
	temp_bg_image_holder[6] = new Image();
	temp_bg_image_holder[6].src = temp_bg_image_folder + "order-o.png";
	temp_bg_image_holder[7] = new Image();
	temp_bg_image_holder[7].src = temp_bg_image_folder + "partners-o.png";
	
	temp_bg_simage_holder[0] = new Image();
	temp_bg_simage_holder[0].src = temp_bg_simage_folder + "biophysical-heart-o.png";
	temp_bg_simage_holder[1] = new Image();
	temp_bg_simage_holder[1].src = temp_bg_simage_folder + "biophysical-longevity-o.png";
	temp_bg_simage_holder[2] = new Image();
	temp_bg_simage_holder[2].src = temp_bg_simage_folder + "biophysical-you-o.png";
	temp_bg_simage_holder[3] = new Image();
	temp_bg_simage_holder[3].src = temp_bg_simage_folder + "biophysical250-o.png";
	temp_bg_simage_holder[4] = new Image();
	temp_bg_simage_holder[4].src = temp_bg_simage_folder + "forms-o.png";
	temp_bg_simage_holder[5] = new Image();
	temp_bg_simage_holder[5].src = temp_bg_simage_folder + "general-biomarker-research-o.png";
	temp_bg_simage_holder[6] = new Image();
	temp_bg_simage_holder[6].src = temp_bg_simage_folder + "research-by-category-o.png";
	temp_bg_simage_holder[7] = new Image();
	temp_bg_simage_holder[7].src = temp_bg_simage_folder + "featured-biomarker-o.png";
	temp_bg_simage_holder[8] = new Image();
	temp_bg_simage_holder[8].src = temp_bg_simage_folder + "biophysical250-glossary-o.png";
	temp_bg_simage_holder[9] = new Image();
	temp_bg_simage_holder[9].src = temp_bg_simage_folder + "top-research-articles-o.png";
	temp_bg_simage_holder[10] = new Image();
	temp_bg_simage_holder[10].src = temp_bg_simage_folder + "biophysical-difference-o.png";
	temp_bg_simage_holder[11] = new Image();
	temp_bg_simage_holder[11].src = temp_bg_simage_folder + "collaborations-studies-o.png";
	temp_bg_simage_holder[12] = new Image();
	temp_bg_simage_holder[12].src = temp_bg_simage_folder + "faq-o.png";
	temp_bg_simage_holder[13] = new Image();
	temp_bg_simage_holder[13].src = temp_bg_simage_folder + "news-releases-o.png";
	temp_bg_simage_holder[14] = new Image();
	temp_bg_simage_holder[14].src = temp_bg_simage_folder + "newsletters-o.png";
	temp_bg_simage_holder[15] = new Image();
	temp_bg_simage_holder[15].src = temp_bg_simage_folder + "media-contacts-o.png";
	temp_bg_simage_holder[16] = new Image();
	temp_bg_simage_holder[16].src = temp_bg_simage_folder + "medical-team-o.png";
	temp_bg_simage_holder[17] = new Image();
	temp_bg_simage_holder[17].src = temp_bg_simage_folder + "medical-advisory-board-o.png";
	temp_bg_simage_holder[18] = new Image();
	temp_bg_simage_holder[18].src = temp_bg_simage_folder + "management-team-o.png";
	temp_bg_simage_holder[19] = new Image();
	temp_bg_simage_holder[19].src = temp_bg_simage_folder + "board-of-directors-o.png";
	temp_bg_simage_holder[20] = new Image();
	temp_bg_simage_holder[20].src = temp_bg_simage_folder + "contact-us-o.png";
	temp_bg_simage_holder[21] = new Image();
	temp_bg_simage_holder[21].src = temp_bg_simage_folder + "become-a-partner-o.png";
	temp_bg_simage_holder[22] = new Image();
	temp_bg_simage_holder[22].src = temp_bg_simage_folder + "biophysical-glossary-o.png";
	
	
});


// ** Load hover tip javascript if neccessary **
// **                                         **
$(function(){ // (executes when the dom is ready)
	
	// function to get window width
	function getWindowWidth() {
		var theWidth;
		if (window.innerWidth) {
			theWidth = window.innerWidth
		} else if (document.documentElement && document.documentElement.clientWidth) {
			theWidth = document.documentElement.clientWidth
		} else if (document.body) {
			theWidth = document.body.clientWidth
		};
		return theWidth;
	};
	
	// function to change x coordinate based on width of browser window and width of our floating box
	function updatedX(x) {
		if (getWindowWidth()-x < 489) {
			return x - (520 - (getWindowWidth()-x));
		} else {
			return x-50;
		};
	};

	// use globals to track mouse position
	var hovertipMouseX;
	var hovertipMouseY;
	function hovertipMouseUpdate(e) {
	  var mouse = hovertipMouseXY(e);
	  hovertipMouseX = mouse[0];
	  hovertipMouseY = mouse[1];
	}

	// http://www.howtocreate.co.uk/tutorials/javascript/eventinfo
	function hovertipMouseXY(e) {
	  if( !e ) {
	    if( window.event ) {
	      //Internet Explorer
	      e = window.event;
	    } else {
	      //total failure, we have no way of referencing the event
	      return;
	    }
	  }
	  if( typeof( e.pageX ) == 'number' ) {
	    //most browsers
	    var xcoord = e.pageX;
	    var ycoord = e.pageY;
	  } else if( typeof( e.clientX ) == 'number' ) {
	    //Internet Explorer and older browsers
	    //other browsers provide this, but follow the pageX/Y branch
	    var xcoord = e.clientX;
	    var ycoord = e.clientY;
	    var badOldBrowser = ( window.navigator.userAgent.indexOf( 'Opera' ) + 1 ) ||
	      ( window.ScriptEngine && ScriptEngine().indexOf( 'InScript' ) + 1 ) ||
	      ( navigator.vendor == 'KDE' );
	    if( !badOldBrowser ) {
	      if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
	        //IE 4, 5 & 6 (in non-standards compliant mode)
	        xcoord += document.body.scrollLeft;
	        ycoord += document.body.scrollTop;
	      } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
	        //IE 6 (in standards compliant mode)
	        xcoord += document.documentElement.scrollLeft;
	        ycoord += document.documentElement.scrollTop;
	      }
	    }
	  } else {
	    //total failure, we have no way of obtaining the mouse coordinates
	    return;
	  }
	  return [xcoord, ycoord];
	}
	
	if (($("body").find(".hovertip").length) > 0) {
		$(".hovertip").each(function() {
			var showID;
			$(this).mousemove(hovertipMouseUpdate);
			showID = "#"+$(this).attr("target");
			$(this).hover(function(){
			   $(showID).css(	{'visibility':'visible','position':'absolute','top': hovertipMouseY + 20 + 'px','left': updatedX(hovertipMouseX) + 'px'}).fadeIn("fast");
			 },function(){
			   $(showID).fadeOut("normal");
			 });
		});
		// call this
		$("body").mousemove(hovertipMouseUpdate);
	};
		
});


// ** Changes search field to actual "search" element **
// **                                                 **
$(function(){ // (executes when the dom is ready)
	if ($.browser.safari) {
		$("#search-query").each(function(i){
			$(this).attr("value","");
			$(this).attr("type","search");
			$(this).attr("autosave","com.biophysical.search");
			$(this).attr("results","10");
			$(this).attr("placeholder","");
			$(this).css({'color':'#000000','font-size':'16px','width':'150px'});
		});
	};
});


/* tabbed content */
$.fn.tabs = function(options) {
    // basic stuff
    var ON_CLASS = 'on';
    var OFF_CLASS = 'tabs-hide';
    // options
    var on = options && options.on && (typeof options.on == 'number' && options.on > 0) ? options.on - 1 : 0;
    return this.each(function() {
        $(this).find('>div').not(':eq(' + on + ')').addClass(OFF_CLASS);
				$($('.anchors a')[on]).addClass(ON_CLASS);
        var container = this;				
        $(".anchors").find('a').click(function() {
            if (!$(this).is('.' + ON_CLASS)) {
                var re = /([_\-\w]+$)/i;
                var target = $('#' + re.exec(this.href)[1]);
                if (target.size() > 0) {
                    $(container).find('>div:visible').addClass(OFF_CLASS);
                    target.removeClass(OFF_CLASS);
                };
								$(".anchors a."+ON_CLASS).removeClass(ON_CLASS);
								$(this).addClass(ON_CLASS);
            };
            return false;
        });
    });
};
