// JavaScript Document
/**
* Animates the Product tabs
* @author gabe@fijiwebdesign.com
*/

// toolbar object
var productToolbar = function() {
	this.id = 'product_toolbar';
	this.toolbar = $('product_toolbar');
	if (this.toolbar) {
		// init toolbar
		this.tools = this.toolbar.getElements('a');
		this.panel = $('product_panes');
		this.panes = this.panel.getElements('[class=product_pane]');
		this.pointer = $('product_tab_pointer');
		this.active_tool = $('active_tool');
		this.active_pane = $(this.active_tool.rel);
		this.init();
		this.ready = true;
	}
};

productToolbar.prototype = {
	init: function() {
		// show tool
		$(this.pointer).setStyles({
	   		display: 'none',
			position: 'absolute',
			margin: '0'
	    });
		// attach handlers
		this.tools.each(function(el) {
			// handle onclick
			el.addEvent('click', function(event) {
										  
				myProductToolbar.tools.each(
					function(el) {
						el.removeClass('active_tool');
					}
				);
				el.addClass('active_tool');
				myProductToolbar.active_tool = el;
				myProductToolbar.active_pane = $(el.rel);
				
				myProductToolbar.refreshPanes();
				myProductToolbar.scrollWinToToolbar();
				myProductToolbar.showPointer(el);
				
				event = new Event(event).stop();

			});
		}, this);
		// show only active pane
		this.refreshPanes();
	},
	
	// styles all first words in h1, h2, h3, h4
	addStyleForFirstWord: function() {
		['h1', 'h2', 'h3', 'h4'].forEach(function(tag) {
			$$(tag).forEach(function(el) {
				while(el.firstChild && el.firstChild.tagName != '#text') {
					el = el.firstChild;
				}
				el = el.parentNode;
				el.innerHTML = el.innerHTML.replace(/^\s*([^\s]+)/i, '<span>$1</span>');
			});
		});
	},

	// refresh panes
	refreshPanes: function() {
		// hide product panes
		this.panes.each(function(el) {
			$(el).setStyle('display', 'none');
		});
		// show active pane
		$(this.active_pane).setStyles({
			display: 'block'
	    });
	},
	
	// show pointer under el
	showPointer: function(el) {
		var x = $(el).getLeft() + 41;
		var y = $(myProductToolbar.panel).getTop() - 8;
		$(this.pointer).setStyles({
			top: y+'px',
			left: x+'px',
			display: 'block'
		});
		new Fx.Style($(this.pointer), 'left', {
			duration:700,
			wait: true
		})//.start(x); // bug in IE7
	},
	
	// scroll window to toolbar
	scrollWinToToolbar: function() {
		var Scroll = new Fx.Scroll(window, {
			wait: false,
			duration: 200,
			transition: Fx.Transitions.Quad.easeInOut
		});
		Scroll.toElement(this.toolbar);	
	}

};

// init toolbar
var myProductToolbar = {};
window.addEvent('domready', function() {
	myProductToolbar = new productToolbar();
	myProductToolbar.addStyleForFirstWord();
});

// fix the intro cols and toolbar pointer
window.addEvent('load', function() {
	if (myProductToolbar && myProductToolbar.ready) {
		setTimeout(function() {
			myProductToolbar.showPointer(myProductToolbar.active_tool);
		}, 500);
	}
});
