(function($) {

/* klasa timera */
function Timer() {
	this._defaults = 
	{
		//1-aukcja, 0-lista
		typ: 1,
		ilosc: 1,

		//url ajaxa
		url: '',
		url_bits: '',
		url_add_bit: '',
		
		//id timera-ów 1,2,3,4
		ids: [],
		
		//dane id;time|id;time
		callback: ''
	};
}

var PROP_NAME = 'timer';

$.extend(Timer.prototype, {
	
	setDefaults: function(inst) {
		this.typ = this._get(inst, 'typ');
		this.url = this._get(inst, 'url');
		this.url_bits = this._get(inst, 'url_bits');
		this.url_add_bit = this._get(inst, 'url_add_bit');
		this.ids = this._get(inst, 'ids');
		this.callback = this._get(inst, 'callback');
		this.last_time = new Array(this._get(inst, 'ilosc'));
		this.hold_time = 0;
		this.reload = 0;
		this.colorTime = '00:00:05';
		this.zaloguj = this._get(inst, 'zaloguj');
		this.doladuj = this._get(inst, 'doladuj');
		//lang
		this.langFinish = 'Finished';
		this.langHold = 'Pauze';
		this.langHoldAuction = 'Pauze: 00:00 - 8:00';
		this.langWaluta = ' $';
		this.langIlosc = 'Bids count: ';
		this.langOkres = 'Period: ';
		this.langBezLimitu = 'no limit';
		this.brakPazurki = '-';
		this.langProcent = '%';
	},
	
	/* default Akcja */
	_defaultAkcja: function(target, options) 
	{
		//rozdzielenie opcji
		var inst = {};
		inst.options = $.extend({}, options);
		
		//zapamiętanie opcji przekazanych w konstruktorze
		target = $(target);
		$.data(target[0], PROP_NAME, inst);
		
		//init default
		this.setDefaults(inst);
	},
	
	/* Timer::_startTimer
	 * rozpoczęcie interwału dla funkcji
	 */
	_startTimer: function()
	{
		if (this.typ)
		{
			//inicjalizacja zegara
			this._inicjuj_timeTimer(this.callback, 'init');
			this.intervalID = window.setInterval(this._odswiez_timeTimer, 1000);
		}
		else
		{
			//inicjalizacja zegarów
			this._inicjuj_timesTimer(this.callback, 'init');
			this.intervalID = window.setInterval(this._odswiez_timesTimer, 1000);
		}
	},
	
	/* Timer::_stopTimers
	 * zatrzymanie wykonywania akcji interałowej
	 */
	_stopTimers: function()
	{
		window.clearInterval(this.intervalID);
	},
	
	/* Timer::_stopTimer
	 * zatrzymanie wykonywania akcji interałowej
	 */
	_stopTimer: function(id, text)
	{
		$('#Countdown_'+id).removeClass('hasCountdownColor');
		$('#Countdown_'+id).countdown('destroy');;
		$('#Countdown_'+id).html(text);
	},
	
	/* Timer::_odswiez_timeTimer
	 * zapytanie zwraca czasy dla timerów 
	 */
	_odswiez_timesTimer: function() 
	{
	    $.ajax({
		url: $.timer.url,
		type: 'post',
		data: 'id='+$.timer.ids,
		success:
			function (callback)
			{
				if ($.timer.reload==1)
				{
					typ_akcji = 'init';
					$.timer.reload = 0;
					
					//pokaż przyciski
					id = $.timer.ids.split(',');
					for (var i = 0; i < id.length; i++) 
					{
						$('#button_add_bit_'+id[i]).show();
					}
				}
				else
					typ_akcji = 'change';
				$.timer._inicjuj_timesTimer(callback, typ_akcji);
			}
		});
	},
	
	/* Timer::_odswiez_timeTimer
	 * zapytanie zwraca czas dla timera
	 */
	_odswiez_timeTimer: function() 
	{
	    $.ajax({
		url: $.timer.url,
		type: 'post',
		data: 'id='+$.timer.ids,
		success:
			function (callback)
			{
				if ($.timer.reload==1)
				{
					typ_akcji = 'init';
					$.timer.reload = 0;
					$('#button_add_bit_'+$.timer.ids).show();
				}
				else
					typ_akcji = 'change';
				$.timer._inicjuj_timeTimer(callback, typ_akcji);
			}
		});
	},
	
	/* Timer::_inicjuj_timesTimer
	 * w zależności od danych parsowanie ponowne timerów
	 */
	_inicjuj_timesTimer: function(callback, typ_akcji) 
	{
		//wyłącz interval, gdy już nic nie jest odbierane
		if(callback=='')
		{
			this._stopTimers();
		}
		
		//id;time|id;time
		tabs = callback.split('|');
		hold = 0;

		//parsowanie każdego licznika
		for (var i = 0; i < tabs.length; i++) 
		{
			//id;time;price;login
			tab = tabs[i].split(';');
			
			if (tab[1] == 'finish')
			{
				this._stopTimer(tab[0], this.langFinish);
			}
			else if (tab[1] == 'hold')
			{
				this._stopTimer(tab[0], this.langHold);
				hold = 1;
				$('#button_add_bit_'+tab[0]).hide();
			}
			//jeśli kolejny czas jest większy niż poprzedni 10..9..8..15 to odświeżamy
			else if (this.last_time[tab[0]] < tab[1] || typ_akcji == 'init')
			{
				//20:00:00
				dane = tab[1].split(':');
				this._parsuj_timeTimer(tab[0], dane[0], dane[1], dane[2], typ_akcji);
			}
			else if (tab[1] <= this.colorTime) // dodaj podświetlenie
			{
				$('#Countdown_'+tab[0]).addClass('hasCountdownColor');
			}
			else if (tab[1] > this.colorTime) // usuń podświetlenie
			{
				$('#Countdown_'+tab[0]).removeClass('hasCountdownColor');
			}
			
			//zapisz czas
			this.last_time[tab[0]] = tab[1];
			
			//sprawdź hold i zapisz
			if (this.hold_time==1 && hold == 0)
			{
				this.reload = 1;
			}
			this.hold_time = hold;
			
			//odśwież login, price
			this._parsuj_priceLoginTimer(tab[0], tab[2], tab[3]);
		}
	},
	
	/* Timer::_inicjuj_timeTimer
	 * w zależności od danych parsowanie ponowne timerów
	 */
	_inicjuj_timeTimer: function(callback, typ_akcji) 
	{		
		hold = 0;

		//id;time;price;login
		tab = callback.split(';');
		
		if (tab[1] == 'finish')
		{
			$('#button_add_bit_'+tab[0]).hide();
			this._stopTimer(tab[0], this.langFinish);
			this._stopTimers();
		}
		else if (tab[1] == 'hold')
		{
			this._stopTimer(tab[0], this.langHoldAuction);
			hold = 1;
			$('#button_add_bit_'+tab[0]).hide();
		}
		//jeśli kolejny czas jest większy niż poprzedni 10..9..8..15 to odświeżamy
		else if (this.last_time[tab[0]] < tab[1] || typ_akcji == 'init')
		{
			//20:00:00
			dane = tab[1].split(':');
			this._parsuj_timeTimer(tab[0], dane[0], dane[1], dane[2], typ_akcji);
		}
		else if (tab[1] <= this.colorTime) // dodaj podświetlenie
		{
			$('#Countdown_'+tab[0]).addClass('hasCountdownColor');
		}
		else if (tab[1] > this.colorTime) // usuń podświetlenie
		{
			$('#Countdown_'+tab[0]).removeClass('hasCountdownColor');
		}
		
		//zapisz czas
		this.last_time[tab[0]] = tab[1];
		
		//sprawdź hold i zapisz
		if (this.hold_time==1 && hold == 0)
		{
			this.reload = 1;
		}
		this.hold_time = hold;

		//odśwież bits
		if(tab.length > 2)
			this._parsuj_bitsTimer(tab[0], tab[2].split('!!'));
		else{
			html  = '<div class="login">'+this.brakPazurki+'</div>'+
					'<div class="czas">'+this.brakPazurki+'</div>'+
					'<div class="cena">'+this.brakPazurki+'</div>'+
					'<div class="clear"></div>';
			$("#bits").html(html);
			$("#login_"+tab[0]).html(this.brakPazurki);
		}
	},
	
	/* Timer::_parsuj_timeTimer
	 * parsowanie danego timera
	 */
	_parsuj_timeTimer: function(id,hh,mm,ss,typ)
	{
		var time = this._oblicz_timeTimer(hh,mm,ss);

		if (typ == 'change')
		{
			$('#Countdown_'+id).countdown('change', {until: time});
			$('#Countdown_'+id).addClass('hasCountdownColor');
			//czekaj 1 sek
			setTimeout(function(){
				$('#Countdown_'+id).removeClass('hasCountdownColor');
			},1000);
		}
		else
		{
			$('#Countdown_'+id).countdown({until: time, compact: true});
		}	
	},
	
	/* Timer::_parsuj_priceLoginTimer
	 * return wyświetlenie danych o bitach
	 */
	_parsuj_priceLoginTimer: function(id,price,login)
	{
		if(login=='') login='&nbsp;';
		$("#price_bits_"+id).html(this.langWaluta+price);
		$("#login_"+id).html(login);
		
		this._oblicz_procent(id,price);
	},
	
	/* Timer::_oblicz_procent
	 * return procent oszczednosci
	 */
	_oblicz_procent: function(id,price)
	{
		var price_orginal = parseFloat($("#price_orginal_"+id).text());
		
		if(price_orginal>0)
		{
			var procent = ((price_orginal-price)/price_orginal)*100;
			$("#procent_oszczednosci_"+id).html(procent.toFixed(2)+this.langProcent);
		}
		else
			$("#procent_oszczednosci_"+id).html(this.brakPazurki);
	},
	
	/* Timer::_oblicz_timeTimer
	 * return ustalenie nowego czasu timera
	 */
	_oblicz_timeTimer: function(hh,mm,ss)
	{
		if (hh<10) hh = hh.substring(1);
		if (mm<10) mm = mm.substring(1);
		if (ss<10) ss = ss.substring(1);
		var time = new Date();
		time.setHours(time.getHours() + parseInt(hh));
		time.setMinutes(time.getMinutes() + parseInt(mm));
		time.setSeconds(time.getSeconds() + parseInt(ss));
		return time;
	},
	
	/* Timer::_add_bitTimer
	 * return wykonanie update bita
	 */
	_add_bitTimer: function(name, id)
	{	
		$.ajax({
		url: $.timer.url_add_bit,
		type: 'post',
		data: 'id='+id,
		success:
			function (callback)
			{
				if(callback == 'zaloguj')
				{
					window.location.href = $.timer.zaloguj;
				}
				else if(callback == 'doladuj')
				{
					window.location.href = $.timer.doladuj;
				}
				else if(callback != '')
				{
					//parsuj dane o bitach usera
					$.timer._parsuj_bitsUser(callback);
				}
			}
		});
	},
	
	/* Timer::_parsuj_bitsUser
	 * return wyświetlenie danych o bitach usera
	 */
	_parsuj_bitsUser: function(callback)
	{
		var html='';
		
		//bits;data|bits;data
		tabs = callback.split('|');

		//parsowanie każdej danej
		for (var i = 0; i < tabs.length; i++) 
		{
			//bits;data
			tab = tabs[i].split(';');
			if(tab[1] == '' ) tab[1] = this.langBezLimitu;
			html += '<div class="count">'+this.langIlosc+'<b>'+tab[0]+'</b></div>'+
					'<div style="clear: both"></div>';
		}
		$("#user_bits").html(html);
	},
	
	/* Timer::_parsuj_bitsTimer
	 * return wyświetlenie danych o bitach
	 */
	_parsuj_bitsTimer: function(id,tab)
	{
		var html='';
		for (var i = 0; i < tab.length; i++) 
		{
			dane = tab[i].split('!');
			//wygrywający
			if (i==0)
				$.timer._parsuj_priceLoginTimer(id, dane[2], dane[0]);
			html += '<div class="login">'+dane[0]+'</div>'+
					'<div class="czas">'+dane[1]+'</div>'+
					'<div class="cena">'+this.langWaluta+parseFloat(dane[2]).toFixed(2)+'</div>'+
					'<div class="clear"></div>';
		}
		$("#bits").html(html);
	},

	/* pobranie danej z tablicy dla danej instancji */
	_get: function(inst, name) {
		return (inst.options[name] != null ?
			inst.options[name] : $.timer._defaults[name]);
	}
});

/* Główna funkcja, która wywołana jest dla danej instancji,
 * w zależności od parametru wywołuje się funkcja obiektu
 */
$.fn.timer = function(options) {
	var otherArgs = Array.prototype.slice.call(arguments, 1);

	return this.each(function() 
	{
		if (typeof options == 'string') 
		{
			//name_function|param1|param2|... OR name_function
			tab = options.split('|');
			if(tab.length > 1) 
				$.timer['_' + tab[0] + 'Timer'].apply($.timer, tab);
			else
				$.timer['_' + options + 'Timer'].apply($.timer, [this].concat(otherArgs));
		}
		else {
			$.timer._defaultAkcja(this, options);
		}
	});
};

/* Initialise the countdown functionality. */
$.timer = new Timer(); // singleton instance

})(jQuery);
