// JavaScript Document

(function($){

$.fn.tabs = function(options) {
	var defaults = {
		titles: '',
		tabClass: 'tab',
		tabTitleClass: '.title',
		hideTitle: true,
		activeTab: 0
	}
	
	var options = $.extend(defaults, options);
	
	return this.each(function(){
		var tabContent_wrapper = $(this);
		var tabs = '';
		var tabCount = 0;
		
		if (options.titles != '') {
			var titles = options.titles.split(', ');
		} else {
			var titles = new Array();	
		}
		
		tabContent_wrapper.children().each(function(){
			$(this).addClass('tabContent');
			$(this).addClass('tabContent_' + tabCount);
			if(options.titles == '') {
				titles[tabCount] = $(this).children(options.tabTitleClass).text();
			};
			if(options.hideTitle == true) {
				$(this).children(options.tabTitleClass).hide();	
			}
			if(tabCount == options.activeTab) {
				$(this).css('display', 'block');
			} else {
				$(this).css('display', 'none');
			}
			tabCount ++;
		});
		
		for (var i in titles) {
			if(i == options.activeTab) {
				activeClass = 'selected';
			} else {
				activeClass = '';
			}
			tabs += '<li class="tab tab_' + i + ' ' + activeClass + '" rel="' + i + '" ><a href="#' + titles[i].replace(' ', '-') + '">' + titles[i] + '</a></li>';
		}
		$(this).prepend('<ul class="tabs clear">' + tabs + '</ul>');
		// $('<br clear="all" />').insertAfter('ul.tabs');
		// $(this).children('ul').children('li:first').addClass('selected');
		
		var tabLink = $('.tab', tabContent_wrapper);
		var tabContent = $('.tabContent', tabContent_wrapper);
		
		tabLink.click(function(){
			var index = parseInt($(this).attr('rel'));
			var target = $('.tabContent_' + index, tabContent_wrapper);
			tabContent_wrapper.children('ul.tabs').children('li').removeClass('selected');
			$(this).addClass('selected');
			tabContent.hide();
			target.fadeIn('fast');
			return false;
		});
	});

};
})(jQuery);
