/**
 * Calculates the User's local time using JS.
 * 
 */
 
jQuery.fn.localTime = function() {
      this.self = this;
      self.selectedFormat = arguments[0];
      self.section = arguments[1];

      self.format = function() {
        if (self.section == 'billing') {
          switch(self.selectedFormat) {
	          case 'en': return '%m/%d/%Y'; break;
	          case 'es': return '%d de %n %Y'; break;
	          case 'fr': return '%d %f %Y'; break;
	          case 'pt': return '%d de %r %Y'; break;
	          case 'de': return '%d. %g %Y'; break;
	          case 'it': return '%d %t %Y'; break;
	          default: return '<nobr>%d %b %Y</nobr>';
          }
        } else if (self.section == 'timeOnly') {
          switch (self.selectedFormat) {
	          case 'en': return '%I:%M'; break;
	          case 'es': return '%I:%M'; break;
	          case 'fr': return '%I h %M'; break;
	          case 'pt': return '%I:%M'; break;
	          case 'de': return '%I.%M'; break;
	          case 'it': return '%I:%M'; break;
	          default: return '<nobr>%I:%M</nobr>';
          }
        } else {       
	        switch(self.selectedFormat) {
	            case 'en': return '%b %d, %Y at %I:%M %p'; break;
		        case 'es': return '%d de %n %Y %H:%M'; break;
		        case 'fr': return 'le %d %f %Y %H h %M'; break;
	            case 'pt': return '%d de %r %Y %H:%M'; break;
	            case 'de': return '%d. %g %Y %H.%M'; break;
	            case 'it': return '%d %t %Y, %H:%M'; break;
	            default: return '<nobr>%d %b %Y</nobr> at <nobr>%H:%M</nobr>';
            }
        }
      };
      
      self.calculateTime = function(gmt) {
        return self.strftime(new Date(parseInt(gmt) * 1000));
      };
      
      self.strftime = function(theDate) {
        var fmt = self.format();
        
        for (var s in self.strftime_funcs)
          if (s.length == 1)
            fmt = fmt.replace('%' + s, self.strftime_funcs[s](theDate));
        
        return fmt;
      };
      
      self.strftime_funcs = {
        zeropad: function(n) { return n>9 ? n : '0'+n; },
        A:       function(t) { return ['Sunday','Monday','Tuedsay','Wednesday','Thursday','Friday','Saturday'][t.getDay()] }, //English Days
        F:       function(t) { return ['Dimanche','Lundi','Mardi','Mercredi','Jeudi','Vendredi','Samedi'][t.getDay()] }, //French Days
        N:       function(t) { return ['Domingo','Lunes','Martes','Mi&eacute;rcoles','Jueves','Viernes','S&aacute;bado'][t.getDay()] }, //Spanish Days
        G:       function(t) { return ['Sonntag','Montag','Dienstag','Mittwoch','Donnerstag','Freitag','Samstag'][t.getDay()] }, //German Days
        R:       function(t) { return ['Domingo','Segunda-feira','Ter&ccedil;a-feira','Quarta-feira','Quinta-feira','Sexta-feira','S&aacute;bado'][t.getDay()] }, //Portuguese Days
        T:       function(t) { return ['domenica','lunedì-feira','martedì','mercoledì','giovedì','venerdì','sabato'][t.getDay()] }, //Italian Days
        
        b:       function(t) { return ['January','February','March','April','May','June', 'July','August', 'September','October','November','December'][t.getMonth()] }, //English Months
        f:       function(t) { return ['janvier','février','mars','avril','mai','juin', 'juillet','août', 'septembre','octobre','novembre','décembre'][t.getMonth()] }, //French Months
        n:       function(t) { return ['enero','febrero','marzo','abril','mayo','junio', 'julio','agosto', 'septiembre','octubre','noviembre','diciembre'][t.getMonth()] }, //Spanish Months
        g:       function(t) { return ['Junuar','Februar','März','April','Mai','Juni', 'Juli','August', 'September','Oktober','November','Dezember'][t.getMonth()] }, //German Months
        r:       function(t) { return ['janeiro','fevereiro','março','abril','maio','junho', 'julho','agosto', 'setembro','outubro','novembro','dezembro'][t.getMonth()] }, //Portuguese Months
        t:       function(t) { return ['gennaio','febbraio','marzo','aprile','maggio','giugno', 'luglio','agosto', 'settembre','ottobre','novembre','dicembre'][t.getMonth()] }, //Italian Months
        
        c:       function(t) { return t.toString(); },
        d:       function(t) { return this.zeropad(t.getDate()); },
        H:       function(t) { return this.zeropad(t.getHours()); },
        I:       function(t) { if(t.getHours() == 12){return t.getHours();}return this.zeropad((t.getHours() + 12) % 12); },
        m:       function(t) { return this.zeropad(t.getMonth()+1); }, // month-1
        M:       function(t) { return this.zeropad(t.getMinutes()); },
        p:       function(t) { return this.H(t) < 12 ? 'AM' : 'PM'; },
        S:       function(t) { return this.zeropad(t.getSeconds()); },
        w:       function(t) { return t.getDay(); }, // 0..6 == sun..sat
        y:       function(t) { return this.zeropad(this.Y(t) % 100); },
        Y:       function(t) { return t.getFullYear(); },
        Z:       function(t) { 
                    if (t.getTimezoneOffset() > 0) {
                        return "-" + this.zeropad(t.getTimezoneOffset()/60) + "00";
                    } else {
                        return "+" + this.zeropad(Math.abs(t.getTimezoneOffset())/60) + "00";
                    }
                },    
        '%':     function(t) { return '%'; }
      };
      
      return this.each(function() {
        jQuery(this).html(self.calculateTime(jQuery(this).attr('gmt_time')));
      });
};

jQuery.fn.localAge = function() {
    this.self = this;

	self.getDaysInMonth = function (month, year) {
		  return 32 - new Date(year, month - 1, 32).getDate();
	};
	
	self.fixDate = function (day, month, year) {
		  var daysInMonth;
		  
		if (day <= 0) {    		
		  	month--;
		  	
		  	if (month <= 0) {
		  		month = 12 + month; // max month + possibly negative month
		  		year--;
		  	}
		  	
		  	day = self.getDaysInMonth(month, year) + day; // days in month + possibly negative day
		} else if (month <= 0) {
			month = 12 + month; // max month + possibly negative month
			year--;
			
			daysInMonth = self.getDaysInMonth(month, year);
			
			if (day > daysInMonth)
				day = daysInMonth - (day - daysInMonth - 1);
		}
		  
		  return { day: day, month: month, year: year };
	};
	
	self.calculateAge = function (gmt) {
		  return self.strfage(1000 * parseInt(gmt));
	};
	
	self.strfage = function (timestamp) {
		  var today, day, month, year, threshold, newDate, dayOfWeek, startingYear, startingMonth;
		
		today = new Date();
		day = today.getDate();
		month = today.getMonth() + 1;
		year = today.getFullYear();
		
		threshold = new Date(year, month - 1, day).getTime();
		
		if (timestamp >= threshold)
			return mhDictionary.profile.today;
			
		day--;
		
		newDate = self.fixDate(day, month, year);
		day = newDate.day;
		month = newDate.month;
		year = newDate.year;
		threshold = new Date(year, month - 1, day).getTime();
			
		if (timestamp >= threshold)
			return mhDictionary.profile.yesterday;
			
		dayOfWeek = today.getDay();
		if (dayOfWeek > 0) {
			day -= dayOfWeek;
			
			newDate = self.fixDate(day, month, year);
			day = newDate.day;
			month = newDate.month;
			year = newDate.year;
			threshold = new Date(year, month - 1, day).getTime();
	  		
		  	if (timestamp >= threshold)
		  		return mhDictionary.profile.thisWeek;
		}
		
		day -= 7;
		
		newDate = self.fixDate(day, month, year);
		day = newDate.day;
		month = newDate.month;
		year = newDate.year;
		threshold = new Date(year, month - 1, day).getTime();
			
		if (timestamp >= threshold)
			return mhDictionary.profile.lastWeek;
			
		if (month == (today.getMonth() + 1) && day > 1) { // last week isn't last month
		  	day = 1;
		  	
		  	threshold = new Date(year, month - 1, day).getTime();
		  		
		  	if (timestamp >= threshold)
		  		return mhDictionary.profile.thisMonth;
		}
		
		month--;
		
		newDate = self.fixDate(day, month, year);
		day = newDate.day;
		month = newDate.month;
		year = newDate.year;
		threshold = new Date(year, month - 1, day).getTime();
			
		if (timestamp >= threshold)
			return mhDictionary.profile.lastMonth;
			
		startingMonth = month;
			
		for (month--; month > 0; month--) {
			newDate = self.fixDate(day, month, year);
			day = newDate.day;
			month = newDate.month;
			year = newDate.year;
			threshold = new Date(year, month - 1, day).getTime();
			
		  	if (timestamp >= threshold)
		  		return mhDictionary.profile.monthsAgo.replace('%MONTHS%', startingMonth - month + 2);
		}
		
		year--;
		
		newDate = self.fixDate(day, month, year);
		day = newDate.day;
		month = newDate.month;
		year = newDate.year;
		threshold = new Date(year, month - 1, day).getTime();
		
		if (timestamp >= threshold)
			return mhDictionary.profile.lastYear;
			
		startingYear = year;
		
		do {
			year--;
			
			newDate = self.fixDate(day, month, year);
			day = newDate.day;
			month = newDate.month;
			year = newDate.year;
			threshold = new Date(year, month - 1, day);
		} while (timestamp < threshold); // let's hope it's not too long ago
			
		return mhDictionary.profile.yearsAgo.replace('%YEARS%', startingYear - year + 1);
	};
    
    return this.each(function() {
      jQuery(this).html(self.calculateAge(jQuery(this).attr('gmt_time')));
    });
};