var tabs_firsttime = false;
var tabs_click = false;

Handlebars.registerHelper('tabs', function(hookname, tabauth, options) {
	let fragment = window.location.hash.substr(1);
	let tabheader = '';
	let tabbody = '';
	let tabcount = typeof window.activepage == 'undefined' || typeof window.activepage._tab == 'undefined' || window.activepage._tab === null ? 0 : window.activepage._tab.length;
	for(let i = 0; i < tabcount; i++) {
		let tab = window.activepage._tab[i],
			current_body = '',
			tab_name = tab.name;
		tab.id = hookname + '-' + i;
		tab.index = i;
		if (typeof tab.icon != 'undefined') tab_name = tab.icon + ' ' + tab_name;
		tabheader += `<li data-fragment="${tab.fragment}" data-auth="${tabauth}"><a href="#${tab.fragment}">${tab_name}</a></li>`;
		if (typeof tab.data != 'undefined' && typeof tab.data.body == 'string') {
			current_body = tab.data.body;
		} else if (typeof tab.data != 'undefined') {
			let source   = $('#' + tab.data.template).html();
			if (typeof source == 'undefined') {
				console.log('unable to locate template #' + tab.data.template);
				current_body = '';
			} else {
				let template = Handlebars.compile(source);
				current_body = template(tab.data);
			}
		}
		tabbody += `<div id="${tab.fragment}">${current_body}</div>`;
	}
	tabs_firsttime = true;
	let container = `<div class="component-tabs"><ul>${tabheader}</ul>${tabbody}</div>`;
	return new Handlebars.SafeString(container);
});

function locateByFragment(fragment) {
	if (typeof window.activepage != 'undefined' && typeof window.activepage._tab != 'undefined' && window.activepage._tab !== null ) {
		
		for(var i = 0; i < window.activepage._tab.length; i++) {
			var tab = window.activepage._tab[i]
			if (tab.fragment == fragment) return tab;
		}
	}
	return null;
}

// only when clicking on a tab, not for going back/forward
function pushTabURL(fragment) {
	var url = window.location.href;
	var p = url.indexOf('#');
	if (p > -1) url = url.substring(0, p);
	history.pushState({tabFragment: fragment}, null, url + '#' + fragment);
}

$(window).on('popstate', function(e) {
	if (typeof e.originalEvent.state == 'object') {
		var state = e.originalEvent.state;
		if (state !== null && typeof state.tabFragment != 'undefined') {
			e.preventDefault();
			var tab = locateByFragment(state.tabFragment);
			if (tab !== null) {
				var index = tab.index;
				$('.component-tabs').tabs('option', 'active', index);
			}
		}
	}
});

function displayTabContent(newTab, newPanel, dom_tab = null) {
	var fragment = newTab.data('fragment');
	var tabauth = newTab.data('auth');
	var tab = locateByFragment(fragment);
    if (tab === null) return;
	if (tabs_click) pushTabURL(tab.fragment);
	tabs_click = false;
	if (typeof tab.data == 'undefined') {
		$.ajax({
			dataType: 'json',
			async: true,
			url: '/~/tabs/select/' + tabauth + '/' + tab.fragment,
			data: {url: window.location.href},
			type: 'GET'
		}).done(function(data) {
			if (typeof data.result != 'undefined') {
				main.showStatus(data);
			}
			tab.data = data;
			if (typeof tab.data.body == 'string') {
				newPanel.html(tab.data.body);
			} else {
				var template = main.loadTemplate(tab.data.template);
				newPanel.html(template(tab.data));
			}
			main.renderDataTables(tab.data, newPanel);
			$(document).triggerHandler('loaded.template', [data, newPanel]);
			$(dom_tab).triggerHandler('tabactive', [tab.data, newPanel, fragment]);
		});
	} else if (dom_tab != null && dom_tab.firsttime) {		// data for first loaded tab is already present
		if (typeof tab.data.body == 'string') {
			newPanel.html(tab.data.body);
		} else {
			var template = main.loadTemplate(tab.data.template);
			newPanel.html(template(tab.data));
		}
		main.renderDataTables(tab.data, newPanel); 
		$(document).triggerHandler('loaded.template', [tab.data, newPanel]);
		dom_tab.firsttime = false;
		$(dom_tab).triggerHandler('tabactive', [tab.data, newPanel, fragment]);
	} else if (dom_tab != null) {
		$(dom_tab).triggerHandler('tabactive', [tab.data, newPanel, fragment]);
	}
}

$(document).on('loaded.template', function(e, data, $container) {
	var tab;
	var tab_created = false;
	$('.component-tabs', $container).each( function() {
		let $tab = $(this);
		if (!$tab.hasClass('ui-tabs')) {
			$tab.tabs({
				beforeActivate: function( event, ui ) {
					displayTabContent(ui.newTab, ui.newPanel, this);
				}
			});
			tab_created = true;
			this.firsttime = true;
		}
	});
	if (tab_created) {
		$('div.ui-tabs li.ui-tab a', $container).on('mousedown', function(e) {
			var $tab = $(this).closest('li');
			if (!$tab.hasClass('ui-state-active')) {
				tabs_click = true;
			}
		});
		var hash = window.location.hash.substring(1);
		if (tabs_firsttime && hash == '') {
			if (typeof data._default != 'undefined') hash = data._default;
		}
		if (tabs_firsttime && hash != '') {
			tab = locateByFragment(hash);
			if (tab !== null) {
				var index = tab.index;
				let $tab = $('.component-tabs');
				$tab.tabs('option', 'active', index);
				var newTab = $('li[data-fragment="' + hash + '"]');
				var newPanel = $('#' + hash);
				displayTabContent(newTab, newPanel, $tab[0]);
			}
		}
	}
}).on('page.refresh', function(e, data) {
	if (typeof data.active_tab != 'undefined') {
		var hash = data.active_tab;
		var tab = locateByFragment(hash);
		delete tab.data;
		var index = tab.index;
		let $tab = $('.component-tabs');
		$('.component-tabs').tabs('option', 'active', index);
		var newTab = $('li[data-fragment="' + hash + '"]');
		var newPanel = $('#' + hash);
		displayTabContent(newTab, newPanel, $tab[0]);
	}
});
