/**
 * UNavigator (UniNvigator based on SWFObject and UniUploader)
 * 
 * Author and idea: Sitnikov Igor (sitnikov@kpmedia.ua)
 * Modified and updated by Tarasov Vladimir and Maksym  Borshchanenko
 * Copyright (C) 2009, Dark Side (Bigmir)NET)
 */

function TGallery ( config )
{
    this.$ = function ( id ) { return document.getElementById(id) || false }

    var that = this;
    var obj  = null;

    this.cache = {
        pic   : [],
        pager  : []
    }; 

    this.current    = config.current             ||  0;      // текущий элемент массива content
    this.first      = this.current               ||  0;

    this.content    = config.content             ||  {};     // набор элементов
    this.count      = config.count               ||  0;      // количество элементов

    /**
    * перечисляем id элементов в которых должна отображаться галлерея
    */
    this.layer      = this.$(config.layer)       ||  null;   // элемент в который выводится текущий объект
    this.descLayer  = this.$(config.descLayer)   ||  null;   // описание
    this.dateLayer  = this.$(config.dateLayer)   ||  null;   // контейнер для даты
    this.authorLayer = this.$(config.authorLayer)||  null;

    this.nextLayer  = this.$(config.nextLayer)   ||  null;   // ссылка вперед
    this.prevLayer  = this.$(config.prevLayer)   ||  null;   // ссылка назад

    /**
    * Пейджер
    */
    this.pagerLayer = this.$(config.pagerLayer)  ||  null;   // пейджер объектов
    this.pageLayer  = config.pageLayer           ||  null;   // объект пейджера
    this.pageCurrentClassName  = config.pageCurrentClassName           ||  'current';   // объект пейджера

    this.pagerNext  = this.$(config.pagerNext)   ||  null;   // кнопка пейджера "вперед"
    this.pagerPrev  = this.$(config.pagerPrev)   ||  null;   // кнопка пейджера "назад"

    this.pages      = config.pages               ||  9; // кол-во элементво в пейджере

    this.start      = 0;
    this.stop       = this.pages - 1;

    this.basePath   = config.basePath            ||  null; // полный путь к объекту (без названия файла)

    this.half       = Math.floor( this.pages/2 );

    this.toReplace  = config.toReplace           ||  null;

    // добавление события к элементу
    this.addEvent = function(node,type,fn,useCapture)
    {
        if(node.addEventListener)
        {
            node.addEventListener(type,fn,useCapture);
        }
        else if(node.attachEvent)
        {
            node["e"+type+fn] = fn;
            node[type+fn] = function(){node["e"+type+fn](window.event);};
            node.attachEvent("on"+type,node[type+fn]);
        }
    };

    // показать следующий элемент
    this.next = function() { return this.show( this.current + 1 ) };

    // показать предыдущий элемент
    this.prev = function() { return this.show( this.current - 1 ) };

    // основная функция для работы галлереи
    this.show = function( id )
    {
        // проверяем наличии объекта картинки
        if( ! this.content[id])
        {
            return false;
        }
        this.current = id;

        // создаем кэш картинки
        if( ! this.cache.pic[this.current])
        {
            this.cache.pic[this.current] = new Image();
            this.cache.pic[this.current].src = this.basePath + this.content[this.current].src;
			if (typeof(this.content[this.current].alt) !== undefined)
				this.cache.pic[this.current].alt = this.content[this.current].alt;
			if (typeof(this.content[this.current].title) !== undefined)
				this.cache.pic[this.current].title = this.content[this.current].title;
        }

        // загружаем картинку
        this.beforeLoad();
        if (this.load())
        {
            this.showNextButton();
            this.showPrevButton();

            // если картинку успешно загрузилась, начинаем отрисовку пейджера
            this.pager(this.current);

            // функция которая может быть переопределена для управления дополнительными данными
            this.afterLoad();
        }
        return false;
    }

    // подгрузка картинки в браузер пользователя
    this.load = function()
    {
        // если картинка успешно загрузилась
        if( this.cache.pic[this.current].complete == true )
        {
            // убераем картинку-часики
            if (this.layer)
            {
                this.obj.style.visibility = 'visible';
                this.layer.style.background = '';
            }

            // и рисуем большую картинку на экране
            this.draw();
            return true;
        }
        else
        {
            // ставим картинку-часики
            if (this.layer)
            {
                this.layer.style.background = 'url("http://k.img.com.ua/static/img/icon/cr/ajax-loader.gif") no-repeat 50% 50% #FFFFFF';
                this.obj.style.visibility = 'hidden';
            }
            // и немножко ждем
            return setTimeout(function() { that.load() }, 100 );
        }
    }

    // выводим картинку на экран
    this.draw = function()
    {
        this.obj.src = this.cache.pic[this.current].src;
		if ( typeof(this.cache.pic[this.current].alt) !== undefined )
			this.obj.alt = this.cache.pic[this.current].alt;
		if ( typeof(this.cache.pic[this.current].title) !== undefined )
			this.obj.title = this.cache.pic[this.current].title;

        if( typeof this.content[this.current].description != "undefined" )
        {
            if( this.descLayer )
            {
                this.descLayer.innerHTML = this.content[this.current].description;
            }

            if ( this.dateLayer )
            {
                this.dateLayer.innerHTML = this.content[this.current].date;
            }
        }
        return true;
    }

    // показываем/скрываем кнопку "следующая"
    this.showNextButton = function()
    {
        if (this.nextLayer)
        {
            this.nextLayer.style.display = (typeof this.content[this.current + 1] == 'object') ? '' : 'none';
        }
    }

    // показываем/скрываем кнопку "предыдущая"
    this.showPrevButton = function()
    {
        if (this.prevLayer)
        {
            this.prevLayer.style.display = (typeof this.content[this.current - 1] == 'object') ? '' : 'none';
        }
    }

/**
* функции пейджера
*/
    this.pager = function( id )
    {
        // преверяем на существование контейнера с элементами пейджера
        if ( ! this.pagerLayer)
        {
            return false;
        }

        var current = id == null ? this.current : id;

        var page = this.pages ? Math.floor(current/this.pages) : 0;
        this.start = page ? page * this.pages : 0;
        this.stop  = this.start + this.pages - 1;

        //проверяем что пример кнопки действительно существует(активной и нет)
        this.pagerLayer.innerHTML = '';

        for (var i = this.start; i <= this.stop; i++)
        {
            if ((typeof(this.content[i]) != 'object'))
            {   
                continue;
            }

            // создаем и вставляем на страницу элементы
            var it = this.drawPageItem(i);
            if (typeof(it) == 'object')
            {
                this.pagerLayer.appendChild(it);
            }
        }

        this.pagerShowNextButton();
        this.pagerShowPrevButton();
    }

    this.pagerShowNextButton = function()
    {
        if (this.pagerNext)
        {
            this.pagerNext.style.display = (typeof(this.content[this.stop + 1]) == 'object') ? '' : 'none';
        }
    }

    this.pagerShowPrevButton = function()
    {
        if (this.pagerPrev)
        {
            this.pagerPrev.style.display = (typeof(this.content[this.start - 1]) == 'object') ? '' : 'none';
        }
    }

    //показываем pager со смещением вправо
    this.pagerShowNext = function()
    {
        return this.pager(this.stop + this.half + 1);
    }

    //показываем pager со смещением влево
    this.pagerShowPrev = function()
    {
        return this.pager(this.start - this.half - 1);
    }

    // создание одного элемента пейджера
    this.drawPageItem = function(i)
    {
        var item_id = 'gallery_page';
        var example = this.$(item_id);

        if ( ! example)
        {
            return false;
        }

        var clone = example.cloneNode(true);
        clone.id = this.pageLayer + i;

        if (i != this.current && this.pageCurrentClassName)
        {
            clone.className = clone.className.replace(this.pageCurrentClassName, '');
        }

        var inf = this.content[i];
        // наполняем содержимым

        if (this.toReplace)
        {
            var len = this.toReplace.length;
            var k,f,s = '';

            for (var a=0; a<len; a++)
            {
                k = this.toReplace[a];
                f = this.content[this.first][k];
                s = this.content[i][k];
                clone.innerHTML = clone.innerHTML.replace(f, s);
            }
        }

        // волшебное событие onclick c выключением перехода по ссылке
        this.addEvent(clone, 'click', function(e)
        {
            e.preventDefault ? e.preventDefault() : e.returnValue = false;
            that.show(i);
        });

        return clone;
    }

    // o = объект который нужно клонировать
    // id = новый идентификатор по которому можно будет в будущем его найти
    // replaces = подмена текущих значений переменными
    this.clonePageItem = function(o, id)
    {
        var hidden_id = 'clone_elements';
        var hidden = this.$(hidden_id);

        if ( ! hidden)
        {
            var divs = document.getElementsByTagName('div');
            if (divs && typeof(divs[0]) == 'object')
            {
                hidden = document.createElement('div');
                hidden.style.display = 'none';
                hidden.id = hidden_id;

                divs[0].appendChild(hidden);
            }
        }

        var example = o.cloneNode(true);

        example.id = id;
        hidden.appendChild(example);
    }

    // конструктор класса
    this.construct = function()
    {
        if (this.pagerLayer)
        {
            //сначала текущего
            var o = this.$(this.pageLayer + this.current);
            if (o)
            {
                this.clonePageItem(o, 'gallery_page');
            }

            // цепляем события на кнопки далее и предыдущая пейджера
            if (this.pagerNext)
            {
                this.addEvent(this.pagerNext, 'click', function(e)
                {
                    e.preventDefault ? e.preventDefault() : e.returnValue = false;
                    that.pagerShowNext();
                });
            }
            if (this.pagerPrev)
            {
                this.addEvent(this.pagerPrev, 'click', function(e)
                {
                    e.preventDefault ? e.preventDefault() : e.returnValue = false;
                    that.pagerShowPrev();
                });
            }

            // переписываем пейджер для того чтобы присвоить всем элементам события
            this.pager(this.cuurent);
        }

        this.showNextButton();
        this.showPrevButton();

        // цепляем события на кнопки далее и предыдущая.
        if (this.nextLayer)
        {
            this.addEvent(this.nextLayer, 'click', function(e)
            {
                e.preventDefault ? e.preventDefault() : e.returnValue = false;
                that.next();
            });
        }
        if (this.prevLayer)
        {
            this.addEvent(this.prevLayer, 'click', function(e)
            {
                e.preventDefault ? e.preventDefault() : e.returnValue = false;
                that.prev();
            });
        }

        // ищем главный элемент
        if (this.layer)
        {
            // ищем контейнер с картинкой.
            var imgs = this.layer.getElementsByTagName('img');
            if (imgs && imgs[0] != 'undefined')
            {
                // эта переменная отвечает непосредственно за саму картинку
                this.obj = imgs[0];
            }

            // цепляем на ссылку событие "следующая картинка"
            var links = this.layer.getElementsByTagName('a');
            if (links)
            {
                this.addEvent(links[0], 'click', function(e)
                {
                    e.preventDefault ? e.preventDefault() : e.returnValue = false;
                    that.next();
                });
            }
        }
    }

    this.beforeLoad = function()
    { ;}

    this.afterLoad = function()
    {
        if (this.$('photo_counter'))
        {
            this.$('photo_counter').innerHTML = this.current + 1;
        }

        if (this.authorLayer)
        {
            var author = this.content[this.current].author;

            var text = 'Автор &nbsp;&nbsp;';

            if (author)
            {
                text += '<a href="' + author.link + '">' + author.name + '</a>';
            }
            else
            {
                text += '<span class="red">Афиша</span>';
            }
            this.authorLayer.innerHTML = text;
        }
    }

    /**
    * здесь происходит инициализация класса.
    */
    this.construct();
}