var counter     = 1;
var max_count   = 7;
var aPreLoad    = new Array();
var aPreLoadi   = 0;
var my_slider 	= null;
var story_nav 	= null;
var timer_story = null;

Fx.Properties = Fx.Styles.extend({
			increase: function(){for (	var p in this.now) this.element[p] = this.now[p];	}
		});

Fx.FlyingScroller = Fx.Properties.extend({
	initialize: function(el, options){
		this.parent(el, options);
		this.options = Object.extend(this.options || {}, Object.extend({
			paddingLeft: 0,
			paddingTop: 0
		}, options || {}));
	},
	toElement: function(el, paddingLeft, paddingTop){
		this.goTo(el.offsetLeft - (paddingLeft || this.options.paddingLeft || 0), el.offsetTop - (paddingTop || this.options.paddingTop || 0));
	},
	goTo: function(x, y){
		this.start({
			'scrollLeft': [this.element.scrollLeft, x],
			'scrollTop': [this.element.scrollTop, y]
		})
	}
});

var da_images = [ '','img/error.png'];


/**************************************************************

	Script		: Rounded Corners
	Version		: 1.2
	Authors		: Samuel Birch
	Desc		: Image based rounded corners for divs and images

**************************************************************/

var RoundedCorners = new Class({
							  
	getOptions: function(){
		return {
			radius: 20,
			cls: 'box',
			overlay: false
		};
	},

	initialize: function(className, options){
		this.setOptions(this.getOptions(), options);
		
		this.boxes = $$(className);
		this.boxes.each(function(el){
			this.setup(el);
		}, this);
		
	},
	
	setup: function(box){
		
		var container = new Element('div').addClass(this.options.cls+'Container').setStyles({
			position: 'relative',
			width: box.getStyle('width').toInt()+box.getStyle('paddingLeft').toInt()+box.getStyle('paddingRight').toInt()+'px',
			height: box.getStyle('height').toInt()+box.getStyle('paddingTop').toInt()+box.getStyle('paddingBottom').toInt()+'px',
			margin: box.getStyle('margin')
		}).injectBefore(box).adopt(box);
		
		if(window.ie){
			container.setStyle('height', box.getStyle('height'));
		}
		
		box.setStyles({
			position: 'absolute',
			top: '0px',
			left: '0px',
			margin: '0px',
			border: 'none',
			background: 'none',
			zIndex: 2
		});
		
		var cornerContainer = new Element('div').setStyles({
			position: 'absolute',
			top: '0px',
			left: '0px',
			zIndex: 1
		}).injectAfter(box);
		
		if(this.options.overlay){
			cornerContainer.setStyle('zIndex', 3);
		}
		
		var num = 0;
		
		//top
		var topLeft = new Element('div').addClass(this.options.cls+'TopLeft').addClass(this.options.cls+'Float').setStyles({
			width: this.options.radius+'px',
			height: this.options.radius+'px'
		}).injectInside(cornerContainer);
		
		var top = new Element('div').addClass(this.options.cls+'Top').addClass(this.options.cls+'Float').setStyles({
			width: container.getStyle('width').toInt()-(this.options.radius*2)+'px'
		}).injectInside(cornerContainer);
		top.setStyle('height', (this.options.radius-top.getStyle('borderTopWidth').toInt())+'px');
		
		var topRight = new Element('div').addClass(this.options.cls+'TopRight').addClass(this.options.cls+'Float').setStyles({
			width: this.options.radius+'px',
			height: this.options.radius+'px'
		}).injectInside(cornerContainer);
	}

});
RoundedCorners.implement(new Events);
RoundedCorners.implement(new Options);

/*************************************************************/

var HealthTabs = new Class({

	initialize: function(container, options) {
		this.options = Object.extend({
			click_class		:	'active',
			which_active	:	'first'
		}, options || {});

		this.container    = $(container);
		this.container_id = container;

		this.navs_els = $$('#' + this.container_id + ' ul.tab-nav li a');
		this.tabs_els = $$('#' + this.container_id + ' .tabs');

		//var tab1 = new RoundedCorners('#tt', {radius: 10});
		//var tab2 = new RoundedCorners('#tt2', {radius: 10});

		this.navs_els.each(function(item) {
		
			item.addEvent('click', function(e){
					
					item.removeClass(this.options.click_class);
					this.activate(item);
					
					try {
					e = new Event(e);
					e.stop();
					}
					catch(er) {}
				
				}.bind(this)
			);
		}.bind(this));

    	//hide all
    	this.tabs_els.each(function(el)
		{
			el.setStyle('display', 'none');
		});

		if(this.options.which_active != 'none')
		{
			if(this.options.which_active == 'first')
			{
				this.activate(this.navs_els[0]);
			}
			else
			{
				this.activate(this.options.which_active);
			}
		}
	},

	activate: function(tab){

		if($type(tab) == 'string')
		{
			myTab = $$('#' + this.container_id + ' ul li a').filterByAttribute('href', '=', tab)[0];
			tab = myTab;
		}

		if($type(tab) == 'element')
		{
			var newTab = tab.getProperty('href');
			newTab = newTab.substring(1);

			if($defined(this.active_tab))
			{
				this.active_tab.setStyle('display', 'none');
			}

			this.active_tab = this.tabs_els.filterById(newTab);
			this.active_tab.setStyle('display', 'block');

			this.navs_els.removeClass('active');

			tab.addClass('active');
		}
	}

});

function dofireEvent(thisid)
{
	$(thisid).fireEvent('click');
}

var HealthAngle =
{

	start: function()
	{

		if ($('stories'))
		{
			timer_story = timerme.periodical(8000);

			story_nav = new Fx.FlyingScroller($('story-holder'), {
					transition: Fx.Transitions.Quad.easeInOut,
					duration: 700,
					paddingLeft: 0,
					paddingTop: 0

				});
		}

		if($('categories'))
		{
			//HealthTabs.init('categories');
			health_tabs = new HealthTabs('categories');
		}
		
		if($('about-section'))
		{
			//HealthTabs.init('categories');
			health_tabs = new HealthTabs('about-section');
		}

		count = 0;
		$$('table.resource-table tr').each(function(el) {
			el.addClass(count++ % 2 == 0 ? 'odd' : 'even');
		});

		//login slider
		if ($('form-login'))
		{
			my_slider = new Fx.Slide('form-login', {duration: 200});
			my_slider.hide();
			
			
		}
		
		//login slider
		if ($('story-friend'))
		{
			my_friend = new Fx.Slide('story-friend', {duration: 200});
			my_friend.hide();
			
			$('a-friend').addEvent('click',function(e){
					var e = new Event(e);
					e.stop();
					e.stopPropagation();
					$('story-response').empty();
				   return HealthAngle.toggle_friend();

				});		
				
			$('form-friend').addEvent('submit', function(e) {
				/**
				 * Prevent the submit event
				 */
				new Event(e).stop();
			 
				/**
				 * This empties the log and shows the spinning indicator
				 */
				var log = $('story-response').empty().addClass('ajax-loading');
			 	if(this.action.indexOf('?xhr') == -1) this.action += '?xhr=1';
			 	
				/**
				 * send takes care of encoding and returns the Ajax instance.
				 * onComplete removes the spinner from the log.
				 */
				this.send({
					onComplete: function(resp) {
						if(!$defined(resp)) return;
						if(resp == '1')
						{
							$('story-response').empty();
							$('story-response').setHTML('<div class="f2f-success"><em>Your message has been sent.</em></div>');
							HealthAngle.toggle_friend();
						}
						else
						{
							$('story-response').setHTML(resp);
						}						
						$('story-response').removeClass('ajax-loading');
					}
				});
			});				
		}
		
		$$('a').each(function(el) {
			if(el.rel && el.rel.test(/^external/i))
			{
				el.setProperty('target','_blank');
			}			
			else if(el.rel && el.rel.test(/^print/i))
			{
				el.addEvent('click', function(e){
					e = new Event(e);
					window.print();
					e.stop();
					return false;
				
				});
			}
			
			else if(el.rel && el.rel.test(/^google/i))
			{
				el.setProperty('target','_blank');
				el.addEvent('click',function()
				{
					var track_id = this.rel.match(/^google\[(.*)\]$/);
					if(track_id)
					{
						pageTracker._trackPageview(track_id[1]);
					}
	
				});
			}
			
			});
			

		//all rollovers
    	$$('img','input').each(function(el)
		{
			if(el.hasClass('roll'))
			{
				var ftype = el.src.substring(el.src.lastIndexOf('.'), el.src.length);

				//CREATE A NEW ATTRIBUTE FOR ROLLOVER (for fyi = '_over')
				//NOTE: this assumes xyz.gif AND xyz_hr.gif (or jpg works too)
				var hsrc = el.src.replace(ftype, '_h'+ftype);

				//STORE FAKE ATTRIBUTE ON IMAGE TAG
				el.setAttribute('hsrc', hsrc);
				el.setAttribute('nsrc', el.src);
				aPreLoad[aPreLoadi] = new Image();
				aPreLoad[aPreLoadi].src = hsrc;
				aPreLoadi++;

				el.addEvent('mouseover',function(){
					this.setAttribute('src', this.getAttribute('hsrc'));
				});

				el.addEvent('mouseout',function(){
				   this.src = this.src.replace(/_h\./g,'.');
				});
			}
		});
		
			
		if($('share_n_1')) 
		{

			var completer1 = new Autocompleter.Local($('share_n_1'), tokens, {
				'delay': 100,
				'filterTokens': function() {
					var regex = new RegExp('' + this.queryValue.escapeRegExp(), 'i');
					return this.tokens.filter(function(token){
						return (regex.test(token[0]) || regex.test(token[1]));
					});
				},
				'injectChoice': function(choice) {
					var el = new Element('li')
						.setHTML(this.markQueryValue(choice[0]))
						.adopt(new Element('span', {'class': 'example-info'}).setHTML(this.markQueryValue(choice[1])));
					el.inputValue = choice[0];
					this.addChoiceEvents(el).injectInside(this.choices);
				}
			});
		}
		
		
		
		//external links
    	$$('a').each(function(el)
		{
			if(el.getAttribute('rel')=='external')
			{
				el.setAttribute('target','hangle-external');
			}
			else if(el.getAttribute('href').match('http:'))
			{
				//experimental
				if(el.getProperty('target'))
				{
					el.setAttribute('target','hangle-external');					
				}
			}
		});	

	},

	prev: function()
	{
		$clear.pass(timer_story).delay(0);//make it stop
		counter--;
		if(counter == 0) counter = 1;
		story_nav.clearTimer().toElement($('story'+counter));
		this.move();
		return false;
	},

	next: function()
	{
		$clear.pass(timer_story).delay(0);//make it stop
		counter++;
		if(counter == (max_count+1)) counter = max_count;
		this.move();
		return false;
	},

	move: function()
	{
		$('s-num').setHTML(counter);
		story_nav.clearTimer().toElement($('story'+counter));
		timer_story = timerme.periodical(8000);
		$('people').setAttribute('src', da_images[counter]);
	},
	
	toggle: function()
	{
		my_slider.toggle();
		return false;
	},
	
	toggle_friend: function()
	{
		my_friend.toggle();
		return false;
	}
};

function timerme()
{
	$clear.pass(timer_story).delay(0);//make it stop
	counter++;
	if(counter == (max_count+1)) counter = 1;
	HealthAngle.move();
}

function init()
{
	HealthAngle.start();
	//domtab.init();
	
	/* Tips 3 
	var Tips3 = new Tips($$('.tips'), {
		showDelay: 400,
		hideDelay: 400,
		fixed: true
	});
	*/
	var Tips1 = new Tips($$('.tips'));
	
	google_track_links();
	
}

function init_images()
{
	if ($('stories'))
	{				
		//pre load images
		for(var x = 1; x < da_images.length; x++)
		{
			new Asset.image(da_images[x]);
		}
		
	}
	
	$$('img.fixPNG').each(function(el) {
				fixPNG(el)
				});	
}


var arVersion = navigator.appVersion.split("MSIE")
var version = parseFloat(arVersion[1])

function fixPNG(myImage) 
{

    if ((version >= 5.5) && (version < 7) && (document.body.filters)) 
    {
       var imgID = (myImage.id) ? "id='" + myImage.id + "' " : ""
	   var imgClass = (myImage.className) ? "class='" + myImage.className + "' " : ""
	   var imgTitle = (myImage.title) ? 
		             "title='" + myImage.title  + "' " : "title='" + myImage.alt + "' "
	   var imgStyle = "display:inline-block;" + myImage.style.cssText
	   var strNewHTML = "<span " + imgID + imgClass + imgTitle
                  + " style=\"" + "width:" + myImage.width 
                  + "px; height:" + myImage.height 
                  + "px;" + imgStyle + ";"
                  + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
                  + "(src=\'" + myImage.src + "\', sizingMethod='scale');\"></span>"
	   myImage.outerHTML = strNewHTML	  
    }
}

function google_track_links()
{
	//no tracker then quite
	if(!pageTracker) return;

	var host = window.location.host;
		
	//go thru each link
	$$('a').each(function(el)
	{
		//if rel tag is google
		if(el.rel && el.rel.test(/^google/i))
		{
			el.addEvent('click',function()
			{
				var track_id = this.rel.match(/^google\[(.*)\]$/);
				if(track_id)
				{
					pageTracker._trackPageview(track_id[1]);
				}

			});
		}
		else if(el.host != host)	
		{
			//removed 
			//else if(el.href && el.href.test(/^http:\/\//))
			el.addEvent('click',function()
			{
				var track_id = this.href.match(/^http:\/\/([^/]+)/);
				if(track_id)
				{
					pageTracker._trackPageview('outgoing/'+track_id[1]);
				}

			});
		}
	});
}

window.addEvent('domready', init);
window.addEvent('load', init_images);