﻿Date.prototype.toUSString = function(){
    return this.format('m-d-Y H:i:s');
};

Ext.History.on('change', function(t){
    var cal = DS.calendar.instance;
    if (t){
        if (t.indexOf('day:') == 0){
            cal.showEvents({
                thisDay: true,
                baseDate: new Date(parseInt(t.substring(4)))
            });
        } else if (t.indexOf('week:') == 0){
            cal.showEvents({
                thisWeek: true,
                baseDate: new Date(parseInt(t.substring(5)))
            });
        } else if (t.indexOf('month:') == 0){
            cal.showEvents({
                thisMonth: true,
                baseDate: new Date(parseInt(t.substring(6)))
            });
        }
    } else {
        cal.showEvents({ thisWeek: true, baseDate: cal.origDate });
    }
});

if (typeof DS == 'undefined') DS = {};
DS.calendar = function(config){
    config = config || {};
    Ext.apply(this, config);
    this.origDate = this.baseDate = this.baseDate || new Date();
    this.events = {};
    this.imNew = true;
    this.category = 0;
    DS.calendar.instance = this;
};

Ext.override(DS.calendar, {
    filter: function(f){
        var cat = 0;
        switch (f){
            case 'Games Only':
                cat = 1;
                break;
            case 'Practices Only':
                cat = 2;
                break;
            case 'Scrimmages Only':
                cat = 3;
                break;
            case 'Tournaments Only':
                cat = 14;
                break;
        }
        var o = {};
        switch (this.curView){
            case 'day':
                o.thisDay = true;
                break;
            case 'week':
                o.thisWeek = true;
                break;
            case 'month':
                o.thisMonth = true;
                break;
        }
        
        this.category = cat;
        this.imNew = true;
        this.showEvents(o);
    },
    
    getToday: function(d){
        if (!d) d = this.baseDate;
        return d.clearTime(true);
    },
    
    getThisPastSunday: function(d){
        if (!d) d = this.baseDate;
        return d.clearTime(true).add('1', - (d.getDay()));
    },
    
    getFirstDayOfMonth: function(d){
        if (!d) d = this.baseDate;
        return d.getFirstDateOfMonth();
    },
    
    getLastDayOfMonth: function(d){
        if (!d) d = this.baseDate;
        return this.getEndOfDay(d.getLastDateOfMonth());
    },
    
    getEndOfDay: function(d){
        return d.clearTime(true).add(Date.HOUR, 23).add(Date.MINUTE, 59).add(Date.SECOND, 59);
    },
    
    gotoTeamSchedule: function(id){
        if (id == 0) return;
        window.location = '/team/id/' + id + '/page/schedule.aspx';
    },
    
    next: function(){
        switch (this.curView){
            case 'day':
                Ext.History.add('day:' + this.baseDate.add(Date.DAY, 1).getTime());
                break;
            case 'week':
                Ext.History.add('week:' + this.baseDate.add(Date.DAY, 7).getTime());
                break;
            case 'month':
                Ext.History.add('month:' + this.baseDate.add(Date.MONTH, 1).getTime());
                break;
        }
    },
    
    prev: function(){
        switch (this.curView){
            case 'day':
                Ext.History.add('day:' + this.baseDate.add(Date.DAY, -1).getTime());
                break;
            case 'week':
                Ext.History.add('week:' + this.baseDate.add(Date.DAY, -7).getTime());
                break;
            case 'month':
                Ext.History.add('month:' + this.baseDate.add(Date.MONTH, -1).getTime());
                break;
        }
    },
    
    renderMiniCalendars: function(d){
        d = d.clone();
        d.setMonth(this.curMonth);
        d = d.getFirstDateOfMonth();
        
        var render = function(x,n){
            var days = [];
            for (var i = 0; i < x.getDaysInMonth(); i++){
                var day = x.add(Date.DAY, i);
                days.push({ day:day, hasEvents:this.events[day.getFullYear() + '-' + day.getDayOfYear()] ? true : false });
            }
            var s = this.miniCalTemplate.apply({ date:x, days:days });
            if (n == 1) this.calOne.update(s);
            if (n == 2) this.calTwo.update(s);
        }.createDelegate(this);
        
        var pd = d.add(Date.MONTH, 1);
        render(d, 1);
        render(pd, 2);
    },
    
    setupMiniCalendars: function(s,e){
        this.renderMiniCalendars(s);
        switch (this.curView){
            case 'day':
                this.calOne.select('.day-' + s.getDate()).addClass('selected');
                break;
            case 'week':
                if (e.getMonth() != this.curMonth){
                    this.calTwo.select('.week-1').addClass('selected');
                }
                this.calOne.select('.week-' + s.getDate()).addClass('selected');
                break;
            case 'month':
                this.calOne.select('.all-' + s.getMonth()).addClass('selected');
                break;
        }
    },
    
    miniCalTemplate: new Ext.XTemplate(
        '<div class="month">{[values.date.format("F").toUpperCase()]}</div>',
        '<a class="btn all-{[values.date.getMonth()]}" href="javascript:void(0);" onclick="Ext.History.add(\'month:{[values.date.getTime()]}\');">all</a>',
        '<div class="cube">S</div><div class="cube">M</div><div class="cube">T</div><div class="cube">W</div><div class="cube">T</div><div class="cube">F</div><div class="cube">S</div>',
        '<br style="clear: both;" />',
        '<tpl for="days">',
            '<tpl if="xindex == 1">',
                '{[this.fillSpaces(parent.date)]}',
            '</tpl>',
            '<tpl if="xindex == 1 || values.day.getDay() == 0">',
                '<a class="btn week-{[values.day.getDate()]}" href="javascript:void(0);" onclick="Ext.History.add(\'week:{[values.day.getTime()]}\');">week</a>',
            '</tpl>',
            '<a href="javascript:void(0);" class="cube day-{[values.day.getDate()]} {[values.hasEvents ? "has-events" : ""]}" onclick="Ext.History.add(\'day:{[values.day.getTime()]}\');">{[values.day.getDate()]}</a>',
            '<tpl if="xindex == xcount || values.day.getDay() == 6">',
                '<br style="clear: left;" />',
            '</tpl>',
        '</tpl>', {
            fillSpaces: function(d){
                var s = '';
                for (var i = 0; i < d.getDay(); i++)
                    s += '<div class="cube">&nbsp;</div>';
                return s;
            }
        }
    ).compile(),
    
    showEvents: function(o){
        if (o.baseDate) this.baseDate = o.baseDate;
        if (!o.start || !o.end){
            if (o.thisDay){
                this.curView = 'day';
                o.start = this.getToday();
                o.end = this.getEndOfDay(o.start);
            } else if (o.thisWeek){
                this.curView = 'week';
                o.start = this.getThisPastSunday();
                o.end = this.getEndOfDay(o.start.add(Date.DAY, 6));
            } else if (o.thisMonth){
                this.curView = 'month';
                o.start = this.getFirstDayOfMonth();
                o.end = this.getLastDayOfMonth();
            } else {
                return;
            }
        }
        
        this.view.update('<div style="text-align: center;">Loading...</div>');
    
        var loadEvents = function(){
            this.setupMiniCalendars(o.start, o.end);
            
            var ev = [];
            var daysLapse = Math.ceil(o.end.getElapsed(o.start) / (1000 * 60 * 60 * 24.0));
            for (var i = 0; i < daysLapse; i++){
                var d = o.start.add(Date.DAY, i);
                var a = this.events[d.getFullYear() + '-' + d.getDayOfYear()];
                if (a) ev.push(a);
            }
            this.view.update(this.template.apply(ev));
            var frmt;
            if (o.start.getMonth() == o.end.getMonth()){
                frmt = o.start.getDate() == o.end.getDate() ? '{0} {1}' : '{0} {1}-{2}';
            } else {
                frmt = '{3} {1} - {4} {2}';
            }
            this.date.update(String.format(frmt, o.start.format('F'), o.start.getDate(), o.end.getDate(), o.start.format('M'), o.end.format('M')));
            frmt = o.start.getFullYear() == o.end.getFullYear() ? '{0}' : '{0} - {1}';
            this.year.update(String.format(frmt, o.start.getFullYear(), o.end.getFullYear()));
        }.createDelegate(this);
        
        var fetch = false;
        if (this.imNew){ fetch = true; this.imNew = false; }
        else if (this.curMonth != o.start.getMonth()){
            fetch = true;
            this.baseDate = o.start;
        }
        
        if (fetch){
            this.events = {};
            this.curMonth = o.start.getMonth();
            var firstTry = true;
            var req = function(){
                Ext.Ajax.request({
                    url: '/service/EventsCalendar.ashx',
                    params: {
                        t: o.start.getTime(),
                        type: this.type,
                        id: this.typeID,
                        category: this.category
                    },
                    callback: function(o,s,r){
                        if (s){
                            var ev = Ext.decode(r.responseText);
                            for (var i = 0; i < ev.length; i++){
                                var e = ev[i];
                                var strDate;
                                strDate = eval(e.date.replace(/\/Date\((\d+)\)\//gi, "new Date($1)"));
                                e.date = strDate;
                                var key = e.date.getFullYear() + '-' + e.date.getDayOfYear();
                                if (!this.events[key]) this.events[key] = [];
                                this.events[key].push(e);
                            }
                            loadEvents();
                        } else {
                            if (firstTry){
                                firstTry = false;
                                this.view.update('<div style="text-align: center;">Hmm, had a problem retrieving event data. Trying again...</div>');
                                req();
                            } else {
                                this.view.update('<div style="text-align: center;">Sorry, we\'re not able to retrieve event data at this time. Please try again later.</div>');
                            }
                        }
                    },
                    scope: this
                });
            }.createDelegate(this);
            req();
        }
        else
            loadEvents();
    },
    
    template: new Ext.XTemplate(
        '<tpl for=".">',
            '<tpl if="xindex != 1">',
                '<div class="day-sep">&nbsp;</div>',
            '</tpl>',
            '<div class="row">',
                '<div class="day">{[this.getDate(values[0].date)]}</div>',
                '<div style="float: left; background-color: #fff;">',
                    '<div class="filler-row">&nbsp;</div>',
                    '<tpl for=".">',
                        '<tpl if="xindex != 1">',
                            '<div class="row-sep">&nbsp;</div>',
                        '</tpl>',
                        '<div class="column" style="width: 74px;">{[this.getTime(values.date)]}</div>',
                        '<div class="column" style="width: 234px;">{[this.getEvent(values)]}</div>',
                        '<div class="column" style="width: 228px;">{[this.getDetails(values)]}</div>',
                        '<br style="clear: left;" />',
                    '</tpl>',
                    '<div class="filler-row">&nbsp;</div>',
                '</div>',
                '<br style="clear: left;" /><div style="height: 1px; background-color: #fff">&nbsp;</div>',
            '</div>',
        '</tpl>', {
            getDate: function(d){
                return '<a href="javascript:void(0);" onclick="Ext.History.add(\'day:' + d.getTime() + '\');">' + d.format('n/j') + '</a><br />' + d.format('D').toUpperCase();
            },
            
            getDetails: function(o){
                var s = '';
                
                if (o.status == 9 || o.status == 0){
                    var status = o.status == 9 && o.footprint ? 'Rescheduled' : o.status == 9 ? 'Canceled' : 'Postponed';
                    var format = '<span style="color: red;">*{0}*</span>';
                    s += String.format(format + '<br />', status);
                }
                
                if (o.opponents != null && o.opponents.length > 0){
                    for (var i = 0; i < o.opponents.length; i++){
                        var opp = o.opponents[i];
                        if (i == 0) o.opponentScore = opp.opponentScore;
                        s += String.format('{3}{0} <a href="/team/id/{1}.aspx">{2}</a><br />', opp.home ? '@' : 'vs.', opp.opponentID, opp.opponent, o.category == 3 ? 'Scr ' : '');
                    }
                } else if (o.category == 2) {
                    s += 'Practice<br />';
                }
                if (!o.location || o.location == ''){
                    s += 'Location: TBD';
                } else {
                    s += o.location;
                    if (o.directionsURL && o.directionsURL != '')
                        s += ' - <a href="' + o.directionsURL + '" target="_blank">Directions</a>';
                }
                if (o.homeScore && o.opponentScore && o.winLossTie && o.homeScore != '' && o.opponentScore != '' && o.winLossTie != ''){
                    s += String.format('<br />{0} {1}-{2}', o.winLossTie, parseInt(o.homeScore), parseInt(o.opponentScore));
                    s += String.format('<br /><a href="/team/id/{0}/page/boxscore/eventid/{1}.aspx">Box Score</a>', o.teamID, o.eventID);
                }
                
                if (o.eventID > 0 && o.schoolLMID > 0)
                    s += String.format('<br /><a href="javascript:window.open(\'http://viewmyschedule.digitalsports.com/lmpublic/event_details.asp?eid={0}&sid={1}\',\'event_details\',\'width=530,height=525,scrollbars=yes,resizable=yes\');void(0);">More Details</a>', o.eventID, o.schoolLMID);
                
                return s;
            },
            
            getEvent: function(o){
                if (o.teamID > 0){
                    return String.format('<a href="/team/id/{0}.aspx">{5}&nbsp;{4}<br/>{3}<br />{1} {2}</a><br /><a style="font-weight: normal;" href="/team/id/{0}/page/schedule.aspx">view schedule</a>', o.teamID, o.gender.toUpperCase(), o.level.toUpperCase(), o.sport.toUpperCase(),o.opponent.toUpperCase(),(o.home ? "vs" : "@"));
                } else {
                    return o.eventName;
                }
            },
            
            getTime: function(d){
                var localTime;
                var localOffSet;
                var utc;
                var serverTime;
		var newTime;
                var offset;
                var estTime;
		var estNewTime;
                localTime = d.getTime();
                localOffSet = d.getTimezoneOffset() * 60000;
                utc = localTime + localOffSet;
                offset = -4;   
                estTime = utc + (3600000*offset);
		serverTime = new Date(estTime);		
		if (isDaylight(serverTime))
		{
			offset = -4;
			estNewTime = utc + (3600000*offset);			
			newTime = new Date(estNewTime);				
			return newTime.format('g:i A');
		}
		else
		{
			offset = -5;
			estNewTime = utc + (3600000*offset);			
			newTime = new Date(estNewTime);				
			return newTime.format('g:i A');		
			return serverTime.format('g:i A');
		}				
		
            }
        }
    ).compile()
});

Ext.onReady(function(){
    Ext.History.init();
});
function isDaylight(oDate) {
 
    // 2nd sunday of march
    var dstStartDate = new Date();
    dstStartDate.setMonth(2);
    dstStartDate.setDate(1);
    dstStartDate.setDate(8 - dstStartDate.getDay() + 7);
 
    // first sunday of november
    var dstEndDate = new Date();
    dstEndDate.setMonth(10);
    dstEndDate.setDate(1);
    //dstEndDate.setDate(6 - dstEndDate.getDay());
 
    if ((oDate.getMonth() > dstStartDate.getMonth()) && (oDate.getMonth() < dstEndDate.getMonth())) {
        bInDST = true;
    } else if (oDate.getMonth() == dstStartDate.getMonth()) {
        if (oDate.getDate() >= dstStartDate.getDate()) {
            bInDST = true;
        } else {
            bInDST = false;
        }
    } else if (oDate.getMonth() == dstEndDate.getMonth()) {
        if (oDate.getDate() < dstEndDate.getDate()) {
            bInDST = true;
        } else {
            bInDST = false;
        }
    } else {
        bInDST = false;
    }
    return bInDST;
}