/**
 * Version: 1.0 Alpha-1 
 * Build Date: 13-Nov-2007
 * Copyright (c) 2006-2007, Coolite Inc. (http://www.coolite.com/). All rights reserved.
 * License: Licensed under The MIT License. See license.txt and http://www.datejs.com/license/. 
 * Website: http://www.datejs.com/ or http://www.coolite.com/datejs/
 */
Date.CultureInfo={name:"hr-HR",englishName:"Croatian (Croatia)",nativeName:"hrvatski (Hrvatska)",dayNames:["nedjelja","ponedjeljak","utorak","srijeda","četvrtak","petak","subota"],abbreviatedDayNames:["ned","pon","uto","sri","čet","pet","sub"],shortestDayNames:["ne","po","ut","sr","če","pe","su"],firstLetterDayNames:["n","p","u","s","č","p","s"],monthNames:["siječanj","veljača","ožujak","travanj","svibanj","lipanj","srpanj","kolovoz","rujan","listopad","studeni","prosinac"],abbreviatedMonthNames:["sij","vlj","ožu","tra","svi","lip","srp","kol","ruj","lis","stu","pro"],amDesignator:"",pmDesignator:"",firstDayOfWeek:1,twoDigitYearMax:2029,dateElementOrder:"dmy",formatPatterns:{shortDate:"d.M.yyyy",longDate:"d. MMMM yyyy",shortTime:"H:mm",longTime:"H:mm:ss",fullDateTime:"d. MMMM yyyy H:mm:ss",sortableDateTime:"yyyy-MM-ddTHH:mm:ss",universalSortableDateTime:"yyyy-MM-dd HH:mm:ssZ",rfc1123:"ddd, dd MMM yyyy HH:mm:ss GMT",monthDay:"d. MMMM",yearMonth:"MMMM, yyyy"},regexPatterns:{jan:/^sij(ečanj)?/i,feb:/^veljača/i,mar:/^ožu(jak)?/i,apr:/^tra(vanj)?/i,may:/^svi(banj)?/i,jun:/^lip(anj)?/i,jul:/^srp(anj)?/i,aug:/^kol(ovoz)?/i,sep:/^ruj(an)?/i,oct:/^lis(topad)?/i,nov:/^stu(deni)?/i,dec:/^pro(sinac)?/i,sun:/^ne(d(jelja)?)?/i,mon:/^po(n(edjeljak)?)?/i,tue:/^ut(o(rak)?)?/i,wed:/^sr(i(jeda)?)?/i,thu:/^če(t(vrtak)?)?/i,fri:/^pe(t(ak)?)?/i,sat:/^su(b(ota)?)?/i,future:/^next/i,past:/^last|past|prev(ious)?/i,add:/^(\+|after|from)/i,subtract:/^(\-|before|ago)/i,yesterday:/^yesterday/i,today:/^t(oday)?/i,tomorrow:/^tomorrow/i,now:/^n(ow)?/i,millisecond:/^ms|milli(second)?s?/i,second:/^sec(ond)?s?/i,minute:/^min(ute)?s?/i,hour:/^h(ou)?rs?/i,week:/^w(ee)?k/i,month:/^m(o(nth)?s?)?/i,day:/^d(ays?)?/i,year:/^y((ea)?rs?)?/i,shortMeridian:/^(a|p)/i,longMeridian:/^(a\.?m?\.?|p\.?m?\.?)/i,timezone:/^((e(s|d)t|c(s|d)t|m(s|d)t|p(s|d)t)|((gmt)?\s*(\+|\-)\s*\d\d\d\d?)|gmt)/i,ordinalSuffix:/^\s*(st|nd|rd|th)/i,timeContext:/^\s*(\:|a|p)/i},abbreviatedTimeZoneStandard:{GMT:"-000",EST:"-0400",CST:"-0500",MST:"-0600",PST:"-0700"},abbreviatedTimeZoneDST:{GMT:"-000",EDT:"-0500",CDT:"-0600",MDT:"-0700",PDT:"-0800"}};
Date.getMonthNumberFromName=function(name){var n=Date.CultureInfo.monthNames,m=Date.CultureInfo.abbreviatedMonthNames,s=name.toLowerCase();
for(var i=0;
i<n.length;
i++){if(n[i].toLowerCase()==s||m[i].toLowerCase()==s){return i;
}}
return-1;
};
Date.getDayNumberFromName=function(name){var n=Date.CultureInfo.dayNames,m=Date.CultureInfo.abbreviatedDayNames,o=Date.CultureInfo.shortestDayNames,s=name.toLowerCase();
for(var i=0;
i<n.length;
i++){if(n[i].toLowerCase()==s||m[i].toLowerCase()==s){return i;
}}
return-1;
};
Date.isLeapYear=function(year){return(((year%4===0)&&(year%100!==0))||(year%400===0));
};
Date.getDaysInMonth=function(year,month){return[31,(Date.isLeapYear(year)?29:28),31,30,31,30,31,31,30,31,30,31][month];
};
Date.getTimezoneOffset=function(s,dst){return(dst||false)?Date.CultureInfo.abbreviatedTimeZoneDST[s.toUpperCase()]:Date.CultureInfo.abbreviatedTimeZoneStandard[s.toUpperCase()];
};
Date.getTimezoneAbbreviation=function(offset,dst){var n=(dst||false)?Date.CultureInfo.abbreviatedTimeZoneDST:Date.CultureInfo.abbreviatedTimeZoneStandard,p;
for(p in n){if(n[p]===offset){return p;
}}
return null;
};

Date.locale_information={
name:"hr-HR"
,englishName:"Croatian (Croatia)"
,nativeName:"hrvatski (Hrvatska)"
,dayNames:["ponedjeljak","utorak","srijeda","četvrtak","petak","subota","nedjelja"]
,abbreviatedDayNames:["pon","uto","sri","čet","pet","sub","ned"]
,shortestDayNames:["po","ut","sr","če","pe","su","ne"]
,firstLetterDayNames:["p","u","s","č","p","s","n"]
,monthNames:["siječanj","veljača","ožujak","travanj","svibanj","lipanj","srpanj","kolovoz","rujan","listopad","studeni","prosinac"]
,abbreviatedMonthNames:["sij","vlj","ožu","tra","svi","lip","srp","kol","ruj","lis","stu","pro"]
,amDesignator:""
,ordinals:['1.', '2.', '3.', '4.', '5.']
,first:['prvog']
,last:['zadnji']
,pmDesignator:""
,firstDayOfWeek:1
,repeatNames:{
yearly:'godišnji'
,doesNotRepeat:'ne ponavlja se'
,monthly:'mjesečni'
,daily:'dnevni'
,weekly:'sedmični'
,everyYear:'svake godine'
,everyMonth:'svaki mjesec'
,everyDay:'svaki dan'
,everyWeek:'svaki tjedan'
,everynYears:'svake %n godine'
,everynMonths:'svaka %n mjeseca'
,everynDays:'svaka %n dana'
,everynWeeks:'svaka %n tjedna'
,everyFirstDay:'svaki prvi dan'
,everyLastDay:'svaki dan posljednji'
,allDays:'svakog dana'
,onTheFirstDay:'na prvi dan'
,onTheLastDay:'na zadnji dan'
,untilDate:'do %n'
,onDays:'na %n'
,onDay:'na %n. dana'
,onDOW:'na %n'
,pluralYear:'godine'
,pluralMonth:'mjeseca'
,pluralDay:'dana'
,pluralWeek:'tjedna'
}
,twoDigitYearMax:2029
,dateElementOrder:"dmy"
,formatPatterns:{
	shortDate:"%d.%m.%Y"
	,longDate:"%d. %B %Y"
	,shortTime:"%H:%m"
	,longTime:"%H:%m:%s"
	,fullDateTime:"%d. %B %Y %H:%m:%s"
	,sortableDateTime:"%Y-%m-%dT%H:%m:%s"
	,universalSortableDateTime:"%Y-%m-%d %H:%m:%sZ"
	,rfc1123:"%a, %d %b %Y %H:%m:%s GMT"
	,monthDay:"%d. %B"
	,yearMonth:"%B, %Y"	
}
,regexPatterns:{
jan:/^sij(ečanj)?/i
,feb:/^veljača/i
,mar:/^ožu(jak)?/i
,apr:/^tra(vanj)?/i
,may:/^svi(banj)?/i
,jun:/^lip(anj)?/i
,jul:/^srp(anj)?/i
,aug:/^kol(ovoz)?/i
,sep:/^ruj(an)?/i
,oct:/^lis(topad)?/i
,nov:/^stu(deni)?/i
,dec:/^pro(sinac)?/i
,sun:/^ne(d(jelja)?)?/i
,mon:/^po(n(edjeljak)?)?/i
,tue:/^ut(o(rak)?)?/i
,wed:/^sr(i(jeda)?)?/i
,thu:/^če(t(vrtak)?)?/i
,fri:/^pe(t(ak)?)?/i
,sat:/^su(b(ota)?)?/i
,future:/^next/i
,past:/^last|past|prev(ious)?/i
,add:/^(\+|after|from)/i
,subtract:/^(\-|before|ago)/i
,yesterday:/^yesterday/i
,today:/^t(oday)?/i
,tomorrow:/^tomorrow/i
,now:/^n(ow)?/i
,millisecond:/^ms|milli(second)?s?/i
,second:/^sec(ond)?s?/i
,minute:/^min(ute)?s?/i
,hour:/^h(ou)?rs?/i
,week:/^w(ee)?k/i
,month:/^m(o(nth)?s?)?/i
,day:/^d(ays?)?/i
,year:/^y((ea)?rs?)?/i
,shortMeridian:/^(a|p)/i
,longMeridian:/^(a\.?m?\.?|p\.?m?\.?)/i
,timezone:/^((e(s|d)t|c(s|d)t|m(s|d)t|p(s|d)t)|((gmt)?\s*(\+|\-)\s*\d\d\d\d?)|gmt)/i
,ordinalSuffix:/^\s*(st|nd|rd|th)/i
,timeContext:/^\s*(\:|a|p)/i
}
,abbreviatedTimeZoneStandard:{GMT:"-000",EST:"-0400",CST:"-0500",MST:"-0600",PST:"-0700"}
,abbreviatedTimeZoneDST:{GMT:"-000",EDT:"-0500",CDT:"-0600",MDT:"-0700",PDT:"-0800"}};

Date.locale = Date.locale_information;
/* 

%a 	Locale’s abbreviated weekday name. 	 
%A 	Locale’s full weekday name. 	 
%b 	Locale’s abbreviated month name. 	 
%B 	Locale’s full month name.
%d 	Day of the month as a decimal number [01,31].
%f 	Microsecond as a decimal number [0,999999], zero-padded on the left
%H 	Hour (24-hour clock) as a decimal number [00,23].
%I 	Hour (12-hour clock) as a decimal number [01,12].
%j 	Day of the year as a decimal number [001,366].
%m 	Month as a decimal number [01,12]. 	 
%M 	Minute as a decimal number [00,59]. 	 
%p 	Locale’s equivalent of either AM or PM.
%S 	Second as a decimal number [00,61]. 	(3)
%U 	Week number of the year (Sunday as the first day of the week) as a decimal number [00,53]. 
All days in a new year preceding the first Sunday are considered to be in week 0. 	(4)
%w 	Weekday as a decimal number [0(Sunday),6]. 	 
%W 	Week number of the year (Monday as the first day of the week) as a decimal number [00,53]. 
All days in a new year preceding the first Monday are considered to be in week 0.
%y 	Year without century as a decimal number [00,99]. 	 
%Y 	Year with century as a decimal number. 	 
%z 	UTC offset in the form +HHMM or -HHMM (empty string if the the object is naive). 	(5)
%Z 	Time zone name (empty string if the object is naive). 	 
%% 	A literal '%' character.
*/
Date.prototype.toFormattedString = function (f)
{
    var nd = this.getDayName();
    f = f.replace(/%Y/g, this.getFullYear());
    f = f.replace(/%y/g, String(this.getFullYear()).substr(2,2));
    
    f = f.replace(/%b/g, this.getMonthNameAbbr());
    f = f.replace(/%B/g, this.getMonthName());
    
    f = f.replace(/%m/g, String(this.getMonth()+1).padLeft('0',2));
    
    f = f.replace(/%a/g, this.getAbbrDayName());
    f = f.replace(/%A/g,this.getDayName());
    f = f.replace(/%d/g, String(this.getDate()).padLeft('0',2));
    return f;
};

Date.prototype.getMonthNameAbbr = function (){
	return Date.locale_information.abbreviatedMonthNames[this.getMonth()];
};

Date.prototype.getMonthName = function (){
	return Date.locale_information.monthNames[this.getMonth()];
};

Date.prototype.getDayName = function (){
	return Date.locale_information.dayNames[this.getDay()];
};
Date.prototype.getAbbrDayName = function (){
	return Date.locale_information.abbreviatedDayNames[this.getDay()];
};

Date.parseToObject = function(string) {
    var date = Date.parse(string);
    if (!date){
    	return null;
    }
    date = new Date(date);
    return (date == 'Invalid Date' || date == 'NaN') ? null : date.neutral();
};

var Template  = function(){};
Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/;
Template.prototype.initialize = function(template, pattern) {
    this.template = template.toString();
    this.pattern  = pattern || Template.Pattern;
};

Template.prototype.evaluate = function(object) {
	return this.template.gsub(this.pattern, function(match) {
		var before = match[1];
		if (before == '\\'){ return match[2];}
		return before + (object[match[3]] || '').toString();
	});
};

String.prototype.gsub = function(pattern, replacement) {
	var result = '', source = this, match;
	replacement = arguments.callee.prepareReplacement(replacement);

	while (source.length > 0) {
		match = source.match(pattern);
		if (match) {
			var rep = replacement(match);
			result += source.slice(0, match.index);
			result += (rep || '').toString();
			source  = source.slice(match.index + match[0].length);
		} else {
			result += source;
			source = '';
		}
	}
	return result;
};

String.prototype.gsub.prepareReplacement = function(replacement) {
	if (typeof replacement == 'function'){
		return replacement;
	}
	
	var template = new Template(replacement);
	return function(match) { return template.evaluate(match); };
};



Date.prototype.getIsoWeekday = function() {
  return (this.getDay() + 6) % 7;
};

String.prototype.padLeft = function (value, size) 
{
    var x = this;
    while (x.length < size) {x = value + x;}
    return x;
};


// modified from http://alternateidea.com/blog/articles/2008/2/8/a-strftime-for-prototype
Date.prototype.strftime =  function(format) {
    var day = this.getIsoWeekday() -1, month = this.getMonth();
    var hours = this.getHours(), minutes = this.getMinutes();
    function pad(num) { return num.toString().padLeft(2); }

    function parse_function(part) {
    	var rval = '';
		switch(part[1]) {
			case 'a': rval = Date.locale.abbreviatedDayNames[day].escapeHTML(); break;
			case 'A': rval = Date.locale.dayNames[day].escapeHTML(); break;
			case 'b': rval = Date.locale.abbreviatedMonthNames[month].escapeHTML(); break;
			case 'B': rval = Date.locale.monthNames[month].escapeHTML(); break;
			case 'c': rval = this.toString(); break;
			case 'd': rval = pad(this.getDate()); break;
			case 'H': rval = pad(hours); break;
			case 'I': rval = (hours % 12 === 0) ? 12 : pad(hours % 12); break;
			case 'm': rval = pad(month + 1); break;
			case 'M': rval = pad(minutes); break;
			case 'p': rval = hours >= 12 ? 'PM' : 'AM'; break;
			case 'S': rval = pad(this.getSeconds()); break;
			case 'w': rval = day; break;
			case 'y': rval = pad(this.getFullYear() % 100); break;
			case 'Y': rval = this.getFullYear().toString(); break;
		}
		return rval;
    }
    
    try {
    	return format.gsub(/\%([aAbBcdHImMpSwyY])/, goog.bind(parse_function, this));
    } catch(e){
    	console.error(e);
    }
};

Date.prototype.neutral = function() {
    return new Date(this.getFullYear(), this.getMonth(), this.getDate(), 12);
};

function days_between(date1, date2) {

    // The number of milliseconds in one day
    var ONE_DAY = 1000 * 60 * 60 * 24;

    // Convert both dates to milliseconds
    var date1_ms = date1.getTime();
    var date2_ms = date2.getTime();

    // Calculate the difference in milliseconds
    var difference_ms = Math.abs(date1_ms - date2_ms);
    
    // Convert back to days and return
    return Math.round(difference_ms/ONE_DAY);

}

function parse_iso_date(s){
    var ymd = s.split('-');
    
    //console.log(parseInt(ymd[0], 10), parseInt(ymd[1], 10)-1, parseInt(ymd[2], 10))
    var d = new Date();
    d.setYear(parseInt(ymd[0], 10));
    d.setMonth(parseInt(ymd[1], 10)-1);
    d.setDate(parseInt(ymd[2], 10));
    
    return reset_time(d);
}


