// NOTE: Avoid using any requires up here as
// this file may be included on the client.
function DateTime (dateOrString, time) {

    this._date
    this.offset
    
    // generate a new datetime of now
    if (!dateOrString) {
        this._date = new Date()
        // we shouldnt have to do this, if you need this to be 0 you should handle it then
        this._date.setUTCMilliseconds(0)
        this._date.setUTCSeconds(0)
    }
    
    // if you're a DateTime object or an old timemodule object
    else if (dateOrString instanceof DateTime) {
        return dateOrString
    }
    
    // if you're a string with time
    else if (time) {
        this._date = DateTime.dateFromString(dateOrString, time)
    }
    
    // if you're a dateTime string
    else if (typeof dateOrString === 'string') {
        this._date = DateTime.dateFromString(dateOrString)
    }
    
    // if you're a native date
    else if (dateOrString instanceof Date) {
        this._date = dateOrString
    }
    
    // Assume it is a number Pass it straight to date
    else {
        this._date = new Date(dateOrString)
    }
}

DateTime.Second = 1000
DateTime.Minute = 60 * DateTime.Second
DateTime.HalfHour = 30 * DateTime.Minute
DateTime.Hour = 2 * DateTime.HalfHour
DateTime.Day = 24 * DateTime.Hour

DateTime.months = [
    "January",
    "February",
    "March",
    "April",
    "May",
    "June",
    "July",
    "August",
    "September",
    "October",
    "November",
    "December"
]

DateTime.shortMonths = [
    "Jan",
    "Feb",
    "Mar",
    "Apr",
    "May",
    "Jun",
    "Jul",
    "Aug",
    "Sep",
    "Oct",
    "Nov",
    "Dec"
]	

DateTime.daysOfWeek = [
    "Sunday",
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday"
]

DateTime.shortDaysOfWeek = [
    "Sun",
    "Mon",
    "Tue",
    "Wed",
    "Thu",
    "Fri",
    "Sat"
]

DateTime.dateFromString = function (dateString, timeString) {

    // Needs review: I know this version works.
    // Not sure the setUTC stuff does
    
    // regex: http://underground.infovark.com/2008/07/22/iso-date-validation-regex/
    var iso = dateString.match(/^(\d{4})\D?(0[1-9]|1[0-2])\D?([12]\d|0[1-9]|3[01])(\D?([01]\d|2[0-3])\D?([0-5]\d)\D?([0-5]\d)?\D?(\d{3})?)?Z$/)
    if (iso) {
        // "2011-07-12T03:59:46.000Z", "2011", "07", "12", "T03:59:46.000", "03", "59", "46", "000"
        dateString = iso[1] + "-" + iso[2] + "-" + iso[3]
        timeString = iso[5] + ":" + iso[6] + ":" + iso[7]
    }
    
    
    var string = dateString.replace(/\-/g, "/")
    if (timeString) string += " " + timeString
    
    // replace the timezone with the GMT offsets because javascript only parses mainland USA
    var timezones = {
        "AST":"GMT-400",
        "EST":"GMT-500",
        "EDT":"GMT-400",
        "CST":"GMT-600",
        "CDT":"GMT-500",
        "MST":"GMT-700",
        "MDT":"GMT-600",
        "PST":"GMT-800",
        "PDT":"GMT-700",
        "AKST":"GMT-900",
        "AKDT":"GMT-800",
        "HAST":"GMT-1000",
        "HADT":"GMT-900",
        "SST":"GMT-1100",
        "SDT":"GMT-1000",
        "CHST":"GMT+1000"
    }

    // match results:
    // 0 - full string
    // 1 - datetime string without timezone
    // 2 - timezone
    var stringTimezone = string.match(/^([0-9\/ :]+)([A-Za-z]*)/)

    if (timezones.hasOwnProperty(stringTimezone[2]))
        string = stringTimezone[1] + timezones[stringTimezone[2]]
    else
        string += " UTC"
        
    return new Date(string)
}

DateTime.getTimezone = function() {
	var defaultTz = "EST"
	var tzMap = {
		"Mountain Standard Time": "MST",
		"Mountain Daylight Time": "MDT",
		"Eastern Standard Time": "EST",
		"Eastern Daylight Time": "EDT",
		"Central Standard Time": "CST",
		"Central Daylight Time": "CDT",
		"Pacific Standard Time": "PST",
		"Pacific Daylight Time": "PDT"
	}
	var str = new Date().toString()
	
	// mac
	var matches = str.match(new RegExp("[A-Z]?[A-Z][DS]T", "g")) || []
	var timezone = ""
	var tz = ""
	if (matches.length) timezone = matches[matches.length - 1]
	
	// windows
	if (!timezone) {
		matches = new Date().toString().match(/\((.+)\)$/) || []
		if (matches.length)  tz = matches[matches.length - 1]
		timezone = tzMap[tz]
	}
	
	return timezone || defaultTz
}

DateTime.numberToString = function (num) {
    if (!num) return "00"
    return num.toString().length === 1 ? "0" + num : num
}

DateTime.ordinalSuffixes = {
    1: "st",
    2: "nd",
    3: "rd"
}

DateTime.ordinalSuffix = function (num) {
    if (num === undefined) return ""
    var stringNum = num.toString()
    
    // If the tens digit of a number is 1, then write "th" after the number
    if (stringNum.charAt(stringNum.length - 2) === "1") {
        return "th"
    }
    // do the usual thing
    else {
        return DateTime.ordinalSuffixes[stringNum.charAt(stringNum.length - 1)] || "th"
    }
}

DateTime.prototype.nativeDate = function() {
    return this._date
}

DateTime.prototype.daySuffix = function () {
    return DateTime.ordinalSuffix(this.localDate())
}

DateTime.prototype.year = function () {
    return this._date.getUTCFullYear()
}
DateTime.prototype.localYear = function () {
    return this._date.getFullYear()
}

DateTime.prototype.month = function () {
	return this._date.getUTCMonth() + 1
}
DateTime.prototype.localMonth = function () {
	return this._date.getMonth() + 1
}

DateTime.prototype.date = function () {
    return this._date.getUTCDate()
}
DateTime.prototype.localDate = function () {
    return this._date.getDate()
}

DateTime.prototype.day = function () {
    return this._date.getUTCDay() + 1
}
DateTime.prototype.dayOfWeek = function () {
    return this._date.getUTCDay()
}
DateTime.prototype.localDayOfWeek = function () {
    return this._date.getDay()
}

// defaults to twelve hour time
DateTime.prototype.hours = function (military) {
    if (typeof military === "undefined") military = true
    var hrs = this._date.getUTCHours()
    if (!military && hrs > 12) hrs -= 12
    if (!military && hrs === 0) hrs = 12
    return hrs
}
// defaults to twelve hour time
DateTime.prototype.localHours = function (military) {
    var hrs = this._date.getHours()
    if (!military && hrs > 12) hrs -= 12
    if (!military && hrs === 0) hrs = 12
    return hrs
}
DateTime.prototype.setHours = function (hours) {
    this._date.setUTCHours(hours)
    return this
}

DateTime.prototype.minutes = function () {
    return this._date.getUTCMinutes()
}
DateTime.prototype.localMinutes = function () {
    return this._date.getMinutes()
}
DateTime.prototype.setMinutes = function (mins) {
    this._date.setUTCMinutes(mins)
    return this
}

DateTime.prototype.setSeconds = function (seconds) {
    this._date.setUTCSeconds(seconds)
    return this
}

DateTime.prototype.seconds = function () {
    return this._date.getUTCSeconds()
}

DateTime.prototype.ms = function () {
    return this._date.getUTCMilliseconds()
}


DateTime.prototype.addDays = function (days) {
    this._date.setTime(this.value() + (DateTime.Day * days))
    return this
}

DateTime.prototype.subtractDays = function (days) {
    this._date.setTime(this.value() - (DateTime.Day * days))
    return this
}

DateTime.prototype.addMinutes = function (mins) {
    this._date.setTime(this.value() + (DateTime.Minute * mins))
    return this
}

DateTime.prototype.subtractMinutes = function (mins) {
    this._date.setTime(this.value() - (DateTime.Minute * mins))
    return this
}

DateTime.prototype.addSeconds = function (seconds) {
    this._date.setTime(this.value() + (DateTime.Second * seconds))
    return this
}

DateTime.prototype.subtractSeconds = function (seconds) {
    this._date.setTime(this.value() - (DateTime.Second * seconds))
    return this
}

DateTime.prototype.roundDownToHalfHour = function () {
    var min = this.minutes()
    if (min < 30) this.setMinutes(0)
    else this.setMinutes(30)
    return this
}

DateTime.prototype.roundToHalfHour = function () {
    var min = this.minutes()
    if (min < 15) this.setMinutes(0)
    else if (min > 45) this.setMinutes(60)
    else this.setMinutes(30)
    return this
}

DateTime.prototype.beginingOfDay = function () {
    this._date.setHours(0)
    this._date.setMinutes(0)
    this._date.setSeconds(0)
    this._date.setMilliseconds(0)
    return this
}

//gets tomorrow's date
DateTime.prototype.tomorrow = function (){
    var tomorrow_date = new DateTime(this._date)
    tomorrow_date.addDays(1)
    return tomorrow_date.dateString()
}

// WARNING: THIS IS NOT CORRECT - doesn't account for time zones
// pass in a date from the client instead
DateTime.prototype.tomorrowEndOfDay = function (){
    return this.tomorrow() + " 23:59"
}


DateTime.prototype.toString = function () {
    return ((this.dateString()) + " " + (this.timeString()))
}

DateTime.prototype.toStringWithSeconds = function () {
    return ((this.dateString()) + " " + (this.timeStringWithSeconds()))
}

DateTime.prototype.toLocalString = function (amPm) {
    var str = this.localHours().toString() + ":" + DateTime.numberToString(this.localMinutes())
    if (amPm) str += " " + this.localAmPm()
    return str
}

DateTime.prototype.toMaskedObject = function () {
    return this.toString()
}

DateTime.prototype.value = function () {
    return this._date.getTime()
}

DateTime.prototype.epoch = function () {
    return Math.round(this._date.getTime() / 1000)
}

DateTime.prototype.copy = function () {
    return new DateTime(this.value())
}


DateTime.prototype.shortMonth = function () {
    return DateTime.shortMonths[this.month() - 1]
}
DateTime.prototype.localShortMonth = function () {
    return DateTime.shortMonths[this.localMonth() - 1]
}

DateTime.prototype.longMonth = function () {
    return DateTime.months[this.month() - 1]
}
DateTime.prototype.localLongMonth = function () {
    return DateTime.months[this.localMonth() - 1]
}

DateTime.prototype.amPm = function () {
    var hrs = this.hours()
    return hrs >= 12 ? "PM" : "AM"
}
DateTime.prototype.localAmPm = function () {
    var hrs = this.localHours(true)
    return hrs >= 12 ? "PM" : "AM"
}

DateTime.prototype.longDay = function () {
    return DateTime.daysOfWeek[this.dayOfWeek()]
}
DateTime.prototype.localLongDay = function () {
    return DateTime.daysOfWeek[this.localDayOfWeek()]
}

DateTime.prototype.shortDay = function () {
    return DateTime.shortDaysOfWeek[this.dayOfWeek()]
}
DateTime.prototype.localShortDay = function () {
    return DateTime.shortDaysOfWeek[this.localDayOfWeek()]
}


DateTime.prototype.dateString = function () {
    return ((this.year()) + "-" + (DateTime.numberToString(this.month())) + "-" + (DateTime.numberToString(this.date())))
}
DateTime.prototype.localDateString = function () {
    return ((this.year()) + "-" + (DateTime.numberToString(this.localMonth())) + "-" + (DateTime.numberToString(this.localDate())))
}

DateTime.prototype.timeString = function () {
    return DateTime.numberToString(this.hours()) + ":" + DateTime.numberToString(this.minutes())
}
DateTime.prototype.localTimeString = function (amPm) {
    var str = this.localHours().toString() + ":" + DateTime.numberToString(this.localMinutes())
    if (amPm) str += " " + this.localAmPm()
    return str
}
DateTime.prototype.timeString12 = function () {
    return this.hours(false) + ":" + DateTime.numberToString(this.minutes())
}

DateTime.prototype.timeStringWithSeconds = function () {
    return ((this.timeString()) + ":" + (DateTime.numberToString(this.seconds())))
}


// unless these are some kind of standard format they should not be here, use .format() instead
DateTime.prototype.localPrettyDate = function () {
    return this.localLongDay() + ", " + this.localShortMonth() + " " + this.localDate()
}

DateTime.prototype.localPrettyDateTime = function () {
    return this.localPrettyDate() + " " + this.localTimeString() + " " + this.localAmPm()
}


DateTime.prototype.getTimezoneOffset = DateTime.getTimezoneOffset = function () {
    return new Date().getTimezoneOffset()
}

DateTime.prototype.utcDifference = DateTime.utcDifference = function () {
    var offset = new Date().getTimezoneOffset()
    var diff = (offset / 6 * 10).toString()
    if (diff.length === 3) diff = "0" + diff
    if (offset > 0) diff = "-" + diff
    return diff
}


// takes another DateTime and calculates the minute difference between the 2
DateTime.prototype.minuteOffsetFromDateTime = function (offsetDt) {
    return (this.value() / DateTime.Minute) - (offsetDt.value() / DateTime.Minute)
}
DateTime.prototype.secondOffsetFromDateTime = function (offsetDt) {
    return (this.value() / DateTime.Second) - (offsetDt.value() / DateTime.Second)
}

DateTime.prototype.secondOffsetFromDateTime = function (offsetDt) {
    return (this.value() / DateTime.Second) - (offsetDt.value() / DateTime.Second)
}

// gives an array with 1 dt each day for 'days' days not including the given day, defaults to 3
DateTime.prototype.nextDays = function (days) {
    var dts = [],
        currentDt = this.copy()
    days = days || 3
    for (var i = 0; i < days; i++) {
        currentDt.addMinutes(DateTime.Day / DateTime.Minute)
        dts.push(currentDt.copy())
    }
    return dts
}

// gives a dt for every hour in the current dts day (the local day)
DateTime.prototype.hoursInDay = function () {
    var dts = [], currentDt = this.copy().roundToHalfHour().beginingOfDay()
    while (currentDt.localDate() === this.localDate()) {
        dts.push(currentDt.copy())
        currentDt.addMinutes(60)
    }
    return dts
}


// format, same as PHP, things with ---- are unimplemented, dont forget to write tests :)

// format character     Description     Example returned values
// Day  ---     ---
// d    Day of the month, 2 digits with leading zeros   01 to 31
// D    A textual representation of a day, three letters    Mon through Sun
// j    Day of the month without leading zeros  1 to 31
// l    (lowercase 'L')    A full textual representation of the day of the week    Sunday through Saturday
// N    ISO-8601 numeric representation of the day of the week (added in PHP 5.1.0)     1 (for Monday) through 7 (for Sunday)
// S    English ordinal suffix for the day of the month, 2 characters   st, nd, rd or th. Works well with j
// w    Numeric representation of the day of the week   0 (for Sunday) through 6 (for Saturday)
// ---- z    The day of the year (starting from 0)   0 through 365

// Week     ---     ---
// ---- W    ISO-8601 week number of year, weeks starting on Monday (added in PHP 4.1.0)     Example: 42 (the 42nd week in the year)

// Month    ---     ---
// F    A full textual representation of a month, such as January or March  January through December
// m    Numeric representation of a month, with leading zeros   01 through 12
// M    A short textual representation of a month, three letters    Jan through Dec
// ---- n    Numeric representation of a month, without leading zeros    1 through 12
// ---- t    Number of days in the given month   28 through 31

// Year     ---     ---
// ---- L    Whether it's a leap year    1 if it is a leap year, 0 otherwise.
// ---- o    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
// Y    A full numeric representation of a year, 4 digits   Examples: 1999 or 2003
// ---- y    A two digit representation of a year    Examples: 99 or 03

// Time     ---     ---
// a    Lowercase Ante meridiem and Post meridiem   am or pm
// A    Uppercase Ante meridiem and Post meridiem   AM or PM
// ---- B    Swatch Internet time    000 through 999
// g    12-hour format of an hour without leading zeros     1 through 12
// ---- G    24-hour format of an hour without leading zeros     0 through 23
// ---- h    12-hour format of an hour with leading zeros    01 through 12
// H    24-hour format of an hour with leading zeros    00 through 23
// i    Minutes with leading zeros  00 to 59
// s    Seconds, with leading zeros     00 through 59
// ---- u    Microseconds (added in PHP 5.2.2)   Example: 654321

// Timezone     ---     ---
// ---- e    Timezone identifier (added in PHP 5.1.0)    Examples: UTC, GMT, Atlantic/Azores
// ---- I (capital i)    Whether or not the date is in daylight saving time  1 if Daylight Saving Time, 0 otherwise.
// O    Difference to Greenwich time (GMT) in hours     Example: +0200
// ---- P    Difference to Greenwich time (GMT) with colon between hours and minutes (added in PHP 5.1.3)    Example: +02:00
// ---- T    Timezone abbreviation   Examples: EST, MDT ...
// ---- Z    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 50400

// Full Date/Time   ---     ---
// ---- c    ISO 8601 date (added in PHP 5)  2004-02-12T15:19:21+00:00
// ---- r    » RFC 2822 formatted date   Example: Thu, 21 Dec 2000 16:01:07 +0200
// ---- U    Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)  See also time()

DateTime.prototype.format = (function () {
    // define replaces
    var formats = {
        d: function (d, utc) {
            return utc ? DateTime.numberToString(d.date()) : DateTime.numberToString(d.localDate())
        },
        D: function (d, utc) {
            return utc ? d.shortDay() : d.localShortDay()
        },
        j: function (d, utc) {
            return utc ? d.date() : d.localDate()
        },
        l: function (d, utc) {
            return utc ? d.longDay() : d.localLongDay()
        },
        N: function (d, utc) {
            var day = utc ? d.dayOfWeek() : d.localDayOfWeek()
            return day === 0 ? 7 : day // convert sunday 0 to sunday 7
        },
        S: function (d, utc) {
            return d.daySuffix()
        },
        w: function (d, utc) {
            return utc ? d.dayOfWeek() : d.localDayOfWeek()
        },
        F: function (d, utc) {
            return utc ? d.longMonth() : d.localLongMonth()
        },
        m: function (d, utc) {
            return utc ? DateTime.numberToString(d.month()) : DateTime.numberToString(d.localMonth())
        },
        M: function (d, utc) {
            return utc ? d.shortMonth() : d.localShortMonth()
        },
        Y: function (d, utc) {
            return utc ? d.year() : d.localYear()
        },
        a: function (d, utc) {
            return utc ? d.amPm().toLowerCase() : d.localAmPm().toLowerCase()
        },
        A: function (d, utc) {
            return utc ? d.amPm().toUpperCase() : d.localAmPm().toUpperCase()
        },
        g: function (d, utc) {
            return utc ? d.hours() : d.localHours()
        },
        G: function (d, utc) {
            return utc ? DateTime.numberToString(d.hours()) : DateTime.numberToString(d.localHours())
        },
        H: function (d, utc) {
            return utc ? DateTime.numberToString(d.hours(true)) : DateTime.numberToString(d.localHours(true))
        },
        i: function (d, utc) {
            return utc ? DateTime.numberToString(d.minutes()) : DateTime.numberToString(d.localMinutes())
        },
        s: function (d, utc) {
            return DateTime.numberToString(d.seconds())
        },
        O: function (d, utc) {
            return d.utcDifference()
        }
    }
    
    // fmts is an array of letters to be replaced
    var fmts = Object.keys ? Object.keys(formats) : (function () {
        var a = []
        for (var replace in formats) {
            a.push(replace)
        }
        return a
    }())
    
    // compile
    var search = new RegExp(fmts.join("|"), "g")
    
    // this runs every time format is called
    return function (formatString, utc) {
        var d = this
        return formatString.replace(search, function (ltr) {
            return formats[ltr](d, utc)
        })
    }
}())


if (typeof module !== 'undefined') module.exports = DateTime

