// 20/10/08 rafl@dr.dk

var Localization = {
	
	language: document.getElementsByTagName('html')[0].lang || 'en',

	dayOffset: 3 - new Date(0).getDay(), // account for offset in weekday order. new Date(0).getDay() should be 3 (thursday).
	
	ordinalize: function(i, l){
		return Localization[l || Localization.language].ordinalize(i);
	},
	
	name: function(name, length, i, l){
		var a = Localization[l || Localization.language][name][length || "long"];
		if (i<0) i += a.length;
		return a[i % a.length];
	},
	
	en: {
        ordinalize: function(i){
			var n = i;
        	var exception = ([11, 12, 13].indexOf(n%100)>-1);
            var s = ['st', 'nd', 'rd', 'th'];
            n %= 10;
            if (exception || n>s.length || n==0) n = s.length;
            return i + s[n-1];
        },
		millisecond: {
			singular:	"millisecond",
			plural:		"milliseconds"
		},
		second: {
			singular:	"second",
			plural:		"seconds"
		},
		minute: {
			singular:	"minute",
			plural:		"minutes"
		},
		hour: {
			singular:	"hour",
			plural:		"hours"
		},
        day: {
			singular:	"day",
			plural:		"days",
            short:		["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
            long:		["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
        },
        month: {
			singular:	"month",
			plural:		"months",
            short:		["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
            long:		["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
        }
    },
    
	da: {
        ordinalize: function(i){
            return i + '.';
        },
		millisecond: {
			singular:	"millisekund",
			plural:		"millisekunder"
		},
		second: {
			singular:	"sekund",
			plural:		"sekunder"
		},
		minute: {
			singular:	"minut",
			plural:		"minutter"
		},
		hour: {
			singular:	"time",
			plural:		"timer"
		},
        day: {
			singular:	"dag",
			plural:		"dage",
            short:		["Man", "Tir", "Ons", "Tor", "Fre", "Lør", "Søn"],
            long:		["Mandag", "Tirsdag", "Onsdag", "Torsdag", "Fredag", "Lørdag", "Søndag"]
        },
        month: {
			singular:	"måned",
			plural:		"måneder",
            short:		["Jan", "Feb", "Mar", "Apr", "Maj", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dec"],
            long:		["januar", "februar", "marts", "april", "maj", "juni", "juli", "august", "september", "oktober", "november", "december"]
        }
    }

};

Number.implement({
	ordinalize: function(l){
		return Localization.ordinalize(this, l);
	}			  
});

// Calculate relations between units
// XXtoYY means how many YY goes to an XX.

(function(){
	var u = {MS: 1, SS: 1000, MM: 60, HH: 60, DD: 24};
	var n = u.MS;
	$each(u, function (v, k) {
		u[k] = n *= v;
	});
	$each(u, function (uy, y) {
		$each(u, function (ux, x) {
			if (x!=y) {
				Date[y + "to" + x] = uy/ux;
			}
		});
	});
})();

Date.implement({

	dayName: function (length, l) {
		return Localization.name("day", length || "long", this.getDay() + Localization.dayOffset, l);
	},
	
	monthName: function (length, l) {
		return Localization.name("month", length || "long", this.getMonth(), l);
	},
	
	daysInMonth: function (n) {
		var i = (!n) ? new Date(this.valueOf()) : new Date().setMonth(n);
		var m = i.getMonth();
		var k = i.setMonth(m, 1).valueOf();
		var l = i.setMonth(m+1).valueOf();
		return Math.round((l - k)/Date.DDtoMS);
	},

	copy: function(ms){
		return new Date(this.valueOf() + (ms || 0));	
	},
		
	getHoursFloat: function(){
		return this.getHours() + this.getMinutes()/Date.HHtoMM + this.getSeconds()/Date.HHtoSS;
	}

});

(function(){

	var getUnit = function(unit){
		switch(unit){
			case "y":
			case "year":
				return "year";
				break;
			case "m":
			case "month":
				return "month";
				break;
			case "w":
			case "week":
				return "week";
				break;
			case "d":
			case "day":
			case "date":
				return "date";
				break;
			case "h":
			case "hour":
				return "hour";
				break;
			case "i":
			case "min":
			case "minute":
				return "minute";
				break;
			case "s":
			case "sec":
			case "second":
				return "second";
				break;
			case "ms":
			case "msec":
			case "millisec":
			case "millisecond":
				return "millisecond";
				break;
		}
		return false;
	};
	
	var translate = function(unit, mod){
		mod = mod || 1;
		unit = getUnit(unit);
			
		switch(unit){
			case "year":
				var date = this.copy();
				date.setFullYear(date.getFullYear()+mod);
				return date;
				break;
			case "month":
				var date = this.copy();
				date.setMonth(date.getMonth()+mod);
				return date;
				break;
			case "week":
				ms = 7*Date.DDtoMS;
				break;
			case "date":
				ms = Date.DDtoMS;
				break;
			case "hour":
				ms = Date.HHtoMS;
				break;
			case "minute":
				ms = Date.MMtoMS;
				break;
			case "second":
				ms = Date.SStoMS;
				break;
			case "millisecond":
				ms = 1;
				break;
		}
		return this.copy(ms*mod);
	};

	Date.implement({
			
		next: function(unit){
			return translate.apply(this, [unit]);
		},
		
		prev: function(unit){
			return translate.apply(this, [unit, -1]);
		},
	
		round: function(unit){
			var date = this.copy();
			unit = getUnit(unit);
			
			switch(unit){
				case "year":
					date.setFullYear(date.getFullYear(), 0, 1);
					date.setHours(0, 0, 0, 0);
					break;
				case "month":
					date.setMonth(date.getMonth(), 1);
					date.setHours(0, 0, 0, 0);
					break;
				case "week":
					//
					break;
				case "date":
					date.setDate(date.getDate());
					date.setHours(0, 0, 0, 0);
					break;
				case "hour":
					date.setHours(date.getHours(), 0, 0, 0);
					break;
				case "minute":
					date.setMinutes(date.getMinutes(), 0, 0);
					break;
				case "second":
					date.setSeconds(date.getSeconds(), 0);
					break;
				case "millisecond":
					date.setMilliseconds(date.setMilliseconds());
					break;
			}
			return date;
		}
	});

})();
	

(function() {

    var func = $H({

        // Day of the month without leading zeros	1 to 31
        j: function(d) {
            return d.getDate();
        },

        // Day of the month, 2 digits with leading zeros	01 to 31
        d: function(d) {
            return d.getDate().pad(2);
        },

        // A textual representation of a day, three letters	Mon through Sun
        D: function(d, l) {
            return d.dayName("short", l);
        },

        // (lowercase 'L')	A full textual representation of the day of the week	Sunday through Saturday
        l: function(d, l) {
            return d.dayName("long", l);
        },

        // ISO-8601 numeric representation of the day of the week (added in PHP 5.1.0)	1 (for Monday) through 7 (for Sunday)
        N: function(d) {
            return d.getDay() + 1;
        },

        // ordinal suffix for the day of the month, 2 characters	st, nd, rd or th. Works well with j
        S: function(d, l) {
            var i = d.getDate();
            return (i).ordinalize(l);
        },

        // Numeric representation of the day of the week	0 (for Sunday) through 6 (for Saturday)
        w: function(d) {
            return d.getDay();
        },

        // The day of the year (starting from 0)	0 through 365
        z: function(d) {
            var m = d.getMonth(), i = new Date(d.valueOf()), k = i.setMonth(0, 1).valueOf(), n = d.valueOf();
            return Math.round((n - k) / Date.DDtoMS);
        },

        /* Week: */

        // ISO-8601 week number of year, weeks starting on Monday (added in PHP 4.1.0)	Example: 42 (the 42nd week in the year)
        //W: 

        /* Month: */

        // A full textual representation of a month, such as January or March	January through December
        F: function(d) {
            return d.monthName("long");
        },

        // Numeric representation of a month, with leading zeros	01 through 12
        m: function(d) {
            return (d.getMonth() + 1).pad(2);
        },

        // A short textual representation of a month, three letters	Jan through Dec
        M: function(d) {
            return d.monthName("short");
        },

        // Numeric representation of a month, without leading zeros	1 through 12
        n: function(d) {
            return d.getMonth() + 1;
        },

        // Number of days in the given month	28 through 31
        t: function(d) {
            return d.daysInMonth();
        },

        /* Year */

        // Whether it's a leap year	1 if it is a leap year, 0 otherwise.
        //L: 

        // ISO-8601 year number. This has the same value as Y, except that if the ISO week number (W) belongs to the previous or next year, that year is used instead. (added in PHP 5.1.0)	Examples: 1999 or 2003
        //o: 

        // A full numeric representation of a year, 4 digits	Examples: 1999 or 2003
        Y: function(d) {
            return d.getFullYear();
        },

        // A two digit representation of a year	Examples: 99 or 03
        y: function(d) {
            return (d.getFullYear() + "").substring(2);
        },

        /* Time */

        // Lowercase Ante meridiem and Post meridiem	am or pm
        a: function(d) {
            return (d.getHours() < 12) ? "am" : "pm";
        },

        // Uppercase Ante meridiem and Post meridiem	AM or PM
        A: function(d) {
            return (d.getHours() < 12) ? "AM" : "PM";
        },

        // Swatch Internet time	000 through 999
        //B: 

        // 12-hour format of an hour without leading zeros	1 through 12
        g: function(d) {
            return (d.getHours() % 12) + 1;
        },

        // 24-hour format of an hour without leading zeros	0 through 23
        G: function(d) {
            return d.getHours();
        },

        // 12-hour format of an hour with leading zeros	01 through 12
        h: function(d) {
            return ((d.getHours() % 12) + 1).pad(2);
        },

        // 24-hour format of an hour with leading zeros	00 through 23
        H: function(d) {
            return d.getHours().pad(2);
        },

        // Minutes with leading zeros	00 to 59
        i: function(d) {
            return d.getMinutes().pad(2);
        },

        // Seconds, with leading zeros	00 through 59
        s: function(d) {
            return d.getSeconds().pad(2);
        },

        /* Timezone */

        //Timezone identifier (added in PHP 5.1.0)	Examples: UTC, GMT, Atlantic/Azores
        //e: 

        // (capital i)	Whether or not the date is in daylights savings time	1 if Daylight Savings Time, 0 otherwise.
        //I: 

        // Difference to Greenwich time (GMT) in hours	Example: +0200
        O: function(d) {
            var i = d.getTimezoneOffset();
            var p = (i < 0) ? "-" : "+";
            if (p == "-") i *= -1;
            var m = i % 60;
            var h = (i - m) / 60;
            return p + h.pad(2) + "" + m.pad(2);
        },

        // Difference to Greenwich time (GMT) with colon between hours and minutes (added in PHP 5.1.3)	Example: +02:00
        P: function(d) {
            var i = d.getTimezoneOffset();
            var p = (i < 0) ? "-" : "+";
            if (p == "-") i *= -1;
            var m = i % 60;
            var h = (i - m) / 60;
            return p + h.pad(2) + ":" + m.pad(2);
        },

        // Timezone setting of this machine	Examples: EST, MDT ...
        //T: 

        // Timezone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive.	-43200 through 43200
        //Z: 

        /* Full Date/Time */

        // ISO 8601 date (added in PHP 5)	2004-02-12T15:19:21+00:00
        c: function(d) {
            return d.format("Y-m-d") + "T" + d.format("H:i:sP");
        },

        // RFC 2822 formatted date	Example: Thu, 21 Dec 2000 16:01:07 +0200
        r: function(d) {
            return d.format("D, j M Y H:i:s O");
        },

        // Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)	See also time()
        U: function(d) {
            return d.valueOf();
        }

    });

    var keyReg = new RegExp("[" + func.getKeys().join("") + "]", "g");

    Date.implement({

        formatTvOversigt: function(f, l) {
            var d = this;

            return f.replace(keyReg, function(char) {
                return func[char](d, l || Localization.language);
            });
        }

    });

})();


$D = function(date){
	return date.copy();
};

String.prototype.pad = function (l, s) { var t = this; while (t.length<l) t = (s || "0") + t; return t; };
Number.prototype.pad = function (l) { return new String(this).pad(l); };

