Ajax.Request.prototype.abort = function() {
    this.transport.onreadystatechange = Prototype.emptyFunction;
    this.transport.abort();
    Ajax.activeRequestCount--;
};

var curIdx;
for(var i = 0, l = t2Array.length; i < l; ++i){
	if(t2Array[i] == spHash.image_id){
		curIdx = i;
	}
}

var spot = (function(){
        var _intervals = [];
	var _timings = {}; _timings.i = [];
	var requests = [], img = $('centralImgId'), cId = curIdx, fotoId = t2Array[cId];
	var _blockload = false;
	var _fromgo = 0;
	var _nowgo = 0;
	var _iever = function(){
		var rv = -1;
		if (navigator.appName == 'Microsoft Internet Explorer'){
			var ua = navigator.userAgent;
			var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
			if (re.exec(ua) != null) rv = parseFloat( RegExp.$1 );
		}
		return rv;
	}	

	var hComp = (_iever() == -1 || _iever() > 7) ? true : false;


	var _timeInterval = function( t ) {
		if (!_timings[t]) _timings[t] = new Date();
	    else {
            _timings.i[_timings.i.length] = t + '=' + ( (new Date()).getTime() - _timings[t].getTime() );
            delete _timings[t];
	    }
	}


	var _renderTimings = function() {
		var _fmt = function(a) {
			return (Math.floor(a*1000)/1000)/1000;
		};
		
		var srv_time = 0;
		var render_time = 0;
		var ti = '';
		var iGet = '';
		for(var i = 0; i < _timings.i.length; i++) {
			if(_timings.i[i].split('=')[0] == 'server') {
				srv_time = parseInt(_timings.i[i].split('=')[1]);
			}
			else {
				ti += _timings.i[i].split('=')[0] + ' = <b>' + _fmt(_timings.i[i].split('=')[1]) + '</b> сек<br>';
				iGet += ((iGet.length > 0) ? ',' : '') + _timings.i[i].split('=')[0] + ':' + (_fmt(_timings.i[i].split('=')[1])*1000);
				render_time += parseInt(_timings.i[i].split('=')[1]);
			}
		}
		var d = document.createElement('div');
		d.id = 'renderBlock';
		d.innerHTML = (_fmt(srv_time)) + ' server + ';
		d.innerHTML += (_fmt(render_time)) + ' rendering(browser) = <b>' + _fmt( srv_time + render_time ) + '</b> total<br />';
		d.innerHTML += ti;
		d.innerHTML += '<div style="position: relative;"><div id="renderBlockTOGgLE" style="position: absolute; bottom: 0; left: -60px;">TOGgLE</div></div>';
		//Booster.canvas.appendChild(d);
		
		d = document.createElement('div');
		d.id = 'radar_graphBlock';
		d.innerHTML += '<img id="radar_graph" src="http://img.imgsmail.ru/0.gif" onclick="this.src=\'http://img.imgsmail.ru/0.gif\'" />';
		//Booster.canvas.appendChild(d);
		
		d = document.createElement('img');
		d.width = '1px'; d.height = '1px';
		var r = 'http://' + PhotoImagineHost() + spHash['CurBox'] + spHash['album_id'] + '/' + _prevUrl;
		d.src='http://foto.radar.imgsmail.ru/update?p=foto&t=spot2d&v=' + (_fmt(render_time)*1000) + '&i=' + iGet + '&rnd=' + Math.floor(Math.random()*1000*1000) + (r ? '&r=' + escape(r) : '') + '';
		
		
		_timings = {}; _timings.i = [];
	}

	var _wname;

	var goAfter = function(){
		if(_fromgo == '1'){
			_blockload = false;
			t2hash[fotoId]['iLoaded'] = true;
			clearTimeout(_intLoad)
			spotLine.setCur();
			spot2_envUpdate();
			
			if(!!t2hash[fotoId]['Title']){
				document.title = 'Фото@Mail.ru: ' + spHash['fio'] + ' : ' + t2hash[fotoId]['Title'];
				try{ pAlert.title = 'Фото@Mail.ru: ' + spHash['fio'] + ' : ' + t2hash[fotoId]['Title']; } catch(e) {}
			} else {
				document.title = 'Фото@Mail.ru: ' + spHash['fio'];
				try{ pAlert.title = 'Фото@Mail.ru: ' + spHash['fio']; } catch(e) {}
			}
			
			_intLoad = setTimeout(function(){

				var r = 'http://' + PhotoImagineHost() + spHash['CurBox'] + spHash['album_id'] + '/' + _prevUrl;
				var u = 'http://' + PhotoImagineHost() + spHash['CurBox'] + spHash['album_id'] + '/' + fotoId;

				_wname = new Date().getTime();
				
				if(typeof spHash['user_MyTop'] != 'undefined'){
					var TmpTime = parseInt(spHash['currenttime']);
					if(TmpTime - 43200 < parseInt(spHash['user_MyTop'])){
						_timeInterval('MyTop');
						_timeInterval('MyTop');
					}
				}

				if (spHash.FotoComm) {
					_timeInterval('FotoComm');
					_timeInterval('FotoComm');
				}

				requests.push(spot.goajax(fotoId));

				_timeInterval('counters');

				var _tns = $('spot2tns');
				_tns.innerHTML = '';
				var url = "http://www.tns-counter.ru/V13a****mail_ru/ru/CP1251/tmsec=mail_foto-other/" + Math.floor(Math.random()*1000*1000);
				var _img = new Element('img', {'width': 1, 'height': 1, 'alt': '', 'src': url});
				_tns.appendChild(_img);

				var url = "http://counter.yadro.ru/hit?r"+
								r + ((typeof(screen)=="undefined") ? "" :
								";s" + screen.width+"*"+screen.height+"*"+(screen.colorDepth ?
								screen.colorDepth : screen.pixelDepth) )+ ";u" + u +
								";" + Math.random();
				var _img = new Element('img', {'width': 1, 'height': 1, 'alt': '', 'src': url});
				_tns.appendChild(_img);

				var js = 13;
				var a = ';r='+r+';j='+navigator.javaEnabled()+
					';s='+screen.width+'*'+screen.height+
					';d='+(screen.colorDepth?screen.colorDepth:screen.pixelDepth);
				var url = 'http://top3.mail.ru/counter'+ '?id=865542;js='+js+a+';rand='+Math.random();
				var _img = new Element('img', {'width': 1, 'height': 1, 'alt': '', 'src': url});
				_tns.appendChild(_img);

				_timeInterval('counters');

			}.bind(this), 350);
			cId = parseInt(t2hash[fotoId]['Index']);
			if(t2Array[cId + parseInt(1)]){
				if(spHash.contestMode){
					$('pers_').href = 'http://' + PhotoImagineHost() + spHash.CurBox + spHash.album_id + '/' + t2Array[cId+1];
					$('next_page').href = 'http://' + PhotoImagineHost() + spHash.CurBox + spHash.album_id + '/' + t2Array[cId+1];
					$('pers_').writeAttribute('go', 'true');
					$('next_page').writeAttribute('go', 'true');
				} else {
					if(typeof t2hash[t2Array[cId+1]]['ContestId'] != 'undefined' && t2hash[t2Array[cId+1]]['ContestId'] != ''){
						$('pers_').href = 'http://' + PhotoImagineHost() + spHash.CurBox + spHash.album_id + '/' + t2Array[cId+1];
						$('next_page').href = 'http://' + PhotoImagineHost() + spHash.CurBox + spHash.album_id + '/' + t2Array[cId+1];
						$('pers_').writeAttribute('go', 'true');
						$('next_page').writeAttribute('go', 'true');
					} else {
						$('pers_').href = '#' + t2Array[cId+1];
						$('next_page').href = '#' + t2Array[cId+1];
						$('pers_').writeAttribute('go', 'false');
						$('next_page').writeAttribute('go', 'false');
					}
				}
			} else {
				$('pers_').href = 'http://' + PhotoImagineHost() + spHash.CurBox + spHash.album_id;
				$('next_page').href = 'http://' + PhotoImagineHost() + spHash.CurBox + spHash.album_id;
				$('pers_').writeAttribute('go', 'true');
				$('next_page').writeAttribute('go', 'true');
			}
			if(t2Array[cId - 1]){
				if(spHash.contestMode){
					$('previous_page').href = 'http://' + PhotoImagineHost() + spHash.CurBox + spHash.album_id + '/' + t2Array[cId-1];
					$('previous_page').writeAttribute('go', 'true');
				} else {
					if(typeof t2hash[t2Array[cId-1]]['ContestId'] != 'undefined' && t2hash[t2Array[cId-1]]['ContestId'] != ''){
						$('previous_page').href = 'http://' + PhotoImagineHost() + spHash.CurBox + spHash.album_id + '/' + t2Array[cId-1];
						$('previous_page').writeAttribute('go', 'true');
					} else {
						$('previous_page').href = '#' + t2Array[cId-1];
					}
				}
			} else {
				$('previous_page').href = '#' + fotoId;
			}
			_nowgo = 0;
			_fromgo = 0;
		}
	}

	var _prevent = false;

	var _iPreload = [];
	var _iForPreload = [];
	
	var _preloadUpdate = function(i){
		var _t1 = (new Date()).getTime();
		var _after = t2hash[t2Array[i+1]];
		if(_after && _after['iLoaded'] != true){
			_iForPreload.push(_after['ImgId']);
		}
		
		var _before = t2hash[t2Array[i-1]];
		if(_before && _before['iLoaded'] != true){
			_iForPreload.push(_before['ImgId']);
		}		
		var _t2 = (new Date()).getTime();
	}
	
	var _preloadImages = function(){
		var _after = t2hash[t2Array[cId+1]];
		if(_after && _after['iLoaded'] != true){
			var n5 = new Image();
			n5.src = 'http://' + PhotoContentHost() + spHash.CurBox + spHash.album_id + '/i-' + _after['ImgId'] + '.jpg';
			//_iPreload.push(n5);
			t2hash[_after['ImgId']]['iLoaded'] = true;
		}
		var _before = t2hash[t2Array[cId-1]];
		if(_before && _before['iLoaded'] != true){
			var n5 = new Image();
			n5.src = 'http://' + PhotoContentHost() + spHash.CurBox + spHash.album_id + '/i-' + _before['ImgId'] + '.jpg';
			//_iPreload.push(n5);
			t2hash[_before['ImgId']]['iLoaded'] = true;
		}
	}

	var _intPreload;
	var _intLoad;
	
	/* ajax history, from now */
	
	var _curHash = spHash.image_id;
	var _initFrame = function(){
		setInterval(_frameHandle, 100);
	}

	var _getHash = function(){
		return (location.hash.replace("#","").length == 0) ? spHash.image_id : location.hash.replace("#","");
	}
	
	var _frameHandle = function(){
		var nowHash = _getHash();
		if(/^[0-9]+$/.test(nowHash) && _curHash != nowHash){
			spot.go_(nowHash);
			_curHash = nowHash;
		}
	}
	
	if(hComp){
		_initFrame();
	}
	
	var _prevUrl = spHash.image_id;
	var _x;
	
	var _fixUrls = function(){
		if(t2Array[t2Array.length-1] == spHash['image_id']){
			$('pers_').writeAttribute('go', 'true');
			$('next_page').writeAttribute('go', 'true');
		}
	}

	_fixUrls();
	
	return {
		go: function(el){
			var isGo = $(el).readAttribute('go');
			if(isGo == 'true'){
		        	document.location.href = el.href;
			} else {
				var i = el.hash.replace('#', '');
				_curHash = i;
				if(hComp){document.location.hash = i;}
				//document.location.hash = i;
				spot.go_(i);

				return false;
			}
		},
		go_: function(i) {
			if(fotoId && fotoId == i) return;
			fotoId = i;
			if(_nowgo != fotoId){
				_nowgo = fotoId;
				if(window['curHash'] == 'undefined'){
					window['curHash'] = {}
				}
				window['curHash'] = t2hash[fotoId];
				_blockload = true;
				_fromgo = 1;
				img.src = 'http://' + PhotoContentHost() + spHash.CurBox + spHash.album_id + '/i-' + fotoId + '.jpg';
				var a = $$('#spot_hiddenwrap img')[0];
				a.src = 'http://' + PhotoContentHost() + spHash.CurBox + spHash.album_id + '/i-' + fotoId + '.jpg';
				goAfter();
			}
			return false;
		},
		cancel: function(){
		},
		preventOn: function(){
			_prevent = true;
		},
		callback: function(t) { 
		    var r = 'http://' + PhotoImagineHost() + spHash['CurBox'] + spHash['album_id'] + '/' + _prevUrl;
			var __d = document.createElement('img');
			__d.width = '1px'; __d.height = '1px';
			__d.src='http://foto.radar.imgsmail.ru/update?p=foto0&t=spot2d&i=srvt:' + (new Date().getTime() - _wname) + '&v=0&rnd=' + Math.floor(Math.random()*1000*1000) + (r ? '&r=' + escape(r) : '') + '';

			if(t.responseText.indexOf('"AccessStatus"') != -1){
				var data = t.responseText.evalJSON(true).shift();
				if(data.AccessStatus == 1){
					document.location.replace('http://' + PhotoImagineHost() + '/catalog/static/warning.html?back=http://' + PhotoImagineHost() + spHash.CurBox + spHash.album_id + '/' +spot.showCurrent());
				} else if (data.AccessStatus == 4){
					document.location.reload(true);
				}
			} else { 
				var data = t.responseText.evalJSON(true);
				this.updatecomments(data.comments, 1); 
				this.updatepersons(data.persons);
				if(!spHash.FotoComm) this.updatex2(parseInt(data.currenttime));
				this.updatemegavote(data.doublevoter);
				this.updatefavtags(data.tags);
				this.updateexif(data.exif); 
				if(typeof data.fio != 'undefined') this.updatefio(data.fio, data.extdomain, data.extuser);
				if(typeof data.ownerfio != 'undefined') this.updatefio(data.ownerfio, data.ownerdomain, data.owneruser);
				if(spHash.photomoderator != '') this.updatemoderator(data.moderate);
				_preloadImages();
			}
			_renderTimings();
			_prevUrl = fotoId;

						
		},
		onerror: function(){},
		goajax: function(item){
			var req = (new Ajax.Request('http://' + PhotoImagineHost() + spHash.CurBox + spHash.album_id + '/' + fotoId + '.spot?env=1', {
				method: 'get',
				onFailure: this.onerror.bind(this),
				onExcepton: this.onerror.bind(this),
				onSuccess: this.callback.bind(this)
			})).item = item;
		},
		showCurrent: function(){
			return fotoId;
		},
		updateinfo : function(t) {
			$('PhotoInfoBlock').update(t);
			if(spHash.usertags) {
				$('spot2-usertags-head').show();
				$('UserTags').update(spHash.usertags);
			}
		},
		updatecomments : function(t, page) { 
			$('spot2-comments').update(t);
			
			if($('add_comment_bord_top'))
				if(t == '') 
					$('add_comment_bord_top').hide();
				else 
					$('add_comment_bord_top').show();
		        if(typeof MRIM != 'undefined'){ MRIM.fetch(''); }
		},
                updatepersons : function(t) {
			$('crop_bound').insert(t);
			arrItems = {};
			arrItems['zflag'] = false;
			allocationSwitchShow('crop_bound','allocation');
			allocationSwitchShow('crop_bound','allocation', true);
		},
		updateexif : function(t) { 
			if(t)
				$$('#LeftMenu .i3')[0]
					.show()
					.select('a')[0]
						.writeAttribute('onclick', '')
						.stopObserving('click')
						.observe('click', this.getexif.bindAsEventListener());
			else {
					$$('#LeftMenu .i3')[0]
						.hide()
						.select('a')[0]
							.writeAttribute('onclick', '')
							.stopObserving('click');
					exif_info = {};
				}
		},
		updatex2 : function(t) {
			spHash.currenttime = t;
					
			if(!spHash.muchestimate) {
				curHash.DoubleVote = parseInt(curHash.DoubleVote);
				if(curHash.DoubleVote > spHash.currenttime) {
						$$('#image_Rate_Vote_Access .x2_active')[0].show();
						$$('#image_Rate_Vote_Access .x2')[0].hide();
					}
				else {
						$$('#image_Rate_Vote_Access .x2_active')[0].hide();
						$$('#image_Rate_Vote_Access .x2')[0].show();
					}
			}
		},
		updatemegavote : function(t) { 
			var elm = $$('.mega')[0];
			if(elm) {
				if(t) { 
					elm
						.writeAttribute('onclick', '')
						.stopObserving('click')
						.select('a')[0]
							.writeAttribute('onclick', '')
							.stopObserving('click')
							.observe('click', function() {hide2x();addVote(10, fotoId, spHash.album_id);return false});
									
					if($('mega')) $('mega').writeAttribute('id', 'mega_active');
				}
				else { 
					elm
						.writeAttribute('onclick', '')
						.stopObserving('click')
						.observe('click', function(e){ e = e || window.event; return InfoBlock.show('SmsBox', e,this, 'smsgame', 'abs', 28,'left', false,'','megavote24')})
						.select('a')[0]
							.writeAttribute('click', '')
							.stopObserving('click');
					
					if($('mega_active')) $('mega_active').writeAttribute('id', 'mega');
				}
			}
		},
		updatefavtags : function(t) {
			if($('txtarForAddToFavorId')) $('txtarForAddToFavorId').setValue(t);
		},
		updatefio : function(t, d, u) {
			if(spHash.extfoto) {
				$('spot2-ext-fio').update(t != '' ? t : 'автор оригинального фото');
				$('spot2-ext-fio').writeAttribute('href', 'http://' + pph+ '/' + d + '/' + u +'/');
				$('ExtAuthor').show();
			} else if(spHash.FotoComm && ($('spot2-comm-fio'))) {
				$('spot2-comm-fio').update(t != '' ? t : 'автор загруженного фото');
				$('spot2-comm-fio').writeAttribute('href', 'http://' + pph+ '/' + d + '/' + u +'/');
				$('CommAuthor').show();
			}
		},
		updatemoderator : function(t) { 
			var mt = $('moderator_tools');
			if(mt) { 
			
				mt.select('a').each(function(a) { 
					a.href = a.href.replace(/id=\d+/,'id='+fotoId); 
				});
				
				$('spot2-moderator-mediaid').value = cId;
				$('spot2-moderator-altpreview').value = t.altpreview;
						
				$('spot2-moderatior-moderated').update(t.moderated);
				$('spot2-moderatior-deletedfromcatalog').update(t.deletedfromcatalog);
				$('spot2-moderatior-ip').update(t.ip);
				
				if(t.best != '' && t.best != '0') {	
					$('spot2-moderator-rotation-note').show();
					$('spot2-moderator-rotation-remove').show();
					$('spot2-moderator-rotation-add').hide();
				}else {
					$('spot2-moderator-rotation-note').hide();
					$('spot2-moderator-rotation-remove').hide();
					$('spot2-moderator-rotation-add').show();
				}
				
				if(t.forprevline != '' && t.forprevline != '0' ) {
					$('spot2-moderator-prevline-remove').show();
					$('spot2-moderator-prevline-add').hide();
				}
				else {
					$('spot2-moderator-prevline-remove').hide();
					$('spot2-moderator-prevline-add').show();
				}
			}
			
		},
		getinfo : function() {
				var req = new Ajax.Request('http://' + PhotoImagineHost() + spHash.CurBox + spHash.album_id + '/' + fotoId + '.spot?info=1', {
							method: 'get',
							onFailure: spot.onerror.bind(this),
							onExcepton: spot.onerror.bind(this),
							onSuccess: function(t) { 
								if(t.responseText.indexOf('"AccessStatus"') == -1){
                                                        		spot.updateinfo(t.responseText);
                                                        	}
						}
				});
		},
		listcomments : function(p) { 
				var req = new Ajax.Request('http://' + PhotoImagineHost() + spHash.CurBox + spHash.album_id + '/' + fotoId + '.spot?comments=1&page=' + p, {
					method: 'get',
					onCreate: function(){},
					onFailure: spot.onerror.bind(this),
					onExcepton: spot.onerror.bind(this),
					onComplete: function(t) { 
						if(t.responseText.indexOf('"AccessStatus"') == -1){
							spot.updatecomments(t.responseText, p); 
						}
						if(typeof MRIM != 'undefined'){ MRIM.fetch(''); }
					}
				});
		},
		getexif : function(e) {
			var req = new Ajax.Request('http://' + PhotoImagineHost() + spHash.CurBox + spHash.album_id + '/' + fotoId + '.spot?exif=1', {
					method: 'get',
					onFailure: spot.onerror.bind(this),
					onExcepton: spot.onerror.bind(this),
					onSuccess: function(t) {
						var data = t.responseText.evalJSON(true); 
						if(typeof data != 'undefined') exif_info = data;
						open_exif(e,'top', $$('#LeftMenu .i3 a')[0]);
					}.bind(this)
			});
		}
	};
})();

function findPos(obj){
    var curLeft = curTop = 0;
    if(obj.offsetParent){
        do {
            curLeft += obj.offsetLeft;
            curTop += obj.offsetTop;
            } while (obj = obj.offsetParent);
        return [curLeft,curTop];
    }
}



function open_exif(e, place, aobj) {
    cancelBubbling(e);
    var ol = findPos(aobj);
    ex_div = gebi('exif_div');
    if(ex_div && ex_div.className == 'exifpos_' + place){
        hideContext();
    } else {
        hideContext();
        no = document.createElement('DIV');
        no.id = 'exif_div';
        no.className = 'exifpos_' + place;
        no.style.zIndex = 1000;
        no.style.left = parseInt(ol[0] - 600) + 'px';
        no.innerHTML = '<div id="exif_wrap"><div id="exif_left"><p class="bh">Камера</p><p><span id="exif_title"></span> <span id="exif_type"></span></p><p id="exif_jpeg_place"></p><div id="p_left"></div></div><div id="exif_right"><p class="bh">Условия съемки (EXIF)</p><table id="params_table"></table></div></div>';
        document.body.appendChild(no);
        fill_exif(exif_info, place);
        pos_exif(place, Event.pointerX(e), ol[1]);
       
        ec = document.createElement('IMG');
        ec.src = 'http://img.mail.ru/r/foto2/ico_close.gif';
        ec.className = 'exif_ico_close';
        ec.onclick = function(){ HideExif(); }
        no.appendChild(ec);
    }


}

var commentRepWrap = function(){
	var a = arguments;
	commentRep(a[0],a[1],a[2],a[3],spot.showCurrent(),a[5],a[6],a[7],a[8]);
	return false;
}

