/*jslint browser: true, cap: false, nomen: true, passfail: false, plusplus:true, undef: false, vars: true, unparam: true, white: false */
/*global window, jQuery, ko, _ */

(function ($) {
    "use strict";

    var indexViewModel = {

        currentIndex: ko.observable(0),
        currentPage: ko.observable(1),
        displayItems: ko.observableArray(),

        indexSegmentsForPeople: [
            { id: "poetryinxhtml", text: "Poetry in XHTML5" },
            { id: "poetryinpdf", text: "Poetry in PDF" },
            { id: "poetryinstreams", text: "Poetry in Streams" },
            { id: "digitizedart", text: "Digitized Art" }
        ],
        indexSegmentsForTime: [
            { id: "prose", text: "Prose" },
            { id: "interviewsanddocumentary", text: "Interviews/Documentary" },
            { id: "therasxcontext", text: "the rasx() context" }
        ],
        indexVisitorLinks: [
            { url: "./rasx01.html", title: "about the kinté space" },
            { url: "./kfaqs.html", title: "kinté FAQs" },
            { url: "./khits.html", title: "kinté hits" },
            { url: "./rasx00.html", title: "the kinté space oddity" }
        ],
        items: [],
        itemsCount: ko.observable(0),
        itemsPerPage: 9,
        pageCount: ko.observable(0),

        getCurrentIndex: function () {
            return ((this.currentPage() - 1) * this.itemsPerPage);
        },
        getJSON: function (id) {
            var url = this.getIndexJsonUrl(id);
            var that = this;
            return $.getJSON(url).then(function (data) {
                that.setItems(data);
            });
        },
        getJSONforVisitors: function () {
            var that = this;
            return $.getJSON('./data/VisitorThumbs.json').then(function (data) {
                that.setItemsForVisitors(data);
            });
        },
        getIndexJsonUrl: function (id) {
            return './data/index-' + id + '.json';
        },
        getIsNewValue: function (pubDate) {
            var getDiffDays = function(earlyDate, lateDate)
            {
                //TODO: move this local function into jQuery extension
                //http://stackoverflow.com/questions/2627473/how-to-calculate-the-number-of-days-between-two-dates-using-javascript
                var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
                var diffDays = Math.round(Math.abs((earlyDate.getTime() - lateDate.getTime())/(oneDay)));
                return diffDays;
            };

            var now = new Date();
            var test1 = (getDiffDays(pubDate, now) <= 60);
            return (test1);
        },
        getSlice: function () {
            return this.items.slice(this.currentIndex(),
                    (this.currentIndex() + this.itemsPerPage));
        },
        isNextPageEnabled: ko.observable(true),
        isPreviousPageEnabled: ko.observable(false),
        setDisplayItems: function () {
            var that = this;
            var slice = this.getSlice();
            this.displayItems.remove(function (item) { return item; });
            _(slice).each(function (item) { that.displayItems.push(item); });
        },
        setEnabled: function () {
            this.isNextPageEnabled(this.currentPage() < this.pageCount());
            this.isPreviousPageEnabled(this.currentPage() > 1);
        },
        setItems: function (data) {
            var that = this;
            this.items = _(data.ChildDocuments)
                .sortBy(function (d) { return $.rx.dateTime.getJsonDate(d.CreateDate); }).reverse();

            _(this.items).each(function (item) {
                //Add .isNew property:
                var pubDate = $.rx.dateTime.getJsonDate(item.CreateDate);
                item.isNew = that.getIsNewValue(pubDate);
                
                //Format long titles:
                if(item.Title.length > 85) {
                    item.Title = item.Title.substring(0, 80) + '...';
                }
            });

            this.currentIndex(0);
            this.currentPage(1);
            this.itemsCount(this.items.length);
            this.pageCount(Math.ceil(this.itemsCount() / this.itemsPerPage));
            this.setDisplayItems();
            this.setEnabled();
        },
        setItemsForVisitors: function (data) {
            this.items = data.ChildDocuments;

            this.currentIndex(0);
            this.currentPage(1);
            this.itemsCount(this.items.length);
            this.pageCount(Math.ceil(this.itemsCount() / this.itemsPerPage));
            this.setDisplayItems();
            this.setEnabled();
        },
        setNextPage: function () {
            this.currentPage(this.currentPage() + 1);
            this.setEnabled();
            if (this.currentPage() > this.pageCount()) { this.currentPage(this.pageCount()); }
            this.currentIndex(this.getCurrentIndex());
            this.setDisplayItems();
        },
        setNextPageClickGate: function () {
            if (this.isNextPageEnabled()) { this.setNextPage(); } else { return false; }
        },
        setPreviousPage: function () {
            this.currentPage(this.currentPage() - 1);
            this.setEnabled();
            if (this.currentPage() < 1) { this.currentPage(1); }
            this.currentIndex(this.getCurrentIndex());
            this.setDisplayItems();
        },
        setPreviousPageClickGate: function () {
            if (this.isPreviousPageEnabled()) { this.setPreviousPage(); } else { return false; }
        },
        triggerAfterAdd: function (item, iterator) {
            $(window.document).trigger('afterAdd',
                ['IndexFlowTemplate', item, iterator]);
        }
    };

    var readyIndexFlow = function (flow) {
        if (!flow.hasClass('IndexSegments')) { return; }

        var id = $('h2 > a:first', flow).attr('id');

        $('h2 > a', flow).click(function (event) {
            event.preventDefault();
            indexViewModel.getJSON($(this).attr('id'));
        });

        indexViewModel.getJSON(id).then(function () {
            $('#IndexBox > #NavigationFlow > .NavigationBox').setBackgroundColorWithAlpha('#00ff7e').show();
            $('#IndexBox > #IndexFlow > .IndexLoading').remove();
        });
    };

    var readySplashFlow = function (flow) {
        var thumbsflow = $('#IndexBox > #IndexFlow > #ThumbsFlow');

        $.getJSON('./data/IndexSplash.json')
            .then(function (data, textStatus, jqXHR) {
                _(data.ChildDocuments).each(function (item) {
                    //Add .isNew property:
                    var pubDate = $.rx.dateTime.getJsonDate(item.CreateDate);
                    item.isNew = indexViewModel.getIsNewValue(pubDate);
                });

                flow.html($('#SplashFlowTemplate').tmpl(data.ChildDocuments));
                $('div.SplashFlowItem', flow).setBackgroundColorWithAlpha('#006633');
            });

        if (thumbsflow.length > 0) {
            if (window.screen && (window.screen.width < 1024)) {
                thumbsflow.remove();
            }
            else {
                $.getJSON('./data/IndexThumbs.json')
                    .then(function (data, textStatus, jqXHR) {
                        thumbsflow.html($('#ThumbsFlowTemplate').tmpl(data.ChildDocuments));
                    });
            }
        }
    };

    var readyVisitorsFlow = function (flow) {
        if (!flow.hasClass('IndexSegments')) { return; }

        indexViewModel.getJSONforVisitors().then(function () {
            $('#IndexBox > #NavigationFlow > .NavigationBox').setBackgroundColorWithAlpha('#00ff7e').show();
            $('#IndexBox > #IndexFlow > .IndexLoading').remove();
        });

    };

    ko.applyBindings(indexViewModel);

    $(window.document).bind('afterAdd',
        function (event, templateName, item, iterator) {
            switch (templateName) {
                case 'IndexFlowTemplate':
                case 'SplashFlowTemplate':
                    $(item).setBackgroundColorWithAlpha('#006633').show();

                    //Load Index thumbs:
                    if ($(item).hasClass('IndexVisitors')) {
                        var a = $('a', item);
                        var data =
                            {
                                thumbAlt: a.attr('data-alt'),
                                thumbSrc: a.attr('data-src')
                            };
                        a.empty();
                        $('#IndexThumbTemplate').tmpl(data).appendTo(a);
                    }

                    break;
            }
        });

    $(window.document).ready(function () {
        //splash:
        var flow = $('#IndexBox > #IndexFlow > #SplashFlow');
        if (flow.length > 0) { readySplashFlow(flow); }

        //index_people:
        flow = $('#IndexBox > #HeaderFlow > .IndexPeopleMenu');
        if (flow.length > 0) { readyIndexFlow(flow); }

        //index_time:
        flow = $('#IndexBox > #HeaderFlow > .IndexTimeMenu');
        if (flow.length > 0) { readyIndexFlow(flow); }

        //index_visitors:
        flow = $('#IndexBox > #HeaderFlow > .IndexVisitorsMenu');
        if (flow.length > 0) { readyVisitorsFlow(flow); }
    });
} (jQuery));

