﻿var thumbnail = Class.create();
 thumbnail.prototype = {
     // Инициализация скрипта
     initialize: function(width_max, height_max, width_min, height_min, name, code) {
         try {
             var objBody = document.getElementsByTagName("body").item(0);
 
             var objOverlay = document.createElement("div");
             objOverlay.setAttribute('id','overlay');
             objOverlay.style.display = 'none';
             Event.observe(objOverlay, 'click', this.close.bindAsEventListener(this));
             objBody.appendChild(objOverlay);
             
             var box = '<table id="rnd_tbl" ><tr><td class="rnd_1"></td><td class="rnd_2" rowspan="3"><div class="f_body">'
                 + '<div id="s25_desc_img"><strong id="s25_img_name"></strong><small  id="s25_img_code"></small></div>'
                 + '<div id="s25_thumb_preload"><img src="' + http_path + 'images/loading.gif" alt="Загрузка" /></div>'
                 + '<div id="s25_thumb_img"></div><div id="s25_photo_cnt">Просмотр фотографий <code id="s25_curr_cnt"></code>&nbsp;из <code id="s25_all_cnt"></code></div>'
                 + '<div id="s25_thumb_ctrl"><img src="/images/minus.png" alt="-" title="Уменьшить" id="s25_thumb_zoomout" /><img src="/images/plus.png" alt="+" title="Увеличить" id="s25_thumb_zoomin" /><img src="/images/prev_img.png" alt="<-" title="Предыдущая" id="s25_thumb_prev" /><img src="/images/next_img.png" alt="->" title="Следующая" id="s25_thumb_next"/></div>'
                 + '</div></td><td class="rnd_3"><img id="s25_thumb_close" src="/images/ico_close.gif" alt="X" /></td></tr><tr><td class="rnd_4"><div>&#160;</div></td><td class="rnd_5"><div>&#160;</div></td></tr><tr><td class="rnd_6"></td><td class="rnd_7"></td></tr></table>'
             var t = document.createElement('div');
             t.id="s25_thumb_box"
             t.innerHTML = box;
             document.body.insertBefore(t, document.body.firstChild);
             //new Insertion.top(document.body, '<div id="s25_thumb_box"><table id="s25_thumb_tbl"><tr><td colspan="2" id="s25_thumb_td"><table><td id="s25_thumb_img"></td></table></td></tr><tr><td>Кнопки</td><td>Выход</td></tr></table></div>');
             if (this.get_zoom() == 8) {
                 this._width = width_max;
                 this._height = height_max;
             } else {
                 this._width = width_min;
                 this._height = height_min;
             }
             this._min_width = width_min
             this._min_height = height_min
             this._max_width = width_max
             this._max_height = height_max
             
             $('s25_img_name').innerHTML = name;
             $('s25_img_code').innerHTML = 'Код товара: ' + code;
             this.thumb_box = $('s25_thumb_box')
             this.thumb_curr_cnt = $('s25_curr_cnt');
             this.thumb_all_cnt = $('s25_all_cnt');
             this.thumb_img = $('s25_thumb_img');
             this.thumb_ctrl = $('s25_thumb_ctrl');
             this.thumb_close = $('s25_thumb_close');
             this.thumb_preload = $('s25_thumb_preload');
 
             this.add_styles();
             
             this.thumb_box.addClassName('sb');
             // Собираем все ссылки c rel = thumbnail
             this.images = $$("a[rel='thumbnail']")
             this.images.each(function(el, index){
                 //Вешаем обработчик на ссылку, для отображения картинки
                 Event.observe(el, 'click', this.load_img.bindAsEventListener(this, index));
             }.bind(this))
             this.thumb_all_cnt.innerHTML = this.images.length;
             
             //Вешаем обработчики событий на кнопки
             Event.observe($('s25_thumb_prev'), 'click', this.prev.bindAsEventListener(this));
             Event.observe($('s25_thumb_next'), 'click', this.next.bindAsEventListener(this));
             Event.observe($('s25_thumb_zoomout'), 'click', this.zoom_out.bindAsEventListener(this));
             Event.observe($('s25_thumb_zoomin'), 'click', this.zoom_in.bindAsEventListener(this));
             //На ссылку закрыть вешаем событие закрыть
             Event.observe($('s25_thumb_close'), 'click', this.close.bindAsEventListener(this));
             //На уход со странички вешаем событие подчистки данных
             Event.observe(window, 'unload', this.cleanup.bindAsEventListener(this));
             //На изменение размеров странички - выравниваем картинку по центру.
             Event.observe(window, 'resize', this.on_resize.bindAsEventListener(this));
         } catch(e) {
             throw window.Error? new Error(e) : e;
             //throw: e;
         }
     },
     hide_shadow: function(evt) {
         this.overlay_showed = false
         new Effect.Fade('overlay', { duration: 0.2});
         showSelectBoxes();
     },
     add_styles: function() {
         this.thumb_preload.setStyle({
             'top': (parseInt(this._height,10) - 55)/2 + 'px',
             'left': (parseInt(this._width,10) - 54)/2 + 'px'
         });
         this.thumb_img.setStyle({
             'width': this._width + 'px',
             'height': this._height + 'px'
         });
     },
     show_preload: function() {
         this.thumb_img.setStyle({
             'visibility': 'hidden'
         });
         this.thumb_preload.setStyle({
             'display': 'block'
         });
     },
     hide_preload: function() {
         this.thumb_preload.setStyle({
             'display': 'none'
         });
         this.thumb_img.setStyle({
             'visibility': 'visible'
         });
     },
     // Переменная, в которой хранятся обрабатываемые изображения.
     images: null,
     overlay_showed: false,
     
     //Индекс текущего изображения в списке обрабатываемых изображений
     current_img_index: null,
     
     // Получение текущего значения zoom`а
     get_zoom: function() {
         var z = getCookie('phzoom');
         if (z != undefined && z != null && (z == 4 || z == 8)) {
             return z;
         } else {
             return 4;
         }
     },
     
     set_zoom: function(z) {
         if (z != undefined && z != null && (z == 4 || z == 8)) {
             setCookie('phzoom', z, getExpDate(30,0,0), '/', cookie_http_path);
         } else {
             setCookie('phzoom', z, getExpDate(30,0,0), '/', cookie_http_path);
         }
     },
     
     //Переход к предыдущему изображению
     prev: function(evt) {
         try {
             if (! isNaN(parseInt(this.current_img_index)) && this.current_img_index > 0) {
                 this.load_img(evt, this.current_img_index - 1);
             }
         } catch (e) {}
     },
     
     //Переход к следующему изображению
     next: function(evt) {
         try {
             if (!isNaN(parseInt(this.current_img_index)) && this.images != null &&  (this.images.length - 1) > this.current_img_index) {
                 this.load_img(evt, this.current_img_index + 1);
             }
         } catch (e) {}
     },
     
     //Увеличение изображения
     zoom_in: function(event) {
         if (this.get_zoom() != 8) {
             this.set_zoom(8);
             this._width = this._max_width
             this._height = this._max_height
             //this.close(event);
             this.add_styles();
             this.load_img(event, this.current_img_index);
         }
     },
     
     //Уменьшение изображения
     zoom_out: function(event) {
         if (this.get_zoom() != 4) {
             this.set_zoom(4);
             this._width = this._min_width
             this._height = this._min_height
             //this.close(event);
             this.add_styles();
             this.load_img(event, this.current_img_index);
         }
     },
     
     //Загрузка изображения
     load_img: function(e, index) {
         if (this.overlay_showed == false) {
             Element.setHeight('overlay', $('contents').getDimensions().height);
             new Effect.Appear('overlay', { duration: 0.1, from: 0.7, to: 0.7 });
             this.overlay_showed = true
         }
         this.thumb_img.innerHTML = '';
         this.current_img_index = index;
         var el = this.images[index];
         //this.show_box()
         var href = el.getAttribute("href")
         var z = this.get_zoom();
         var re = /(\d+)\/([-_,\w]+\.\w{1,3})$/i;
         if (z != undefined && z != null) {
             var href = el.getAttribute("href").replace(re, z + "/$2");
         } else {
             var href = el.getAttribute("href");
         }
         this.thumb_box.removeClassName('z8');
         this.thumb_box.removeClassName('z4');
         this.thumb_box.addClassName('z' + z);
         
         
         if (this.images.length > 1) {
             $('s25_thumb_next').src = http_path + 'images/next_img.png';
             $('s25_thumb_prev').src = http_path + 'images/prev_img.png';
         }
         if (index < 1) {
             $('s25_thumb_prev').src = http_path + 'images/gprev_img.png';
         }
         if (index  >= (this.images.length - 1)) {
             $('s25_thumb_next').src = http_path + 'images/gnext_img.png';
         }
         if (z == 4) {
             $('s25_thumb_zoomin').src = http_path + 'images/plus.png';
             $('s25_thumb_zoomout').src = http_path + 'images/gminus.png';
         } else {
             $('s25_thumb_zoomin').src = http_path + 'images/gplus.png';
             $('s25_thumb_zoomout').src = http_path + 'images/minus.png';
         }
         this.thumb_curr_cnt.innerHTML = parseInt(index + 1);
 
         this.show_box()
         this.show_preload();
         
         new Insertion.Bottom(this.thumb_img, '<img src="' + href + '" alt="' + href + '" />');
         var img = this.thumb_img.down('img');
         Event.observe(img, 'load', this.center_img.bindAsEventListener(this, img));
         Event.observe(this.thumb_img, 'click', this.close.bindAsEventListener(this));
         
         // Обязательно тормозим выполнение события, иначе произойдет переход по ссылке
         Event.stop(e);
     },
     
     center_img: function(evt, img) {
         try {
             var src = img.src, alt = img.alt;
             img.remove();
             new Insertion.Bottom(this.thumb_img, '<img src="' + src + '" alt="' + alt + '" />');
             img = this.thumb_img.down('img');
             if (img.height > 50 && img.height < this._height) {
                 img.setStyle({
                     'top': (this._height - img.height)/2 + 'px'
                 })
             }
             this.show_box()
             this.hide_preload();
         } catch (e) {}
     },
 
     show_box: function() {
         try {
             var doc = getPageSize();
             var obj = this.thumb_box.getDimensions()
             var scroll = getPageScroll()
       if (this.get_zoom() == 8)
       {
           var h = (obj.height > 600) ? obj.height : 600;
       } else
       {
           var h = (obj.height > 450) ? obj.height : 450;
       }
             this.thumb_box.setStyle({
                 'left': doc[2]/2-obj.width/2+'px',
                 'top': (doc[3]>h) ? (scroll[1] + doc[3]/2-h/2 - 40)+'px' : scroll[1] + 10 + 'px',
                 'visibility': 'visible'
             });
             
         } catch(e) {
             throw window.Error? new Error(e) : e;
         }
     },
 
     on_resize: function() {
         try {
             if (this.thumb_box.getStyle('visibility') == 'visible') {
                 var doc = getPageSize();
                 var obj = this.thumb_box.getDimensions()
                 var scroll = getPageScroll()
                 this.thumb_box.setStyle({
                     'left': doc[2]/2-obj.width/2+'px',
                     'top': (doc[3]>obj.height) ? scroll[1] + doc[3]/2-obj.height/2+'px' : scroll[1] + 10 + 'px'
                 });
                 }
         } catch(e) {}
     },
 
     //Закрытие окна с изображением
     close: function(evt) {
         this.thumb_img.innerHTML = '';
         this.thumb_box.setStyle({
             'top': '-2000px',
             'left': '-2000px',
             'visibility': 'hidden'
         });
         this.hide_shadow(evt);
         Event.stop(evt);
     },
 
     //Очистка документа от обработчиков и прочей ерунды (воизбежание мемликов)
     cleanup: function() {
         Event.unloadCache();
         this._width = null;
         this._height = null;
         this._min_width = null
         this._min_height = null
         this._max_width = null
         this._max_height = null
         this.thumb_preload = null
         this.thumb_close = null
         this.thumb_ctrl = null
         this.thumb_img = null
         this.thumb_box = null
         this.thumb_curr_cnt = null;
         this.thumb_all_cnt = null;
     }
 }
 

