﻿KyteBrowser = function(id, renderMode, ajaxHandlerUrl, maxResult, template, channelUri, initialTab) {
    this.id = '#' + id + ' ';
    this.renderMode = renderMode;
    this.ajaxHandlerMethodUrl;
    this.maxResult = maxResult;
    this.template = template;
    this.channelUri = channelUri;
    this.params = {};
    this.result;

    this.container = $('#' + id + '');
    this.listingDiv = this.container.find('#kyteListing');
    this.mostWatchedTab = this.container.find('#MostWatched');
    this.mostRecentTab = this.container.find('#MostRecent');

    if (this.renderMode == 'shows') {
        this.ajaxHandlerMethodUrl = ajaxHandlerUrl + "/GetShows";
        this.params = {};
        this.params['channelUri'] = this.channelUri;
        this.params['firstResult'] = 0;
        this.params['maxResult'] = this.maxResult;

        if (initialTab == "MostWatched") {
            this.params['orderSpec'] = 'totalWatches-d';
        }
        else if (initialTab == "MostRecent") {
			this.params['orderSpec'] = 'createdTime-d';
        }
        this.Render();

        var obj = this;
        this.mostWatchedTab.click(function() {
            obj.params['orderSpec'] = 'totalWatches-d';
            obj.Render();
            obj.SetSelected(obj.mostWatchedTab);
        });
        this.mostRecentTab.click(function() {
            obj.params['orderSpec'] = 'createdTime-d';
            obj.Render();
            obj.SetSelected(obj.mostRecentTab);
        });
    }
    else if (this.renderMode == 'channels') {
        this.ajaxHandlerMethodUrl = ajaxHandlerUrl + "/GetChannels";
        this.params = {};
        this.params['orderSpec'] = 'totalWatches-d';
        this.params['firstResult'] = 0;
        this.params['maxResult'] = this.maxResult;
        this.Render();

        var obj = this;
        this.mostWatchedTab.click(function() {
            obj.Render(this.params);
            obj.SetSelected(obj.mostWatchedTab);
        });
    }

    // Static property initialization
    KyteBrowser.MemberAjaxHandler = ajaxHandlerUrl + "/GetMemberID";
    KyteBrowser.MemberProfileUrlBase = "/user/default.aspx?mid=";
}

KyteBrowser.prototype.ApplyTemplate = function() {
    this.listingDiv.setTemplateURL(this.template);
    this.listingDiv.processTemplate(this.result);

    this.firstPage = this.container.find('#firstPage');
    this.prevPage = this.container.find('#prevPage');
    this.nextPage = this.container.find('#nextPage');
    this.lastPage = this.container.find('#lastPage');
}

KyteBrowser.prototype.Render = function() {
    var obj = this;
    $.ajax({
        type: 'POST',
        url: this.ajaxHandlerMethodUrl,
        data: JSON.stringify(obj.params),
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        dataFilter: function(data, type) {
            return data.replace(/"\\\/(Date\([0-9-]+\))\\\/"/gi, 'new $1');
        },
        success: function(msg) {
            obj.result = msg.d;
            obj.ApplyTemplate();
            obj.RenderPagination();
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            return;
        },
        async: false
    });
}

KyteBrowser.prototype.RenderPagination = function() {
    var obj = this;
    obj.firstPage.click(function() {
        obj.params['firstResult'] = 0;
        obj.Render();
    });
    obj.prevPage.click(function() {
        obj.params['firstResult'] = Math.max(obj.result.Position - obj.params['maxResult'], 0);
        obj.Render();
    });
    obj.nextPage.click(function() {
        obj.params['firstResult'] = Math.min(obj.result.Position + obj.params['maxResult'], obj.result.TotalSize);
        if (obj.params['firstResult'] < obj.result.TotalSize) obj.Render();
    });
    obj.lastPage.click(function() {
        obj.params['firstResult'] = obj.result.TotalSize - Math.min(obj.params['maxResult'], obj.result.TotalSize);
        obj.Render();
    });
}

KyteBrowser.prototype.SetSelected = function(obj) {
    obj.siblings().removeClass('tab-selected');
    obj.addClass('tab-selected');
}

KyteBrowser.AddCommas = function(nStr) {
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

KyteBrowser.ConvertDuration = function(ms)
{
    ms = Math.round(ms / 1000);
    seconds = ms % 60;
    ms = Math.floor(ms / 60);
    minutes = ms % 60;
    ms = Math.floor(ms / 60);
    hours = ms;
    return (hours == 0 ? '' : hours.toString() + ' hr ') +  minutes.toString() + ' min ' + seconds.toString() + ' sec';
}

KyteBrowser.BuildMemberProfileUrl = function(memberID) {
    var url = window.location.protocol + "//" + window.location.hostname + KyteBrowser.MemberProfileUrlBase + memberID;
    return url;
}

KyteBrowser.MemberProfileLink = function(kyteLogin) {
    var link = '';
    $.ajax({
        type: 'POST',
        url: KyteBrowser.MemberAjaxHandler,
        data: '{"kyteLogin":"' + kyteLogin + '"}',
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function(msg) {
            memberID = msg.d;
            if (memberID != null && memberID != undefined && memberID != 0)
            {
                link = KyteBrowser.BuildMemberProfileUrl(memberID);
                window.location = link;
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            return;
        },
        async: false
    });
}

KyteBrowser.TimeAgoInWords = function(from) {
    var to = new Date();
    var distance_in_seconds = ((to - from) / 1000);
    var distance_in_minutes = Math.floor(distance_in_seconds / 60);

    if (distance_in_minutes < 20) { return 'just now'; }
    if (distance_in_minutes < 45) { return distance_in_minutes + ' minutes ago'; }
    if (distance_in_minutes < 90) { return 'about 1 hour ago'; }
    if (distance_in_minutes < 1440) { return 'about ' + Math.floor(distance_in_minutes / 60) + ' hours ago'; }
    if (distance_in_minutes < 2880) { return '1 day ago'; }
    if (distance_in_minutes < 43200) { return Math.floor(distance_in_minutes / 1440) + ' days ago'; }
    if (distance_in_minutes < 86400) { return 'about 1 month ago'; }
    if (distance_in_minutes < 525960) { return Math.floor(distance_in_minutes / 43200) + ' months ago'; }
    if (distance_in_minutes < 1051199) { return 'about 1 year ago'; }

    return 'over ' + Math.floor(distance_in_minutes / 525960) + ' years ago';
}

