/**
 * @author alexander.farkas
 */
(function($){
    $.fn.extend({
        tab: function(options){
            var args = Array.prototype.slice.call(arguments, 1), tabO;
            if(this.length){
				if (typeof options == "string") {
                    var tab = $.data(this[0], "accordion-tab");
                    tab[options].apply(tab, args);
                }
                else 
                    if (!$.data(this, "accordion-tab")) {
                         tabO = new $.tab(this, options);
                    }
			}
			return this.each(function(){
                if (!$.data(this, "accordion-tab") && tabO) {
                    $.data(this, "accordion-tab", tabO);
                }
                
            });
        }
    });
	$.tab = function(elms, s){
		this.s = $.extend({
                activeClass: 'on',
                firstActive: false,
                animationToggle: false,
                complete: function(){
                },
                closeOnClick: false,
                closeOther: true,
                onEvent: 'click',
                noAction: false,
                diaShow: false,
				tabListSel: false
            }, s);
			
			var that = this,
			tabID = 'tab-'+new Date().getTime(),
			ariaRoles,
			ariaStates;
			this.controls = elms;
			this.timerID = null;
			this.panels = [];
			if (this.s.diaShow) {
                this.timerID = setInterval(function(){
					that.diaShow.call(that);
				}, s.diaShow);
            }
			if(this.s.tabListSel){
				$(this.s.tabListSel).attr({'role': 'tablist'});
				ariaRoles = ['tab', 'tabpanel'];
			} else {
				ariaRoles = ['button', 'region'];
			}
			this.controls.each(function(i){
                var jElm = $(this),
				eId = jElm.attr('id');
				if(!eId){
					eId = tabID+i;
					jElm.attr({'id': eId});
				}
                that.panels.push($(that.getIDfromAnker(jElm)));
                that.panels[i].one('mouseover.tabsAperto focus.tabsAperto', function(){
                    clearInterval(that.timerID);
                }).attr({role: ariaRoles[1], 'aria-labelledby': eId, tabIndex: '-1', 'aria-hidden': 'false'})
					.css({
	                    outline: 'none'
	                });
                if (that.s.firstActive && i === 0) {
                    jElm.addClass(that.s.activeClass)
						.attr({'aria-selected': 'true'});
                }
                else
                    if (!jElm.is('.' + that.s.activeClass)) {
                        that.panels[i].css({
                            display: 'none'
                        }).attr({'aria-hidden': 'true'});
						jElm.attr({'aria-selected': 'false'});
                    } else {
						jElm.attr({'aria-selected': 'true'});
					}
                    jElm.bind(that.s.onEvent, function(e){
						clearInterval(this.timerID);
						that.showHide.call(that, this, e);
						return false;
					});
                
                jElm.bind('click.tabsAperto', function(e){
					that.clickHandler.call(that, this, e);
					return false;
				}).attr({role: ariaRoles[0]});				
			});
	};
	$.extend($.tab.prototype, {
		getIDfromAnker: function(jElm){
            var id = jElm.attr('href'), 
			fund = id.indexOf('#');
            id = (fund != -1) ? id.substr(fund) : false;
            return id;
        },
		diaShow: function(){
            var n, that = this;
            this.controls.each(function(i){
                if ($(this).is('.' + that.s.activeClass)) {
                    n = i + 1;
                    return false;
                }
            });
            var next = (this.controls[n]) ? this.controls[n] : this.controls[0];
            this.showHide(next);
        },
		showHide: function(elm, e) {
            var jElm = $(elm);
            if (!this.s.closeOnClick && jElm.is('.' + this.s.activeClass)) {
                return false;
            }
            var curActive = (this.s.closeOther) ? 
				this.controls.filter('.' + this.s.activeClass) : 
				$([]), 
				curID = null, 
				newID = this.getIDfromAnker(jElm);
            jElm.toggleClass(this.s.activeClass);
            if (!jElm.is('.' + this.s.activeClass)) {
                curActive = jElm;
            } else {
				jElm.attr({'aria-selected': 'true'});
			}
            if (curActive.length) {
                curActive.removeClass(this.s.activeClass);
				curActive.attr({'aria-selected': 'false'});
                curID = this.getIDfromAnker(curActive);
            }
            if (curID === newID) {
                newID = [];
                curActive = $([]);
            }
            var curActiveBlock = $(curID);
            var toActivateBlock = $(newID);
			if(curActiveBlock[0] && curActiveBlock[0] === document){
				curActiveBlock = $([]);
			}
			if(toActivateBlock[0] && toActivateBlock[0] === document){
                toActivateBlock = $([]);
			}
            if (!this.s.noAction) {
                if (!this.s.animationToggle) {
					
					curActiveBlock
						.hide()
						.attr({'aria-hidden': 'true'});
                    toActivateBlock
						.show()
						.attr({'aria-hidden': 'false'});
				
                    if (!e || (e && e.type == 'click')) {
						setTimeout(function(){
		                	toActivateBlock.focus();
		                }, 200);
                    }
                }
                else {
					
                    $.each(this.panels, function(){
                        this.stop(true, true);
                    });
                    curActiveBlock[this.s.animationToggle]().attr({'aria-hidden': 'true'});
                    toActivateBlock[this.s.animationToggle](function(){
                        if (e && e.type == 'click') {
							setTimeout(function(){
		                       toActivateBlock[0].focus();
		                    }, 200);
                        }
                    }).attr({'aria-hidden': 'false'});
                }
            }
            this.s.complete(jElm, toActivateBlock, curActive, curActiveBlock);
        },
		clickHandler: function(elm, e){
            var that = this;
			e.preventDefault();
			if (this.s.onEvent.indexOf('click') == -1) {
                var jElm = $(elm);
                setTimeout(function(){
                    $(that.getIDfromAnker(jElm)).focus();
                }, 9);
            }
            return false;
        }
	});
})(jQuery);

