/** 
 *	Copyright (c) by znpd.pl
 * 
 **/

Cufon.replace('#sub-header h2, #content h2, #content h3, .cufon');

var date = new Date, now = date.getTime(), nows = now/1000, last_response,
mininterval = 100000, chat_loaded = false;

$(function() {
	$('.popinfo, abbr').popinfo();
	
	$('.connections span.conn-type').live('click', function() {
		$(this).replaceWith($('.conn-sel.tpl').clone().removeClass('tpl').val($(this).data('conn')).change(function() {
			var that = $(this);
			$.post('/ajax.php?action=change-connection', {mode: 'connection', value: $(this).val(), id: $(this).closest('tr').data('id')}, function() {
				that.replaceWith($('<span class="conn-type editable" />').text(that.find('option:selected').text()).data('conn', that.val()));
			});
		}));
	});
	
	$('.connections span.conn-ver').live('click', function() {
		that = $(this);
		$.post('/ajax.php?action=change-connection', {mode: 'verified', value: that.text() == 'nie'?1:0, id: $(this).closest('tr').data('id')}, function() {
			that.text(that.text() == 'tak'?'nie':'tak');
		});
	});
	
	$('.connections span.conn-desc').live('click', function() {
		var thatc = $('.conn-edit.tpl').clone().removeClass('tpl');
		txt = $(this).text();
		var thati = thatc.find('input').val(txt == 'edytuj'?'':txt);
		var thats = thatc.find('span');
		$(this).replaceWith(thatc);
		thats.click(function() {
			$.post('/ajax.php?action=change-connection', {mode: 'description', value: thati.val(), id: $(this).closest('tr').data('id')}, function() {
				thatc.replaceWith($('<span class="conn-desc editable" />').text(thati.val() == ''?'edytuj':thati.val()));
			});
		});
	});
	
	$('.addv').click(function() {
		var ctr = $(this).closest('tr');
		ctr.find('.money:last').clone().insertBefore(this).before('<br>').val('');
		var ctrdl = ctr.find('.date:last');
		ctrdl.clone().removeAttr('id').removeClass('hasDatepicker').insertAfter(ctrdl).before('<br>').val('').datepicker({maxDate:0,minDate:ctrdl.attr('rel')}).datepicker("setDate", date);
		var ctrsl = ctr.find('.status:last');
		ctrsl.clone().insertAfter(ctrsl).val('own');
		return false;
	});

	if ($.browser.msie && $.browser.version == 6)
	{
		$('input[type=text], input[type=password]').addClass('iText');
		$('input[type=submit]').addClass('iSubmit');
		$('input, textarea, #header li, #header ul ul').hover(function(){$(this).addClass('hover');},
			function(){$(this).removeClass('hover');});
		$('#header > ul, #header > ul > li, #header > ul > li > a').addClass('mc');
	} 	
	
	$.tablesorter.addParser({
        id: "money",
        is: function (s) {
            return /(zł)$/.test($.trim(s));
        }, format: function (s) {
            return $.tablesorter.formatFloat(s.replace('zł', '').replace(' ', '').replace(',', '.'));
        }, type: "numeric"
    });

	$('.sorter').tablesorter();
	
	$('.portalUser input').autocomplete({source:'/ajax.php?action=username',minLength:3, selectFirst:false});
	$('.portalUser select').change(function() {
		$(this).parent().find('input').autocomplete({"source": '/ajax.php?action=username&portal='+$(this).val()});	
	}).change();
	
	/*$('#tabs > ul a').each(function() {
		if ($(this).attr('href').charAt(0) != '#')
			this.href += (this.href.indexOf('?') != '-1'?'&':'?')+'ajax=1';
	});
	
	$('#tabs').bind( "tabsload", function(event, ui) {
		$(ui.panel).find("table.sorter").tablesorter();
		$(ui.panel).find(".plot").each(function() {	
			$plot_stript = $(this).attr('rel');
			$(this).after($plot_stript);
		});
		
		$(ui.panel).find('.portalUser input').autocomplete({source:'/ajax.php?action=username',minLength:3, selectFirst:false});
		$(ui.panel).find('.portalUser select').change(function() {
			$(this).parent().find('input').autocomplete({"source": '/ajax.php?action=username&portal='+$(this).val()});	
		}).change();
		
		//document.location = document.location.pathname + '#tab-' + ui.panel.id;
	}).tabs({cache:true, idPrefix: 'n', panelTemplate: '<div><img src="http://static.znpd.pl/gfx/ui/ui-anim_basic_16x16.gif"> Trwa ładowanie treści...</div>'})
	.bind('tabsshow', function(event, ui){
		location = location.pathname + location.search + '#tab-' + ui.panel.id;
	}).tabs('select', document.location.hash.slice(5));*/
	
	if ($('#tabs').length>0)
	{
		function go_hash(hash, li) {
			li.addClass('ui-state-active ui-tabs-selected');
			$('.tab').hide();
			target = $(hash).show();
			id = target.attr('id');
			target.attr('id', id+'-temp');
			location = location.pathname + location.search + hash;
			target.attr('id', id);
			
			$('#tabs').trigger('tabsshow', li.index());
		}
		$('#tabs').addClass( "ui-tabs ui-widget ui-widget-content ui-corner-all" );
		$('#tabs > ul').addClass( "ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all" );
		$('#tabs > ul li').addClass( "ui-state-default ui-corner-top" ).hover(
			function() {$(this).addClass('ui-state-hover');},function() {$(this).removeClass('ui-state-hover');});
		$('#tabs > div').addClass( "tab ui-tabs-panel ui-widget-content ui-corner-bottom" );
		var
			History = window.History, // Note: We are using a capital H instead of a lower h
			State = History.getState(),
			rootUrl = History.getRootUrl();
		//console.log(rootUrl);
	
		// Log Initial State
		//History.log('initial:', State.data, State.title, State.url);
	
		// Bind to State Change
		
		if ( History.enabled ) {
			$(window).bind('statechange',function(){ // Note: We are using statechange instead of popstate
				// Log the State
				var State = History.getState(),
				url = State.url,
				relativeUrl = escape(url.replace(rootUrl,''));
				
				if (State.data != null)
				{
					//var nhref = relativeUrl.replace('?', '-').replace('&', '-').replace('.', '-').replace('/', '-');
					$('.tab').hide();
					if ($('#'+State.data.id).length == 0)
					{
						$('<div />').addClass('tab ui-tabs-panel ui-widget-content ui-corner-bottom').attr('id', State.data.id).appendTo('#tabs').html('<div><img src="http://static.znpd.pl/gfx/ui/ui-anim_basic_16x16.gif"> Trwa ładowanie treści...</div>');
						$.get('/'+relativeUrl+(relativeUrl.indexOf('?') != '-1'?'&':'?')+'ajax=1', function(data) {
							$('#'+State.data.id).replaceWith(data);
							var panel = $('#'+State.data.id);
							panel.addClass('ui-tabs-panel ui-widget-content ui-corner-bottom');
							panel.find("table.sorter").tablesorter();
							panel.find(".plot").each(function() {	
								$plot_stript = $(this).attr('rel');
								$(this).after($plot_stript);
							});
							
							panel.find('.portalUser input').autocomplete({source:'/ajax.php?action=username',minLength:3, selectFirst:false});
							panel.find('.portalUser select').change(function() {
								$(this).parent().find('input').autocomplete({"source": '/ajax.php?action=username&portal='+$(this).val()});	
							}).change();
							
							panel.find('.popinfo, abbr').popinfo();
							
							Cufon.refresh();//'#content h2, #content h3, .cufon');
						}).error(function() {
							$('#'+State.data.id).replaceWith("<p>Wystąpił błąd w trakcie ładowania zakładki. Prosimy spróbować ponownie później</p>.");
						});
					} else {
						$('#'+State.data.id).show();
					}
					
					_gaq.push(['myTracker._trackPageview']);
				}
				
				//History.log('statechange:', State.data, State.title, relativeUrl);
			});
			
			$('#tabs > ul a, a.tabt').live('click', function() {
				//if ($(this).attr('href').charAt(0) != '#')
					//this.href += (this.href.indexOf('?') != '-1'?'&':'?')+'ajax=1';
				$('#tabs > ul li').removeClass('ui-state-active ui-tabs-selected');
				
				var href = $(this).attr('href');
				if (href.charAt(0) == '#')
				{
					go_hash(href, $(this).parent());
				} else {	
					splt = this.rel.split('-');
					$('#tabs').trigger('tabsshow', $('#tabs > ul li a[rel='+this.rel+'], #tabs > ul li a[rel='+splt[0]+']').parent().addClass('ui-state-active ui-tabs-selected').index());
					History.pushState({id: this.rel}, $(this).text(), this.href);
				}
				return false;
			});
			
			$('.tab').hide();
			if (State != undefined && State.data != null && typeof State.data.id != 'undefined')
			{			
				$('#'+State.data.id+', #'+State.data.id.split('-')[0]).show();				
				$('#tabs > ul li a[rel='+State.data.id+'], #tabs > ul li a[rel='+State.data.id.split('-')[0]+']').parent().addClass('ui-state-active ui-tabs-selected');
			} else {
				hash = document.location.hash;
				if (hash.length>1 && $('#tabs > div'+hash).length>0)
				{
					go_hash(hash, $('#tabs > ul a[href='+hash+']').parent());
				} else {
					$('#tabs > div:eq(0)').show();
					$('#tabs > ul li:eq(0)').addClass('ui-state-active ui-tabs-selected');
				}
			}
		} else {
			$('#tabs > ul a, a.tabt').each(function() {
				if (this.href.indexOf('#') == -1)
				{
					this.href = this.href+'#'+this.href.split('/').pop().split('-')[0];
				}
			}).click(function() {
				$('#tabs > ul li').removeClass('ui-state-active ui-tabs-selected');
				
				var href = $(this).attr('href');
				if (href.charAt(0) == '#')
				{
					go_hash(href, $(this).parent());
				}
			});
			hash = document.location.hash;
			if (hash.length>1 && $('#tabs > div'+hash).length>0 && $('#tabs > ul a[href$='+hash.substring(1)+']').length)
			{
				go_hash(hash, $('#tabs > ul a[href$='+hash.substring(1)+']').parent());
			} else {
				$('#tabs > div:eq(0)').show();
				$('#tabs > ul li:eq(0)').addClass('ui-state-active ui-tabs-selected');
			}
		}		
	}

	$.datepicker.setDefaults($.datepicker.regional['pl']);
	
	if ($('input.date').length>0)
		$('input.date').datepicker({maxDate: 0}).each(function() {
			if ($(this).attr('rel') != '')
			{
				$(this).datepicker('option', 'minDate', $(this).attr('rel'));
			}
		}).attr('readonly', 'readonly');
	
	var aworking = false;
	$('.ajax').live('click', function() {
		var that = $(this);
		if (!aworking)
		{			
			switch (this.rel)
			{
				case 'reloadTab':
					action = function() {
						aworking = false;
						$.fancybox.hideActivity();
						$(window).trigger('statechange');
						//alert($('#tabs').tabs('option', 'selected'));
						//$tabs = $('#tabs');
						//$tabs.tabs('load', $tabs.tabs('option', 'selected'));
					};
					aworking = true;
					$.fancybox.showActivity();
					var state = History.getState();
					$('#'+state.data.id).remove();
					
					$.get($(this).attr('href'), action);
					
					/*$tabs = $('#tabs');
					tid = $tabs.tabs("option", "selected");
					$('#tabs').tabs('url', tid, this.href+'&ajax=1');
					$('#tabs').tabs('load', tid);*/
					//$.get($(this).attr('href'), action); 
				break;
				default:
					aworking = true;
					$.fancybox.showActivity();
					action = function(ra) {
						aworking = false;
						$.fancybox.hideActivity();
						$.each(ra, function(key, r) {
							that.closest('tr').find('.lastLogin').text(r.lastLogin);
							if (r.paid == 1) {
								that.closest('tr').remove();
							}
						});
					}
					$.getJSON($(this).attr('href'), action);
				break;
			}
		}
		return false;
	});
	
	$('#userInvestments tbody td').live('click', function() {
		if (!aworking)
		{
			aworking = true;
			$.fancybox.showActivity();
			$.getJSON('/ajax.php?action=investments', {pd:user, pb:$(this).closest('tr').attr('rel'), portal: portal}, function(r){
				aworking = false;
				$.fancybox.hideActivity();
				$.fancybox(r.html, {
					'width' : 1000,
					'height': '75%',
					autoDimensions: false,
					'autoScale' : false
				});
				Cufon.replace('#fancybox-content h2');
				$("#fancybox-content table").tablesorter({ 
				headers: {
					10: {sorter:false}
					}
				});
				$('#load_pbpd_chart').click(function() {
					$.fancybox.showActivity();
					$.getJSON('/ajax.php?action=pbpd_chart', $.parseJSON($(this).attr('rel')), function(r) {
						$.fancybox.hideActivity();
						$('#pbpd_chart_container').replaceWith(r.html);
					});
					return false;
				});
			});
		}
		
		return false;
	}); 
	
	$('#userInvestors tbody td').live('click', function() {
		if (!aworking)
		{
			aworking = true;
			$.fancybox.showActivity();
			$.getJSON('/ajax.php?action=investments', {pb:user, pd:$(this).closest('tr').attr('rel'), portal: portal}, function(r){
				aworking = false;
				$.fancybox.hideActivity();
				$.fancybox(r.html, {
					'width' : 1000,
					'height': '75%',
					autoDimensions: false,
					'autoScale' : false
				});
				Cufon.replace('#fancybox-content h2');
				$("#fancybox-content table").tablesorter({ 
				headers: {
					10: {sorter:false}
					}
				});
				$('#load_pbpd_chart').click(function() {
					$.fancybox.showActivity();
					$.getJSON('/ajax.php?action=pbpd_chart', $.parseJSON($(this).attr('rel')), function(r) {
						$.fancybox.hideActivity();
						$('#pbpd_chart_container').replaceWith(r.html);
					});
					return false;
				});
			});
		};
	});
	
	$('#user-stats tbody tr').live('click', function() {
		m = $(this).find('td:first-child').text();
		if (m != 'RAZEM')
		{
			$.fancybox.showActivity();
			$.getJSON('/ajax.php', {action: 'month', user: user, month: m, portal: portal}, function(r) {
				$.fancybox(r.html, {
					'width' : 1000,
					'height': '75%',
					autoDimensions: false,
					'autoScale' : false,
					onComplete:function() {
						Cufon.replace('#fancybox-content h2');
						$("#fancybox-content table").tablesorter({ 
						headers: {
							11: {sorter:false}
							}
						});
					}
				});
			});
		}
	});
	
	$("#user-stats").bind('sortStart', function() {
		$("#user-stats tbody .summary").hide();
	}).bind('sortEnd', function() {
		if ($('#user-stats .headerSortDown').is(':first-child'))
			$("#user-stats tbody .summary").show().insertAfter($('#current'));
	});
	
	srel = $('#statsUser').attr('rel');
	$('#statsUser').autocomplete({source:'/ajax.php?action=username'+(srel?'&portal='+srel:''),minLength:3, selectFirst:false});
	
	if (typeof notices !== "undefined" && notices.length>0) 
	{
		for (i=0;i<notices.length;i++)
		$.gritter.add({
			// (string | mandatory) the heading of the notification
			title: 'Uwaga!',
			// (string | mandatory) the text inside the notification
			text: notices[i],
			// (bool | optional) if you want it to fade out on its own or just sit there
			sticky: false, 
			// (int | optional) the time you want it to be alive for before fading out
			time: 10000
		});
	}
	
	$('.sidebar').localScroll({hash: true});
	
	//$.localScroll.hash();
	
	$('.do-filter').change(function() {
		$('.'+$(this).attr('id')).toggle();
	});
	
	$('[rel=lightbox]').fancybox({autoScale: false});
	
	$('#changePwd').fancybox({onComplete:function() {
		Cufon.replace('#fancybox-content h2');
		$('#changePwdForm').submit(function() {
			if ($('#old-password').val() == '')
			{
				alert('Musisz podać stare hasło!');
			} else if ($('#new-password').val() == '') {
				alert('Musisz podać nowe hasło!');
			} else if ($('#new-password').val() != $('#new-password2').val()) {
				alert('Podane hasła się różnią!');
			} else if ($('#new-password').val().length < 6) {
				alert('Wybrane hasło jest za krótkie!');
			} else {
				$.fancybox.showActivity();
				$.post('ajax.php?action=haslo', $(this).serialize(), function(r) {
					if (r=='1')
					{
						alert('Hasło zostało zmienione.');
						$.fancybox.close();
					} else {
						alert(r);
					}
				});
			}
			return false;
		});
	}});
	
	$('#remindPwd').fancybox({onComplete:function() {
		Cufon.replace('#fancybox-content h2');
		$('#remindPwdForm').submit(function() {
			if ($('#remind-user').val() == '' && $('#remind-mail').val() == '')
			{
				alert('Musisz podać nazwę użytkownika lub adres e-mail!');
			} else {
				$.fancybox.showActivity();
				$.post('ajax.php?action=remind', $(this).serialize(), function(r) {
					if (r=='1')
					{
						alert('Nowe hasło zostało wysłane na adres podany podczas rejestracji.');
						$.fancybox.close();
					} else {
						alert(r);
					}
				});
			}
			return false;
		});
	}});
	
	$('input.bonus').change(function() {
		var iid = $(this).attr('rel').split('-')[1];
		$('a[rel='+iid+']').removeClass('green tick');
	});
	
	$('a.bonus').click(function() {
		that = this;
		$(this).addClass('throbber');
		$.post('ajax.php?action=bonus', {iid: this.rel, bonus: $('[name=bonus-'+this.rel+']').val()}, function() {
			$(that).removeClass('throbber').addClass('green tick');
		});
		return false;
	});
	
	if ($.browser.mozilla == undefined || $.browser.version < 3.6)
		$('#addonFirefox').remove();

	var chr = /Chrome\/(\d+)/.exec(navigator.userAgent);
	if (!chr||chr[1]<13)
		$('#addonChrome').remove();
	
	if ($.browser.opera == undefined || $.browser.version < 11)
		$('#addonOpera').remove();

	$('.cslider, .ncslider').change(function() {
		if ((this.checked && this.className == 'cslider') || (!this.checked && this.className == 'ncslider'))
			$('#'+this.id+'_c').slideDown(); else
			$('#'+this.id+'_c').slideUp();
	}).change();
	
	$('#kokos_name').autocomplete({source:'/ajax.php?action=username&portal=1',minLength:3, selectFirst:false});
	$('#fin_name').autocomplete({source:'/ajax.php?action=username&portal=0',minLength:3, selectFirst:false});
	$('#sekrata_user').autocomplete({source:'/ajax.php?action=username&portal=4',minLength:3, selectFirst:false});
	
	$('#registerForm').submit(function() {
		$('.ferror').remove();
		ok = true;
		
		kokosc = $('#kokos').is(':checked');
		finansowoc = $('#finansowo').is(':checked');
		sekratac = $('#sekrata').is(':checked');
		
		if (kokosc && $('#kokos_name').val() == '')
		{
			$('#kokos_c').prepend('<div class="ferror">Musisz podać nazwę użytkownika</div>');
			ok = false;
		}
		if (finansowoc && $('#fin_name').val() == '')
		{
			$('#finansowo_c').prepend('<div class="ferror">Musisz podać nazwę użytkownika</div>');
			ok = false;
		}
		if (sekratac && $('#sekrata_user').val() == '')
		{
			$('#sekrata_c').prepend('<div class="ferror">Musisz podać nazwę użytkownika</div>');
			ok = false;
		}
		
		if (!sekratac && !kokosc && !finansowoc)
		{
			$('#kokos').parent().before('<div class="ferror">Wybierz przynajmniej jeden portal</div>');
			ok = false;
		}
		
		if (!$('#a-rules').is(':checked'))
		{
			$('#a-rules').parent().append(' <span class="ferror">Zaakceptuj regulamin</span>');
			ok = false;
		}
		
		if (!ok)
			$('.ferror').hide().slideDown();
		
		return ok;
	});
	
	$('#mail_same').change(function() {
		if (this.checked)
			$('#kokos_mail_c').slideUp(); else
			$('#kokos_mail_c').slideDown();
	}).change();
	
	if ($.jqplot) {
		$.jqplot.moneyFormatter = function (format, val) {
			return numberWithCommas($.jqplot.sprintf(format, val))+" zł";
		};
		
		function numberWithCommas(x) {
			return x.toString().replace(/\B(?=(?:\d{3})+(?!\d))/g, " ");
		}
	}
	
	$('#lform').submit(function() {
		if (!$('#a-rules').is(':checked')) {
			$('#a-rules').parent().css({border: '1px solid red', padding: '3px'});
			alert('Musisz zaakceptować regulamin!');
			return false;
		}
	});

})

$.fn.popinfo = function() {
	if ($('#popinfo').length == 0)
		$('<div id="popinfo" />').appendTo('body').hide().css('opacity', 0.95);
	$(this).each(function() {
		var t = $(this);
		if (this.title != '')
		{
			t.attr('btitle', this.title);
			this.title = '';
			
			t.hover(function() {
				$('#popinfo').stop(false, true).html($(this).attr('btitle')).show();
			}, function() {
				$('#popinfo').stop(false, true).hide();
			}).mousemove(function(e) {
				$('#popinfo').css({
					left: e.pageX,// - $(this).offset().left,
					top: e.pageY+20// - $(this).offset().top
				});
			});
			
			// Znikanie dymku po kliknięciu (np. alert)
			t.click(function() {
				$('#popinfo').stop(false, true).hide();
			});
		}
	});
};
