var animt = null;
var initl = null;

$(document).ready(function() {
	var data = new Date();
	podmianatxt();
	
	if ($('div.indexcnt').size() > 0) listaMonet(iid);
	
	$('div.coins').hide();
	$('.date-pick').datePicker({ startDate: '1970-01-01', endDate: data.getFullYear() + '-' + (data.getMonth() < 9 ? '0' : '') + (data.getMonth() + 1) + '-' + (data.getDate() < 10 ? '0' : '') + data.getDate() });
		
	if ($('.cchart, .info-c').size() > 0)
	{
		$('.cchart, .info-c').each(function () {
			thid = $(this).attr('class');
			data = new Date();
			chid = $(this).find('input:hidden').val();
			$(this).media({
					width: 560,
					height: 330,
					src: 'frontend/swf/wykres.swf?xml=' + bp + '/index/' + (thid == 'cchart' ? 'wykresmonety' : 'wykresindeksu') + '/id/' + chid + '/start/0/end/' + data.getTime() + '/proc/',
					params: {
						quality: 'high',
						bgcolor: '#ffffff',
						menu: 'false',
						wmode: 'transparent'
					}
			});
		});
	}
});

var podmianatxt = function ()
{
	$('div.info-l h2').each(function () { $(this).html('<img src="frontend/img/h.php?c=d0a760&t=' + escape($(this).html()) + '&a=c&s=22&m=120" alt="' + $(this).html() + '" />'); });
	$('div.info-l h3 span').each(function () { $(this).html('<img src="frontend/img/h.php?t=' + escape($(this).html()) + '&a=c&s=14" alt="' + $(this).html() + '" style="vertical-align: middle" />'); });
	$('div.info-r h3').each(function () { $(this).html('<img src="frontend/img/h.php?t=' + escape($(this).html()) + '&s=10&m=190" alt="' + $(this).html() + '" />'); });
	$('div.info-t h2 span.name').each(function () { $(this).html('<img src="frontend/img/h.php?t=' + escape($(this).html()) + '&s=24&c=d0a760&m=340" alt="' + $(this).html() + '" />'); });
	$('div.info-t h2 span.year').each(function () { $(this).html('<img src="frontend/img/h.php?t=' + escape($(this).html()) + '&s=18" alt="' + $(this).html() + '" />'); });
	$('div.portfeld a').each(function () { $(this).html('<img src="frontend/img/h.php?c=d0a760&t=' + escape($(this).html()) + '&a=c&s=15&m=950" alt="' + $(this).html() + '" />'); });
	$('div.portfeld span').each(function () { $(this).html('<img src="frontend/img/h.php?c=d0a760&t=' + escape($(this).html()) + '&a=c&s=15&m=950" alt="' + $(this).html() + '" />'); });
};

var animacja = function (elem)
{
	$(elem).animate({ 'left': '-=160px' }, 1600, 'linear', function () { $(this).find('li:first').clone().appendTo(this); $(this).find('li:last').show(); $(this).find('li:first').remove(); $(this).css('left', 0); $(this).dequeue(); animacja($(this)); });
};

var togglecoins = function (id, wallet)
{
	if ($('#clist-' + id + ':visible').size() > 0)
	{
		$('#clista-' + id).find('a').removeClass('exp');
		$('#clist-' + id).slideUp(1000);
		$('#clista-' + id).find('#tab1').html('<a id="tab1" href="#" onclick="this.blur(); return togglecoins(' + id + ')"><img src="frontend/img/cle.gif" alt="Rozwiń listę monet" /></a>');
		$('#clista-' + id).find('#tab2').html('<a id="tab2" href="#" onclick="this.blur(); return togglecoinstab(' + id + ')"><img src="frontend/img/tab-exp.gif" alt="Rowiń tabelę monet" /></a>');
	}
	else
	{
		$('#clisttab-' + id).find('a').removeClass('exp');
        $('#clisttab-' + id).slideUp(1000);
        $('#clista-' + id).find('a').addClass('exp');
		$('#clist-' + id).slideDown(2000);
		$('#clista-' + id).find('#tab1').html('<a id="tab1" href="#" onclick="this.blur(); return togglecoins(' + id + ')"><img src="frontend/img/clc.gif" alt="Zwiń listę monet" /></a>');
		$('#clista-' + id).find('#tab2').html('<a id="tab2" href="#" onclick="this.blur(); return togglecoinstab(' + id + ')"><img src="frontend/img/tab-exp.gif" alt="Rozwiń tabelę monet" /></a>');
	}
	if (wallet != 1) return false;
};

var togglecoinstab = function (id, wallet)
{
    if ($('#clisttab-' + id + ':visible').size() > 0)
    {
		$('#clisttab-' + id).find('a').removeClass('exp');
		$('#clisttab-' + id).slideUp(1000);
		$('#clista-' + id).find('#tab1').html('<a id="tab1" href="#" onclick="this.blur(); return togglecoins(' + id + ')"><img src="frontend/img/cle.gif" alt="Rozwiń listę monet" /></a>');
		$('#clista-' + id).find('#tab2').html('<a id="tab2" href="#" onclick="this.blur(); return togglecoinstab(' + id + ')"><img src="frontend/img/tab-exp.gif" alt="Rozwiń tabelę monet" /></a>');
    }
    else
    {
		$('#clist-' + id).find('a').removeClass('exp');
        $('#clist-' + id).slideUp(1000);
        $('#clisttab-' + id).find('a').addClass('exp');
		$('#clisttab-' + id).slideDown(2000);
		$('#clista-' + id).find('#tab1').html('<a id="tab1" href="#" onclick="this.blur(); return togglecoins(' + id + ')"><img src="frontend/img/cle.gif" alt="Rozwiń listę monet" /></a>');
		$('#clista-' + id).find('#tab2').html('<a id="tab2" href="#" onclick="this.blur(); return togglecoinstab(' + id + ')"><img src="frontend/img/tab-col.gif" alt="Zwiń tabelę monet" /></a>');
    }
    if (wallet != 1) return false;
};

var suggestPrice = function (iid, pid)
{
	if ($('#coin-' + iid + '-' + pid).find('div.prompt').size() == 0)
	{
		$('#coin-' + iid + '-' + pid).append('<div class="prompt" style="display: none">Zasugeruj cenę:<br /><input type="text" style="width: 80%" class="price" id="cprice-' + iid + '-' + pid + '"/> zł<br /><input type="button" value="OK" onclick="saveSuggestPrice(' + iid +', ' + pid + ')" /> <input type="button" value="Anuluj" onclick="hidePrompt(' + iid +', ' + pid + ')" /></div>');
		$('#coin-' + iid + '-' + pid).find('div.prompt').fadeIn();
	}
	return false;
};

var saveSuggestPrice = function (iid, pid)
{
	var value = $('#cprice-' + iid + '-' + pid).val();
	if (isNaN(value) || value*1 < 0)
	{
		$('#coin-' + iid + '-' + pid).find('div.prompt')
			.find('input.price')
				.css('color', '#ff0000')
				.end()
			.animate({ 'left': '-10px', 'right': '20px' }, 'fast', 'swing')
			.animate({ 'left': '20px', 'right': '-10px' }, 'fast', 'swing')
			.animate({ 'left': '-10px', 'right': '20px' }, 'fast', 'swing')
			.animate({ 'left': '20px', 'right': '-10px' }, 'fast', 'swing')
			.animate({ 'left': '5px', 'right' : '5px' }, 'normal', 'swing', function () {
				$(this).find('input.price')
					.css('color', '#000000')[0].focus();
				$(this).find('input.price')[0].select();
			});
	}
	else
	{
		$.post(bp + '/logged/zapiszsugestie/', { 'id': pid, 'wartosc': value }, function (ret) {
			if (ret == 'OK')
			{
				$('#coin-' + iid + '-' + pid).find('div.prompt')
					.animate({ 'bottom': '15px' }, 'fast', 'swing')
					.animate({ 'bottom': '-15px' }, 'fast', 'swing')
					.animate({ 'bottom': '15px' }, 'fast', 'swing')
					.animate({ 'bottom': '-15px' }, 'fast', 'swing')
					.animate({ 'bottom' : '0px' }, 'normal', 'swing', function () {
						$(this).fadeOut('normal', function () { $(this).remove(); });
					});
					
				// ukryj napis sugeruj cene
				$('#coin_add_stock_' + pid).fadeOut();
			}
			else
			{
				$('#coin-' + iid + '-' + pid).find('div.prompt')
					.find('input.price')
						.css('color', '#ff0000')
						.end()
					.animate({ 'left': '-10px', 'right': '20px' }, 'fast', 'swing')
					.animate({ 'left': '20px', 'right': '-10px' }, 'fast', 'swing')
					.animate({ 'left': '-10px', 'right': '20px' }, 'fast', 'swing')
					.animate({ 'left': '20px', 'right': '-10px' }, 'fast', 'swing')
					.animate({ 'left': '5px', 'right' : '5px' }, 'normal', 'swing', function () {
						$(this).find('input.price')
							.css('color', '#000000')[0].focus();
						$(this).find('input.price').val(ret);
						$(this).find('input.price')[0].select();
					});
			}
		});
	}
};

var hidePrompt = function (iid, pid)
{
	$('#coin-' + iid + '-' + pid).find('div.prompt').fadeOut('normal', function () { $(this).remove(); });
};

var changeChart = function (iid, txt, cur)
{
	data = new Date();
	isProc = $('input:radio[name=values-' + iid + ']:checked').val() == 2 ? true : false;
	
	if (txt == 1)
	{
		$('input:radio[name=graphdate-' + iid + ']').removeAttr('checked');
	}
	
	if ($('input:radio[name=graphdate-' + iid + ']:checked').size() > 0)
	{
		startDate = $('input:radio[name=graphdate-' + iid + ']:checked').val();
		endDate = data.getTime();
		
		if (cur != 0)
		{
			sdata1 = new Date(parseInt(startDate) * 1000);
			edata1 = new Date(parseInt(cur) * 1000);
			
			sdata1 = sdata1.getFullYear() + '-' + (sdata1.getMonth() < 9 ? '0' : '') + (sdata1.getMonth() + 1) + '-' + (sdata1.getDate() < 10 ? '0' : '') + sdata1.getDate();
			edata1 = edata1.getFullYear() + '-' + (edata1.getMonth() < 9 ? '0' : '') + (edata1.getMonth() + 1) + '-' + (edata1.getDate() < 10 ? '0' : '') + edata1.getDate();
			
			$('#date1-' + iid).val(sdata1).dpSetSelected(sdata1);
			$('#date2-' + iid).val(edata1).dpSetSelected(edata1);
		}
	}
	else
	{
		sdata = $('#date1-' + iid).val().split('-');
		edata = $('#date2-' + iid).val().split('-');
		
		sdata = new Date(parseInt(sdata[0], 10), parseInt(sdata[1], 10) - 1, parseInt(sdata[2], 10));
		edata = new Date(parseInt(edata[0], 10), parseInt(edata[1], 10) - 1, parseInt(edata[2], 10));
		
		startDate = sdata.getTime() / 1000;
		endDate = edata.getTime() / 1000;
		
		if (startDate >= endDate)
		{
			alert('Data początkowa musi być wcześniejsza od daty końcowej!');
			return false;
		}
	}
	
	thid = $('#chart-' + iid).attr('class');
	$('#chart-' + iid).media({
		width: 560,
		height: 330,
		src: 'frontend/swf/wykres.swf?xml=' + bp + '/index/' + (thid == 'cchart' ? 'wykresmonety' : 'wykresindeksu') + '/id/' + iid + '/start/' + startDate + '/end/' + endDate + '/proc/' + (isProc ? '1' : ''),
		params: {
			quality: 'high',
			bgcolor: '#ffffff',
			menu: 'false',
			wmode: 'transparent'
		}
	});
};

var changeIndeksStatus = function (iid, status)
{
	$('.przeliczpan').hide();
	$.post(bp + '/wallet/changestatus/', { 'id': iid, 'status': status }, function (ret) {
		if (ret == 'OK')
		{
			var newstatus;
			var newtext;
			if (status == 1) { 
				newstatus = 0;
				newtext = 'ukryj indeks';
			} else { 
				newstatus = 1;
				newtext = 'publikuj indeks';
			}
			 
			$('#zmienstatus').html('<a class="csuggest" href="#" onclick="return changeIndeksStatus(' + iid + ', ' + newstatus + ')">' + newtext + '</a>');
		}
		else /* błąd */
		{
			if (ret == 'ERR_PUBLIC') 
			{
				$('.przeliczpan').html('Nie masz wystarczającej<br />liczby punktów.');
				$('.przeliczpan').show();
			}
		}
	});
	return false;
};

var addCoinToIndeks = function (iid, cid, param1, exist)
{
	$('#message').fadeOut('fast');
	addate = prompt('Od kiedy moneta ma być uwzględniona w indeksie', exist == true ? getTodayWithHour() : timestampToDate(0));
	if (addate === null)
		return false;
	datets = dateToTimestamp(addate);
	if (datets === false)
	{
		alert('Nieprawidłowa data');
		return false;
	}
	
	$.post(bp + '/wallet/addcoin/', { 'id': iid, 'idm': cid, 'date': datets, 'ajax': 1 }, function (ret) {
		if (ret == 'OK') {
			if(param1 == 1) {
	            $('#wallet_coind_'+cid).hide();
	            $('#wallet_coin_'+cid).hide();
	            $('#remove_'+cid).show();
	            $('#add_again_'+cid).hide();
	            $('#coin_delete_'+cid).show();
				$('#coin_show_'+cid).show();
				$('#coin_add_stock_'+cid).show();			
			} else {
				$('#message').html('Moneta dodana!').fadeIn();
				$('#dodana_'+cid).html('');
			}
			
			// update przewijanej listy monet
			listaMonet(iid);
			
		} else {
			alert('Nieprawidłowa data dodania monety!');
		}
	});
	return false;
};

var deleteCoinFromIndeks = function (iid, cid)
{
	if (confirm('Wszystkie dotychczasowe notowania monety zostaną utracone.\nCzy NA PEWNO skasować monetę z indeksu?'))
	{
		$.post(bp + '/wallet/reallydelcoin/', { 'idi': iid, 'idm': cid }, function (ret) {
			if (ret == 'OK') {
	            $('#wallet_coind_'+cid).show();
	            $('#wallet_coin_'+cid).hide();
	            $('#remove_'+cid).hide();
	            $('#add_again_'+cid).hide();
	            $('#coin_delete_'+cid).hide();
				$('#coin_add_stock_'+cid).hide();
				
				// update przewijanej listy monet
				listaMonet(iid);
			}
		});
	}
	return false;
};

var removeCoinFromIndeks = function (iid, cid)
{
	adddate = prompt('Od kiedy moneta ma nie być uwzględniona w indeksie',getTodayWithHour());
    if (adddate === null)
        return false;
    datets = dateToTimestamp(adddate);
    if (datets === false)
    {
        alert('Nieprawidłowa data');
        return false;
    }
	
	$.post(bp + '/wallet/removecoin/', { 'id': iid, 'idm': cid, 'data':datets }, function (ret) {
        if (ret == 'OK') {

            $('#wallet_coin_'+cid).show();
            $('#remove_'+cid).hide();
            $('#add_again_'+cid).show();
            
            // update przewijanej listy monet
			listaMonet(iid);
            
        }
        else
            alert('Nieprawidłowa data usunięcia monety!');
    });
    return false;
};

var dateToTimestamp = function (datestr)
{
	data1 = datestr.split(' '); if (data1.length != 2) return false;
	data2 = data1[0].split('-'); if (data2.length != 3) return false;
	data3 = data1[1].split(':'); if (data3.length != 3) return false;
	rdata = new Date(parseInt(data2[0], 10), parseInt(data2[1], 10) - 1, parseInt(data2[2], 10), parseInt(data3[0], 10), parseInt(data3[1], 10), parseInt(data3[2], 10));
	rdata = rdata.getTime() / 1000;
	if (isNaN(rdata)) rdata = false;
	return rdata;
};

var getTodayWithHour = function ()
{
	dat = new Date();
	mon = dat.getMonth() + 1;
	day = dat.getDate();
	hrs = dat.getHours();
	min = dat.getMinutes();
	sec = dat.getSeconds();
	
	if (mon < 10)
		mon = '0' + mon;
	if (day < 10)
		day = '0' + day;
	if (hrs < 10)
		hrs = '0' + hrs;
	if (min < 10)
		min = '0' + min;
	if (sec < 10)
		sec = '0' + sec;
	fda = dat.getFullYear() + '-' + mon + '-' + day + ' ' + hrs + ':' + min + ':' + sec;
	return fda;
};

var odswierzWykres = function(iid,ddolna,dgorna)
{
	/* załaduj ponownie wykres */
	$('.cchart, .info-c').html('');
	$('.cchart, .info-c').each(function () {
		thid = $(this).attr('class');
		data = new Date();
		$(this).media({
				width: 560,
				height: 330,
				src: 'frontend/swf/wykres.swf?xml=' + bp + '/index/' + (thid == 'cchart' ? 'wykresmonety' : 'wykresindeksu') + '/id/' + iid + '/start/0/end/' + data.getTime() + '/proc/',
				params: {
					quality: 'high',
					bgcolor: '#ffffff',
					menu: 'false',
					wmode: 'transparent'
				}
		});
	});
	/* wybierz pkt na wykresie i zmień zakres dat */ 
	$('div .set01 input').each(function() {
		var value = $(this).val();
		if (value == 1) $(this).attr('checked', 'checked');
	});
	$('div .set02 input#date1-' + iid).val(ddolna);
	$('div .set02 input#date2-' + iid).val(dgorna);
	
	/* zrob update wartosci indeksu */
	$.post(bp + '/index/nowawartosc/', { 'id': iid }, function (ret) {
		$('div.info-l h3 span').each(function () { $('#idwart').html('<img src="frontend/img/h.php?t=' + escape(ret) + '&a=c&s=14" alt="' + ret + '" style="vertical-align: middle" />'); });
	});
	
	/* zrob update zmiany indeksu */
	$.post(bp + '/index/zmiana/', { 'id': iid }, function (ret) {
		if (ret > 0) image = 'frontend/img/idx-up.gif';
		else if (ret < 0) image = 'frontend/img/idx-dn.gif';
		else image = 'frontend/img/idx-no.gif';
		$('div.info-l h3 img#zmianai').html('img id="zmianai" src="' + image + '" alt="" style="vertical-align: middle" />');			
	});		
}

var przeliczIndeks = function(iid, ddolna, dgorna)
{
	$('.przeliczpan').html('<p>Przeliczanie indeksu...</p><img src="frontend/img/loader.gif" />');
	$('.przeliczpan').fadeIn();
	$.post(bp + '/recalcindeks/index/', { 'id': iid, 'ajax': 1 }, function (ret) {
		if (ret == 'OK') {
			$('.przeliczpan').fadeOut();
			odswierzWykres(iid,ddolna,dgorna);
		} else if (ret == 'BRAK_MONET') {
			$('.przeliczpan').html('Brak monet');
			odswierzWykres(iid,ddolna,dgorna);
		} else {
			$('.przeliczpan').html('Wystąpił błąd<br />podczas przeliczania<br />indeksu');
			odswierzWykres(iid,ddolna,dgorna);
		}
	});
	
	return false;
};

var timestampToDate = function (ts)
{
    dat = new Date(parseInt(ts) * 1000);
    mon = dat.getMonth() + 1;
    day = dat.getDate();
    hrs = dat.getHours();
    min = dat.getMinutes();
    sec = dat.getSeconds();
    
    if (mon < 10)
        mon = '0' + mon;
    if (day < 10)
        day = '0' + day;
    if (hrs < 10)
        hrs = '0' + hrs;
    if (min < 10)
        min = '0' + min;
    if (sec < 10)
        sec = '0' + sec;
    fda = dat.getFullYear() + '-' + mon + '-' + day + ' ' + hrs + ':' + min + ':' + sec;
    return fda;
};

var listaMonet = function (id)
{
	$.post(bp + '/index/listamonet/', { 'id': id }, function (ret) {
		$('div.indexcnt ul.indexes').html(ret);
		if ($('.indexes').size() > 0)
		{
			$('.indexes').css('left', 0);
			initl = $('.indexes:first')[0].offsetLeft;
			setTimeout(function () { animacja($('.indexes:has(li:gt(4))')); }, 1000);
		}
	});
	
};

