/// <reference path="../ScriptReference/jquery-1.7.1.js"/>
/// <reference path="jquery-ui-1.8.18.custom.js"/>
/// <reference path="Mediasite.Core.js"/>
/// <reference path="Mediasite.Player.Core.js"/>
/// <reference path="modernizr-2.5.3.js"/>

Mediasite.namespace("Player");

// BookmarkStore
// +===========================================================================
Mediasite.Player.BookmarkStore = function (presentationId, presentationDuration, isLive, clockSkew) {
    var self = this;

    var _defaultPositionValue = 0.0;
    var _minimumPositionValue = 0.0;
    var _maximumPositionValue = 10000 * 24.0 * 60.0 * 60.0 * 1000; // How could we need more than 10K days?
    var _noBookmarkZoneSize = 3000;
    var _maximumBookmarks = 10;
    var _bookmarksKeyName = "bookmarks";

    var _lastStartTime = null;

    presentationDuration = isNaN(presentationDuration) ? 0 : presentationDuration;

    this.start = function (startTime) {
        _lastStartTime = startTime;
    };

    this.save = function (position, playbackTicketId) {

        var serverPosition = 0;

        //bail if we don't have access to local storage, or is live, or _lastStartTime is null
        if (!Mediasite.Player.Support.localstorage || isLive || _lastStartTime === null) {
            return;
        }

        //bail if position = _lastStartTime
        var durationViewed = (position - _lastStartTime) / 1000;
        if (durationViewed === 0) {
            return;
        }

        //grab bookmarks from storage
        var bookmarks = JSON.parse(localStorage.getItem(_bookmarksKeyName));
        var bookmarksOriginalString = JSON.stringify(bookmarks);

        if (bookmarks === null) { bookmarks = []; }

        //delete existing bookmark
        for (i = 0; i < bookmarks.length; i++) {
            if (bookmarks[i].presentationId === presentationId) {
                bookmarks.splice(i, 1);
            }
        }

        //add bookmark (if valid position)
        if (position > _minimumPositionValue && position < _maximumPositionValue && Math.abs(presentationDuration - position) > _noBookmarkZoneSize) {
            var _date = new Date();
            var _timestamp = Date.UTC(_date.getFullYear(), _date.getMonth(), _date.getDate(), _date.getHours(), _date.getMinutes(), _date.getSeconds(), _date.getMilliseconds());
            var _timestamp = _timestamp - clockSkew; // adjust for server skew
            bookmarks.push({ presentationId: presentationId, position: position, savedAt: _timestamp / 1000 });
            serverPosition = position;
        }

        //truncate
        bookmarks.sort(compareSavedAt);
        while (bookmarks.length > _maximumBookmarks) {
            bookmarks.shift();
        }

        //store bookmarks (if any change) in localstorage
        if (JSON.stringify(bookmarks) !== bookmarksOriginalString) {
            if (bookmarks.length === 0) {
                localStorage.removeItem(_bookmarksKeyName);
            } else {
                localStorage.setItem(_bookmarksKeyName, JSON.stringify(bookmarks));
            }
        }

        _lastStartTime = null;
        return bookmarks.length;

    };

    this.retrieve = function () {
        if (!Mediasite.Player.Support.localstorage) {
            return _defaultPositionValue;
        }

        var bookmarks = JSON.parse(localStorage.getItem(_bookmarksKeyName));

        var bookmark = { position: 0, savedAt: 0 };

        if (bookmarks !== null) {
            for (i = 0; i < bookmarks.length; i++) {
                if (bookmarks[i].presentationId === presentationId) {
                    bookmark.position = Math.min(Math.max(bookmarks[i].position, _minimumPositionValue), _maximumPositionValue);
                    bookmark.savedAt = bookmarks[i].savedAt;
                    return bookmark;
                }
            }
        }

        return bookmark;

    };

    function compareSavedAt(a, b) {
        if (a.savedAt < b.savedAt)
            return -1;
        if (a.savedAt > b.savedAt)
            return 1;
        return 0;
    };



    this.watchViewTracking = function (viewTracking, playbackTicketId) {
        viewTracking.addHandler({
            start: function (start) {
                self.start(start * 1000);
            },
            end: function (start, end, important) {
                self.save(end * 1000, playbackTicketId);
            }
        });
    };

};
// -=====
