﻿//Класс, управляющий каруселью

function CarouselControlClass() {

    this.objViewPortContainer = new Object();
    this.objSliderContainer = new Object();
    this.objActiveTeaserFrame = new Object();
    this.objThumbnailsList = new Object();
    this.objCurrentlyActiveItem = new Object();
    this.objNewActiveItem = new Object();

    //Значение ширины превьюшки достаточно стабильно, поэтому его можно использовать в качестве константы.
    //В идеале, ширину и отступы надо расчитывать динамически, но это задача для будущих версий =)
    this.iThumbnailWidth = new Number(80);
    this.iThumbnailMarginRightValue = new Number(5);

    this.iItemsNumber = new Number();
    this.iItemPosition = new Number();

    this.iNewActiveItemOffsetLeft = new Number();

    if (typeof CarouselControlClass._initialized == "undefined") {

        CarouselControlClass.prototype.ThumbnailImageClickEvent = function(objElementID) {
            this.objNewActiveItem = $(objElementID);
            this.objThumbnailsList = this.objNewActiveItem.parent();
            this.objSliderContainer = this.objNewActiveItem.parent().parent();
            this.objActiveTeaserFrame = this.objSliderContainer.children("div .selectedItemFrame");
            this.objViewPortContainer = this.objSliderContainer.parent();

            this.iItemPosition = this.objNewActiveItem.prevAll().size();
            this.ClearItemsSelection();

            this.SetActiveItem(this.iItemPosition);
            this.objNewActiveItem = this.FindActiveItem();

            this.ShowTeaserData();

            this.HighlightActiveItem();
        };

        CarouselControlClass.prototype.ArrowClickEvent = function(objArrow, iDirection) {
            this.objViewPortContainer = $(objArrow).parent().children("div .viewPort");
            this.objSliderContainer = this.objViewPortContainer.children(":first");

            //Второй раз присвоить контейнер нужно для того, чтобы дурацкий js начал правильно определять его размеры =)
            this.objViewPortContainer = this.objSliderContainer.parent();

            this.objActiveTeaserFrame = this.objSliderContainer.children("div .selectedItemFrame");
            this.objThumbnailsList = this.objSliderContainer.children(":last");
            this.objCurrentlyActiveItem = this.FindActiveItem();

            this.iItemsNumber = this.objThumbnailsList.find("li").size();

            var iItemTempPosition = new Number();
            this.objThumbnailsList.find("li").each(function(index) {
                if ($(this).hasClass("active")) {
                    iItemTempPosition = index;
                }
            });
            this.iItemPosition = iItemTempPosition;

            this.ClearItemsSelection();

            //Нажата стрелка вправо —>
            if (0 < iDirection) {
                if (this.iItemPosition < this.iItemsNumber - 1)
                    this.SetActiveItem(++this.iItemPosition);
                else
                    this.SetActiveItem(0);
            }
            //<— Нажата cтрелка влево
            else {
                if (0 < this.iItemPosition)
                    this.SetActiveItem(--this.iItemPosition);
                else
                    this.SetActiveItem(this.iItemsNumber - 1);
            }

            this.objNewActiveItem = this.FindActiveItem();

            this.ShowTeaserData();

            this.HighlightActiveItem();
        };

        CarouselControlClass.prototype.ShowTeaserData = function(strLCID, strID) {
            //Получаем ID превьюшки
            var strItemID = this.objNewActiveItem.attr("id").split('_')[1];

            var url = "/WebServices/Carousel.asmx/GetTeaser";
            var params = "strLCID=1049&strID=" + strItemID; //Данные по локали надо брать откуда-то динамически

            $.ajax({
                type: "POST",
                url: url,
                data: params,
                success: function(data) {
                    var objTeaserContainer = $("#sportEventTeaser");
                    objTeaserContainer.fadeOut("normal", function() {
                        var strTeaserText = $(data).find("string").text();

                        var iDelTagStartPosition = strTeaserText.indexOf("<del>");
                        var iFinishBetDateTextStartPosition = iDelTagStartPosition + 5; //длина тэга "<del>"
                        var iDelTagEndPosition = strTeaserText.indexOf("</del>");

                        var strFinishBetDate = strTeaserText.substring(iFinishBetDateTextStartPosition, iDelTagEndPosition);
                        $("#SportEventTeaserFinishBetDate").html(strFinishBetDate);

                        objTeaserContainer.html(strTeaserText.substring(iDelTagEndPosition + 6)); //длина тега "</del>"
                        objTeaserContainer.fadeIn();
                    });
                },
                error: function(data) {
                    alert("Ошибка обращения к веб-сервису");
                }
            });
        };

        CarouselControlClass.prototype.SetActiveItem = function(iNewActiveItemPosition) {
            this.objThumbnailsList.find("li:eq(" + iNewActiveItemPosition + ")").addClass("active");
        };

        CarouselControlClass.prototype.FindActiveItem = function() {
            var objActiveItem = new Object();
            if (0 < this.objThumbnailsList.children(".active").size()) {
                objActiveItem = this.objThumbnailsList.children(".active :first");
            }
            else
                objActiveItem = this.objThumbnailsList.children(":first");

            return objActiveItem;
        };

        CarouselControlClass.prototype.ClearItemsSelection = function() {
            this.objThumbnailsList.find("li").each(function() {
                $(this).removeClass("active");
            });
        };

        CarouselControlClass.prototype.HighlightActiveItem = function() {
            this.iNewActiveItemOffsetLeft = this.objNewActiveItem.position().left;
            this.objSliderContainer.css("left", 0 - this.GetSliderContainerLeftOffset());
            this.objActiveTeaserFrame.css("left", this.iNewActiveItemOffsetLeft);
        };

        CarouselControlClass.prototype.GetSliderContainerLeftOffset = function() {
            var iSliderContainerOffsetLeft = new Number();
            if (this.objViewPortContainer.width() < (this.iNewActiveItemOffsetLeft + this.iThumbnailWidth)) {
                if (this.iNewActiveItemOffsetLeft < this.objViewPortContainer.width())
                    iSliderContainerOffsetLeft = this.iThumbnailWidth - (this.objViewPortContainer.width() - this.iNewActiveItemOffsetLeft);
                else
                    iSliderContainerOffsetLeft = (this.iNewActiveItemOffsetLeft + this.iThumbnailWidth) - this.objViewPortContainer.width();
            }
            else {
                if (this.iNewActiveItemOffsetLeft < 0)
                    iSliderContainerOffsetLeft = this.iNewActiveItemOffsetLeft;
            }

            return iSliderContainerOffsetLeft;
        };

        CarouselControlClass._initialized = true;
    }
}

var CarouselControl = new CarouselControlClass();