﻿if(jQuery !== 'undefined' )
{

    Cuke.Localization = {
    
        LoadCultureInfo : function(a)
        {
        
            if (this.CultureInfoReady)
            {
                if (typeof a === 'function')
                    a();
            }
            else
            {
                if (!this.waiting) this.waiting = [];
                if (typeof a === 'function') this.waiting.push(a);
            }
            
            if (! this.CultureInfoLoading )
            {
                var t = this;
                this.CultureInfoLoading = true;
                $j.getJSON( Cuke.RootUrl + "Cuke/Localization/Localization.ashx", function(data)
                {
                    Cuke.Localization.CultureInfo = data;
                    Cuke.Localization.CultureInfoReady = true;
                    for(var i=0;i<t.waiting.length;i++) 
                    { 
                        t.waiting[i](); 
                    }
                    t.waiting = null;
                });
            }
        },
        
        FormatDate : function(pattern, date)
        {
           function _d()
           {
                return date.getUTCDate();
           }
           
           function _dd()
           {
                var dd = date.getUTCDate();
                if (dd < 10) return '0' + dd;
                else return dd;
           }
           
           function _ddd()
           {
                return Cuke.Localization.CultureInfo.AbreviatedDayNames[date.getUTCDay()];
           }
           
           function _dddd()
           {
                return Cuke.Localization.CultureInfo.DayNames[date.getUTCDay()];
           }
           
           function _M()
           {
                return date.getUTCMonth();
           }
           
           function _MM()
           {
                var MM = date.getUTCMonth();
                if (MM < 10) return '0' + MM;
                else return MM;
           }
           
           function _MMM()
           {
                return Cuke.Localization.CultureInfo.AbreviatedMonthNames[date.getUTCMonth()];
           }
           
           function _MMMM()
           {
                return Cuke.Localization.CultureInfo.MonthNames[date.getUTCMonth()];
           }
           
           function _yy()
           {
                return date.getUTCFullYear().substr(-2);
           }
           
           function _yyyy()
           {
                return date.getUTCFullYear();
           }

           return pattern.replace(/(dddd)|(ddd)|(dd)|(d)|(MMMM)|(MMM)|(MM)|(M)|(yyyy)/g, function(a) 
           {
                return eval('_'+a+'()');
           });
        },
        
        CultureInfo : null,
        CultureInfoReady : false,
        CultureInfoLoading : false
    };
}

(function($) {
    $.scrollLeft = function()
    {
        this.parent().css("overflow", "hidden");
        this.parent().css("position", "relative");
        
        var width = this.width();
        this.css("width", width + 'px');
        this.css("position", "absolute");
        rep.css("position", "absolute");
        
        if (dir > 0)
            rep.css("left", '-' + width + 'px');
        else
            rep.css("left", width + 'px');
    }
})(jQuery);

(function($) {

    function _(s) {
        if (Cuke) return Cuke.GetString(s);
        return s;
    }

    $.extend($.fn, {

        // Build a Cuke Calendar on each item from the jQuery Object.
        CukeCalendar: function(options) {
            var Sel = this;

            var Cal = [];
            this.each(function() {
                var oCal = $.data($(this)[0], 'CukeCalendar');
                if (!oCal) {
                    oCal = new $.CukeCalendar(options, $(this));
                    $.fn.CukeCalendars.push(oCal);
                    $.data($(this)[0], 'CukeCalendar', oCal);
                    Cuke.Localization.LoadCultureInfo(function() { oCal.load(); })
                }
                Cal.push(oCal);
            });



            if (Sel.length == 1) return Cal[0];
            return Cal;
        },

        CukeCalendars: []
    });

    VEvent = function(dStart, dEnd, url, summary, uid, extra, cssClass) {
        this.dStart = dStart;
        this.dEnd = dEnd;
        this.url = url;
        this.summary = summary;
        this.uid = uid;
        this.extra = {};
        if (extra) this.extra = extra;
        this.cssClass = [];
        if (cssClass) this.cssClass = cssClass;
    };

    $.extend(VEvent, {
        prototype: {
            addClasses: function(el) {
                for (var i = 0; i < this.cssClass.length; i++) {
                    el.addClass(this.cssClass[i]);
                }
            }
        }
    });

    // constructor for CukeCalendar
    $.CukeCalendar = function(options, el) {
        this.settings = $.extend({}, $.CukeCalendar.defaults, options);
        this.el = el;
        this.el.append('<div class="CukeCalendar"><div class="Body"></div></div>');
        this.content = $("div.Body", this.el);
        this.init();
    };

    $.extend($.CukeCalendar, {

        defaults: {
            FirstDayOfWeek: 1,
            Days: [],
            Months: [],
            MinDate: new Date(1900, 1, 1),
            MaxDate: new Date(2100, 1, 1),
            Weekends: { 0: true, 6: true },
            AllowSelection: true,
            MultiSelection: false,
            AllPrevDisabled: false,
            ShowOtherMonthDays: false,
            SingleEvent: true,
            Number: 2,
            NumberByLine: 2,
            Space: 4
        },

        setDefaults: function(settings) {
            $extend({}, $.CukeCalendar.defaults, settings);
        },

        prototype: {

            init: function() {
                this.content.html('<div style="text-align:center;"><img style="margin:auto;" src="' + Cuke.Skin + 'MiniSkin/CukeCalendar/Std/loader.gif"/></div>');
                this.hidden = $("input.SelectedDates", this.el);
                var tp = new Date();
                this.today = new Date(Date.UTC(tp.getUTCFullYear(), tp.getUTCMonth(), tp.getUTCDate()));
                this.selected = [];
                this.selecting = new Date();
                if (this.hidden.attr("value"))
                    this.selected = JSON.parse(this.hidden.attr("value"));
                this.events = [];

                this.date = new Date(Date.UTC(this.today.getUTCFullYear(), this.today.getUTCMonth(), 1));
                if (!this.isDateBetween(this.date, this.settings.MinDate, this.settings.MaxDate)) {
                    if (this.selected.length > 0) this.ensureVisible(this.selected[0]);
                    else this.ensureVisible(this.settings.MinDate);
                }

                if (this.settings.AllPrevDisabled) {
                    var d = new Date();
                    this.addEvent(new VEvent(new Date(Date.UTC(1900, 1, 1)), new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate() - 1)), '', '', '', { disabled: true }, ["disabled"]));
                }
            },

            loaded: false,

            load: function() {
                var h = JSON.parse(this.hidden.attr("value"));
                if (h) this.selected = h;
                this.culture = Cuke.Localization.CultureInfo;
                this.loaded = true;
                this.render();
            },

            prev: function() {

                var d = new Date(Date.UTC(this.date.getUTCFullYear(), this.date.getUTCMonth() - 1, this.date.getUTCDate()));
                this.date = d;
                this.renderCal(d, true);
                //Anim
                $(".CalendarWrap:last", this.content).remove();
                var cur = this.date;
                if (this.onDisplayIntervalChange) {
                    for (var i = 0; i < this.onDisplayIntervalChange.length; i++) {
                        this.onDisplayIntervalChange[i](cur);
                    }
                }
            },

            next: function() {
                var d = new Date(Date.UTC(this.date.getUTCFullYear(), this.date.getUTCMonth(), this.date.getUTCDate()));
                d = new Date(d.setUTCMonth(d.getUTCMonth() + this.settings.Number));
                this.date = new Date(this.date.setUTCMonth(this.date.getUTCMonth() + 1));
                this.renderCal(d);
                //Anim
                $(".CalendarWrap:first", this.content).remove();
                var cur = this.date;
                if (this.onDisplayIntervalChange) {
                    for (var i = 0; i < this.onDisplayIntervalChange.length; i++) {
                        this.onDisplayIntervalChange[i](cur);
                    }
                }

            },

            scrollNext: function(a) {

            },

            ensureVisible: function(d) {
                if (this.date.getFullYear() != d.getFullYear() || this.date.getMonth() != d.getMonth()) {
                    this.date = d;
                    if (this.loaded) this.render();

                    if (this.onDisplayIntervalChange) {
                        for (var i = 0; i < this.onDisplayIntervalChange.length; i++) {
                            this.onDisplayIntervalChange[i](d);
                        }
                    }
                }
            },

            ensureFirstSelectedVisible: function() {
                if (this.selected[0]) this.ensureVisible(this.selected[0]);
            },

            render: function() {
                this.content.html("");
                $(".Nav", this.content.parent()).remove();
                this.renderNav();
                this.calendars = [];
                var d;
                d = new Date(Date.UTC(this.date.getUTCFullYear(), this.date.getUTCMonth(), 1));
                for (var i = 0; i < this.settings.Number; i++) {
                    this.calendars.push(this.renderCal(d));
                    d = new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth() + 1, 1));
                }
				Cuke.SyncDic.dispatch("calendarAfterRender", this);
            },

            // Renders the Navigation Table
            renderNav: function() {

                var s = '' +

                '<table class="Nav">' +
                    '<tbody>' +
                        '<tr>' +
                            '<td style="text-align: left;" class="NavPrev">' +
                                '<a Class="NavLink"><<</a>' +
                            '</td>' +
                            '<td style="text-align: center;" class="NavText">' +
                               '<a Class="NavLink">' + Cuke.GetString('Cuke.Time.Today') + '</a>' +
                            '</td>' +
                            '<td style="text-align: right;" class="NavNext">' +
                                '<a Class="NavLink">>></a>' +
                            '</td>' +
                        '</tr>' +
                    '</tbody>' +
                '</table>';

                var div = this.content.parent();
                div.prepend(s);
                var c = this;
                var nav = $(".Nav", div);

                $(".NavPrev > a", nav).click(function() { c.prev(); });
                $(".NavNext > a", nav).click(function() { c.next(); });
                $(".NavText > a", nav).click(function() { c.ensureVisible(new Date()); });
            },

            // Renders the Calendar
            renderCal: function(date, before) {
                var $this = this;
                var m = this.culture.MonthNames[date.getUTCMonth()];
                var sMonth = '' +
                    '<div class="CalendarWrap">' +
                        '<div class="CalendarItem">' +
                            '<p class="Title">' +
                                 m.substr(0, 1).toUpperCase() + m.substr(1) + ' ' + date.getUTCFullYear() +
                            '</p>' +
                            '<table class="Calendar">' +
                                '<thead>' +
                                    '<tr></tr>' +
                                '</thead>' +
                                '<tbody>' +
                                    '<tr></tr>' +
                                '</tbody>' +
                            '</table>' +
                        '</div>' +
                    '</div>';

                var table;

                if (before) {
                    this.content.prepend(sMonth);
                    table = $(".Calendar:first", this.el);
                }
                else {
                    this.content.append(sMonth);
                    table = $(".Calendar:last", this.el);
                }
                var div = table.parent().parent();

                var head = $("thead > tr", table);
                var tbody = $("tbody", table);

                var tp = new Date();

                var iDate = new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()));
                iDate.setUTCDate(1);
                var d = (iDate.getUTCDay() - this.settings.FirstDayOfWeek) % 7;
                if (d < 0) d += 7;
                iDate = new Date(date);
                iDate.setUTCDate(0-d);
                iDate.setUTCDate(iDate.getUTCDate() + 1);

                var day = iDate.getUTCDate();

                for (var i = 0; i < 7; ++i) {
                    d = (i + this.settings.FirstDayOfWeek) % 7;

                    head.append('<td>' + this.culture.DayNames[d].substr(0, 1).toUpperCase() + this.culture.DayNames[d].substr(1, 2) + '</td>');

                    if (this.today.getUTCDay() == d && this.today.getUTCMonth() == date.getUTCMonth() && this.today.getUTCFullYear() == date.getUTCFullYear())
                        $("td:last", head).addClass("Today");

                    if (this.settings.Weekends[d])
                        $("td:last", head).addClass("Weekend");
                }

                var disabled = false;
                var hidden = false;
                var tr = $("tr:last", tbody);
                var cur, ev;
                for (var i = 0; i < 42; i++, iDate.setUTCDate(day + 1)) {
                    if (!this.isDateBetween(iDate, this.settings.MinDate, this.settings.MaxDate))
                        disabled = true;

                    if (this.settings.AllPrevDisabled && iDate.getUTCTime() < this.today.getUTCTime())
                        disabled = true;

                    if (iDate.getUTCDay() == this.settings.FirstDayOfWeek) {
                        tbody.append("<tr></tr>");
                        tr = $("tr:last", tbody);
                    }

                    tr.append('<td><div class="CellWrap"><div class="Num">' + iDate.getUTCDate() + '</div><span class="abbr" title=' + JSON.stringify(iDate) + '></span><div></td>');
                    cur = $("td:last", tr);
                    ev = this.getEvents(iDate, cur);

                    if (this.settings.Weekends[iDate.getUTCDay()]) cur.addClass("Weekend");
                    if (iDate.getUTCMonth() != date.getUTCMonth()) cur.addClass("OtherMonth");
                    if (this.isSameDay(this.today, iDate)) cur.addClass("Today");
                    if (this.isSelected(iDate)) cur.addClass("Selected");
                    if (ev) cur.addClass("VEvent");
                    if (this.settings.AllPrevDisabled && iDate.getUTCTime() < this.today.getUTCTime()) cur.addClass("Disabled");


                    if (this.settings.AllowSelection && !disabled) {
                        cur.mouseup(function() {
                            $this.dateClicked(this);
                        });
                    }
                    day = iDate.getUTCDate();
                    disabled = false;
                }
                div.width((99 / this.settings.NumberByLine) + '%');
                return div;
            },

            dateClicked: function(el) {
                var d = $("span", el).attr("title");
                this.selecting = JSON.parse('"' + d + '"');

                //Todo(Lookup for disabled elements more secure)
                if (!$(el).hasClass("Disabled") && this.selecting > this.settings.MinDate && this.selecting < this.settings.MaxDate) {
                    if (this.settings.MultiSelection) {
                        var x = -1;
                        for (var i = 0; i < this.selected.length; i++) {
                            if (this.compare(this.selected[i], this.selecting) == 0)
                                x = i;
                        }
                        if (x < 0) this.selected.push(this.selecting);
                        else this.selected.splice(x, 1);

                        $(el).toggleClass("Selected");
                    }
                    else {
                        this.selected = [this.selecting];
                        $("td.Selected", this.content).removeClass("Selected");
                        $(el).addClass("Selected");
                    }

                    this.hidden.attr("value", JSON.stringify(this.selected));


                    if (this.onselect) {
                        for (var i = 0; i < this.onselect.length; i++) {
                            this.onselect[i](this.selecting);
                        }
                    }
                }
            },

            selectDate: function(d) {

                if (d < this.settings.MinDate) d = this.settings.MinDate;
                if (d > this.settings.MaxDate) d = this.settings.MaxDate;

                var ds;
                if (typeof d === "object") ds = JSON.stringify(d);
                else { ds = d; d = JSON.parse('"' + ds + '"') };

                this.selecting = d;

                var el = $j("span[title=" + ds + "]", this.el).parent().parent();

                if (!$(el).hasClass("Disabled")) {
                    if (this.settings.MultiSelection) {
                        var x = -1;
                        for (var i = 0; i < this.selected.length; i++) {
                            if (this.compare(this.selected[i], this.selecting) == 0)
                                x = i;
                        }
                        if (x < 0) this.selected.push(this.selecting);
                        else this.selected.splice(x, 1);

                        $(el).toggleClass("Selected");
                    }
                    else {
                        this.selected = [this.selecting];
                        $("td.Selected", this.content).removeClass("Selected");
                        $(el).addClass("Selected");
                    }

                    this.hidden.attr("value", JSON.stringify(this.selected));

                    if (this.onselect) {
                        for (var i = 0; i < this.onselect.length; i++) { this.onselect[i](this.selecting); }
                    }

                    return true;
                }
                else return false;
            },

            select: function(a) {
                if (!this.onselect) this.onselect = [];
                this.onselect.push(a);
            },

            displayIntervalChange: function(a) {
                if (!this.onDisplayIntervalChange) this.onDisplayIntervalChange = [];
                this.onDisplayIntervalChange.push(a);
            },

            clearSelectedDate: function() {
                this.hidden.attr("value", '[]');
            },

            isSelected: function(a) {
                for (var i = 0; i < this.selected.length; i++) {
                    if (this.isSameDay(a, this.selected[i]))
                        return true;
                }
            },

            isSameDay: function(a, b) {
                if (typeof a !== 'object') a = JSON.parse('"' + a + '"');
                if (typeof b !== 'object') b = JSON.parse('"' + b + '"');

                if (a.getFullYear() != b.getFullYear()) return false;
                if (a.getMonth() != b.getMonth()) return false;
                if (a.getDate() != b.getDate()) return false;

                return true;
            },

            toDate: function(str) {
                return JSON.parse('"' + str + '"');
            },

            getEvents: function(a, cur) {
                var ev = [];
                for (var i = 0; i < this.events.length; i++) {
                    var d = this.events[i];

                    if (this.isDateBetween(a, d.dStart, d.dEnd) || this.isSameDay(a, d.dStart) || this.isSameDay(a, d.dEnd))
                        ev.push(d);
                }
                if (ev.length > 0) {
                    var w;
                    $("span", cur).before('<div class="Events"></div>');
                    for (var x = 0; x < ev.length; x++) {

                        $("div.Events", cur).append('<div class="Event"></div>');
                        if (this.settings.SingleEvent) $("div.Events", cur).addClass("Single");
                        
                        if (this.isSameDay(a, ev[x].dStart)) {
                            w = (24 - ev[x].dStart.getHours()) * 100 / 24;
                            $("div.Event:last", cur).append('<div class="Start" style="width:' + w + '%;"></div>');
                        }
                        else if (this.isSameDay(a, ev[x].dEnd)) {
                            w = ev[x].dEnd.getHours() * 100 / 24;
                            $("div.Event:last", cur).append('<div class="End" style="width:' + w + '%;"></div>');
                        }
                        else if (this.isDateBetween(a, ev[x].dStart, ev[x].dEnd)) {
                            $("div.Event:last", cur).append('<div style="width:100%"></div>');
                        }
                       
                        ev[x].addClasses($("div.Event:last div", cur));
                    }
                    return ev;
                }

                return false;
            },

            isDateBetween: function(date, start, end) {
                var t = date.getTime();
                if (t < start.getTime()) return false;
                if (t > end.getTime()) return false;
                return true;
            },

            compare: function(d, o) {
                d = d.getTime();
                o = o.getTime();

                if (d == o) return 0;
                if (d > o) return 1;
                else return -1;
            },

            addEvent: function(event) {
                this.events.push(event);
                var t = this;
                this.events.sort(function(a, b) {
                    return t.compare(a.dStart, b.dStart);
                });
            },

            addEventsFromDataArray: function(js) {
                var c = JSON.parse(js);
                var ev;
                for (var x = 0; x < c.length; x++) {
                    ev = c[x];
                    this.addEvent(new VEvent(ev.Start, ev.End, ev.Name, ev.Url, ev.Summary, ev.Extra, ev.Classes));
                }
            }
        }
    });

})(jQuery);
