/**
 * $Id: library.js,v 1.16 2010/05/11 14:28:32 hassana Exp $ 
 */
var mybool = true;
var count = 0;
jQuery(document).ready(function() {	

//	var min = FlashVersionTest("11.0.115");
	/*	if(!min){ 
		$('object').css('display','none');
	} */
	flashDegrader();
	timedCount(true);
	showRegion();

	//Map functions
	function showRegion(){
		var currentRegion = "";
		$('.pctareas').addClass('fancy');

		$('area').click(function() {
			// alert('anchor: '+$(this).attr("href").split('#')[1]);
			currentRegion = "#"+$(this).attr("href").split('#')[1];
			$('.regions:visible').toggle();
			$(currentRegion).parent().toggle();		

			$(currentRegion+' a').click(function(){

				var id = $(this).attr("href").split('=')[1];
				$.get("patients/map/text",
						{ id: ""+id+"" },
						function(returned_data)
						{
							$('.pctresult').remove();
							$(currentRegion).parent().append(returned_data);
						});
				return false;

			});

			return false;
		});
	}
	$('p.accessibility a').click(function(){
		//alert("hello world "+this.href.split('#')[1]);
		var href = "#"+this.href.split('#')[1];
		$('html, body').animate({
			scrollTop: $(href).offset().top
		}, 0);
	});
	//Test to see if there are any elements that need sliding action
	if($("#slider").length >0){
		var $panels = $('#slider .scrollContainer > div');
		var $container = $('#slider .scrollContainer');

		// if false, we'll float all the panels left and fix the width 
		// of the container
		var horizontal = true;

		// float the panels left if we're going horizontal
		if (horizontal) {
			$panels.css({
				'float' : 'left',
				'position' : 'relative' // IE fix to ensure overflow is hidden
			});

			// calculate a new width for the container (so it holds all panels)
			$container.css('width', $panels[0].offsetWidth * $panels.length);
		}

		// collect the scroll object, at the same time apply the hidden overflow
		// to remove the default scrollbars that will appear
		var $scroll = $('#slider .scroll').css('overflow', 'hidden');

		// apply our left + right buttons
//		$scroll
//		.before('<img class="prev" src="stylesheets/images/left.png" />')
//		.after('<img class="next" src="stylesheets/images/right.png" />');

		// handle nav selection
		function selectNav() {
			$(this)
			.parents('ul:first')
			.find('a')
			.removeClass('selected')
			.end()
			.end()
			.addClass('selected');
		}

		$('.navigation').find('a').click(selectNav);

		// go find the navigation link that has this target and select the nav
		function trigger(data) {
			var el = $('#slider .navigation').find('a[href$="' + data.id + '"]').get(0);
			selectNav.call(el);
		}

		if (window.location.hash) {
			//alert("found hash link "+window.location.hash.substr(1));
			trigger({ id : window.location.hash.substr(1) });
		} else {
			$('ul.navigation a:first').click();
		}

		// offset is used to move to *exactly* the right place, since I'm using
		// padding on my example, I need to subtract the amount of padding to
		// the offset.  Try removing this to get a good idea of the effect
		var offset = parseInt((horizontal ? 
				$container.css('paddingTop') : 
					$container.css('paddingLeft')) 
					|| 0) * -1;


		var scrollOptions = {
				target: $scroll, // the element that has the overflow

				// can be a selector which will be relative to the target
				items: $panels,

				navigation: '.navigation a.nav',

				// selectors are NOT relative to document, i.e. make sure they're unique
				prev: 'img.left', 
				next: 'img.right',

				// allow the scroll effect to run both directions
				axis: 'xy',

				onAfter: trigger, // our final callback

				offset: offset,

				// duration of the sliding effect
				duration: 300,

				// easing - can be used with the easing plugin: 
				// http://gsgd.co.uk/sandbox/jquery/easing/
				easing: 'swing'
		};

		// apply serialScroll to the slider - we chose this plugin because it 
		// supports// the indexed next and previous scroll along with hooking 
		// in to our navigation.
		$('#slider').serialScroll(scrollOptions);

		// now apply localScroll to hook any other arbitrary links to trigger 
		// the effect
		$.localScroll(scrollOptions);

		// finally, if the URL has a hash, move the slider in to position, 
		// setting the duration to 1 because I don't want it to scroll in the
		// very first page load.  We don't always need this, but it ensures
		// the positioning is absolutely spot on when the pages loads.
		scrollOptions.duration = 1;
		$.localScroll.hash(scrollOptions);
		
	}

	//Lightbox popout with fade effect
	$("a.lightbox").overlay({ 

		// start exposing when overlay starts to load 
		onBeforeLoad: function() { 

		// this line does the magic. it makes the background image sit on top of the mask 
		this.getBackgroundImage().expose({color: '#000'}); 
	},  

	// when overlay is closed take the expose instance and close it as well 
	onClose: function() { 

		var flashitems = $('.lightflash');        

		for(var i=0; i<flashitems.length; i++){

			var removed = flashitems[i].cloneNode(true);
			var parent = flashitems[i].parentNode;
			//document.getElementById('content').appendChild(removed);
			parent.removeChild(flashitems[i]);

			//alert(parent.firstChild.nodeName);
			parent.insertBefore(removed, parent.firstChild);
			//parent.appendChild(removed);

		}

		$.expose.close(); 
	}        


	});



	//Test to see if there are any elements needing fading action
	if($('.faded').length >0){

		function checkSelected(){
			$(this)
			.parents('ul:first')
			.find('li')
			.removeClass('active')
			.end()     			
			.end()
			.parents('li:first')
			.addClass('active')
			.end();
		}

		if(window.location.hash){
			$('.faded').css('display', 'none');
			$('#'+window.location.hash.substr(1)).css('display','block');

			var anchors = $('.sidenavigation').find('a');

			for(var i=0; i<anchors.length; i++){
				if(anchors[i].href.match(window.location.hash.substr(1))){ 
					checkSelected.call($(anchors[i]))
				}
			}
		}
		else{
			$('.faded:gt(0)').css('display', 'none');
		}
		$('.fadenav').click(function(){

			$clicked = $(this);


			var targetId = $clicked.attr('href').split('#')[1];

			$('#content').find('.faded:visible').fadeOut('fast', function(){
				//once the fade out is completed, we start to fade in the right div
				checkSelected.call($clicked);
				var next = $(this).parent().find('#'+targetId); 
				next.fadeIn();

			})    	     
			return false;
		});
	}
	//Load external rel links in a new window
	$('a[rel="external"]').click(function(){this.target = "_blank";});

	//Transparent background for lightbox
	$('.overlay').supersleight({shim: 'images/x.gif'});


});

function flashEnd(){

	var lighboxes = $('a.lightbox');

	for(var i=0; i<lighboxes.length; i++){

		var id = lighboxes[i];

		if($(id).overlay().isOpened()){		
			$(id).overlay().close();
		}

	}

}

//Returns a string flash version
function getFlashVersion(){ 
	// ie 
	try { 
		try { 
			// avoid fp6 minor version lookup issues 
			// see: http://blog.deconcept.com/2006/01/11/getvariable-setvariable-crash-internet-explorer-flash-6/ 
			var axo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash.6'); 
			try { axo.AllowScriptAccess = 'always'; } 
			catch(e) { return '6,0,0'; } 
		} catch(e) {} 
		return new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1]; 
		// other browsers 
	} catch(e) { 
		try { 
			if(navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin){ 
				return (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]).description.replace(/\D+/g, ",").match(/^,?(.+),?$/)[1]; 
			} 
		} catch(e) {} 
	} 
	return '0,0,0'; 
}
//Test for a minimum required version of flash
function FlashVersionTest(rv){

	var stringversion = getFlashVersion();

	var d = stringversion.split(",");

	var ver = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];

	var pv = ver, v = rv.split(".");
	v[0] = parseInt(v[0], 10);
	v[1] = parseInt(v[1], 10) || 0; // supports short notation, e.g. "9" instead of "9.0.0"
	v[2] = parseInt(v[2], 10) || 0;
	return (pv[0] > v[0] || (pv[0] == v[0] && pv[1] > v[1]) || (pv[0] == v[0] && pv[1] == v[1] && pv[2] >= v[2])) ? true : false;	
}

function flashDegrader(){

	var min = FlashVersionTest("9.0.115");

	if(!min)
	{		
		var newdiv;		
		var objects = document.getElementsByTagName('object');
		var i=0;

		while(objects.length>0)
		{
			var current = objects[i];
			var parent = objects[i].parentNode;
			newdiv = document.createElement('div');
			parent.insertBefore(newdiv, current);
			newdiv.innerHTML = current.innerHTML;				
			parent.removeChild(current);
		}
	}	
}


function timedCount(first){
	//console.log("count: "+count);
	if(first){
		//alert("first case");
		if(count < 3000){
			alternate();
			setTimeout("timedCount("+true+")",count);
			count+=200;
		}

		else{
			setTimeout("timedCount("+false+")",1000);
		}
	}
	else{
		alternate();
		setTimeout("timedCount("+false+")",5000);
	}

}

function alternate(){

	if(mybool){
		$('#burst').css("background-position", "left -232px");
		mybool = false;
	}
	else{
		$('#burst').css("background-position", "left top");	
		mybool = true;
	}
}


