$(function() {
	/*
	 * Tabs
	 */
	var _findTabs = function() {
		var _found = [];
		$(".tabs").each(function(_container) {
			var _data = {
				container : $(this),
				tabs : []
			};

			$(".tab", $(this)).each(function(_container) {
				var _theTab = {
					id : $(this).attr('id'),
					title : $("> h3", $(this)).text(),
					contents : $("div.tab-contents", $(this))
				};
				_data.tabs.push(_theTab);
			});

			_found.push(_data);
		});
		return _found;
	};

	var _hideTab = function(_id) {
		$('#tabl-' + _id).removeClass('selected');
		$('#tabc-' + _id).css('display', 'none');
	};

	var _showTab = function(_id) {
		$('#tabl-' + _id).addClass('selected');
		$('#tabc-' + _id).css('display', 'block');
	};

	var _prepareTabContainer = function(_root) {
		_root.container.empty();

		var _titles = $('<ul/>').addClass('tab-buttons');
		_titles.appendTo( $('#hd-page') );

		for ( var j in _root.tabs) {
			var _theTab = _root.tabs[j];
			if (j == 0 || location.hash == '#' + _theTab.id) {
				_root.selected = _theTab.id;
			}

			var _link = $('<a/>').attr('id', 'tabb-' + _theTab.id)
					.attr('href', '#' + _theTab.id).text(_theTab.title);
			$('<li/>').attr('id' , 'tabl-' + _theTab.id )
				.appendTo(_titles).append(_link);
			_link.click(
					function() {
						_hideTab(_root.selected);
						_root.selected = $(this).attr('id').replace(
								/^tabb-/, '');
						_showTab(_root.selected);
					});
			_theTab.contents.css('display', 'none').attr('id',
					'tabc-' + _theTab.id).appendTo(_root.container);
		}
		_showTab(_root.selected);
	};

	var _prepareTabs = function(_tabs) {
		for ( var i in _tabs) {
			_prepareTabContainer(_tabs[i]);
		}
	};
	
	var _handleFakeTabs = function( ) {
		var _buttons = [];
		$('.tab-buttons a').each( function( _button ) {
			$(this).remove( );
			_buttons.push( $(this) );
		});
		if ( _buttons.length == 0 ) {
			return false;
		}

		var _titles = $('<ul/>').addClass('tab-buttons');
		_titles.appendTo( $('#hd-page') );
		for ( var i in _buttons ) {
			var _button = _buttons[ i ];
			var _content = $('<li/>').appendTo(_titles).append(_button);
			if ( _button.hasClass( 'selected-tab' ) ) {
				_content.addClass( 'selected' );
			}
		}
		
		return true;
	};

	var _tabs = _findTabs();
	if ( _handleFakeTabs() && _tabs.length != 0 ) {
		// FIXME: we should display "sub-tabs" somehow
		// For now we simply ignore the JS tabs
	} else if ( _tabs.length != 0 ) {
		_prepareTabs(_tabs);
	}

	/*
	 * Hidden descriptions
	 */
	$("div.auto-hide").each(function() {
		var _div = $(this);
		_div.css('display', 'none');
		var _visible = false;
		$('<a/>').attr('href', '#').text('...').click(function() {
			if (_visible) {
				_div.css('display', 'none');
			} else {
				_div.css('display', 'block');
			}
			_visible = !_visible;
			return false;
		}).insertBefore(_div);
	});

	/*
	 * "Jump to planet"
	 */
	$("p#jump-to-planet").each(
			function() {
				var _form = $('<form/>').attr('action', '/').submit(function() {
					return false;
				});
				var _fdiv = $('<div/>').appendTo(_form);
				var _select = $('<select/>').attr('name', 'planet').addClass(
						'input').appendTo(_fdiv);
				$('<option/>').attr('value', '').text(
						$('span.jtp-text', $(this)).text() + " ...").appendTo(
						_select);
				$('a', $(this)).each(
						function() {
							$('<option/>').attr('value', $(this).attr('href'))
									.text($(this).text()).appendTo(_select);
						});

				_select.change(function() {
					var _target = $("option:selected", $(this)).attr('value');
					if (_target == "") {
						return false;
					}
					location.href = _target;
					return true;
				});
				$(this).empty();
				_form.appendTo($(this));
			});

	/*
	 * Map cells
	 */
	var _mapClasses = [ 'map-bg-none', 'map-bg-allied', 'map-bg-own',
			'map-bg-enemy', 'map-bg-other' ];
	$(".map a").each(
			function() {
				var _cls = $(this).hasClass("own-planet") ? 2 : ($(this)
						.hasClass("allied-planet") ? 1 : ($(this).hasClass(
						"enemy-planet") ? 3
						: ($(this).hasClass("other-planet") ? 4 : 0)));
				var _href = $(this).attr('href');
				var _pDiv = $(this).parent();
				_pDiv.mouseenter(function() {
					$(this).addClass(_mapClasses[_cls]).addClass('map-invert');
				}).mouseleave(
						function() {
							$(this).removeClass(_mapClasses[_cls]).removeClass(
									'map-invert');
						}).click(function() {
					location.href = _href;
					return false;
				});
			});

	/*
	 * Fleet ships
	 */
	$(".fleet-details").each(function() {
		var _id = $(this).attr('id');
		var _name = $("td.name", $(this));
		var _ships = $("#" + _id + "-ships");
		_ships.css('display', 'none');
		_name.click(function() {
			if (_ships.css('display') == 'none') {
				_ships.css('display', 'table-row');
			} else {
				_ships.css('display', 'none');
			}
		});
	});

	/*
	 * Planets - buildings/ships details
	 */
	$("#buildings-types .building-type").css('display', 'none');
	$('#ff-civ-build-type').change(function() {
		$("#buildings-types .building-type").css('display', 'none');
		$("#building-type-" + $(this).val()).css('display', 'block');
	});
	$("#ships-types .ship-type").css('display', 'none');
	$('#ff-mil-build-type').change(function() {
		$("#ships-types .ship-type").css('display', 'none');
		$("#ship-type-" + $(this).val()).css('display', 'block');
	});

	/*
	 * Battles
	 */
	$("#ff-view-battle-tick")
			.each(
					function() {
						$(this).next().remove();
						$(this).css('width', '95%');
						$(this).change(function() {
							var _baseUrl = location.href;
							_baseUrl = _baseUrl.replace(/-latest$/, "");
							_baseUrl = _baseUrl.replace(/-at-[0-9]+/, "");
							_baseUrl += "-at-" + $(this).val();
							location.href = _baseUrl;
						});

						$("tr.ship-type").css('display', 'none');
						$("td.ships-expander").each(function() {
							$(this).text('*').css('cursor', 'pointer');
						}).click(
								function() {
									var _tr = $(this).parent().next();
									while (_tr != null
											&& _tr.hasClass("ship-type")) {
										if (_tr.css('display') == 'none') {
											_tr.css('display', 'table-row')
													.data('visible', true);
										} else {
											_tr.css('display', 'none').data(
													'visible', false);
										}
										_tr = _tr.next();
									}
								});

						$("td.forces-expander")
								.each(
										function() {
											$(this).text('+').css('cursor',
													'pointer');
											var _tr = $(this).parent().next();
											while (_tr != null
													&& _tr.hasClass("group")) {
												_tr = _tr.next();
											}
											while (_tr != null
													&& _tr.hasClass("empire")) {
												_tr.css('display', 'none');
												_tr = _tr.next();
											}
										})
								.click(
										function() {
											var _tr = $(this).parent().next();
											while (_tr != null
													&& _tr.hasClass("group")) {
												_tr = _tr.next();
											}

											var _mode = null;
											while (_tr != null
													&& _tr.hasClass("empire")) {
												if (_mode === null) {
													_mode = (_tr.css('display') == 'none') ? 'table-row'
															: 'none';
												}
												var _rMode;
												if (_tr.hasClass("ship-type")) {
													_rMode = _tr
															.data('visible') ? _mode
															: 'none';
												} else {
													_rMode = _mode;
												}
												_tr.css('display', _rMode);
												_tr = _tr.next();
											}
										});
						$("tr.tip").css('display', 'table-row');
					});

	/* Chat button */
	$("a.open-chat-button").click(function() {
		window.open(this.href);
		return false;
	});

	/* Message selection button */

	$("span#message-box-selector").each(
			function() {
				var _title = $(this).attr('title');
				$(this).replaceWith(
						$('<input/>').addClass('input').attr('type', 'button')
								.attr('title', _title).val('X').css('cursor',
										'pointer').click(function() {
									$("input.message-selection").click();
								}));
			});
});