/*jslint browser: true, cap: false, nomen: true, passfail: false, plusplus:true, undef: false, vars: true, unparam: true, white: true */
/*global window, jQuery, ko, _ */
(function ($) {
    "use strict";

    $.ajaxSetup({
        cache: false,
        dataType: 'json'
    });

    var megaBrowserViewmodel = {
        currentGallery: ko.observable({}),
        currentIndex: ko.observable(0),
        currentPage: ko.observable(1),
        displayItems: ko.observableArray(),
        firstUrl: '',
        imagesPath:'',
        isNextPageEnabled: true,
        isPreviousPageEnabled: false,
        items: [],
        itemsCount: ko.observable(0),
        itemsPerPage: 5,
        pageCount: ko.observable(0),
        thumbsPath: '',

        getCurrentIndex: function () {
            return ((this.currentPage() - 1) * this.itemsPerPage);
        },
        getJSON: function () {
            var that = this;
            return $.getJSON($.rx.megaBrowserRoot + 'data/browse.json').then(function (data) {
                that.imagesPath = data.megabrowser.imagesPath;
                that.thumbsPath = data.megabrowser.thumbsPath;
                that.setItems(data);
                that.setCurrentGallery();
            });
        },
        getUrl: function (fragment, isForThumb) {
            if(!fragment) {
                return null;
            }
            if(fragment.indexOf($.rx.megaBrowserRoot) === 0) {
                return (isForThumb) ? fragment : fragment.replace(this.thumbsPath, this.imagesPath);
            }
            else if((fragment.indexOf($.rx.megaBrowserRoot) === -1) &&
                (fragment.indexOf('http://') === 0)) {
                return fragment;
            }
            else{
                return (isForThumb) ? $.rx.megaBrowserRoot + this.thumbsPath + fragment :
                $.rx.megaBrowserRoot + this.imagesPath + fragment;
            }
        },
        getSlice: function () {
            return this.items.slice(this.currentIndex(),
                (this.currentIndex() + this.itemsPerPage));
        },
        setCurrentGallery: function (id) {
            if(!id){
                id = this.items[0].id;
            }
            var that = this;
            var result = _(this.items).select(function (gallery) {
                return (gallery.id === id);
            });
            if (_(result).isArray && (result.length > 0)) {
                var o = result[0];
                $.each(o.images, function(index, image){
                    if(image.thumb && (image.thumb.indexOf('http://') !== 0)) {
                        o.images[index].thumb = that.getUrl(image.thumb, true);
                    }

                });
                this.currentGallery(o);
                this.firstUrl = this.getUrl(this.currentGallery().images[0].thumb, false);
            }
        },
        setDisplayItems: function () {
            var that = this;
            var slice = this.getSlice();
            this.displayItems.remove(function (item) {
                return item;
            });
            _(slice).each(function (item, index) {
                item.isFirstDisplayItem = (index === 0);
                item.isLastDisplayItem = (index === (slice.length - 1));
                item.isNextPageEnabled = that.isNextPageEnabled;
                item.isPreviousPageEnabled = that.isPreviousPageEnabled;
                that.displayItems.push(item);
            });
        },
        setEnabled: function () {
            this.isNextPageEnabled = (this.currentPage() < this.pageCount());
            this.isPreviousPageEnabled = (this.currentPage() > 1);
        },
        setItems: function (data) {
            this.items = data.megabrowser.galleries;
            this.currentGallery(this.items[0]);
            this.currentIndex(0);
            this.currentPage(1);
            this.itemsCount(this.items.length);
            this.pageCount(Math.ceil(this.itemsCount() / this.itemsPerPage));
            this.setEnabled();
            this.setDisplayItems();
        },
        setNextPage: function () {
            if (!this.isNextPageEnabled) {
                return false;
            }
            this.currentPage(this.currentPage() + 1);
            this.setEnabled();
            if (this.currentPage() > this.pageCount()) {
                this.currentPage(this.pageCount());
            }
            this.currentIndex(this.getCurrentIndex());
            this.setDisplayItems();
            return true;
        },
        setPreviousPage: function () {
            if (!this.isPreviousPageEnabled) {
                return false;
            }
            this.currentPage(this.currentPage() - 1);
            this.setEnabled();
            if (this.currentPage() < 1) {
                this.currentPage(1);
            }
            this.currentIndex(this.getCurrentIndex());
            this.setDisplayItems();
            return true;
        },
        triggerAfterAdd: function (item, iterator) {
            $(window.document).trigger('afterAdd', [item, iterator]);
        }
    };

    ko.applyBindings(megaBrowserViewmodel);
    
    var setMegaImage = function (url) {
        var flow = $('#MegaImageFlow');
        var img = new Image();
        flow.addClass('Loading').empty();
        $(img).load(function () {
            var img = this;
            $(img).hide();

            flow.animate({
                height: img.height
            },
            {
                duration: 1000,
                complete: function () {
                    flow.removeClass('Loading').append(img);
                    $(img).css('display', 'inline').fadeIn();
                    setMegaImageArrowButtons(img, url);
                }
            });
        })
        .error(function () {
            })
        .attr('src', url);
    };
    
    var setMegaImageArrowButtons = function(img, url) {
        var images = _(megaBrowserViewmodel.currentGallery().images).pluck('thumb');
        var imageIndex = _(images).indexOf(url.replace('browse/', 'browse/thumbs/'));

        var anchorFlow = $('<a href="#"></a>');
        anchorFlow.click(function(event){
            event.preventDefault();
            var i = ((imageIndex + 1) >= images.length) ? 0 : ++imageIndex;
            var uri = images[i].replace('browse/thumbs/','browse/');
            setMegaImage(uri);
        });

        $(img).wrap(anchorFlow);
    };

    var setMegaThumbs = function () {
        var carousel = $('#MegaCarouselFlow');
        carousel.tinycarousel({
            display: 8
        });

        $('a.MegaThumb', carousel).click(function (event) {
            event.preventDefault();
            var a = $(this);
            var url = megaBrowserViewmodel.getUrl(a.attr('data-imageurl'), false);
            setMegaImage(url);
        });

        $("a[rel^='prettyPhoto']", carousel).prettyPhoto({
            deeplinking: false
        });

        if (megaBrowserViewmodel.firstUrl) {
            setMegaImage(megaBrowserViewmodel.firstUrl);
        }
    };

    var readyMegaGallery = function () {
        megaBrowserViewmodel.getJSON().then(function (data) {
            setMegaThumbs();
        });
    };
    
    var readyMegaBabble = function() {
        $.ajax({
            dataType:'xml',
            type:'GET',
            url:$.rx.megaBrowserRoot + 'rest/babble'
        }).then(function (data, status, jqXHR) {
            var flow = $('#MegaBabbleAjaxBlock');
            flow.html(jqXHR.responseText);
        });
    };

    $(window.document).bind('afterAdd',
        function (event, item, iterator) {
            var a = null;

            var handlerForGallery = function (event) {
                event.preventDefault();
                a = $(item);
                megaBrowserViewmodel.setCurrentGallery(a.attr('id'));
                setMegaThumbs();
            };

            var handlerForNavigation = function (event) {
                event.preventDefault();
                a = $(item);
                switch (a.attr('id')) {
                    case 'Back':
                        megaBrowserViewmodel.setPreviousPage();
                        break;

                    case 'Forward':
                        megaBrowserViewmodel.setNextPage();
                        break;
                }
            };

            if ($(item).hasClass('GalleryTitle')) {
                a = $(item);
                a.unbind('click', handlerForGallery);
                a.bind('click', handlerForGallery);
            }

            if ($(item).hasClass('Navigation')) {
                a = $(item);
                a.unbind('click', handlerForNavigation);
                a.bind('click', handlerForNavigation);
            }
        });

    $(window.document).ready(function () {
        var flow = $('#MegaImageFlow');
        if (flow.length > 0) {
            readyMegaGallery();
        }

        flow = $('#MegaBabbleAjaxBlock');
        if (flow.length > 0) {
            readyMegaBabble();
        }
        
        flow = $('#IndexList');
        if (flow.length > 0) {
            window.setTimeout(function(){
                window.location.href = $.rx.megaBrowserRoot + 'browse';
            }, 2000);
        }
    });
} (jQuery));

