// Prohlizec galerie
var GalleryBrowser = function(config)
{
    var that = this;

    // pomocna promenna pro pozouvani
    this.delta = 0;

    // IMG s velkym obrazkem
    this.fullImg = $("#"+config['big_image_id']);
    // kontejner pro nahledy
    this.thumbs = $("#"+config['thumbnails_id']);
    // vsechny nahledy - ukazatele
    this.itemsPtrs = $("#"+config['thumbnails_id']+" ."+config['thumbnail_class']);
    // pod jakym indexem je zvyrazneny aktualni obrazek
    this.currentIndex = config['current_index'];
    // trida pro oznaceny thumbnail
    this.selectedClass = config['selected_class'];
    // trida elementu, ve kterem je cesta k velkemu obrazku
    this.fullimageClass = config['fullimage_class'];
    // sirka jedne polozky, mezi kterymi se listuje a posouva
    this.itemWidth = config['item_width'];
    // interval kroku animace
    this.delay = config['animation_delay'];
    // rychlost animace
    this.speed = config['animation_speed'];
    // vsechnby nahledy HTML
    this.itemsCount = this.itemsPtrs.length;
    this.items = new Array(this.itemsCount);
    this.itemsPtrs.each(function(i, o) {
        that.items[i] = $( $('<div></div>').html($(o).clone()) ).html();
    });
    // kliknuti na obrazek
    this.itemsPtrs.live('click', function(e) {
        that.SlideTo(this);
        return false;
    });
    // pocet viditelnych pozic
    this.visibleCount = config['visible_count'];
    // kolik polozek se zkutecne zobrazi (muze byt mene nez visibleCount, kdyz je mene polozek nez pozic
    this.maxCount = Math.min(this.items.length, this.visibleCount);
    // pokud je obrazku vic nez je viditelnych pozic, budeme ve scrollovacim rezimu
    this.scrollable = this.visibleCount < this.items.length;

    // kdyz je jich akorat, nebudeme slidovat
    if(this.itemsCount <= this.visibleCount) this.currentIndex = 0;

    // text mezi polozkami
    this.htmlBetween = config['html_between'] ? config['html_between'] : '';
    // text pred polozkami
    this.htmlBefore = config['html_before'] ? config['html_before'] : '';
    // text za polozkami
    this.htmlAfter = config['html_after'] ? config['html_after'] : '';

    // callback funkce pri zvoleni thumbnailu
    this.chosenCallback = config['onchosen'];

    // LEFT | RIGHT ... ze ktere strany se zobrazi obrazek navic
    this.showMore = null;
    // pomocna promenna udrzujici informaci o tom, ze se sliduje
    this.sliding = false;

    // div s progressbarem pri nacitani velkeho obrazku
    if(config['loader_image'] || config['loader_div_id'])
    {
        this.loaderDiv = document.createElement('div');
        $(this.loaderDiv).css({'position': 'absolute'});
        if(config['loader_div_id'])
        {
            $(this.loaderDiv).attr({'id' : config['loader_div_id']});
        }
        if(config['loader_image'])
        {
            $(this.loaderDiv).css({'background': 'url("'+config['loader_image']+'") center center no-repeat'});
        }
    }

    // navesime na vsechny elementy pro 'dalsi' a 'predchozi' udalost kliknuti
    if(config['next_class'])
    {
        $("."+config['next_class']).live('click', function() {
            var next = that.currentIndex < that.itemsCount-1 ? that.currentIndex+1 : 0;
            that.SlideTo($(that.items[next])[0]);
            return false;
        });
        
        $(document).keydown(function(event){
          if (event.keyCode == 39){
            var next = that.currentIndex < that.itemsCount-1 ? that.currentIndex+1 : 0;
            that.SlideTo($(that.items[next])[0]);
            return false;          
          }
        });        
    }
    if(config['previous_class'])
    {
        $("."+config['previous_class']).live('click', function() {
            var prev = that.currentIndex > 0 ? that.currentIndex-1 : that.itemsCount-1;
            that.SlideTo($(that.items[prev])[0]);
            return false;
        });
        
        $(document).keydown(function(event){
          if (event.keyCode == 37){
            var prev = that.currentIndex > 0 ? that.currentIndex-1 : that.itemsCount-1;
            that.SlideTo($(that.items[prev])[0]);
            return false;         
          }
        });         
    }


    // Funkce nascrolluje na predany obrazek
    this.SlideTo = function(obj)
    {
        if(that.sliding) return;
        var selectedIndex = -1;
        for(var i=0; i<that.itemsCount; i++)
        {
            if($(that.items[i]).attr('id') == obj.id)
            {
                selectedIndex = i;
                break;
            }
        }
        var moveBy = selectedIndex - that.currentIndex;
        // byl-li nalezen index a neni to aktualni index, tak budeme rolovat
        if(selectedIndex > -1 && selectedIndex != that.currentIndex)
        {
            that.ShowLoader();
            
            that.sliding = true;
            // oznacime novy thumbnail
            var iSelected = $(that.items[selectedIndex]);
            iSelected.addClass(that.selectedClass);
            that.items[selectedIndex] = $( $('<div></div>').html(iSelected) ).html();
            // odznacime stary thumbnail
            var iNotSelected = $(that.items[that.currentIndex]);
            iNotSelected.removeClass(that.selectedClass);
            that.items[that.currentIndex] = $( $('<div></div>').html(iNotSelected) ).html();

            // nacteme aktualni obrazek
            var chosen = $(that.items[selectedIndex]);
            var url = chosen.children("." + that.fullimageClass).html();
            var newImg = new Image();
            $(newImg).load(function() {
                that.fullImg.attr({'src': url});
                that.HideLoader();
            });
            $(newImg).error(function() { that.HideLoader(); });
            $(newImg).attr({'src': url});

            if(that.scrollable)
            {
                // spustime animaci
                var totalPixels = moveBy*that.itemWidth;
                if(totalPixels < 0) totalPixels = -totalPixels;
                var pixelsLeft = totalPixels;
                recache = true;
                var slideInterval = window.setInterval(function() {

                    pixelsLeft = Math.round(pixelsLeft/that.speed)-0.5;
                    if(moveBy > 0)
                    {
                        that.showMore = 'RIGHT';
                        if(totalPixels-pixelsLeft >= that.itemWidth)
                        {
                            that.items.push(that.items.shift());
                            totalPixels -= that.itemWidth;
                            recache = true;
                        }
                        that.delta = (-(totalPixels - pixelsLeft))-3;
                    }
                    else
                    {
                        that.showMore = 'LEFT';
                        if(totalPixels-pixelsLeft >= that.itemWidth)
                        {
                            that.items.unshift(that.items.pop());
                            totalPixels -= that.itemWidth;
                            recache = true;
                        }
                        that.delta = totalPixels - pixelsLeft - that.itemWidth;
                    }

                    // ukoncime animaci ukoncenim intervalu, pokud jsme se presunuli az na konec
                    if(totalPixels <= 0)
                    {
                        recache = true;
                        //alert('moved');
                        window.clearInterval(slideInterval);
                        that.Choose();
                        that.delta = 0;
                        that.showMore = null;
                        that.sliding = false;
                    }

                    // obnovime pohled
                    that.Display(recache);
                    recache = false;

                }, that.delay);
            }
            else
            {
                that.currentIndex = that.currentIndex + moveBy;
                that.Choose();
                that.delta = 0;
                that.showMore = null;
                that.Display(true);
                that.sliding = false;
            }
        }
    };


    // Funkce zobrazi prvnich maxCount nahledu v kontejneru
    this.Display = function(recache)
    {
        if(recache)
        {
            var content = that.htmlBefore;
            var itemHtml = '';
            // pokud mame zobrazit navic jeden vlevo, zobrazime ten posledni, ktery se tam potom stejne presune
            if(that.showMore == 'LEFT')
            {
                itemHtml = $(that.items[that.itemsCount-1]);
                content += $( $('<div></div>').html(itemHtml) ).html();
                content += that.htmlBetween;
            }
            // zobrazeni regulernich
            for(var i=0; i<that.maxCount; i++)
            {
                itemHtml = $(that.items[i]);

                content += $( $('<div></div>').html(itemHtml) ).html();
                if(i < that.maxCount-1)
                {
                    content += that.htmlBetween;
                }
            }
            if(this.showMore == 'RIGHT')
            {
                content += that.htmlBetween;
                itemHtml = $(that.items[that.maxCount]);
                content += $( $('<div></div>').html(itemHtml) ).html();
            }
            content += that.htmlAfter;
            that.thumbs.html(content);
        }
        that.thumbs.css({'left' : that.delta});
    };

    // Funkce zavola callback funkci pri zvoleni thumbnailu a pripadne nascrollovani na neho
    this.Choose = function()
    {
        var chosen = $(that.items[that.currentIndex]);
        var url = chosen.children("." + that.fullimageClass).html();
        that.fullImg.attr({'src' : url});
        if(that.chosenCallback != undefined)
        {
            that.chosenCallback(chosen[0]);
        }
    };


    // skryje loader
    this.HideLoader = function()
    {
        $(that.loaderDiv).remove();
    };

    // zobrazi loader
    this.ShowLoader = function()
    {
        if(that.fullImg != null)
        {
            var oldImgPos = that.fullImg.offset();
            var oldImgWidth = that.fullImg.width();
            var oldImgHeight = that.fullImg.height();
            $(that.loaderDiv).css({
                'left': oldImgPos.left.toString() + 'px',
                'top': oldImgPos.top.toString() + 'px',
                'width': oldImgWidth.toString() + 'px',
                'height': oldImgHeight.toString() + 'px'
            });
            $(document.body).append(that.loaderDiv);
        }
    };

    this.Display();

}
