﻿/// <reference name="MicrosoftAjax.js"/>



Type.registerNamespace("TUI.WebControls");



TUI.WebControls.ImageSliderSlidingDirection = function() {}
TUI.WebControls.ImageSliderSlidingDirection.prototype =
{
    horizontal: 0,
    vertical: 1
}
TUI.WebControls.ImageSliderSlidingDirection.registerEnum('TUI.WebControls.ImageSliderSlidingDirection');



TUI.WebControls.ImageSlider = function(element)
{
    TUI.WebControls.ImageSlider.initializeBase(this, [element]);
    this._selectedImageChangingSequenceComplete = false;
    this._firstInitialLoadFinished = false;
    this._staticBrowsing = null;
    this._startupPositionIdentifier = -1;
    this._currentImageIndex = -1;
    this._imageDimension = -1;
    this._imageDistance = -1;
    this._totalImagesCount = 0;
    this._intervalID = -1;
    this._$list = null;
    this._$listItems = null;
    this._clientImageType = null;
    this._slidingDirection = TUI.WebControls.ImageSliderSlidingDirection.horizontal;
}
TUI.WebControls.ImageSlider.prototype =
{
    start: function() {
        var startupPositionIdentifier = this.get_startupPositionIdentifier() != -1 ? this.get_startupPositionIdentifier() : null;
        this.getImages(this.get_maximumVisibleImages(), startupPositionIdentifier, true, Function.createDelegate(this, this.callbackGetStarImagesInitial), Function.createDelegate(this, this.callbackGetStarImagesFailed));
    },
    getImages: function(length, startPositionIdentifier, includeStartPositionImage, callbackSucceededDelegate, callbackFailedDelegate) {
        var ajaxDelegate = this.get_ajaxHandlerMethodDelegate();
        ajaxDelegate(this.get_ajaxHandlerImageSourceIdentifiers(), length, startPositionIdentifier, includeStartPositionImage, callbackSucceededDelegate, callbackFailedDelegate);
    },
    add_selectedImageChanging: function(handler) {
        this.get_events().addHandler('selectedImageChanging', handler);
    },
    remove_selectedImageChanging: function(handler) {
        this.get_events().removeHandler(handler);
    },
    add_selectedImageChanged: function(handler) {
        this.get_events().addHandler('selectedImageChanged', handler);
    },
    remove_selectedImageChanged: function(handler) {
        this.get_events().removeHandler(handler);
    },
    add_imageRetrievalFailed: function(handler) {
        this.get_events().addHandler('imageRetrievalFailed', handler);
    },
    remove_imageRetrievalFailed: function(handler) {
        this.get_events().addHandler(handler);
    },
    startSlideShow: function(delay) {
        var expression = String.format("$($get('{0}')).find('div.button-next').click()", this.get_id());
        this._intervalID = window.setInterval(expression, delay ? delay : 5500);
        $(this.get_element()).find('div.button-next').click();
    },
    pauseSlideShow: function() {
        window.clearInterval(this._intervalID);
        this._intervalID = -1;
    },
    onSelectedImageChanging: function(e) {
        if (!this.get_selectedImageChangingSequenceComplete()) {
            /*
            * For both dynamic and static browsing, the whole sequence of changing the selected
            * image (including possible animation and image preloads) must be complete in order 
            * to accept new clicks from the user.
            */
            return;
        }

        var 
            targetImageIndex,
            slidingDistancePixels,
            direction;

        if (e.target.tagName.toLowerCase() == 'img') {
            // A click directly on a thumbnail image
            targetImageIndex = this.get_$listItemImages().index(e.target);
        }
        else {
            // A click on the next/previous buttons
            targetImageIndex = this.get_currentImageIndex() + ($(e.target).hasClass('button-previous') ? -1 : 1);
            if (this.get_staticBrowsing()) {
                // Prevent out of bounds browsing
                var imagesLength = this.get_$listItemImages().length;
                if ((targetImageIndex > (imagesLength - 1) || targetImageIndex < 0) && ((imagesLength >= 8 && this.get_isTemaOrBlueSite()) || (imagesLength >= 12 && !this.get_isTemaOrBlueSite()))) {
                    return;
                }
                if ((imagesLength < 8) || (imagesLength < 12 && !this.get_isTemaOrBlueSite())) {
                    if (targetImageIndex > (imagesLength - 1)) {
                        targetImageIndex = 0;
                    }
                    else if (targetImageIndex < 0) {
                        targetImageIndex = imagesLength - 1;
                    }
                }
            }
        }
        if (targetImageIndex == this.get_currentImageIndex()) {
            // The image that is already selected was clicked - abort
            return;
        }
        this.set_selectedImageChangingSequenceComplete(false);

        // Trigger the selectedImageChanging event, if handlers attached
        var handler = this.get_events().getHandler('selectedImageChanging');
        if (handler) { handler(this, Sys.EventArgs.Empty); }

        this.set_slidingDistanceImagesCount(targetImageIndex - this.get_currentImageIndex());
        slidingDistancePixels = this.get_slidingDistanceImagesCount() * this.get_imageDistance();
        direction = (this.get_slidingDistanceImagesCount() > 0 ? 'left' : 'right');
        $(this.get_currentImage()).removeClass('selected');

        if (this.get_staticBrowsing()) {
            // Simple browsing mode
            // Change the currentImageIndex
            var $currentImageArrow = $(this.get_element()).find('div.current-image-arrow');

            if (this.get_slidingDirection() == TUI.WebControls.ImageSliderSlidingDirection.horizontal) {
                $currentImageArrow.css('left', $currentImageArrow.get(0).offsetLeft + slidingDistancePixels);
            }
            else {
                $currentImageArrow.css('top', $currentImageArrow.get(0).offsetTop + slidingDistancePixels);
            }

            this.set_currentImageIndex(targetImageIndex);
            this.onSelectedImageChanged();
        }
        else {
            // Advanced browsing mode
            // Slide the selected image into view
            var animationProperties =
                this.get_slidingDirection() == TUI.WebControls.ImageSliderSlidingDirection.horizontal ?
                { left: (direction == 'left' ? '-=' : '+=') + Math.abs(slidingDistancePixels)} :
                { top: (direction == 'left' ? '-=' : '+=') + Math.abs(slidingDistancePixels) };

            this.get_$list().animate
            (
                animationProperties,
                500,
                Function.createDelegate(this, function() {
                    // Animation effect when sliding clicked image into place has finished, now start preloading periphery images
                    var positionIdentifier = this.get_$listItemImages().filter(this.get_slidingDistanceImagesCount() > 0 ? ':last' : ':first').get(0).control.get_positionIdentifier();
                    this.getImages(this.get_slidingDistanceImagesCount(), positionIdentifier, false, Function.createDelegate(this, this.callbackGetStarImages), null);
                })
            );
        }
    },
    onSelectedImageChanged: function() {
        $(this.get_currentImage()).addClass('selected');

        // Trigger the selectedImageChanged event, if handlers attached
        var handler = this.get_events().getHandler('selectedImageChanged');
        if (handler) { handler(this, Sys.EventArgs.Empty); }

        this.set_selectedImageChangingSequenceComplete(true);
    },
    onImageRetrievalFailed: function() {
        // Trigger the selectedImageChanged event, if handlers attached
        var handler = this.get_events().getHandler('imageRetrievalFailed');
        if (handler) { handler(this, Sys.EventArgs.Empty); }
    },
    callbackGetStarImagesFailed: function() {
        this.onImageRetrievalFailed();
    },
    callbackGetStarImages: function(data) {
        var 
            result = Sys.Serialization.JavaScriptSerializer.deserialize(data),
            direction = result.length > 0 ? 'left' : 'right';

        this.set_totalImagesCount(result.totalItems);

        if (this.get_totalImagesCount() == 0) {
            this.callbackGetStarImagesFailed();
            return;
        }

        this.createAndInsertLoadedImages(result.images, direction);
        this.removeSuperflousImages(result.length, direction);
        this.onSelectedImageChanged();
    },
    callbackGetStarImagesInitial: function(data) {
        var 
            result = Sys.Serialization.JavaScriptSerializer.deserialize(data),
            direction = result.length > 0 ? 'left' : 'right';

        this.set_totalImagesCount(result.totalItems);
        this.set_staticBrowsing(this.get_totalImagesCount() <= this.get_maximumVisibleImages());

        if (this.get_totalImagesCount() == 0) {
            this.callbackGetStarImagesFailed();
            return;
        }

        // Add the loaded images
        if (this.get_staticBrowsing()) {
            if (this.get_totalImagesCount() < 8 && this.get_totalImagesCount() > 3 && this.get_isTemaOrBlueSite()) {
                this.createAndInsertLoadedImages(result.images, 'lessThanEight');
            }
            else {
                this.createAndInsertLoadedImages(result.images.slice(0, Math.floor(this.get_totalImagesCount() / 2)), 'right');
                this.createAndInsertLoadedImages(result.images.slice(Math.floor(this.get_totalImagesCount() / 2), this.get_totalImagesCount()), 'left');
            }
        }
        else {
            this.createAndInsertLoadedImages(result.images, direction);
        }

        if (this.get_staticBrowsing() || this.get_firstInitialLoadFinished()) {
            var 
                $imageSlider = $(this.get_element()),
                preselectedImageIndex = 0;

            // Both handlers has finished loading images or only one load neccessary because of small number of images
            $(this.get_element()).find('div.button-previous, div.button-next').click(Function.createDelegate(this, this.onSelectedImageChanging));
            if (this.get_staticBrowsing()) {
                if (this.get_startupPositionIdentifier() != -1) {
                    // Determine the index of the image that should be preselected
                    var $listItemImages = this.get_$listItemImages();
                    for (var i = 0; i < $listItemImages.length; i++) {
                        if ($listItemImages.get(i).control.get_positionIdentifier() == this.get_startupPositionIdentifier()) {
                            preselectedImageIndex = i;
                            break;
                        }
                    }
                    // Adjust position of the current photo arrow icon
                    var 
                        $photoArrow = $imageSlider.find('div.current-image-arrow'),
                        photoArrowOffset = this.get_slidingDirection() == TUI.WebControls.ImageSliderSlidingDirection.horizontal ? $photoArrow.get(0).offsetLeft : $photoArrow.get(0).offsetTop,
                        position = photoArrowOffset - Math.floor($listItemImages.length / 2) * this.get_imageDistance() + preselectedImageIndex * this.get_imageDistance();
                    if (this.get_totalImagesCount() < 8 && this.get_totalImagesCount() > 3 && this.get_isTemaOrBlueSite()) {
                        if (this.get_slidingDirection() == TUI.WebControls.ImageSliderSlidingDirection.horizontal) {
                            if (this.get_totalImagesCount() % 2 == 0) {
                                position += parseInt(this.get_$listItems().eq(0).css('width')) / 2;
                            }
                        }
                        else {
                            var differenceBetweenLiAndImageHeight = parseInt(this.get_$listItems().eq(0).css('height')) - parseInt(this.get_imageDimension());
                            position = parseInt(this.get_$list().parent().css('top')) + parseInt(this.get_$listItems().eq(0).css('padding-top')) + Math.floor((parseInt(this.get_$listItems().eq(0).css('height')) / 2)) - differenceBetweenLiAndImageHeight + "px";
                        }
                    }

                    if (this.get_slidingDirection() == TUI.WebControls.ImageSliderSlidingDirection.horizontal) {
                        $photoArrow.css('left', position);
                    }
                    else {
                        $photoArrow.css('top', position);
                    }
                }
                else {
                    preselectedImageIndex = Math.floor(this.get_$listItems().length / 2);
                }
            }
            else {
                preselectedImageIndex = Math.floor((2 * this.get_maximumVisibleImages() - 1) / 2);
            }
            this.set_currentImageIndex(preselectedImageIndex);
            this.onSelectedImageChanged();
        }
        else {
            // Tell the other handler that the first load has finished
            this.set_firstInitialLoadFinished(true);

            // Get remaining images to the left
            var startupPositionIdentifier = this.get_startupPositionIdentifier() != -1 ? this.get_startupPositionIdentifier() : null;
            this.getImages(-(this.get_maximumVisibleImages() - 1), startupPositionIdentifier, false, Function.createDelegate(this, this.callbackGetStarImagesInitial), Function.createDelegate(this, this.callbackGetStarImagesFailed));
        }
    },
    createAndInsertLoadedImages: function(images, direction) {
        var 
            newListItemStr = "<li><img /></li>",
            $newListItem,
            position = null;

        // Create and insert the loaded star images
        var 
            $listItems = this.get_$listItems(),
            currentImage,
            currentImageControl;

        for (i = 0; i < images.length; i++) {
            $newListItem = $(newListItemStr);
            $newListItem.css('visibility', 'hidden');
            if (direction == 'left' || direction == 'lessThanEight') {
                this.get_$list().append($newListItem);
            }
            else {
                this.get_$list().prepend($newListItem);
            }
            currentImage = $newListItem.find('img').get(0);
            currentImageControl = $create(this.get_clientImageType(), images[i], null, null, currentImage);
            currentImage.src = currentImageControl.get_thumbnailImageUrl();
            currentImage.title = currentImageControl.get_thumbnailImageTitle();
            if (direction == 'left') {
                if (position == null) {
                    if ($listItems.length > 0) {
                        var lastImageOffset = this.get_slidingDirection() == TUI.WebControls.ImageSliderSlidingDirection.horizontal ? $listItems.filter(':last').get(0).offsetLeft : $listItems.filter(':last').get(0).offsetTop;
                        position = lastImageOffset + this.get_imageDistance();
                    }
                    else {
                        position = -Math.ceil(this.get_imageDimension() / 2);
                    }
                }
                else {
                    position += this.get_imageDistance();
                }
            }
            else if (direction == 'right') {
                if (position == null) {
                    if ($listItems.length > 0) {
                        var firstImageOffset = this.get_slidingDirection() == TUI.WebControls.ImageSliderSlidingDirection.horizontal ? $listItems.filter(':first').get(0).offsetLeft : $listItems.filter(':first').get(0).offsetTop;
                        position = firstImageOffset - this.get_imageDistance();
                    }
                    else {
                        position = -Math.ceil(this.get_imageDimension() / 2) - this.get_imageDistance();
                    }
                }
                else {
                    position -= this.get_imageDistance();
                }
            }
            else {
                if (position == null) {
                    if ($listItems.length > 0) {
                        var firstImageOffset = this.get_slidingDirection() == TUI.WebControls.ImageSliderSlidingDirection.horizontal ? $listItems.filter(':first').get(0).offsetLeft : $listItems.filter(':first').get(0).offsetTop;
                        position = firstImageOffset - this.get_imageDistance();
                    }
                    else {
                        //vertical list, fix position
                        if (this.get_slidingDirection() != TUI.WebControls.ImageSliderSlidingDirection.horizontal) {
                            position = -184;
                        }
                        //horizontal list calculate position depending on number of images.
                        else {
                            var newPosition = /*(this.get_$list().parent().outerWidth() / 2)*/-((this.get_totalImagesCount() / 2) * this.get_$listItems().eq(0).outerWidth());
                            var differenceBetweenImgAndLiWidth = this.get_$listItems().eq(0).outerWidth() - this.get_imageDimension();
                            newPosition += Math.ceil((differenceBetweenImgAndLiWidth / 2));
                            position = newPosition;
                        }

                    }
                }
                else {
                    position += this.get_imageDistance();
                }
            }

            if (this.get_slidingDirection() == TUI.WebControls.ImageSliderSlidingDirection.horizontal) {
                $newListItem.css('left', position);
            }
            else {
                $newListItem.css('top', position);
            }

            $newListItem.css('visibility', 'visible');
            $addHandler(currentImage, 'click', Function.createDelegate(this, this.onSelectedImageChanging));
        }
    },
    removeSuperflousImages: function(length, direction) {
        // Remove invisible superflous images
        var removeFilterExpression;
        if (direction == 'left') {
            removeFilterExpression = String.format(':lt({0})', Math.abs(length));
        }
        else {
            removeFilterExpression = String.format(':gt({0})', this.get_$listItems().length - Math.abs(length) - 1);
        }
        this.get_$listItems().filter(removeFilterExpression).remove();
    },
    get_currentImageIndex: function() {
        return this._currentImageIndex;
    },
    set_currentImageIndex: function(value) {
        this._currentImageIndex = value;
    },
    get_selectedImageChangingSequenceComplete: function() {
        return this._selectedImageChangingSequenceComplete;
    },
    set_selectedImageChangingSequenceComplete: function(value) {
        this._selectedImageChangingSequenceComplete = value;
    },
    get_slidingDistanceImagesCount: function() {
        return this._slidingDistanceImagesCount;
    },
    set_slidingDistanceImagesCount: function(value) {
        this._slidingDistanceImagesCount = value;
    },
    get_currentImage: function() {
        var $listImages = this.get_$listItemImages();
        return $listImages.length > 0 ? $listImages.get(this.get_currentImageIndex()) : null;
    },
    get_$list: function() {
        // TODO: This property might be to expensive, consider caching the jQuery object
        return $(this.get_element()).find('div.image-list-container ol');
    },
    get_$listItems: function() {
        // TODO: This property might be to expensive, consider caching the jQuery object
        return $(this.get_element()).find('div.image-list-container li');
    },
    get_$listItemImages: function() {
        // TODO: This property might be to expensive, consider caching the jQuery object
        return $(this.get_element()).find('div.image-list-container img');
    },
    get_imageDistance: function() {
        if (this._imageDistance == -1) {
            var $listItems = this.get_$listItems();
            if ($listItems.length == 0) {
                var err = Error.invalidOperation('It is an error trying to access property imageDistance before any images have been loaded into the list.');
                throw err;
            }
            this._imageDistance =
                this.get_slidingDirection() == TUI.WebControls.ImageSliderSlidingDirection.horizontal ?
                $listItems.outerWidth() : $listItems.outerHeight();
        }
        return this._imageDistance;
    },
    get_imageDimension: function() {
        if (this._imageDimension == -1) {
            var $listItemImages = this.get_$listItemImages();
            if ($listItemImages.length == 0) {
                var err = Error.invalidOperation('It is an error trying to access property imageDimension before any images have been loaded into the list.');
                throw err;
            }
            this._imageDimension =
                this.get_slidingDirection() == TUI.WebControls.ImageSliderSlidingDirection.horizontal ?
                $listItemImages.outerWidth() : $listItemImages.outerHeight();
        }
        return this._imageDimension;
    },
    get_isTemaOrBlueSite: function() {
        return this._isTemaOrBlueSite;
    },
    set_isTemaOrBlueSite: function(value) {
        this._isTemaOrBlueSite = value;
    },
    get_maximumVisibleImages: function() {
        return this._maximumVisibleImages;
    },
    set_maximumVisibleImages: function(value) {
        this._maximumVisibleImages = value;
    },
    get_totalImagesCount: function() {
        return this._totalImagesCount;
    },
    set_totalImagesCount: function(value) {
        this._totalImagesCount = value;
    },
    get_ajaxHandlerMethodDelegate: function() {
        return this._ajaxHandlerMethodDelegate;
    },
    set_ajaxHandlerMethodDelegate: function(value) {
        this._ajaxHandlerMethodDelegate = value;
    },
    get_ajaxHandlerImageSourceIdentifiers: function() {
        return this._ajaxHandlerImageSourceIdentifiers;
    },
    set_ajaxHandlerImageSourceIdentifiers: function(value) {
        this._ajaxHandlerImageSourceIdentifiers = value;
    },
    get_firstInitialLoadFinished: function() {
        return this._firstInitialLoadFinished;
    },
    set_firstInitialLoadFinished: function(value) {
        this._firstInitialLoadFinished = value;
    },
    get_startupPositionIdentifier: function() {
        return this._startupPositionIdentifier;
    },
    set_startupPositionIdentifier: function(value) {
        this._startupPositionIdentifier = value;
    },
    get_staticBrowsing: function() {
        if (this._staticBrowsing == null) {
            var err = Error.invalidOperation('Property staticBrowsing cannot be accessed until after the initial image load has completed.');
            throw err;
        }
        return this._staticBrowsing;
    },
    set_staticBrowsing: function(value) {
        this._staticBrowsing = value;
    },
    get_clientImageType: function() {
        return this._clientImageType;
    },
    set_clientImageType: function(value) {
        if (!value.implementsInterface(TUI.WebControls.ICircularListImage)) {
            var err = Error.notImplemented(String.format('The ImageList has been set to create internal image objects of type {0} but this type does not implement interface TUI.WebControls.ICircularListImage as required', value.getName()));
            throw err;
        }
        this._clientImageType = value;
    },
    get_slideShowRunning: function() {
        return this._intervalID != -1;
    },
    get_slidingDirection: function() {
        return this._slidingDirection;
    },
    set_slidingDirection: function(value) {
        this._slidingDirection = value;
    }
}
TUI.WebControls.ImageSlider.registerClass('TUI.WebControls.ImageSlider', Sys.UI.Control);




if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();