//http://github.com/kangax/protolicious/blob/master/event.simulate.js
/**
* Event.simulate(@element, eventName[, options]) -> Element
*
* - @element: element to fire event on
* - eventName: name of event to fire (only MouseEvents and HTMLEvents interfaces are supported)
* - options: optional object to fine-tune event properties - pointerX, pointerY, ctrlKey, etc.
*
* $('foo').simulate('click'); // => fires "click" event on an element with id=foo
*
**/
(function(){
  
  var eventMatchers = {
    'HTMLEvents': /^(?:load|unload|abort|error|select|change|submit|reset|focus|blur|resize|scroll)$/,
    'MouseEvents': /^(?:click|mouse(?:down|up|over|move|out))$/
  }
  var defaultOptions = {
    pointerX: 0,
    pointerY: 0,
    button: 0,
    ctrlKey: false,
    altKey: false,
    shiftKey: false,
    metaKey: false,
    bubbles: true,
    cancelable: true
  }
  
  Event.simulate = function(element, eventName) {
    var options = Object.extend(Object.clone(defaultOptions), arguments[2] || { });
    var oEvent, eventType = null;
    
    element = $(element);
    
    for (var name in eventMatchers) {
      if (eventMatchers[name].test(eventName)) { eventType = name; break; }
    }
 
    if (!eventType)
      throw new SyntaxError('Only HTMLEvents and MouseEvents interfaces are supported');
 
    if (document.createEvent) {
      oEvent = document.createEvent(eventType);
      if (eventType == 'HTMLEvents') {
        oEvent.initEvent(eventName, options.bubbles, options.cancelable);
      }
      else {
        oEvent.initMouseEvent(eventName, options.bubbles, options.cancelable, document.defaultView,
          options.button, options.pointerX, options.pointerY, options.pointerX, options.pointerY,
          options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, options.button, element);
      }
      element.dispatchEvent(oEvent);
    }
    else {
      options.clientX = options.pointerX;
      options.clientY = options.pointerY;
      oEvent = Object.extend(document.createEventObject(), options);
      element.fireEvent('on' + eventName, oEvent);
    }
    return element;
  }
  
  Element.addMethods({ simulate: Event.simulate });
})()

// Counters

var i = 0;


// Only run if we have tabs (tabs is written out dynamically)

if(Object.isElement($('tabs'))){
	var panels = $$('.panel');
	var tabCount = panels.length;
	
	for(i=0;i<tabCount;i++){
		panels[i].addClassName('inactive-tab-body');
	}
	
	// based on the count, write buttons to the page
	var str = '<li class="prevnext"><a href="#prevtab">&laquo;</a></li>';
	for(i=1;i<tabCount+1;i++){
		str += '<li><a href="#tab' + i + '">' + i + '</a></li>';	
	}
	str += '<li class="prevnext"><a href="#nexttab">&raquo;</a></li>';
	$('tabs').update(str);
	
	var tabsbottom = $($$('div.pagination.top')[0].cloneNode(true));
	var tmpstr = tabsbottom.innerHTML.replace(/currenttop/g, 'currentbottom').replace(/totaltop/, 'totalbottom').replace(/tabs/, 'tabsbottom');
	tabsbottom.update(tmpstr);
	tabsbottom.removeClassName('top').addClassName('bottom');
	$('article').insert(tabsbottom, { after: panels[tabCount - 1] });
	
	
	$('totaltop').update(tabCount.toString());
	$('totalbottom').update(tabCount.toString());
	
	
	
	var Fabtabs = Class.create();
	
	Fabtabs.prototype = {
	        initialize : function(element) {
	                this.element = $(element);
	                var options = Object.extend({}, arguments[1] || {});
	                this.menu = $A(this.element.getElementsByTagName('a')).findAll(function(value) { return !$(value).up().hasClassName('prevnext'); });
					this.prevnext = $A(this.element.getElementsByTagName('a')).findAll(function(value) { return $(value).up().hasClassName('prevnext'); });
					
	                this.show(this.getInitialTab());
	                this.menu.each(this.setupTab.bind(this));
					this.prevnext.each(this.setupPrevNext.bind(this));
					$('tabsbottom').update(this.element.innerHTML);
					new BottomFabtabs('tabsbottom');
	        },
	        setupTab : function(elm) {
	                Event.observe(elm,'click',this.activate.bindAsEventListener(this),false)
	        },
	        setupPrevNext : function(elm) {
	                Event.observe(elm,'click',this.activatePrevNext.bindAsEventListener(this),false)
	        },
	        activate :  function(ev) {
	                var elm = Event.findElement(ev, "a");
	                Event.stop(ev);
	                this.show(elm);
	
	                this.menu.without(elm).each(this.hide.bind(this));
					$('tabsbottom').update(elm.up().up().innerHTML);
					new BottomFabtabs('tabsbottom');
	        },
	        activatePrevNext :  function(ev) {
	                var elm = Event.findElement(ev, "a");
	                Event.stop(ev);
					var activeTab = $$('ul#tabs a.active-tab')[0]
					if(elm.href.match(/next/) && this.menu.last() != activeTab) {
						$(this.menu[this.menu.indexOf(activeTab) + 1]).simulate('click');
					} else if(elm.href.match(/prev/) && this.menu.first() != activeTab) {
						$(this.menu[this.menu.indexOf(activeTab) - 1]).simulate('click');
					}
	        },
	        hide : function(elm) {
	                $(elm).removeClassName('active-tab');
	                try{
	                $(this.tabID(elm)).removeClassName('active-tab-body');
	                $(this.tabID(elm)).addClassName('inactive-tab-body');
					}
					catch(err)
					{}
	               
	        },
	        show : function(elm) {
	                $(elm).addClassName('active-tab');
	                $(this.tabID(elm)).removeClassName('inactive-tab-body');
	                $(this.tabID(elm)).addClassName('active-tab-body');
	                var currenttab = this.tabID(elm);
	                currenttab = currenttab.substr(3);
	                currenttab = parseInt(currenttab);
	                $('currenttop').update(currenttab);
					$('currentbottom').update(currenttab);
					
					if(elm == this.menu.last()) {
						this.prevnext.last().hide();
						this.prevnext.first().show();
					} else if(elm == this.menu.first()) {
						this.prevnext.first().hide();
						this.prevnext.last().show();
					} else {
						this.prevnext.first().show();
						this.prevnext.last().show();
					}
	        },
	        tabID : function(elm) {
	        		try{
					return elm.href.match(/#(\w.+)/)[1];
	                }
	                catch(err)
	                {
	                }
	        },
	        getInitialTab : function() {
	                if(document.location.href.match(/#(\w.+)/)) {
	                        var loc = RegExp.$1;
	                        var elm = this.menu.find(function(value) { return value.href.match(/#(\w.+)/)[1] == loc; });
	                        return elm || this.menu.first();
	                } else {
	                        return this.menu.first();
	                }
	        }
	}
	
	var BottomFabtabs = Class.create();
	
	BottomFabtabs.prototype = {
	        initialize : function(element) {
	                this.element = $(element);
	                var options = Object.extend({}, arguments[1] || {});
	                this.menu = $A(this.element.getElementsByTagName('a'));
	                this.menu.each(this.setupTab.bind(this));
	        },
	        setupTab : function(elm) {
	                Event.observe(elm,'click',this.activate.bindAsEventListener(this),false)
	        },
	        activate :  function(ev) {
	                var elm = Event.findElement(ev, "a");
					Event.stop(ev);
					$($$('ul#tabs a[href$=' + elm.href.match(/(#\w.+)/)[1] + ']')[0]).simulate('click');
	        }
	}
	
	Event.observe(window,'load',function(){ new Fabtabs('tabs'); },false);
}
