//var start = new Date().getTime();
//var end = new Date().getTime();
//var time = end - start;
//alert('Execution time: ' + time);

var _trackCache = { };

function _hash(type, params) {
	var h = location.hash;

	if (type == null) {
		return h.replace('#', '').split(',');
	}

	switch (type) {
		case '':
			var reg = new RegExp(';?(#|stats|map|image)[^;]+;?', 'i');
			h = h.replace(reg, '');
		break;
		
		default:
			var reg = new RegExp(';?' + type + '[^;]+;?', 'i');
			var str = h.replace(reg, '');
			str = (str == '#' || str == '') ? str : str + ';';
			h = str + type + ',' + params.join(',');
	}

	location.hash = (h == '') ? '#' : h;
}

function _hashCallback(hash)
{
	if (hash == '')
		hide();
		
	if (_hash()[0] > 0 && _hash()[1] > 0)
		showTrack(_hash()[0], _hash()[1]);
		//showTrack(parseInt('0x' + _hash()[0]), _hash()[1]);
}

function posLoading() {
	var arrayPageSize	= getPageSize();
	var arrayPageScroll = getPageScroll();

	$('#loading').css({
					left:   ((arrayPageSize[0] - $('#loading').width()) / 2) + 'px',
					top:    arrayPageScroll[1] + ((arrayPageSize[3] - $('#loading').height() - 5) / 2) + 'px'
					});
}

function posWin(width, height, animate) {
	var arrayPageSize	= getPageSize();
	var arrayPageScroll = getPageScroll();

	if (width == undefined) width  = arrayPageSize[2] - 100;
	if (height == undefined) height = arrayPageSize[3] - 80;

	$('#overlay').css({ height: height > arrayPageSize[1] ? height : arrayPageSize[1] });
	$('#image-overlay').css({ height: height - 60 });
	$('#help-overlay').css({ height: height - 60 });
	$('#stats-overlay').css({ height: height - 60 });
	$('#map-overlay').css({ height: height - 60 });
	$('#win').corner('#3F3F3F 13px');

	var style = {
			width:  width,
			height: height,
			left:   ((arrayPageSize[0] - width) / 2) + 'px',
			top:    arrayPageScroll[1] + ((arrayPageSize[3] - height - 5) / 2) + 'px'
		};
	

	if (animate == true)
		$('#win').animate(style);
	else
		$('#win').css(style);
}

function initWin(width, height) {
	posWin(width, height);

	$(window).resize(function() { posWin(width, height) });
	$(window).scroll(function() { posWin(width, height) });
}

function show(func, width, height) {
	initWin(width, height);	
	func;
	$('#overlay').fadeIn('fast', function() {
		$('#win').fadeIn('fast');
	});
}

var hideWin = function() {
	_hash('', []);

	$(window).unbind('resize');
	$(window).unbind('scroll');
	
	$('#win').fadeOut('fast', function() {
		$('#overlay').fadeOut('fast');
	});

	GUnload();
	$('#map-overlay').html('')
	$('#title').html('');
}

function hide() {
	if ($('#image-overlay').is(':visible'))
		$('#image-overlay').fadeOut();

	else if ($('#win').is(':visible'))
		hideWin();
}

function changePreview(type) {
	$('#preview').attr('src', _hash()[0] + '.ps.' + type + '.png');
}

var help = function() {
	$('#title').html('Pomoc');
	
	$.ajax({
		url:			'help',
		type:			'GET',
		timeout:	30000,
		dataType: 'html',
		error: function() {
			$('#win').fadeOut('fast', function() {
				$('#overlay').fadeOut('fast', function() {
					alert('Wystąpił błąd podczas ładowania strony. Spróbuj jeszcze raz.');
				});
			});
		},
		success: function(data) {
			p.html(data);
			p.show();
		}
	});
}

function foldMonth(elem) {
	var img = $(elem);
	var div = $('#list tr[month=\'' + img.attr('month') + '\']');
	var src = img.attr('src');
	var txt = img.attr('alt');
	
	src = src.match('unfold') ? src.replace('unfold', 'fold') : src.replace('fold', 'unfold');
	txt = txt.match('Zwiń') ? txt.replace('Zwiń', 'Rozwiń') : txt.replace('Rozwiń', 'Zwiń');
	
	img.attr({ 'src' : src, 'title' : txt, 'alt' : txt });
	
	if (!src.match('unfold')) {
		div.show();
		//URL(img.attr('type'), ['unfold']);
	}
	
	else {
		div.hide();
		//URL(img.attr('type'), ['fold']);
	}
}

function setColumnList() {
	var columnList = $('#columnList');
	
	$('img#columnListIcon').click(function(e) {
		if (columnList.is(':visible')) {
			columnList.hide();
			return;
		}
		
		var left = e.pageX - columnList.width() - 15;
		var top  = e.pageY + 20;

		columnList.css({'top': top, 'left': left}).show();
		columnList.stopTime('columnList').oneTime(2000, 'columnList', function() { $(this).hide(); });
	});
	
	columnList.mouseout(function() {
		$(this).stopTime('columnList').oneTime(500, 'columnList', function() { $(this).hide(); });
	});

	$('#columnList li').mouseover(function() {
		$(this).parent().stopTime('columnList');
	});	

}

function intTime(s) {
	var m = s.split(':');
	return parseInt(m.pop()) + parseInt(m.pop()) * 60 + parseInt(m.pop()) * 3600;
}

function strTime(seconds) {
	var az = function(val) {
		return (val > 9) ? val : '0' + val;
	}
	
	var hours = Math.floor(seconds / 3600);
	var mins  = Math.floor((seconds - hours * 3600) / 60);
	var secs  = seconds - hours * 3600 - mins * 60;
	var days  = '';
	
	if (hours > 24) {
		days = Math.floor(hours / 24) + 'd ';
		hours -= parseInt(days) * 24;
	}

	return days + az(hours) + ':' + az(mins) + ':' + az(parseInt(secs));
}

var summaryRows = new Array(3);

function makeListSummary() {
	var cnt = new Array(13);
	var sum = new Array(13);
	var max = new Array(13);
	
	for (var i = 0; i < 13; i++) {
		cnt[i] = 0;
		sum[i] = 0;
		max[i] = 0;
	}

	// szukamy widocznych wierszy (znalezionych podczas wyszukiwania)
	var rows = $('#list > tbody > tr.track:visible');
	for (var a = 0, b = rows.length; a < b; a++) {
		var cols = rows[a].cells;
		
		for (var i = 3; i <= 11; i++) {
			var val = $(cols[i]).text();
			// parsujemy czas
			val = (i == 5) ? intTime(val) : parseFloat(val);
			
			sum[i] += val;
			max[i] = (val > max[i]) ? val : max[i];
			
			// dla hr i cad sumujemy wartosci > 0
			if (i < 8 || (i >= 8 && val > 0)) cnt[i]++;
		}
	}

	var sumRow = $('#list > tfoot > tr[type=\'sum\']');
	var avgRow = $('#list > tfoot > tr[type=\'avg\']');
	var maxRow = $('#list > tfoot > tr[type=\'max\']');

	// jesli wszystkie wiersze wyswietlone to odtworzamy podsumowanie
	if ($('#list > tbody > tr.track:hidden').size() == 0) {
		sumRow.html(summaryRows[0]);
		avgRow.html(summaryRows[1]);
		maxRow.html(summaryRows[2]);
	}
	
	else {
		// zapamietujemy podsumowanie
		summaryRows[0] = sumRow.html();
		summaryRows[1] = avgRow.html();
		summaryRows[2] = maxRow.html();

		var suffix = [ '', '', '', 'km', 'm', '', 'km/h', 'km/h', 'bpm', 'bpm', 'rpm', 'rpm' ];
		
		// podsumowanie  (suma)
		for (var i = 3; i <= 5; i++) {
			var val = sum[i];
			val = (i == 5) ? strTime(val) : parseInt(val);
			
			// pierwsze dwie kolumny sa polaczone
			$(sumRow[0].cells[i - 1]).text(val + ' ' + suffix[i]);
		}

		// podsumowanie  (średnia)
		for (var i = 3; i <= 11; i++) {
			if (cnt[i] == 0) cnt[i] = 1;
			var val = sum[i] / cnt[i];
			val = (i == 5) ? strTime(val) : parseInt(val);
			
			$(avgRow[0].cells[i - 1]).text(val + ' ' + suffix[i]);
		}

		// podsumowanie  (maks)
		for (var i = 3; i <= 11; i++) {
			var val = max[i];
			val = (i == 5) ? strTime(val) : parseInt(val);
			
			$(maxRow[0].cells[i - 1]).text(val + ' ' + suffix[i]);
		}
	}
}

var filterList = function() {
	$.uiTableFilter( $('#list'), $("input#searchList").val() );
	
	// odkrycie wszystkich ukrytych wierszy z nazwa miesiaca
	 $('#list > tbody > tr[search=\'false\']:hidden').each(function() { $(this).show(); });
	
	// znalezienie widocznych wierszy (ktore zostaly po zawezeniu wyszukiwania)
	var rows = $('#list > tbody > tr:visible');
	
	// ukrycie wierszy z nazwa miesiaca jesli nastepny wiersz jest rowniez z nazwa miesiaca
	for (var i = 0, j = rows.length; i < j - 1; i++) {
		var row_a = $(rows[i]);
		var row_b = $(rows[i + 1]);
		
		if (row_b.attr('search') == 'false' && row_b.attr('class') == 'month') {
			if (row_a.attr('search') == 'false' && row_a.attr('class') == 'month') row_a.hide();
			if (i == j - 2) row_b.hide();			
		}
	}
	
	makeListSummary();
}

$.tablesorter.addParser({
	id: 'float',
	is: function(s) { return /[\d\.\ kmh]+/.test(s); },
	format: function(s) { return parseFloat(s); },
	type: 'numeric'
});
	
$.tablesorter.addParser({
	id: 'date',
	is: function(s) { return /\d{4}-\d{2}-\d{2}, \d{2}:\d{2}/.test(s); },
	format: function(s) {
		var m = s.match(/(\d{4}-\d{2}-\d{2}, \d{2}:\d{2})/);
		if (m)
			return m[1];
	},
	type: 'text'
});

$(document).bind('keydown', 'esc', function() { hide() });
//$(document).bind('keydown', 'alt+h', function() { show(help(), 600, 400) });

function parseStatsPointsData(data) {
	$('#stats td[type]').each(function() {
		$(this).text(data['stats'][$(this).attr('type')]);
	});

	$('img.graph').each(function() {
		$(this).attr('src', _hash()[0] + '.gs.' + $(this).attr('type') + '.png');
	});
	
	$('#previewSelect')[0].selectedIndex = 0;
	$('#preview').attr('src', _hash()[0] + '.ps.distance.png');
	
};

function showTrack(id, tab) {
	$('#title').html($('#u1n' + id).html());

	// ukrywamy wszystkie warstwy
	$('#win > div').hide();
	
	// pokazujemy gorna i dolna belke
	$('#top-bar').show();
	$('#bottom-bar').show();
	
	// pokazujemy wszystkie zakladki i ustawiamy aktywna
	$('#tabs > li').removeClass('tab-active').show();
	$('#tabs > li:eq(' + (tab - 1) + ')').addClass('tab-active');
	
	// jesli wybrana zakladka to mapa
	if (tab == 4) {
		posWin(undefined, undefined, $('#win').is(':visible'));

		// chowamy statystyki i pokazujemy mape
		$('#stats-overlay').hide;
		var map = $('#map-overlay').show();
	}
	
	else {
		posWin(950, 560, $('#win').is(':visible'));
		
		// chowamy mape i pokazujemy wybrana zakladke ze statystykami
		$('#map-overlay').hide();
		$('#stats-overlay').show().find('div').hide().end().find('div:eq(' + (tab - 1) + ')').show();
	}

	// chowamy zakladke Tetno i kadencja jesli niepotrzebna
	if ($('#list > tbody > tr#' + id).attr('tabs') == 2) {
		$('#tabs > li:eq(2)').hide();
	}

	if (_trackCache[id]) {
		parseStatsPointsData(_trackCache[id]);
		$('#overlay').fadeIn('fast', function() {
			$('#win').fadeIn('fast', function() {
				// mape ladujemy dopiero po pokazaniu diva bo inaczej sie krzaczy
				if ($('#tabs > li.tab-active').attr('tab') == 4)
					createMap($('#map-overlay')[0], _trackCache[id]['points']);
			});
		});
	}
	
	else {
		if ($('#win').is(':visible'))
			return;

		$('#loading').fadeIn(function() {
			$.ajax({
				url:		id + '.js',
				type:		'GET',
				timeout:	30000,
				dataType:	'json',
				error:
					function() {
						$('#loading').fadeOut();
						_hash('', []);
						alert('Wystąpił błąd podczas wczytywania danych. Spróbuj jeszcze raz.');
					},
			
				success:
					function(data) {
						_trackCache[id] = data;
						parseStatsPointsData(data);
						$('#loading').hide();
	
						$('#overlay').fadeIn('fast', function() {
							$('#win').fadeIn('fast', function() {
								// mape ladujemy dopiero po pokazaniu diva bo inaczej sie krzaczy
								if ($('#tabs > li.tab-active').attr('tab') == 4)
									createMap($('#map-overlay')[0], _trackCache[id]['points']);
							});
						});
					}
			});
		});
	}
}

function listLoaded(data) {
	$('#loading').fadeOut();
	$('#list').html(data);

	var list = $('#list');
	
	list.find('tr.track').hover(
		function() { $(this).addClass('hover'); },
		function() { $(this).removeClass('hover'); }
	);
	
	list.click(function(e) {
		var tr = $(e.target).parent();
		if (tr.hasClass('track'))
			// ustawiamy do wyswietlenia pierwsza zakladke w statystykach,
			// pokazaniem zajmie sie _hashCallback
			//_hash(parseInt(tr.attr('id')).toString(16).toUpperCase(), [ 1 ]);
			_hash(parseInt(tr.attr('id')), [ 1 ]);
	});

	list.tablesorter({
		cssHeader: 'sort',
		cssAsc: 'sortAsc',
		cssDesc: 'sortDesc',
		headers: { 0: { sorter: 'date' }, 12: { sorter: false }, 13: { sorter: false } }
	});
	
	// ukrywamy lub pokazujemy wiersz grupujacy miesiace
	list.bind("sortEnd",function() {
		var td = $("#list > thead > tr > td.sortDesc");
		if (td.attr("class") == undefined)
			td = $("#list > thead > tr > td.sortAsc");
			
		if (td.parent().children().index(td) == 0)
			$("#list > tbody > tr.month").show();
		else
			$("#list > tbody > tr.month").hide(); 
    });
    
    list.columnManager({ listTargetID:'columnList', onClass: 'on', offClass: 'off', saveState: false, colsHidden: [8, 10, 12, 13], hideInList: [14] });
	setColumnList();    

	$.history.init(_hashCallback);

	// wyszukiwanie po 500ms po wprowadzeniu ostatniego znaku w pole
    $('#searchList').keyup(function() {
    	$(this).stopTime('searchList').oneTime(500, 'searchList', filterList);
	});
}

$(document).ready(function() {
	$('#tabs > li').hover(
		function() { $(this).addClass('tab-hover'); },
		function() { $(this).removeClass('tab-hover'); }
	).click(function() {
		_hash(_hash()[0], [ $(this).attr('tab') ]);
	});

	$(window).resize(function() { posLoading() });
	$(window).scroll(function() { posLoading() });
	posLoading();

	$('#loading').fadeIn(function() {
		$.ajax({
			url:		'list',
			type:		'GET',
			timeout:	30000,
			dataType:	'text',
			error:
				function() {
					$('#loading').fadeOut();
					alert('Wystąpił błąd podczas ładowania strony. Spróbuj jeszcze raz.');
				},
		
			success:
				function(data) {
					listLoaded(data);
				}
		});
	});

	$('img.graph').click(function() {
		$('#large').attr('src', '').attr('src', $(this).attr('src').replace('gs', 'gl'));
		$('#image-overlay').fadeIn();
	});

	$('img#preview').click(function() {
		$('#large').attr('src', '').attr('src', $(this).attr('src').replace('ps', 'pl'));
		$('#image-overlay').fadeIn();
	});

	// dostepne po wybraniu trybu zaznaczania
	/*$('#list tr.track').toggle( 
		function() { $(this).addClass('selected'); },
		function() { $(this).removeClass('selected'); }
	);*/ 
	
	/* dostepne po wybraniu trybu edycji
	$('.eInput').editable('save.html', {
		indicator : "Zapisywanie...",
		tooltip   : 'Kliknij by edytować...',
		submit		: 'OK'
	});

	$('.eInputD').editable('save.html', {
		loadtype	: 'POST',
		loadurl		: 'load.html',
		loadtext	: '',
		indicator : 'Zapisywanie...',
		tooltip   : 'Kliknij by edytować...',
		submit		: 'OK'
	});

	$('.eSelect').editable('save.html', {
		loadtype	: 'POST',
		loadurl		: 'load.html',
		type			: 'select',
		loadtext	: '',
		indicator : 'Zapisywanie...',
		tooltip   : 'Kliknij by edytować...',
		submit		: 'OK'
	}); */
});
