/* ####  КЛАССЫ - ИНСТРУМЕНТЫ ДЛЯ РАБОТЫ С ИЗОБРАЖЕНИЯМИ ####*/
/* Inetua ImagesTools v3.0 */

/* Главный класс */
function ImagesTools(){
  var _this = this;
  this.imageArray = new Array();              // Массив изображений
  this.totalImagesInArray = 0;                // Всего изображений в массиве

  this.suffix = null;                         // Суффикс додаток для обозначения ID изображений
  this.ln = "thmb_" + this.suffix + "0";


  this.total_image_select;
  this.amount_image_visible = 12;              // Максимальное количество уменьшенных изображений, видимых в списке
  this.currentImgIndex = 0;                   // Порядковый номер отображаемого в текущий момент изображения "галлереи"

  this.indexFirst = 0;                        // Стартовый индекс видимого изображения
  this.indexLast = 0;                         // Конечный индекс видимого изображения

  this.img_maxheight = 510;                   // максимальная высота картинки
  this.img_maxwidth = 700;                    // максимальная ширина картинки
  this.wnd_maxwidth = 689;                    // максимальная ширина окна
  this.wnd_maxheight = 478;                   // максимальная высота окна
  this.style_on   = "img_on";
  this.style_off  = "img_off";

  // Метод инициализирует массив изображений.
  // Метод принимает два параметра, родительский объект в котором находятся изображения и метка изображения.
  this.initImage = function(parentObj, tag){
    var tag = (tag||"thumbs");
    var parentObj = (parentObj||false);

    // Находим все ссылки в заданом блоке либо по всему документу
    var docLinks = new Array();
    if(parentObj){
      docLinks = document.getElementById(parentObj).getElementsByTagName('a');
    }else{
      docLinks = document.getElementsByTagName('a');
    }

    // Проходим весь список ссылок, ищем элементы с заданным rel и наполняем массив изображений
    for(var i = 0; i < docLinks.length; i++){
      // Добавим найденный элемент в массив
      if(docLinks[i].rel == tag){
        var smallImg = docLinks[i].getElementsByTagName('img');
        this.addImage(smallImg[0].id, docLinks[i].href, smallImg[0].src, smallImg[0].alt, docLinks[i].title);
      }
    }

    // Вычисляем количество изображений в массиве
    this.totalImagesInArray = this.imageArray.length;
  }

  // Метод перелистывает страницы с превью
  this.selectPage = function(limit){
    var limit = (limit || "0,11");
    var limit = limit.split(",");
    var image_start = limit[0];
    var image_end = limit[1]

    // Запускаем построитель блока превью изображений
    this.createThumbsImageBlock(image_start, image_end);
  }

  // Метод формирует / перестраивает блок превью изображений
  this.createThumbsImageBlock = function(image_start, image_end){
    // Если массив не содержит данных то прекращаем работу
    if(this.totalImagesInArray == 0){ return false; }

    var total_columns = 4;                                     // Количество столбцов в списке
    var kol_img_visible = 12;                                   // Количество уменьшенных изображений которые должны быть видны в списке
    var image_start = (image_start||0);                        // Позиция первого элемента
    var image_end = (image_end||(kol_img_visible - 1));        // Позиция последнего элемента
    var first_big_image_src = this.imageArray[0].filePuthBig;  // Выбираем путь к первом большому изображению
    var image_block = "";                                      // Переменная в которую сохраняется результат фрмирования блока

    // Делаем срез массива, чтобы выбрать нужные нам изображения
    var slice_array = this.imageArray.slice(image_start, image_end);

    // alert(slice_array.length + ", st " + image_start + ", en" + image_end);

    // Раскладываем изображения по строкам и столбцамм
    var a = 0; var index = image_start;
    for(i = 0; i < total_columns; i++){
      // Открываем столбец
      image_block += "<li><ul>";

      // Формируем строки
      for(j = 0; j < 3; j++){
    //    alert(index);
        // Если элемент не пустой, то формируем строку
        if(slice_array[a] != null){
          image_block += '<li><a href="' + slice_array[a].filePuthBig + '" rel="thumbs" onclick="return imgTools.showBigImage(' + index +');" title="' + slice_array[a].description + '" ><img id="thumbs' + index +'" src="' + slice_array[a].filePuthThumbs + '" alt="' + slice_array[a].title + '" /></a></li>';
        }

        // Выводим пустую ячейку в случае отсутствия каких то данных
        if(slice_array[a] == null && a != kol_img_visible){
          image_block += '<li></li>';
        }

        // Формируем страничную навигацию        
        if(index == image_end){
          // Вычисляем количество страниц
          var total_page = this.totalImagesInArray / kol_img_visible;

          // Формируем ссылки
          var pager = new Array();
          for(n = 0; n <= total_page; n++){
            var start = n * kol_img_visible;
            pager[n] = (start == image_start ? "<b>"+ (n+1) +"</b>" : '<a href="#" onclick="imgTools.selectPage(\'' + start + ',' + ((n * kol_img_visible) + (kol_img_visible - 1)) + '\');">' + (n+1) + '</a>');
          }
          image_block += '<p class="pager">' + pager.join("<span>|</span>") + '</p>';
        }

        a++; index++;
      }

      // Закрываем столбец
      image_block += "</ul></li>";
    }

//  alert(image_block);
    // Вставляем полученный блок в страницу
    document.getElementById("gallery_thumbs").innerHTML = image_block;
  }

  /* #### ПОЛЬЗОВАТЕЛЬСКИЕ МЕТОДЫ */
  // Метод перемещающий маленькие изображения в видимом списке
  this.ScrollingImages = function(direct){
    // Формируем массив изображений для 

    var el;
    for(j = 0; j < this.amount_image_visible; j++){
      if(direct < 0){
        // Устанавливаем стартовый индекс изображению
        if(j == 0){ this.currentImgIndex = this.totalImagesInArray - this.indexFirst; }
        this.currentImgIndex++;  // увеличиваем индекс для сдвига изображений вправо

       // alert(this.currentImgIndex);

        // Если стартовый индекс меньше нуля, то приравниваем 0 и все начинаем сначала
        if(this.currentImgIndex < 0){ this.currentImgIndex = this.totalImagesInArray + this.currentImgIndex; this.indexFirst = 0; }

        // Если стартовый индекс равен кол-ву изображений, то приравниваем 0 и все начинаем сначала
        if(this.currentImgIndex == this.totalImagesInArray){ this.currentImgIndex = 0;}

        // Если стартовый индекс больше кол-ва изображений, то приравниваем 0 и все начинаем сначала
        if(this.currentImgIndex > this.totalImagesInArray){ this.currentImgIndex = this.currentImgIndex - this.totalImagesInArray; }

        // Если последня иттерация цикла, то запоминаем индекс 
        if(j == (this.amount_image_visible - 1)){
          this.indexFirst++;
        }
        // alert(this.indexFirst);


      }else if(direct > 0){
        // Устанавливаем стартовый индекс изображению
        if(j == 0){ this.currentImgIndex = this.indexFirst; }
        this.currentImgIndex++;  // увеличиваем индекс для сдвига изображений влево

        // Если достигнут конец массива, то индекс приравнивается 0 и все начинается сначала
        if(this.currentImgIndex == this.totalImagesInArray){ this.currentImgIndex = 0;}

        // Если последня иттерация цикла, то увеличиваем стартовый индекс 
        if(j == (this.amount_image_visible - 1)){
          this.indexFirst++;
          // Если стартовый индекс равен кол-ву изображений, то приравниваем 0 и все начинаем сначала
          if(this.indexFirst == this.totalImagesInArray){ this.indexFirst = 0;}
        }
      }
      // Присваиваем текущему местоположению новое изображение
      el = document.getElementById("thmb_" + this.suffix + j);
      if(el != null){
        el.src = this.imageArray[this.currentImgIndex].filePuthThumbs;
      }
      //alert(this.indexFirst + ' - ' + this.currentImgIndex);
    }
  }

  // Метод добавляет новое изображение в массив изображений
  this.addImage = function(id, puthBig, puthThumbs, title, description){
    var obj = new Object();
    obj.id = id;
    obj.filePuthBig = puthBig;
    obj.filePuthThumbs = puthThumbs;
    obj.title = title;
    obj.description = description;
    //obj.width = width_big;
    //obj.height = height_big;
    this.imageArray.push(obj);
  }

  // Метод открывает всплывающий windows popup окно при просмотре картинок
  this.ShowBigImg = function(index_place){
    // Вычисляем текущий индекс изображения согласно ее положения в списке отображения.
    index = this.indexFirst + parseInt(index_place);

    // Определяем размеры текущего окна
    var img_width = (this.imageArray[index].width != null ? this.imageArray[index].width : this.wnd_maxwidth);
    var img_height = (this.imageArray[index].height != null ? this.imageArray[index].height : this.wnd_maxheight);

    // Вычисляем середину экрана по вертикали и горизонтали
    var left = parseInt((document.body.clientWidth/2) - (img_width/2));
    var top = parseInt((document.body.clientHeight/2) - (img_height/2));

    newWindow = window.open("","imgWindow","width="+img_width+",height="+img_height+",left="+left+",top="+top);
    newWindow.document.open();
    newWindow.document.write('<html><head><title>ФОТО</title>');
    newWindow.document.write('</head><body style="margin:0;">');
    newWindow.document.write('<div><img id="img_big" src="'+ this.imageArray[index].filePuthBig +'" width="'+ img_width +'" height="'+ img_height +'" alt="" />');
    newWindow.document.write('</div></body></html>');
    newWindow.document.close();
    newWindow.focus();
  }

  // Показываем избражение при клике на превью
  this.showBigImage = function(i){
    // Определяем браузер
    nn = (document.getElementById && navigator.appName == "Netscape") ? 1 : 0;
    ns = (document.layers) ? 1 : 0;
    op = (!nn && !ns && ( navigator.appName == "Opera" || navigator.userAgent.indexOf('Opera') != -1)) ? 1 : 0;
    ie = (!nn && !op && !ns && document.all) ? 1 : 0; 

    // Назначаем объекту изображение
    el = document.getElementById("bigImage");
    if(el != null){
      var new_img = this.imageArray[i].filePuthBig;
      if(ie){
        el.style.filter = "blendTrans(duration=0.8) revealTrans(duration=0.3,transition=10)";
        el.filters(0).apply();
        el.filters(1).apply();
        el.src = new_img;
        el.onload = function(){
          el.filters(0).play();
          el.filters(1).play();
        }
      }else{
        el.src = new_img;
      }
    }
    return false;
  }

  /* #### СЛУЖЕБНЫЕ МЕТОДЫ */
  // Вспомогательная метод получения размера документа
  this._getPageSizeWithScroll = function(){
    if(window.innerHeight && window.scrollMaxY){  // Firefox 
      pageWidth = document.body.clientWidth + window.scrollMaxX;
      pageHeight = window.innerHeight + window.scrollMaxY;
    }else if(document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
      pageWidth = document.body.scrollWidth;
      pageHeight = document.body.scrollHeight;
    }else{ // works in Explorer 6 Strict, Mozilla (not FF) and Safari
      pageWidth = document.body.offsetWidth + document.body.offsetLeft;
      pageHeight = document.body.offsetHeight + document.body.offsetTop;
    }
    arrayPageSizeWithScroll = new Array(pageWidth, pageHeight);
    return arrayPageSizeWithScroll;
  }

  // this._reset();
}
var imgTools = new ImagesTools();

/* Формируем дочерний класс для работы с iBox */
function imageBox(){
  this.iBox = new Object();                    // Объект плавающего слоя Имэдж Бокса
  this.iBox.statusString  = '[num] из [total]' // Строка описания текущего соcтояния iBox

  // Метод инициализации image бокса. Добавляет HTML код бокса к текущему документу и кеширует ссылки на составные элементы
  this.iBoxInit = function(){
    var boxHTML = '<div id="wrapiBox"></div>'
                + '<div id="iBoxContainer">'
                + ' <div id="iMainBox">'
                + '  <div id="iBoxMainImageWrap"><img src="/templates/images/z.gif" id="iBoxMainImage" alt="" /></div>'
                + '  <img src="/templates/images/ajax-loader.gif" alt="" id="iBoxLoading" />'
                + '  <p class="tools">'
                + '   <a href="#" onclick="return obj' + this.suffix + '.iBoxPrev();" id="previBoxLink"><img src="/templates/images/ibox_arrl.gif" alt="Предыдущее" /></a>'
                + '   <span id="iBoxNumberOfImage"></span>'
                + '   <a href="#" onclick="return obj' + this.suffix + '.iBoxNext();" id="nextiBoxLink"><img src="/templates/images/ibox_arrr.gif" alt="Следущее" /></a>'
                + '   <span id="iBoxTitle"></span>'
                + '   <a href="#" onclick="return obj' + this.suffix + '.iBoxClose();" class="close"><img src="/templates/images/close.gif" alt="Закрыть" /></a>'
                + '  </p>'
                + ' </div>'
                + '</div>';
    this.iBox.wrapNode = document.getElementById('wrapiBox');
    if(!this.iBox.wrapNode){ document.write(boxHTML); }

    // Кеширование (ссылок на) DOM узлов составных элементов бокса внутри объекта
    this.iBox.wrapNode      = document.getElementById('wrapiBox');
    this.iBox.boxNode       = document.getElementById('iMainBox');
    this.iBox.progressImg   = document.getElementById('iBoxLoading');
    this.iBox.prevLinkNode  = document.getElementById('previBoxLink');
    this.iBox.nextLinkNode  = document.getElementById('nextiBoxLink');
    this.iBox.infoNode      = document.getElementById('iBoxNumberOfImage');
    this.iBox.wrapImgNode   = document.getElementById('iBoxMainImageWrap');
    this.iBox.mainImg       = document.getElementById('iBoxMainImage');
    this.iBox.titleNode     = document.getElementById('iBoxTitle');

    this.iBox.linkNodesArray  = new Array(); // Массив DOM узлов ссылок на изображения текущей галлереи

    // Создание контейнера для предзагрузки изображений
    this.iBox.preloadImg        = new Image();
    this.iBox.preloadImg.onload = this.iBoxDisplayMainImg();
  }


  // Запуск анимации и инициализации навигации
  this.iBoxDisplayMainImg = function(){
    // инициализация навигации
    var previousImgIndex = this.currentImgIndex - 1;
    this.iBox.prevLinkNode.style.display = (previousImgIndex >= 0 ? '' : 'none'); // Скрыть ссылку "=>"

    var nextImgIndex = this.currentImgIndex + 1;    
    this.iBox.nextLinkNode.style.display =  (nextImgIndex < this.iBox.linkNodesArray.length ? '' : 'none'); // Скрыть ссылку "<="

    if(this.iBox.linkNodesArray.length > 1){
      // Нарисовать порядковый номер в навигации
      var info = this.iBox.statusString.replace('[num]', this.currentImgIndex + 1);
      this.iBox.infoNode.innerHTML = info.replace('[total]', this.iBox.linkNodesArray.length);
    }
    this.iBoxDimMainImage(10);                    // Запускаем анимацию "растворения"
    this.iBox.progressImg.style.display = 'none'; // Убираем индикатор загрузки
    this.iBox.titleNode.innerHTML       = '';
    this.iBox.titleNode.style.display   = 'none'; // Убираем тайтл изображения
  }

  // Ф-ция анимации растворения - увеличивает прозрачность изображения от заданного в opacity значения до нуля (диапазон opacity [0-10])
  this.iBoxDimMainImage = function(opacity){
    var newOpacity;
    if(opacity){
      newOpacity = opacity; // первый вызов ф-ции, задаем свойство
    }else{
      var step   = 2;     // Шаг изменения 
      newOpacity = this.iBox.mainImg.style.opacity*10 - step; // Изменяем значение
    }
    this.iBox.mainImg.style.opacity = newOpacity/10;                          // для всех нормальных броузеров
    this.iBox.mainImg.style.filter  = 'alpha(opacity=' + newOpacity*10 + ')'; // для IE
    if(this.iBox.mainImg.style.opacity > 0){
      setTimeout('this.iBoxDimMainImage()', 35); // продолжим анимацию
    }else{
      this.iBox.mainImg.style.display = 'none';
      this.iBox.mainImg.style.opacity = 0;
      this.iBox.mainImg.style.filter  = 'alpha(opacity=100)';
      this.iBoxResize(); // Запуск анимации ресайза бокса
    }
  }

  // Ф-ция анимирует изменение размеров блока при разнице размеров загружаемых изображений
  this.iBoxResize = function(){
    var leftInnerMargin   = parseInt(this.iBox.wrapImgNode.style.marginLeft, 10) || 0;
    var rightInnerMargin  = parseInt(this.iBox.wrapImgNode.style.marginRight, 10) || 0;
    var leftBorder        = parseInt(this.iBox.boxNode.style.borderLeftWidth, 10) || 0;
    var rightBorder       = parseInt(this.iBox.boxNode.style.borderRightWidth, 10) || 0;
    // Изменение ширины относительно внутреннего блока, однако ширину менять будем внешенему
    var deltaWidth  = this.iBox.wrapImgNode.offsetWidth - this.iBox.preloadImg.width;
    // Вычисляется изменение высоты только для блока вокруг изображения, внешние блоки отресайзятся сами при изменении высоты внутреннего
    var deltaHeight = this.iBox.wrapImgNode.offsetHeight - this.iBox.preloadImg.height;
 
    // Шаг изменения поставим в зависимость от расстояния, чтобы "сначала быстро, потом медленно"
    var widthResizeStep  = deltaWidth / 4;
    var heightResizeStep = deltaHeight / 4;
    widthResizeStep      = (widthResizeStep > 0) ? Math.ceil(widthResizeStep) : Math.floor(widthResizeStep);
    heightResizeStep     = (heightResizeStep > 0) ? Math.ceil(heightResizeStep) : Math.floor(heightResizeStep);
 
    if(Math.abs(deltaWidth) > Math.abs(widthResizeStep)){
      var newWidth              = this.iBox.boxNode.offsetWidth - leftBorder - rightBorder - widthResizeStep;
      this.iBox.boxNode.style.width = newWidth + 'px'; // Изменение ширины внешнего блока, внутренние блоки отресайзятся сами
    }
    if(Math.abs(deltaHeight) > Math.abs(heightResizeStep)){
      var newHeight                  = this.iBox.wrapImgNode.offsetHeight - heightResizeStep;
      this.iBox.wrapImgNode.style.height = newHeight + 'px'; // Изменение высоты внутреннего блока
    }

    if((Math.abs(deltaHeight) > Math.abs(heightResizeStep)) || (Math.abs(deltaWidth) > Math.abs(widthResizeStep))) {
      setTimeout('this.iBoxResize()', 35); // Анимируем дальше
    }else{
      // Стопорим и "добиваем" нужные значения, т.к. в процессе анимации они могли быть вычислены не точно
      this.iBox.boxNode.style.width      = this.iBox.preloadImg.width + leftInnerMargin + rightInnerMargin + 'px';
      this.iBox.mainImg.style.width      = this.iBox.preloadImg.width + 'px';
      this.iBox.wrapImgNode.style.height = this.iBox.preloadImg.height + 'px';
      this.iBox.mainImg.src              = this.iBox.preloadImg.src;
      this.iBox.mainImg.style.display    = 'block';
      // Нарисуем тайтл изображения
      var imageTitle = (this.iBox.linkNodesArray[this.currentImgIndex]) ? this.iBox.linkNodesArray[this.currentImgIndex].title : '';
      if(imageTitle != ''){
        // this.iBox.titleNode.style.display = 'block';
        this.iBox.titleNode.innerHTML     = imageTitle;
      }
      iBoxLightenMainImage(); // Запускаем анимацию "проявления" изображения
      //iBoxAnimSglOverlay('animation3.gif');
      //iBoxAnimMultiOverlay('animation3.gif');
    }
  }

  // Уменьшает прозрачность изображения от текщего значения до полностью непрозрачного - эффект проявления
  this.iBoxLightenMainImage = function(){
    var step        = 2;
    var newOpacity  = this.iBox.mainImg.style.opacity*10 + step;

    this.iBox.mainImg.style.opacity = newOpacity/10;
    this.iBox.mainImg.style.filter  = 'alpha(opacity=' + newOpacity*10 + ')';

    if(this.iBox.mainImg.style.opacity < 1){
      setTimeout('iBoxLightenMainImage()', 35);
    }else{
      this.iBox.mainImg.style.opacity = '';
      this.iBox.mainImg.style.filter  = '';
    }
  }

  // Показ предыдущего изображения "галлереи"
  this.iBoxNext = function(){
    this.iBox.progressImg.style.display = 'block'; // Показать индикатор загрузки

    var nextImgIndex = this.currentImgIndex + 1;
    if(nextImgIndex < this.iBox.linkNodesArray.length){
      this.currentImgIndex = nextImgIndex;
      this.iBox.preloadImg.src  = this.iBox.linkNodesArray[nextImgIndex].href;
    }
    return false;
  }

  // Показ следующего изображения "галлереи"
  this.iBoxPrev = function(){
    this.iBox.progressImg.style.display = 'block'; // Показать индикатор загрузки

    var prevImgIndex = this.currentImgIndex - 1;
    if(prevImgIndex >= 0){
      this.currentImgIndex = prevImgIndex;
      this.iBox.preloadImg.src  = this.iBox.linkNodesArray[prevImgIndex].href;
    }
    return false;
  }

  // Ф-ция закрытия бокса
  this.iBoxClose = function(){
    this.iBox.wrapNode.style.display   = 'none';
    this.iBox.boxNode.style.display    = 'none';
    return false;
  }

  // Отправляет изображение на просмотр в боксе
  this.iBoxOpen = function(domNode){
    var docLinks = document.getElementsByTagName('a');
    this.iBox.progressImg.style.display = 'block'; // Показать индикатор загрузки
    this.iBox.linkNodesArray            = new Array(); 
    // Пройдемся по всему списку ссылок для того чтобы найти элементы с заданным rel инаполнить "галлерею"
    if(domNode.rel != ''){
      for(var i = 0; i < docLinks.length; i++){
        if(docLinks[i].rel == domNode.rel) {
          this.iBox.linkNodesArray.push(docLinks[i]); // Добавим найденный элемент в массив {TODO} IE 5 do not have push
        }
        if(docLinks[i] == domNode){
          this.currentImgIndex = this.iBox.linkNodesArray.length - 1;
        }
      }
    }else{
      this.iBox.linkNodesArray.push(domNode);
      this.currentImgIndex = 0;
    }
    this.iBox.infoNode.innerHTML  = '&#160;';
    this.iBox.titleNode.innerHTML = '';

    // Сделать общий темный фон
    var pagesize                 = this._getPageSizeWithScroll();
    this.iBox.wrapNode.style.display = 'block';
    this.iBox.wrapNode.style.height  = pagesize[1] + 'px';
    this.iBox.wrapNode.style.width   = pagesize[0] + 'px';

    // Вычисляем расстояние от верхнего края (с учетом прокрутки)
    var top = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop;
    // var top = parseInt((pagesize[1] / 2) - (img_height/2));

    this.iBox.boxNode.style.top         = (top + 70) + 'px';
    this.iBox.mainImg.src               = '/templates/images/z.gif';
    this.iBox.wrapImgNode.style.height  = '30px';
    this.iBox.boxNode.style.width       = '200px';
    this.iBox.boxNode.style.display     = 'block';
    this.iBox.preloadImg.src            = domNode.href; // Добавим изображение в очередь загрузки
    //alert('thatsit');
    return false;
  }
}
imageBox.prototype = new ImagesTools();  // Наследуем свойства и методы от родительского класса
var imgBox = new imageBox();
