/**
* $Id: jquery.settabs.js 4694 2010-06-30 11:33:28Z antonenkova $
* 
* Example:	
* 
* <div class = "class">
*
* 	<hx>header1</hx>
*	
*	<p>1</p>
*	<p>2</p>
*	<p>3</p>
*	
*	<hx>header2</hx>
*	
*	<div>1</div>
*	<div>2</div>
*	<div>3</div>	
*
* </div>
*
* <link href="settabs.css" rel="stylesheet" type="text/css">
*
* <script type="text/javascript">
* 	$("div.class").settabs({selector: "hx", anchor: document.location.hash});
* </script>
*
*
*/


(function ($) {	
	
	$.extend($.expr[":"], {  
    	toOpen: function(a) {  
    		return $(a).data("toOpen");  
   		}  
	});  

	$.fn.getAnchor = function(){
		if (anchor = this.children().attr("Name")) { 
			return anchor = "#" + anchor;	
		}
		else {
			return null;
		}
	};
	
	$.fn.getClassNames = function(){
		if (name = this.attr("className")) {
			return name.split(" ");
		}
		else {
			return [];
		}
	};
	
	$.fn.openSelectTab = function(){
		$(".tabHeaderActive").removeClass("tabHeaderActive");
		this.addClass("tabHeaderActive");
		
		var n = this.getClassNames()[0];
		$(".tabContent").each(function(){
			if ($(this).getClassNames()[0] == n){
				$(this).data("toOpen", true);
			}
			else {
				$(this).data("toOpen", false);
				$(this).removeClass("tabContentActive");
			}
		});
			
		return $(".tabContent:toOpen").addClass("tabContentActive");
	}

	$.fn.settabs = function(options){
		
		var options = $.extend({
			selector: "h1",
			anchor: "" 
		}, options);		
		var selector = options.selector.replace("h", "H");	
		
		var count_tabs = $(options.selector, $(this)).size();
		if (count_tabs <= 1) {
			return this;
		}
		
		$(options.selector, $(this))
			.eq(0)
			.before("<div class = 'tabList'></div>")
			.end()
			.each(
				function(index){
					$(this)
						.css("display", "block")
						.addClass("" + index)
						.addClass("tabHeader");	
				
					var elem = this.nextSibling;
			
					var elements = new Array();
			    
					while (elem && elem.nodeName != selector)
					{				
						elements.push(elem);
						elem = elem.nextSibling;
					}
			
					$(elements).wrapAll("<div class=\"" + index + " tabContent\"></div>");
			
					$(this).getAnchor() == options.anchor ? $(this).openSelectTab() : null;
				
					$(this).appendTo(".tabList");			
			})
			.click(
				function(){	
					if ($(this).is("tabHeaderActive")){
							return;
					}
					$(".tabHeaderActive").removeClass("tabHeaderActive");
					$(this).openSelectTab();	
			})
			.hover(
				function(){
					$(this).addClass("tabMouseOver");
				},
				function(){
					$(this).removeClass("tabMouseOver");
			});
	
		if (options.anchor == "") {
			$(options.selector, $(this))
				.eq(0)
				.openSelectTab();
		}
		
		
		$("a[href*=#]").click(function(event){
			if (event.target.pathname == document.location.pathname) 
			{
				$(options.selector).each(function(){
					$(this).getAnchor() == event.target.hash ? $(this).click() : null;			
				}); 
			}
		});
		
		// Вкладка "Купить" в конец
		// Вкладка "Функции" после вкладки "Описание"
		// Вкладка "Другие программы" в конец + рыжий цвет (для by)
		// Вкладка "Другие программы" в конец + рыжий цвет (для by)
		$(options.selector, $(this)).each(function(){
			if ($(this).text().toLowerCase() == "купить") {
				$(this).appendTo(".tabList");
			}
			if ($(this).text().toLowerCase() == "функции") {
				$(this).insertAfter($(options.selector).eq(0));
			}
			if ($(this).text().toLowerCase() == "другие программы") {
				$(this).appendTo(".tabList");
			}
			if ($(this).text().toLowerCase() == "другие карты") {
				$(this).appendTo(".tabList");
			}
		});
		
		
		// замена пробелов в названиях вкладок на $nbsp;
			
		$(options.selector, $(this)).each(function() {
		
			var re = /(\s*[А-Яа-я]+\s*[А-Яа-я]*)/;
			this.innerHTML = this.innerHTML.replace(re, function($1) {
				$1 = $.trim($1).replace(/\s/g, '&'+'nbsp;');	
				return $1;
			});
		
		});

		
		return this;
			
	};
	
	
	
	$.fn.aligntabs = function(options){
		
		if ($(".tabHeader", $(this)).size() == 0) {
			return this;
		}
		
		var options = $.extend({
			width: 500
		}, options);	
		
		
		
		//@todo если options.width меньше ширины самой большой вкладки return
		
		
		var container = this;
		
		var all_width 	= 0;
		var count_tabs_on_line	= new Array();
		var width_increase		= new Array();

		
		
		var	calculateIncrease = function(count_tabs_on_line) {
			
			$.each(count_tabs_on_line, function(i, val) {
				
				var x = 0;
				
				$(".tabHeader", $(container)).not(".*").each(function(index) {
					var header = this;
							
					if (val > index) {
						x +=  $(header).width() + 11; 
						$(header).addClass("*");
					}
					
				});
				
				
				if (x > options.width) {
				
					if (i+1 == count_tabs_on_line.length) {
						count_tabs_on_line[ i+1 ] = 0;
					} 
					count_tabs_on_line[ i ] --;
					count_tabs_on_line[ i+1 ] ++;
						
					width_increase.length = null;
					$(".tabHeader", $(container)).removeClass("*"); 
						
					calculateIncrease(count_tabs_on_line);
					return;
				} 
					
				var diff = options.width - x;
				var increase = diff / val;
				
				var tmp = {
						count: val,
						increase: increase
				};
									
				width_increase.push(tmp);
			});		
		};
		
		
			
		$(".tabHeader", $(this)).each(function(index) {
			all_width += $(this).width() + 11;
			count_tabs = index + 1;			
		});
		
		
		count_lines = Math.ceil(all_width / options.width);
	
		
		while (count_lines > 0) {
			count_tabs_on_line.push(Math.ceil(count_tabs / count_lines));
			count_tabs -=  Math.ceil(count_tabs / count_lines);
			count_lines --;
		}
			
		
		calculateIncrease(count_tabs_on_line);	
		$(".tabHeader", $(container)).removeClass("*");
	
		
		///у последней вкладки в строке margin-right обнуляется,
		/// а ширина увеличивается на 1
		
		$.each(width_increase, function(i, val) {
	
			$(".tabHeader", $(container)).not(".*").each(function(index) {
				
				var header = this;
	
				if (index+1 < val.count) {
					var m = $(this).width() + val.increase;
					$(this).width(m);
					$(header).addClass("*");
				}
				
				if (index+1 == val.count) {
					var m = $(this).width() + val.increase + 1;
					$(this).css("margin-right", "0").width(m);
					$(header).addClass("*");
				}
						
			});		
			
		});
		
		$(".tabHeader", $(container)).removeClass("*");
		
		return this;
	};
		
})(jQuery);
