var DateHelper = {
  lzero : function(num) {
	if (num <= 9)
		return "0"+num;
	else
		return num;
  },

  timeAgoInWords: function(from, opt) {
	if (globalTime == undefined)
		globalTime = Math.floor(new Date().getTime() / 1000);
	
	if (opt != undefined) {
		if (opt.end != undefined) {
			if(Math.abs(globalTime - from) > opt.end) {
				Stamp = new Date(from * 1000);
				return "dnia "+this.lzero(Stamp.getDate()) + "." + this.lzero(Stamp.getMonth() + 1) + "." + Stamp.getFullYear() + " " + 
				this.lzero(Stamp.getHours()) + ":" + this.lzero(Stamp.getMinutes());
			}
		}
	}
	
   return this.distanceOfTimeInWords(globalTime, from, opt);
  },

  distanceOfTimeInWords: function(to, from, opt) {
	defaultOpt = {future:"za ", past:" temu"};
	
	if (opt != undefined) {
		if (opt.future != undefined)
			defaultOpt.future = opt.future;
		
		if (opt.past != undefined)
			defaultOpt.future = opt.past;
	}
	
    seconds_ago = to  - from; 
    isPast = seconds_ago > 0;

    seconds_ago = Math.abs(seconds_ago);
    minutes_ago = Math.floor(seconds_ago / 60);
	hours_ago = Math.floor(seconds_ago / 3600);
	days_ago = Math.floor(seconds_ago / 86400);
	weeks_ago = Math.floor(days_ago / 7);
	months_ago = Math.floor(days_ago / 30);
    years_ago = Math.floor(months_ago / 12);

	if (years_ago > 0)
		tm = years_ago + " " + numberToWord(years_ago, 'rok', 'lata', 'lat');
	else if (months_ago > 0)
		tm = months_ago + " " + numberToWord(months_ago, 'miesiąc', 'miesiące', 'miesięcy');
	else if (weeks_ago > 0)
		tm = weeks_ago + " " + numberToWord(weeks_ago, 'tydzień', 'tygodnie', 'tygodni');
	else if (days_ago > 0)
		tm = days_ago + " " + numberToWord(days_ago, 'dzień', 'dni', 'dni');
	else if (hours_ago > 0)
		tm = hours_ago + " " + numberToWord(hours_ago, 'godzinę', 'godziny', 'godzin');
	else if (minutes_ago > 0)
		tm = minutes_ago + " " + numberToWord(minutes_ago, 'minutę', 'minuty', 'minut');
	else 
		tm = seconds_ago + " " + numberToWord(seconds_ago, 'sekundę', 'sekundy', 'sekund');
	
	if (!isPast)
		return defaultOpt.future + tm;
	else 
		return tm + defaultOpt.past;
  }
}


function numberToWord(number, word1, wordTo4, wordFrom5) {
	if (number == 1)
		return word1;
		
	sub = (""+number).substr(-2, 2);
	
	if (sub >= 11 && sub <= 14 || sub == 0)
		return wordFrom5;
		
	sub = (""+number).substr(-1, 1);
		
	if (sub < 5 && sub > 1)
		return wordTo4;
	
	return wordFrom5;
}

function eachTimeAgo() {
	jQuery.each($(".timeAgoInWords"), function() {
		t = $(this).attr("title").split(";");
		for(i = 1, j = t.length; i < j; i++) {
			if (t[i] == "nil")
				t[i] = undefined;
		}
		opts = {future:t[1], past:t[2], end:t[3]};
		timeAgo = DateHelper.timeAgoInWords(t[0], opts);
		$(this).html(timeAgo);
	    });
}

$(document).ready(function() {
	eachTimeAgo();
	});
