/**
 * mktabs
 *
 * Copyright (c) 2009 Wagner Michael - das MedienKombinat GmbH (www.das-medienkombinat.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 * 
 */

/**
 * Version: 0.1
 * 
 * History
 * * 0.1 Anfangs-Veröffentlichung (based on "jQuery Accessible Tabs" blog.ginader.de)
 * * * Entfernen unwichtiger Dinge (fx, fxspeed, currentInfoText, currentInfoPosition, currentInfoClass)
 * * * Option zur Angabe des Events hinzugefügt (option:event)
 * * * Option zur Angabe einer Klasse für die Tabliste (option:tablistClass)
 */

/**
 * @requires jQuery v1.0.3
 * 
 * @example $('.mktabs').mktabs();
 * @desc Erstellt aus den Elementen in den Containern .mktabs ein Tabsystem
 * 
 * @param Object mit Optionen für das Tabsystem
 * @option (String) 	wrapperClass 	 Class welche um das Ganze Tabsystem herum gewrapt wird.
 * @option (String) 	tablistClass 	 Class für die Tabliste (ul)
 * @option (String) 	currentClass 	 Class für den Aktiven Tab
 * @option (String) 	tabhead 		 Tag oder jQuery Selector von Elementen, welche als Tab Button interpretiert werden soll (original wird gelöscht)
 * @option (String) 	tabbody 		 Tag oder jQuery Selector von Elementen welche als Tab Body interpretiert werden sollen.
 * @option (String) 	event 			 Event, auf das ein Tab reagieren soll
 * 
 * @option (String)		entryIdSelector		Ein Selector, um die ID für das Element herauszufinden (muss im Head liegen). Genutzt wird dessen value .val(). Default wird der aktuelle Timestamp genutzt.
 * @option (String)		entryIdFunction		Wie entryIdSelector, nur das diese Funktion aufgaufgerufen wird, welche die ID liefert. Funktioniert nur, wenn entryIdSelector===false. Der erste Parameter für die Funktion ist das Aktuelle element.
 * @option (boolean)	activeByAnchor		Prüft den Anker (#) in der URL, und öffnet das entsprechende Element des mkaccordions. Ohne diesen Anker wird die active Option genutzt.
 */

(function($) {
    $.fn.extend({
        getUID: function(p){
            return p + new Date().getTime();
        },
        mktabs: function(config) {
            var defaults = {
                wrapperClass: 'mktabcontent',
                tablistClass: 'mktablist',
                currentClass: 'active',
                tabhead: 'h4',
                tabbody: '.tabbody',
                event: "click",
                entryIdSelector: false,
				entryIdFunction: false,
				activeByAnchor: true
            };
            var options = $.extend(defaults, config);
            var o = this;
            
            /* *** Function *** */
			// function entryId liefert die id für das element in dem accordion
			var entryId = function(element, p) {
				var id = false; 
				if(options.entryIdSelector !== false) {
					var entryIdEl = element.find(options.entryIdSelector);
					if(entryIdEl.length) {  id = entryIdEl.val(); }
				} else if(typeof(options.entryIdFunction) === 'function') {
					id = options.entryIdFunction(element);
				}
				if(!id) { id = new Date().getTime(); }
				// timestamp zurückgeben
				return p + id;
			};
			
            return this.each(function() {
                var el = $(this),
                	list = '',
                	contentAnchor = o.getUID('mktabscontent');
                
                $(el).wrapInner('<div class="'+options.wrapperClass+'"></div>');
                	
                $(el).find(options.tabhead).each(function(i,el){
                	var tabsAnchor = entryId($(this), 'mktabs');	
                    var id = '';
//                    if(i === 0){
                        id =' id="'+tabsAnchor+'"';
//                    }
                    list += '<li><a'+id+' href="#'+contentAnchor+'">'+$(this).html()+'</a></li>';
                    $(this).remove();
                });
                $(el).prepend( $('<ul>'+list+'</ul>').addClass(options.tablistClass) );
                $(el).find(options.tabbody).hide();
                $(el).find(options.tabbody+':first').show().before('<a tabindex="0" class="mktabsanchor" name="'+contentAnchor+'" id="'+contentAnchor+'"></a>');
                $(el).find("ul."+options.tablistClass+">li:first").addClass(options.currentClass);
                $(el).find("ul."+options.tablistClass+">li>a").each(function(i){
                    $(this).bind(options.event, function(event){
                        event.preventDefault(); //event verhindern
                        $(el).find('ul>li.'+options.currentClass).removeClass(options.currentClass);
                        $(this).blur();
                        $(el).find(options.tabbody+':visible').hide();
                        $(el).find(options.tabbody).eq(i).show();
                        $('#'+contentAnchor).text($(this).text()).focus();
                        $(this).parent().addClass(options.currentClass);
                    });
                });
                
                // aktiviere element
				var elToActivate = [], elToActivateByAnchor = false;
				// wir aktivieren immer das erste Element
				elToActivate = el.find("ul."+options.tablistClass+">li:first>a");
				
				// element anhand des ankers ermitteln
				if (options.activeByAnchor && window.location.hash.length) {
					var anchor = window.location.hash.substring(1),
						anchors = anchor.split('#');
					//es könnte mehrere anker für tabs und accordeon geben. also gehen wir alle durch 
					//und stoppen beim ersten treffer
					$.each(anchors, function(index, value) { 
						elToActivateByAnchor = el.find('a#'+value);
						if(elToActivateByAnchor.length) {
							elToActivate = elToActivateByAnchor;
							return false;//each schleife stoppen
						}
					});
					
				}
				// wir nutzen den ticker befehl, da noch fremde events existieren können
				if(elToActivate.length) {
					//click
					elToActivate.trigger(options.event);
					// zum anker springen!
					// if(typeof(anchor) !== 'undefined') { window.location.href = window.location.protocol+'//'+window.location.host+window.location.pathname+'#'+anchor; }
					if(elToActivateByAnchor && elToActivateByAnchor.length) {
						$('html, body').animate({scrollTop: elToActivateByAnchor.offset().top+'px'}, {easing:'swing', queue:false});
					}
				}
            });
        }
    });
})(jQuery);
