var spotLine = (function(){
	var _total;
	var _inline = 5;
	var _offset;
	var _current;
	var _box_width = 132;
	var _obj = $('OtherFoto');
	var _boxes = $$('#OtherFoto .lImg');
	var _ccount = _boxes.length;
	var _sleep = 100;

	var _contestMode = (typeof curHash['ContestId'] != 'undefined' && curHash['ContestId'] != '') ? true : false;

	var _forwFull = (curHash['GIndex'] == spHash['album_ImagesCount']) ? true : false;
	var _backFull = (curHash['GIndex'] == 1) ? true : false;
	
	var _preload = [];
	var _pvLoad;
	var _fwLoad;
	
	
	// Вкрутить сюда проверку на близость к концу/началу (глобальному) списка, чтобы не спрашивать лишний аякс при первой загрузке первой или последней фотки.
	
	var _preloadImages = function(){
		if(!_pvLoad && !_fwLoad){
			_pvLoad = t2Array[_offset];
			_fwLoad = t2Array[_offset+4];
		}
		if(_offset - t2hash[_pvLoad]['Index'] < 5 || t2hash[_fwLoad]['Index'] - (_offset + 4) < 5){
			var _f1 = (_offset - 25 < 0) ? 0 : _offset - 25;
			var _t1 = (_offset + 29 > t2Array.length - 1) ? t2Array.length - 1 : _offset + 29;
			for(var i = _f1; i <= _t1; ++i){
				if(t2hash[t2Array[i]]['pLoaded'] != true){
					var n5 = new Image();
					n5.src = 'http://' + PhotoContentHost() + spHash['CurBox'] + spHash['album_id'] + '/p-' + t2hash[t2Array[i]]['ImgId'] + '.jpg';
					_preload.push(n5);
					t2hash[t2Array[i]]['pLoaded'] = true;
				}
			}
			_pvLoad = t2Array[_f1];
			_fwLoad = t2Array[_t1];
		}
    }
	
	
	var _stime;
	var _rewrite = function(){
		clearTimeout(_stime);
		_stime = setTimeout(_preloadImages, 750);
		if(spHash['album_ImagesCount'] > _total){
			if(_total - (_offset + 4) < 40){
				_inject();
			}
			
			if(_offset < 40){
				_injectBefore();
			}
			
		}
		
		for(var bIdx = 0; bIdx < _ccount; ++bIdx){
			var bNow = _boxes[bIdx];
			var curNum = $(bNow).select('div')[0];
			var mvt = $(bNow).select('img.fl-v10')[0];
            var bA = bNow.getElementsByTagName('a');
            var bImg = $(bNow).select('img.fl-img')[0];
            var bA2 = $(bNow).select('a.fl-a2')[0];
		
			var branch = t2hash[t2Array[parseInt(_offset) + parseInt(bIdx)]];
		
			if(branch){
				for(var fi = 0, fl = bA.length; fi < fl; ++fi){
					
					var href = '';
					var gofor;
					if(_contestMode){
						href = 'http://' + PhotoImagineHost() + spHash['CurBox'] + spHash['album_id'] + '/' + branch['ImgId'];
						gofor = true;
					} else {
						if(typeof branch['ContestId'] != 'undefined' && branch['ContestId'] != ''){
							href = 'http://' + PhotoImagineHost() + spHash['CurBox'] + spHash['album_id'] + '/' + branch['ImgId'];
							gofor = true;
						} else {
							href = '#' + branch['ImgId'];
							gofor = false;
						}
					}
					
					bA[fi].href = href;
					$(bA[fi]).writeAttribute('go', (gofor)?'true':'false');
				}
				bImg.src = 'http://' + PhotoContentHost() + spHash['CurBox'] + spHash['album_id'] + '/p-' + branch['ImgId'] + '.jpg';
				if(bA2){
				        if (typeof branch['Title'] != 'undefined' && branch['Title'].length > 0) {
				            bA2.update(branch['Title']);
				        } else {
				            bA2.update('Без названия');
				        }
				}

				if(branch['megaVote']){
					if(mvt){
						mvt.src = 'http://img.imgsmail.ru/mail/ru/images/my/v_10s.png';
						mvt.show();
					}
				} else {
					if(mvt){ 
						mvt.hide(); 
						mvt.src = 'http://img.imgsmail.ru/r/video2/spacer.gif';
					}
				}
				
				
				bNow.writeAttribute('image_id', branch['ImgId']);

				if(bNow.readAttribute('image_id') == _current){
					curNum.update(branch['GIndex'] + '/' + spHash['album_ImagesCount']);
					bNow.addClassName('cur');
				} else {
					curNum.update('&nbsp;');
					bNow.removeClassName('cur');
				}

				
			}
		}
		
		_updateButtons();
		
	}
	
	var _injectSent = false;
	var _inject = function(){
		if(!_injectSent && !_forwFull){
			_injectSent = true;
			var GIndex = t2hash[t2Array[t2Array.length-1]]['GIndex'];
			var GUrl = 'http://' + PhotoImagineHost() + spHash['CurBox'] + spHash['album_id'] + '/' + _current + '.line?from=' + GIndex + '&cnt=100';
			new Ajax.Request(GUrl, {
				method: 'get',
				onSuccess: _injectCallback
			});
		}
	}
	
	var _injectBefore = function(){
		if(!_injectSent && !_backFull){
			_injectSent = true;
			var GIndex = t2hash[t2Array[0]]['GIndex'];
			var GUrl = 'http://' + PhotoImagineHost() + spHash['CurBox'] + spHash['album_id'] + '/' + _current + '.line?from=' + GIndex + '&cnt=-100';
			new Ajax.Request(GUrl, {
				method: 'get',
				onSuccess: _injectBeforeCallback
			});
		}
	}	
	
	var _injectCallback = function(t){
		var _io = t.responseJSON.clone()[0];
		if(_io.t2Array.length == 0){ _forwFull = true; }
		for(var i = 0, l = _io.t2Array.length; i < l; ++i){
			var _id = _io.t2Array[i];
			var _item = _io.t2hash[_id];
			if(!t2hash[_id]){
				t2hash[_id] = {}
				t2hash[_id] = _io.t2hash[_id];
				t2Array.push(_id);
			}
		}
		
		for(var i = 0, l = t2Array.length; i < l; ++i){
			t2hash[t2Array[i]]['Index'] = i;
		}
		
		_total = t2Array.length;
		_rewrite();
		_injectSent = false;
	}
	
	var _injectBeforeCallback = function(t){
		var _io = t.responseJSON.clone()[0];
		if(_io.t2Array.length == 0){ _backFull = true; }
		_io.t2Array = _io.t2Array.reverse();
		for(var i = 0, l = _io.t2Array.length; i < l; ++i){
			var _id = _io.t2Array[i];
			var _item = _io.t2hash[_id];
			if(!t2hash[_id]){
				t2hash[_id] = {}
				t2hash[_id] = _io.t2hash[_id];
				t2Array.unshift(_id);
			}
		}
		_offset = _offset + _io.t2Array.length;
	
		for(var i = 0, l = t2Array.length; i < l; ++i){
			t2hash[t2Array[i]]['Index'] = i;
		}
		
		_total = t2Array.length;
		_rewrite();
		_injectSent = false;
	}	
	
	var _dom = {}
	var _domInit = function(){
		// remove current cell marker
		_boxes.each( function(s){
			s.removeClassName('cur');
		});
		
		_dom['prev_div'] = $$('#OtherFoto .lPrev')[0];
		_dom['prev_but'] = $$('#OtherFoto .lPrev .lButton')[0];
		_dom['next_div'] = $$('#OtherFoto .lNext')[0];
		_dom['next_but'] = $$('#OtherFoto .lNext .lButton')[0];		
		                    
	}
	
	var _initParams = function(){
		_total = t2Array.length;
		_current = spot.showCurrent();
		_offset = t2hash[_current]['Index'];
	}

    var _updateButtons = function(){
		if(_offset + _inline < _total){ _dom['next_div'].addClassName('lOn'); } else { _dom['next_div'].removeClassName('lOn'); }
        if(_offset > 0){ _dom['prev_div'].addClassName('lOn'); } else { _dom['prev_div'].removeClassName('lOn'); }
		if(_total <= _inline){
			_dom['prev_div'].addClassName('noCount'); 
			_dom['next_div'].addClassName('noCount');
		} else {
			_dom['prev_div'].removeClassName('noCount');
			_dom['next_div'].removeClassName('noCount');
		}
    }

	var _mouseScroll = function(e){
		if(e.preventDefault){
			e.preventDefault();
		}
		var x = Event.wheel(e);
		if(x > 0){
			_run = true;
			_listPrev();
			_run = false;
		} else {
			_run = true;
			_listNext();
			_run = false;
		}
		return false;
	}

    var _bindButtons = function(){
		Event.observe(_dom['prev_but'], 'mouseup', _listPrevUp.bindAsEventListener(this));
        Event.observe(_dom['prev_but'], 'mousedown', _listPrevDown.bindAsEventListener(this));

        Event.observe(_dom['next_but'], 'mouseup', _listNextUp.bindAsEventListener(this));
        Event.observe(_dom['next_but'], 'mousedown', _listNextDown.bindAsEventListener(this));
        document.observe('mouseup', _stopRun.bindAsEventListener(this));

		Event.observe(_obj, 'mousewheel', _mouseScroll.bindAsEventListener(this), false );
		Event.observe(_obj, 'DOMMouseScroll', _mouseScroll.bindAsEventListener(this), false );
    }
	
	
    var _run = false;
	var _st;
	var _stopRun = function(){
        _run = false;
        if(_st){ clearInterval(_st); _st = null; }
    }

    var _listPrevUp = function(){ _listPrev(); _stopRun(); if(_st){ clearInterval(_st); } }
    var _listPrevDown = function(){ _run = true; _st = setInterval(_listPrev.bind(this),_sleep) }
    var _listPrev = function(){
		if(_offset > 0){
            if(_run){
				_offset--;
                _updateButtons();
                _rewrite();
            }
        } else {
            _stopRun();
		}
	}

	var _listNextUp = function(){ _listNext(); _stopRun(); if(_st){ clearInterval(_st); } }
	var _listNextDown = function(){ _run = true; _st = setInterval(_listNext.bind(this),_sleep) }
	var _listNext = function(){
		if(_offset + _inline < _total){
			if(_run){
				_offset++;
				_updateButtons();
				_rewrite();
            }
        } else {
            _stopRun();
        }
        //_preloadImages();
    }	
	
	var _correctOffset = function(){
	
		if(t2hash[_current]['Index'] && _inline && _total){
			_offset = t2hash[_current]['Index'] - Math.floor(_inline / 2);
			if(_offset + _inline > _total - 1){ _offset = _offset - (_offset + _inline - _total); }
			if(_offset < 0){ _offset = 0; }
			if(_inline >= _total){ _offset = 0; }
		} else {
			_offset = 0;
		}
	}	
	
	return {
		init: function(){
			_domInit();
			_initParams();
			_correctOffset();
			_lastLoad = spot.showCurrent();
			_rewrite();
			_bindButtons();
			
			
			
			if(!Event.wheel){
				Object.extend(Event, {
					wheel:function (event){
						var delta = 0;
						if (!event) event = window.event;
						if (event.wheelDelta) {
							delta = event.wheelDelta/120;
						} else if (event.detail) { delta = -event.detail/3;     }
						return Math.round(delta); //Safari Round
					}
				});
			}
			
			
		},
		setCurrent: function(id){
			this.current = id;
			_rewrite();
		},
		setCur: function(){
			_initParams();
			_correctOffset();		
			_rewrite();
		},
		report: function(){
		},
		__r: function(){
			console.log('Offset: ', _offset, ', count: ', _total);
		},
		__s: function(i){
			_offset = i;
			//_correctOffset();
			_rewrite();
		},
		_ro: function(){
			return (_obj) ? true : false;
		},
		offset: function(){
			return _offset;
		}
	};
})();
if(spotLine._ro()){spotLine.init();}