function tab_menu_activate(obj, item_styles) {
	var num = obj.nextAll().length;
	obj.attr("class", item_styles[0] + " " + item_styles[2] + ((num == 0) ? (" " + item_styles[1]) : ""));
	// remove href
	var hidden_href = obj.parent().find("div.hidden_href");
	if (hidden_href.length == 0) {
		hidden_href = $("<div class=\"hidden_href\" style=\"display:none;\"></div>");
		obj.parent().prepend(hidden_href);
	}
	hidden_href.html(obj.html());
	obj.html(obj.text());
}

function tab_menu_deactivate(obj, item_styles) {
	var num = obj.nextAll().length;
	obj.attr("class", item_styles[0] + " " + ((num == 0) ? (" " + item_styles[1]) : ""));
	// add href
	//obj.html('<a href="/post/add">' + obj.text() + "</a>");
	obj.html(obj.parent().find("div.hidden_href").html());
}

function tab_menu_click() {
	// find menu parent and get styles all, right, active
	if (!$(this).parent().attr("rel")) {
    var menu_items = $(this).parent().find("div");
    var first_class = $(menu_items[0]).attr("class").split(' ');
    var last_class = $(menu_items[menu_items.length - 1]).attr("class").split(' ');
    $(this).parent().attr("rel", first_class[0] + " " + last_class[1] + " " + first_class[1]);
	}
  var item_styles = $(this).parent().attr("rel").split(' ');
  // cache this element
	var this_elm = this;
	// deactivate old item
	var old_id;
  $(this).parent().find("div." + item_styles[2]).each(function() {
    if (this != this_elm) {
    	tab_menu_deactivate($(this), item_styles);
    	old_id = $(this).attr('id');
    }
  });
  if (old_id) {
  	old_id = old_id.substr(0, old_id.lastIndexOf('_'));
  	$("#" + old_id).hide();
  }
  // show new element
  tab_menu_activate($(this), item_styles);
  var id = $(this).attr('id');
  if (id) {
	 	id = id.substr(0, id.lastIndexOf('_'));
	 	$("#" + id).show();
	 	//
	 	var inputs = $("#" + id).find("input");
	 	if (inputs.length > 0) {
	 		help_block();
	 	  $(inputs[0]).focus();
	 		help_unblock();
	  }
	}
  return false;
}

$(document).ready(function() {
	// find menus
	$(".tab_menu").find("div").click(tab_menu_click);
	// activate first item
	$(".tab_menu").each(function() {
		var links = $(this).find("div");
		if (links.length > 0) {
			$(links[0]).click();
		}
	});
});

