﻿/// <reference path="~/js/jquery-1.3.2-vsdoc.js" />
/// <reference path="~/js/videojug.js" />


/*  filmsuggestion.js 

    object      DiscussionTopicList 
                Control: DiscussionTopicList in FilmSuggestion (Discussions)
                    
    object      DiscussionMessageList
                Control:DiscussionMessageList in FilmSuggestion (FilmSuggestion)

    object      FilmSuggest
                Control: FilmSuggestionDataPanel and other (FilmSuggestion and Discussion)
    
    object      FilmSuggestionPanel
                Control: DiscussionTopicVotePanel, FilmSuggestionPanel (FilmSuggestion and Discussion)
    
    object      DiscussionTopicVotePanel
                Control: DiscussionTopicVotePanel  (FilmSuggestion and Discussion)
*/

//--------------------------------------------------
// DiscussionTopicList class

var DiscussionTopicList = Class.create();

DiscussionTopicList.prototype = {

    initialize: function(thisInstanceName, domContainerId, pagerId, resultCount, domainObjName, listPnl, domainObjType, pageSize, allowUnsubscribe, divNoData, divOuterContainer) {
        if (null == domContainerId)
            throw new Error('ArgumentException: domContainerId is null');

        if (null == listPnl)
            throw new Error('ArgumentException: listPnl is null');

        if (null == domainObjName)
            throw new Error('ArgumentException: domainObjName is null');

        if (null == thisInstanceName)
            throw new Error('ArgumentException: thisInstanceName is null');

        ObjDic.all[thisInstanceName] = this;
        this.thisInstanceName = thisInstanceName;
        this.GA_CONTROL = "DiscussionTopics";
        this.GA_TAGPAGE = vjctx.parentPath[vjctx.parentPath.length - 1];

        this.currentPage = 1;
        this.pageSize = pageSize;
        this.sortOn = 'lastPostDate';
        this.defaultSortOrder = 'desc';
        this.sortOrder = this.defaultSortOrder;

        this.domContainer = $(domContainerId);
        this.pagerId = pagerId;
        this.resultCount = resultCount;
        this.domainObjName = domainObjName;
        this.listPnl = listPnl;
        this.domainObjType = domainObjType;
        this.allowUnsubscribe = allowUnsubscribe;

        this.divNoData = $(divNoData);
        this.divOuterContainer = $(divOuterContainer);

        this.bindSortBtns();
        this.bindRemoveSubscriptionButtons();
        this.showArrow();
        this.buildPager();
    },
    bindSortBtns: function() {
        var sortBtns = $(this.domContainer).getElementsByClassName('sortBtn');
        for (var i = 0; i < sortBtns.length; i++) {
            sortBtns[i].onclick = this.sortClicked.bindAsEventListener(this);
        }
    },
    bindRemoveSubscriptionButtons: function() {
        var subscribeButtons = this.domContainer.getElementsByClassName('RemoveSubscription');
        for (var i = 0; i < subscribeButtons.length; i++) {
            var removeButton = subscribeButtons[i];
            removeButton.onclick = this.removeDiscussion.bindAsEventListener(this);
        }
    },
    showArrow: function() {
        var down = "/images/icons/arrow_down.png";
        var up = "/images/icons/arrow_up.png";
        var colArrows = $(this.domContainer).getElementsByClassName('colArrow');

        for (var i = 0; i < colArrows.length; i++) {
            Element.hide(colArrows[i]);
        }

        var arrow = null;
        for (var i = 0; i < colArrows.length; i++) {
            if (colArrows[i].name == this.sortOn) {
                arrow = colArrows[i];
                break;
            }
        }
        if (null == arrow)
            return false;
        //            throw new Error('arrow was not found for ' + this.sortOn);

        if (this.sortOrder == this.defaultSortOrder) // desc
            arrow.src = down;
        else arrow.src = up;

        Element.show(arrow);
    },
    bigObj: function() {
        this.pageSize = 20;
        this.updateList();
    },
    smallObj: function() {
        this.pageSize = 4;
        this.updateList();
    },
    sortClicked: function(evt) {
        var link = Event.element(evt);
        this.currentPage = 1;

        if (this.sortOn == link.name) {
            this.toggleSortOrder();
        }
        else {
            this.sortOn = link.name;
            this.sortOrder = this.defaultSortOrder;
            if (this.sortOn == 'title')
                this.toggleSortOrder();
        }

        this.updateList();
    },
    toggleSortOrder: function() {
        if (this.sortOrder == 'asc')
            this.sortOrder = 'desc';
        else
            this.sortOrder = 'asc';
    },
    updateList: function() {
        var url = formatUrl('views/tag/discussionsAjax.aspx');
        new Ajax.Updater(this.domContainer, url, { method: 'get', parameters: this.prepareParameters(), evalScripts: true, onSuccess: this.onUpdated.bindAsEventListener(this) });
    },
    prepareParameters: function() {
        return 'Status=update' +
               '&DomainObjName=' + this.domainObjName +
               '&CurrentPage=' + this.currentPage +
               '&PageSize=' + this.pageSize +
               '&DomainObjType=' + this.domainObjType +
               '&SortOn=' + this.sortOn +
               '&SortOrder=' + this.sortOrder +
               '&JsInstanceName=' + this.thisInstanceName +
               '&AllowUnsubscribe=' + this.allowUnsubscribe;
    },
    onUpdated: function(evt) {
        if (evt.status == 203) {
            this.displayNoDataError();
        } else {
            this.bindSortBtns();
            this.bindRemoveSubscriptionButtons();
            this.showArrow();
            this.buildPager();
        }
    },
    buildPager: function() {
        var pageSize = this.getPageSize();

        if (this.resultCount > pageSize) {
            var numberOfPages = Math.ceil(this.resultCount / pageSize);
            var range = PageRangeCalculate(this.currentPage - 1, numberOfPages, 5);
            var pager = new Pager(this.pagerId, range.firstPage + 1, this.currentPage, range.lastPage + 1, numberOfPages);
            var fspager = this;

            $j(pager).bind("pageChangedEvt", function(evt, page) { fspager.pageChanged(page) });
        }
        else {
            Element.update(this.pagerId, '');
        }
    },

    getPageSize: function() {
        return this.pageSize;
    },

    pageChanged: function(page) {
        switch (trim(page.toLowerCase())) {
            case "previous":
                this.currentPage--;
                gaLogAjax(this.GA_CONTROL, "Page-" + page, this.GA_TAGPAGE, this.prevCount++, true, true);
                break;
            case "next":
                this.currentPage++;
                gaLogAjax(this.GA_CONTROL, "Page-" + page, this.GA_TAGPAGE, this.nextCount++, true, true);
                break;
            default:
                this.currentPage = parseInt(page);
                gaLogAjax(this.GA_CONTROL, "Page-" + page, this.GA_TAGPAGE, null, true, true);

        }

        $j('html,body').animate({ scrollTop: $j('#' + this.domContainer.id).offset().top - 150 }, 1000);
        this.updateList();
        this.buildPager();


    },
    removeDiscussion: function(evt) {
        var elt = Event.findElement(evt, 'DIV');
        var discussionId = $(elt).readAttribute('name');
        var url = formatUrl('views/tag/discussionsAjax.aspx');
        new Ajax.Updater(this.domContainer,
                        url, { asynchronous: true, method: 'get', parameters:
                        this.prepareParametersForRemove('removeDiscussionSub', discussionId),
                            evalScripts: true, onSuccess: this.updateList.bindAsEventListener(this)
                        });
    },
    prepareParametersForRemove: function(status, discussionId) {
        return 'Status=' + status +
               '&DiscussionId=' + discussionId +
               '&DomainObjName=' + this.domainObjName +
               '&CurrentPage=' + this.currentPage +
               '&PageSize=' + this.pageSize +
               '&DomainObjType=' + this.domainObjType +
               '&SortOn=' + this.sortOn +
               '&SortOrder=' + this.sortOrder +
               '&JsInstanceName=' + this.thisInstanceName +
               '&AllowUnsubscribe=' + this.allowUnsubscribe;
    },
    displayNoDataError: function() {
        Element.hide(this.divOuterContainer);
        Element.show(this.divNoData);
    }
}


//--------------------------------------------------
// DiscussionMessageList class

var DiscussionMessageList = Class.create();

DiscussionMessageList.prototype = {

    initialize: function(updateContainerId, sortOnDdlId, pagerId, contentUrlName, pageSize, currentPage, resultCount, thisObjectInstanceName, contentID) {
        if (null == updateContainerId)
            throw new Error('Argument exception updateContainerId is null');

        if (null == contentUrlName)
            throw new Error('Argument exception contentUrlName is null');

        if (null == pageSize)
            throw new Error('Argument exception pageSize is null');

        if (null == currentPage)
            throw new Error('Argument exception currentPage is null');
            
        this.GA_CONTROL = "FilmSuggestionList";
        this.GA_TAGPAGE = contentUrlName;
        
        
        this.thisObjectInstanceName = thisObjectInstanceName;
        this.updateContainer = $(updateContainerId);
        this.pagerId = pagerId;
        this.contentUrlName = contentUrlName;
        this.resultCount = resultCount;
        this.contentId = contentID;
        this.sortOnDdl = $(sortOnDdlId);
        if (null != this.sortOnDdl)
            this.sortOnDdl.onchange = this.sortOnChange.bindAsEventListener(this);

        this.sortOnValue = 'MostRecent';

        this.pageSize = pageSize;
        this.currentPage = currentPage;
        this.buildPager();
    },
    updateList: function() {
        var url = formatUrl('views/filmsuggestion/messageListAjax.aspx');
        Loading(this.updateContainer, 'Updating...')
        new Ajax.Updater(this.updateContainer, url, { method: 'GET', parameters: this.getParameters(), evalScripts: true, onComplete: this.onUpdated.bindAsEventListener(this) });
    },
    getParameters: function() {
        return 'contentUrlName=' + this.contentUrlName
        + '&sortOn=' + this.sortOnValue
        + '&pageSize=' + this.pageSize
        + '&currentPage=' + this.currentPage
        + '&timestamp=' + getTimeStamp()
        + '&thisObjectInstanceName=' + this.thisObjectInstanceName;
    },
    onUpdated: function(req) {
        // if(rollAds)
        //    rollAds();
    },
    sortOnChange: function() {
        this.sortOnValue = this.sortOnDdl.options[this.sortOnDdl.selectedIndex].value;
        this.currentPage = 1;
        this.updateList();
        this.buildPager();
    },
    refresh: function() {
        this.updateList();
        this.buildPager();
    },
    buildPager: function() {
        var pageSize = this.pageSize;
        if (this.resultCount > pageSize) {
            var numberOfPages = Math.ceil(this.resultCount / pageSize);
            var range = PageRangeCalculate(this.currentPage - 1, numberOfPages, 5);
            var pager = new Pager(this.pagerId, range.firstPage + 1, this.currentPage, range.lastPage + 1, numberOfPages);
            var fspager = this;

            $j(pager).bind("pageChangedEvt", function(evt, page) { fspager.pageChanged(page) });
        }
        else {
            Element.update(this.pagerId, '');
        }
    },
    pageChanged: function(page) {
        switch (trim(page.toLowerCase())) {
            case "previous":
                this.currentPage--;
                gaLogAjax(this.GA_CONTROL, "Page-" + page, this.GA_TAGPAGE, this.prevCount++, true, true);
                break;
            case "next":
                this.currentPage++;
                gaLogAjax(this.GA_CONTROL, "Page-" + page, this.GA_TAGPAGE, this.nextCount++, true, true);
                break;
            default:
                this.currentPage = parseInt(page);
                gaLogAjax(this.GA_CONTROL, "Page-" + page, this.GA_TAGPAGE, null, true, true);            
        }

        $j('html,body').animate({ scrollTop: $j('#' + this.updateContainer.id).offset().top - 150 }, 1000);       
        this.updateList();
        this.buildPager();
    },
    ajaxRemoveCallback: function(req) {
        if (req.responseText != 'success') {
            alert('There was a problem saving your rating');
        }
        else {
            this.refresh(this);
        }
        return false;
    },

    deleteMessage: function(evt) {
        var ajax = new Ajax.Request(
		    formatUrl('views/home/CommentDelete.ashx'),
		    {
		        method: 'post',
		        parameters: 'entityId=' + this.contentId + '&CommId=' + evt,
		        onComplete: this.ajaxRemoveCallback.bind(this)
		    });
        return false;
    }
}

//--------------------------------------------------
// FilmSuggest class

var FilmSuggest = Class.create();
FilmSuggest.prototype = {
    initialize: function(textbox) {
        this.textbox = $(textbox);
        var handlerUrl = formatUrl("views/Admin/ManageTagsSuggest.ashx");
        this.completer = new Ajax.Autocompleter(this.textbox, "tag_list", handlerUrl, { paramName: "value" });

        this.completer.options.defaultParams = 'mode=content&contenttype=film&contentstate=ok';
    }
}

//--------------------------------------------------
// DiscussionPanel class
DiscussionPostMessage = function(divId, textBoxId, textBoxText) {
    var div = $j('#' + divId)
    var commentTxtBox = $j('#' + textBoxId);

    div.find('.ReplyButton').hover(
        function() { $j(this).addClass('Selected'); },
        function() { $j(this).removeClass('Selected'); }
    );

    if (commentTxtBox.length > 0) {
        commentTxtBox.focus(function(evt) {
            if (!IsAccesAllowed(0))
                commentTxtBox.disabled = true;
            else if (commentTxtBox.val() == textBoxText) {
                commentTxtBox.val('');
                commentTxtBox.removeClass("greyed");
            }
        });
    }
}
//--------------------------------------------------
// DiscussionPanel class
DiscussionQuestionPanel = function(divId, id) {
    var div = $j('#' + divId)

    DiscussionQuestionVoteBox(div.find(".VoteBox"), [id]);
    div.find('.HoverElement').each(function() {
        $j(this).hover(
            function() { $j(this).toggleClass("Selected") },
            function() { $j(this).toggleClass("Selected") });
    });

    div.find('.AnswerButton').click(function() {
        if (IsAccesAllowed(0)) {
            var commentBox = $j('.DiscussionPostMessage TEXTAREA.CommentTextBox');
            $j('html,body').animate({ scrollTop: commentBox.offset().top - 150 }, 1000);
            commentBox.focus();
        }
    });
}


//--------------------------------------------------
// DiscussionPanel class
var DiscussionQuestionVoteBox = function(div, ids) {
    var IDX_BAD = 0;
    var IDX_GOOD = 1;
    var IDX_UNRATED = 2;
    var ratings = new Array();

    setupButtons();
    loadRatings();

    function setupButtons() {
        var buttonContainer = $j('#' + div.attr("id"));
        var ups = buttonContainer.find("div.ThumbsUp");
        ups.each(function() { bindHover($j(this)); $j(this).click(function(evt) { voteUp(evt) }) });
        var downs = buttonContainer.find("div.ThumbsDown");
        downs.each(function() { bindHover($j(this)); $j(this).click(function(evt) { voteDown(evt) }) });
        var reports = buttonContainer.find("div.Report").add(buttonContainer.find("div.ReportText"));
        reports.each(function() {
            $j(this).hover(
                function() { buttonContainer.find("div.Report").addClass("Selected") },
                function() { buttonContainer.find("div.Report").removeClass("Selected") });
        });
    };

    function bindHover(obj) {
        obj.hover(function(evt) { mouseOver(evt); },
                  function(evt) { mouseOut(evt); });
    };

    function voteUp(evt) {
        vote(evt, 5);
    };

    function voteDown(evt) {
        vote(evt, 1);
    };

    function vote(evt, stars) {
        var el = $j(evt.target).parent();
        var re = new RegExp("_([a-f0-9\\-]{36})");
        var id = re.exec(el.attr("id"))[1];

        $j.ajax({
            type: "GET",
            url: formatUrl('views/home/Rating.ashx'),
            data: ({ ContentId: id, Stars: stars }),
            complete: function(req) { voted(id, req) },
            error: error
        });
    };

    function mouseOver(evt) {
        $j(evt.target).parent().addClass("Selected");
    };

    function mouseOut(evt) {
        var voteBoxDiv = $j(evt.target).parents(".VoteBox");
        var ratingInput = voteBoxDiv.find("Input[name$='HiddenRating']");
        var ratingIdx = parseInt(ratingInput.val());
        showImage(voteBoxDiv, ratingIdx);
    };

    function loadRatings(hasClicked) {
        var url = formatUrl('/Controls/filmSuggestion/GetRatings.ashx?' + Math.random());
        $j.getJSON(url,
                  { ids: encodeURIComponent(ids), targetUrl: encodeURIComponent(document.location) },
                  function(json) { ratingsLoaded(json, hasClicked) },
                  function() { error() });
    };

    function ratingsLoaded(json, hasClicked) {
        ratings = json;
        setIcons(hasClicked);
    };

    function error() {
        alert("There was a problem saving your vote!");
    };

    function voted(id, transport) {
        loadRatings(true);
    };

    function setIcons(hasClicked) {
        for (var i = 0; i < ids.length; i++) {
            var id = ids[i];
            var ratingsitem = ratings[id];
            if (ratingsitem) {

                var userStars = ratingsitem[0];
                var posCount = ratingsitem[1];
                var ratingCount = ratingsitem[2];
                var averageRating = ratingsitem[3];

                var userRating;
                switch (userStars) {
                    case 5:
                        userRating = IDX_GOOD;
                        break;
                    case 1:
                        userRating = IDX_BAD;
                        break;
                    default:
                        userRating = IDX_UNRATED;
                        break;
                }

                var voteBoxDiv = findVoteBox(id);

                var ratingInput = voteBoxDiv.find("Input[name$='HiddenRating']")
                ratingInput.val(userRating);

                showImage(voteBoxDiv, userRating);
                if (hasClicked)
                    updateStats(posCount, ratingCount - posCount, voteBoxDiv);
            }

        }
    };

    function showImage(voteBoxDiv, ratingIdx) {
        var thumbsUpImg = voteBoxDiv.find(".ThumbsUp");
        var thumbsDownImg = voteBoxDiv.find(".ThumbsDown");
        var feedbackSpan = voteBoxDiv.find(".FeedbackString");
        switch (ratingIdx) {
            case IDX_BAD:
                thumbsDownImg.addClass('Selected');
                thumbsUpImg.removeClass('Selected');
                updateString(feedbackSpan, "You have Voted 'Bad'");
                break;
            case IDX_GOOD:
                thumbsDownImg.removeClass('Selected');
                thumbsUpImg.addClass('Selected');
                updateString(feedbackSpan, "You have Voted 'Good'");
                break;
            case IDX_UNRATED:
                thumbsUpImg.removeClass('Selected');
                thumbsDownImg.removeClass('Selected');
                updateString(feedbackSpan, "Good Question?");
                break;
        }
    };

    function updateString(feedbackSpan, feedbackString) {
        if (feedbackSpan.html() != feedbackString)
            feedbackSpan.fadeOut("fast", function() { feedbackSpan.html(feedbackString); feedbackSpan.fadeIn("slow"); });
    };


    function updateStats(posCount, negCount, voteBoxDiv) {
        var scoreDiv = voteBoxDiv.parents('.BubbleBox').find('.CurrentScore');
        scoreDiv.fadeOut("slow").fadeTo(500, 1, function() {
            $j(this).find('.Good').html(posCount);
            $j(this).find('.Bad').html(negCount);
            $j(this).fadeIn("slow");
        });   
    };

    function findVoteBox(id) {
        return div.find(".ThumbsUp[id$='" + id + "']").parents(".VoteBox");
    };
};