var stepTimer = {};
var imgpre = { // NAMESPACE
	archive : {},
	getObject : function(id) {
		if (typeof this.archive[id] == "undefined") {
			this.archive[id] = new this.previewList(id);
		}
		return this.archive[id];
	}
};

imgpre.previewList = function(id) { // CONSTRUCTOR
	// Vars and hash
	this.id = id;
	this.inited = false;
	this.image_id;
	this.prevIdArray = [];
	this.prevNameArray = [];
	this.prevDurationArray = [];
	this.prevRateArray = [];
	this.prevJpgArray = [];
	this.prevHtmlArray = [];
	this.curPrevId = null;
	this.curPos = 0;
	this.prevPath = "";
	this.prevPathJpg = "";
	this.prevPathLnk = "";
	this.prevExt = "";
	this.linkPath = "";
	this.linkExt = "";
	this.isRight = 0;
	this.isLeft = 0;
	this.xmlLoad = false;
	this.cellCount = 0;
	this.curLeft = 0;
	// Const
	this.prevWidth = 120;
	this.prevHeight = 120;
	this.prevPaddingRight = 6;
	this.curLeftInterval = 0;
	this.errorArray = {
		1 : "Object initialisation error",
		2 : "NOSCRIPT ID not found",
		3 : "Table of preview list ID is not found",
		4 : "ID of DIV with list is not found",
		5 : "Right scroll ID is not found",
		6 : "Left scroll ID is not found",
		7 : "Preview list is empty",
		8 : "Current preview ID is not set",
		9 : "Add handler is not supported",
		10: "Compare div is not found",
		11: "Preload error"
	};
	// Scroll
	this.resizeTimer = [];
	this.resizeInterval = 100;
	this.initTimeout = 300;
	this.stepTimeout = 110;
	this.stepDirection = "";
	// Prefixes
	this._noscript = "noscript_";
	this._script = "script_";
	this._list = "list_";
	this._goRight = "goright_";
	this._goLeft = "goleft_";
	this._compare = "compare_";
	// HTML-elements
	this.noscript = null;
	this.script = null;
	this.list = null;
	this.goRight = null;
	this.goLeft = null;
	this.compare = null;
	this.preloadDiv = null;
	// Load
	this.alreadyLoaded = {};
	this.loadSpeed = 0;
}

imgpre.previewList.prototype = { // PROTOTYPE
	// ----------- Default -----------
	gebi : function(id) {
		return document.getElementById(id);
	},
	ce : function(name) {
		return document.createElement(name);
	},
	browserDefine : function() {
		this.ua = navigator.userAgent.toLowerCase();
		this.isGecko = this.ua.indexOf("gecko") != -1;
		this.isFF = this.ua.indexOf("firefox") != -1;
	},
	newImg : function(path) {
		var image = new Image();
		image.src = path;
		return image;
	},
	addHandler : function(object, event, handler, useCapture) {
		if (object.addEventListener) {
			object.addEventListener(event, handler, useCapture ? useCapture : false);
		} else if (object.attachEvent) {
			object.attachEvent('on' + event, handler);
		} else alert(this.errorArray[9]);
	},
	screenSize : function() { 
		var w = window.innerWidth ? window.innerWidth : (document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.offsetWidth);
		var h = window.innerHeight ? window.innerHeight : (document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.offsetHeight);
		return {w:w, h:h}; 
	},
	contentCell : function(index,curPos,id,aHref,imgSrc) {
		var cur = '';
		var html = '';
		var megavote = ''; 

		switch(id) {
			case 'listId' : 
				if (curPos == index) {
					var number = '<span class="number_cur">' + parseInt(index+1) + '/' + this.prevIdArray.length + '</span>';
					cur = ' class="on"';
					var fotoname = '<div class="fotoname cur"><a href="' + aHref + '">' + (this.prevNameArray[index] ? this.prevNameArray[index] : 'Без названия') + '</a></div>';
				} else {
					var number = '<span class="number"></span>';
					var fotoname = '<div class="fotoname"><a href="' + aHref + '">' + (this.prevNameArray[index] ? this.prevNameArray[index] : 'Без названия') + '</a></div>';
				}
				if(!!this.megaVoteArray) if(this.megaVoteArray[index] != '') megavote = '<i class="megavote_ico prevline"></i>';
				break;

			case 'likePhoto' : 
				var number = '<span class="number"></span>';
				var fotoname = '';
				break;

			case 'last50' : 
				var number = '<span class="number"></span>';
				var fotoname = '';
				if(!!this.megaVoteArray) if(this.megaVoteArray[index] != '') megavote = '<i class="megavote_ico prevline"></i>';
				break;
		}

		html = '<div>' + number + '<a href="' + aHref + '" title="' + this.prevNameArray[index] + '"><img src="http://img.mail.ru/0.gif" width="'+ this.prevWidth +'" height="' + this.prevHeight + '"' + cur + ' alt="' + this.prevNameArray[index] + '" style="background:url(' + imgSrc + ') center center no-repeat; border-top:none;" /></a>' + megavote + '</div>' + fotoname;
		number = '';
		fotoname = '';
		megavote = '';
		return html;
	},
	// ----------- Init -----------
	findElements : function() {
		this.noscript = this.gebi(this._noscript + this.id);
		if (this.noscript == null) {
			alert(this.errorArray[1] + " : " + this.errorArray[2]);
			return;
		}
		this.script = this.gebi(this._script + this.id);
		if (this.script == null) {
			alert(this.errorArray[1] + " : " + this.errorArray[3]);
			return;
		}
		this.list = this.gebi(this._list + this.id);
		if (this.list == null) {
			alert(this.errorArray[1] + " : " + this.errorArray[4]);
			return;
		}
		this.goRight = this.gebi(this._goRight + this.id);
		if (this.goRight == null) {
			alert(this.errorArray[1] + " : " + this.errorArray[5]);
			return;
		}
		this.goLeft = this.gebi(this._goLeft + this.id);
		if (this.goLeft == null) {
			alert(this.errorArray[1] + " : " + this.errorArray[6]);
			return;
		}
		this.compare = this.gebi(this._compare + this.id);
		if (this.compare == null) {
			alert(this.errorArray[1] + " : " + this.errorArray[10]);
			return;
		}
	},
	init : function() {
		//try {
			this.inited = true;
			this.findElements();
			this.browserDefine();
			if (this.xmlLoad) this.curPrevId = null;
			this.wheelInit();
			this.drawList();
		//} catch(e) {alert(this.errorArray[1]);}

		var id = this.id;
		addHandler(document, "mouseup", function() {imgpre.getObject(id).mouseUpHandler()});
		this.addHandler(this.goLeft, "mousedown", function(evt) {
			evt = evt || window.event;
			if (evt.preventDefault) evt.preventDefault();
		});
		this.addHandler(this.goRight, "mousedown", function(evt) {
			evt = evt || window.event;
			if (evt.preventDefault) evt.preventDefault();
		});
		this.addHandler(this.goLeft, "dragstart", function() {return false;});
		this.addHandler(this.goRight, "dragstart", function() {return false;});
	},
	// ----------- Functional -----------
	drawList : function() {
		if (this.xmlLoad) {
			var _this = this;
			ajax_call_nologin('perl_load_similar',this.image_id,function(arr){
				//_this.curPrevId = 0;
				if (!arr.length) gebi("list_" + this.id).innerHTML = '<span class="t80">Фото нет<\/span>';
				for (var i = 0; i < arr.length; i++) {
					for(var j in arr[i]){
						_this.prevIdArray[i] = i;
						_this.prevNameArray[i] = arr[i]["Title"];
						_this.prevJpgArray[i] = "/" + arr[i]["ImgBox"] + "/p-" + arr[i]["ImgID"] + ".jpg";//if (this.prevJpgArray) 
						_this.prevHtmlArray[i] = arr[i]["UrlHtml"];//if (this.prevHtmlArray) 

					}
				}
				_this.xmlLoad = false;
				_this.drawList();
			});
			return;
		}
		if (this.prevIdArray.length == 0) {
			gebi("list_" + this.id).innerHTML = '<span class="t80">Фото нет<\/span>';
			return;
		}
		// Detect curPos
		for (var i = 0; i < this.prevIdArray.length; i++) {
			if (this.prevIdArray[i] == this.curPrevId) {
				this.curPos = i;
				break;
			}
		}
		// Draw table
		this.resizeHandler();
	},
	setCentral : function() {
		this.curLeft = this.curPos - Math.floor(this.cellCount / 2);
		this.curLeft = this.curLeft < 0 ? 0 : this.curLeft;
		var curRight = this.curLeft + this.cellCount - 1;
		var rem = this.prevIdArray.length - 1 - curRight;

		if (rem < 0) {
			while (rem < 0 && this.curLeft > 0) {
				rem++;
				this.curLeft--;
			}
		}
		
		var PhotoPerlHostPreview = PhotoPerlHost();
		var PhotoContentHostPreview = PhotoContentHost();
		var imgSrc, aHref, index;
		for (var i = 0; i < this.cellCount; i++) {
			var row = this.list.firstChild.rows[0];
			index = this.curLeft + i;
			if (typeof this.prevJpgArray[index] == "undefined") continue;
			imgSrc = 'http://' + PhotoContentHostPreview + this.prevJpgArray[index];// для всего 
			if (this.prevHtmlArray[index]) aHref = this.prevHtmlArray[index];// для ajax
			else aHref = this.prevPathLnk + this.prevIdArray[index] + '.html';// для обычных альбомов и избранного

			row.cells[i].innerHTML = this.contentCell(index,this.curPos,this.id,aHref,imgSrc);
		}
		this.activeLeftRightAngle();
	},
	resizeHandler : function() {
		this.goRight.style.display = this.goLeft.style.display = "";
		var areaWidth = this.compare.offsetWidth - 2 * this.goRight.offsetWidth - 2;
		this.cellCount = Math.floor(areaWidth / (this.prevWidth + this.prevPaddingRight));
		var html = [];
		html.push('<table style="width: 100%;"><tr>');
		for (var i = 0; i < this.cellCount; i++) {
			html.push('<td><img src="http://img.mail.ru/0.gif" width="' + this.prevWidth +'" height="' + this.prevHeight + '" alt="" border="0" /></td>');
		}
		html.push('</tr></table>');
		html = html.join('');
		if (this.list.parentNode) this.list.parentNode.style.border = "1px solid #FFF";
		this.list.innerHTML = html;
		// Show preview
		this.loadPreview(this.curPos);
		this.setCentral();
	},
	loadPreview : function(pos)
	{
		// Load DIV init
		pos = pos || this.curLeft;
		if (this.preloadDiv == null)
		{
			this.preloadDiv = document.createElement("div");
			var s =  this.preloadDiv.style;
			s.position = "absolute";
			s.top = s.left = 0;
			s.visibility = "hidden";
			document.body.appendChild(this.preloadDiv);
		}
		var extra = 2;
		var rightLoad = Math.floor(pos + extra * this.cellCount) < this.prevIdArray.length ? Math.floor(pos + extra * this.cellCount) : this.prevIdArray.length - 1;
		var leftLoad = Math.floor(pos - this.cellCount) > 0 ? Math.floor(pos - this.cellCount) : 0;
		var PhotoContentHostPreview = PhotoContentHost();
		this.preloadDiv.innerHTML = "";
		for (var i = leftLoad; i <= rightLoad; i++)
		{
			if (typeof this.alreadyLoaded[i] != "undefined") continue;
			index = i;
			imgSrc = 'http://' + PhotoContentHostPreview + this.prevJpgArray[index];// для всего 

			//this.preloadDiv.innerHTML += '<img src="' + imgSrc + '" width="120" height="120" alt="" border="0" />';
			this.preloadDiv.innerHTML += '<img src="http://img.mail.ru/0.gif" width="' + this.prevWidth + '" height="' + this.prevHeight + '" alt="" style="background:url(' + imgSrc + ') center center no-repeat;" />';
			this.alreadyLoaded[index] = true;
		}
	},
	activeLeftRightAngle : function() {
		if (this.cellCount >= this.prevIdArray.length) {
			this.goRight.style.display = this.goLeft.style.display = "none";
		} else {
			this.goRight.style.display = this.goLeft.style.display = "";
			// Right
			if (this.curLeft + this.cellCount + 1 > this.prevIdArray.length) {
				this.goRight.innerHTML = "";
				this.isRight = false;
			} else {
				this.goRight.innerHTML = "<a onmousedown=\"imgpre.getObject('" + this.id + "').scrollInit('r');\" onclick=\"return false;\" href=\"#\"><img src=\"http://img.mail.ru/0.gif\" width=\"25\" height=\"" + this.prevHeight + "\" alt=\"\" /></a>";
				this.isRight = true;
			}
			// Left
			if (this.curLeft <= 0) {
				this.goLeft.innerHTML = "";
				this.isLeft = false;
			} else {
				this.goLeft.innerHTML = "<a onmousedown=\"imgpre.getObject('" + this.id + "').scrollInit('l');\" onclick=\"return false;\" href=\"#\"><img src=\"http://img.mail.ru/0.gif\" width=\"25\" height=\"" + this.prevHeight + "\" alt=\"\" /></a>";
				this.isLeft = true;
			}
		}
	},
	scrollInit : function(order) {
		this.stepDirection = order;
		var id = this.id; // IE timer fix
		stepTimer[id] = setInterval("imgpre.getObject('" + id + "').scrollRepeat()", this.initTimeout);
	},
	scrollRepeat : function() {
		this.doStep();
		var id = this.id; // IE timer fix
		if (stepTimer[id] != null) {
			clearInterval(stepTimer[id]);
			stepTimer[id] = null;
			stepTimer[id] = setInterval("imgpre.getObject('" + id + "').scrollRepeat()", this.stepTimeout);
		}
	},
	mouseUpHandler : function() {
		var id = this.id; // IE timer fix
		if (stepTimer[id] == null) return;
		clearInterval(stepTimer[id]);
		stepTimer[id] = null;
		this.doStep();
	},
	doStep : function() {
		var PhotoPerlHostPreview = PhotoPerlHost();
		var PhotoContentHostPreview = PhotoContentHost();
		var imgSrc, aHref, index;
		
		if (this.stepDirection == "l") {
			this.curLeft--;
			var index = this.curLeft;
			var row = this.list.firstChild.rows[0];
			row.deleteCell(this.cellCount - 1);
			imgSrc = 'http://' + PhotoContentHostPreview + this.prevJpgArray[this.curLeft];// для всего 
			if (this.prevHtmlArray[this.curLeft]) aHref = this.prevHtmlArray[this.curLeft];// для ajax
			else aHref = this.prevPathLnk + this.prevIdArray[this.curLeft] + '.html';// для обычных альбомов и избранного

			row.insertCell(0).innerHTML = this.contentCell(index,this.curPos,this.id,aHref,imgSrc);
		} else if (this.stepDirection == "r") {
			this.curLeft++;
			var row = this.list.firstChild.rows[0];
			row.deleteCell(0);
			var curRight = this.curLeft + this.cellCount - 1;
			var index = curRight;
			imgSrc = 'http://' + PhotoContentHostPreview + this.prevJpgArray[curRight];// для всего 
			if (this.prevHtmlArray[curRight]) aHref = this.prevHtmlArray[curRight];// для ajax
			else aHref = this.prevPathLnk + this.prevIdArray[curRight] + '.html';// для обычных альбомов и избранного

			row.insertCell(-1).innerHTML = this.contentCell(index,this.curPos,this.id,aHref,imgSrc);
		}
		this.loadSpeed++;
		if (this.loadSpeed % 5 == 0) this.loadPreview();
		this.activeLeftRightAngle();
		if (this.stepDirection == "l" && !this.isLeft || this.stepDirection == "r" && !this.isRight) {
			var id = this.id; // IE timer fix
			clearInterval(stepTimer[id]);
			stepTimer[id] = null;
		}
	}
}



function createLikePhoto(obj)
{
	if(!imgpre.getObject(obj).inited)
	{
		imgpre.getObject(obj).xmlLoad = true;
		//imgpre.getObject(obj).prevWidth = 45;
		//imgpre.getObject(obj).prevHeight = 45;
		imgpre.getObject(obj).image_id = image_id_createLikePhoto;
		imgpre.getObject(obj).init();
		imgpre.getObject(obj).setCentral();
	}
}
function showLikePhoto(obj)
{
	var obj = (obj || obj != 'defined') ? obj : 'likePhoto';
	var container;
	if (container = gebi('script_' + obj)) {
		if (container.style.visibility == 'visible')
		{
			container.style.visibility = 'hidden';
			container.style.width = '1px';
			container.style.height = '1px';
			container.style.position = 'absolute';
		}
		else
		{
			container.style.visibility = 'visible';
			container.style.width = '100%';
			container.style.height = 'auto';
			container.style.position = 'static';

			createLikePhoto(obj);
		}
	}
	return false;
}

//Wheel plugin
imgpre.previewList.prototype.wheelState = false;
imgpre.previewList.prototype.wheelLength = 1;
imgpre.previewList.prototype.absPosition = function(obj) { 
	var x = y = 0; 
	while(obj) { 
		x += obj.offsetLeft; 
		y += obj.offsetTop; 
		obj = obj.offsetParent; 
	} 
	return {x:x, y:y}; 
}
imgpre.previewList.prototype.defPosition = function(event) { 
	var x = y = 0; 
	if (document.attachEvent != null) { // Internet Explorer & Opera 
		x = window.event.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft); 
		y = window.event.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop); 
	} else if (!document.attachEvent && document.addEventListener) { // Gecko 
		x = event.clientX + window.scrollX; 
		y = event.clientY + window.scrollY; 
	} // else { // do nothing }
	return {x:x, y:y}; 
}
imgpre.previewList.prototype.scrollMode = 0;
imgpre.previewList.prototype.scrollModeTimer = null;
imgpre.previewList.prototype.scrollModeInterval = 1000;
imgpre.previewList.prototype.clearScrollMode = function() {
	this.scrollMode = 0;
	clearTimeout(this.scrollModeTimer);
	this.scrollModeTimer = null;
}
imgpre.previewList.prototype.wheelInit = function() {
	var _this = this;
	var id = this.id;
	var wheel = function(event) {
		if (document.attachEvent) {
			var x_1 = _this.absPosition(_this.list.parentNode).x;
			var x_2 = _this.absPosition(_this.list.parentNode).x + _this.list.parentNode.offsetWidth;
			var y_1 = _this.absPosition(_this.list.parentNode).y;
			var y_2 = _this.absPosition(_this.list.parentNode).y + _this.list.parentNode.offsetHeight;
			var mx = _this.defPosition(event).x;
			var my = _this.defPosition(event).y;
			if ((mx < x_1 || mx > x_2) || (my < y_1 || my > y_2)) { // Указатель вне превлайна
				if (!_this.scrollMode) {
					_this.scrollMode = 1;
					_this.scrollModeTimer = setTimeout("imgpre.getObject('"+id+"').clearScrollMode()", _this.scrollModeInterval);
				}
				if (_this.scrollMode != 2) return;
			}
		} else if (!_this.wheelState) {
			if (!_this.scrollMode) {
				_this.scrollMode = 1;
				_this.scrollModeTimer = setTimeout("imgpre.getObject('"+id+"').clearScrollMode()", _this.scrollModeInterval);
			}
			if (_this.scrollMode != 2) return;
		}
		if (_this.scrollMode == 1) return;
		_this.scrollMode = 2;
		_this.scrollModeTimer = setTimeout("imgpre.getObject('"+id+"').scrollMode=0", _this.scrollModeInterval);
		var delta; // -N down, N up
		event = event || window.event;
		if (event.wheelDelta) {
			delta = event.wheelDelta / 120;
			//if (window.opera) delta = -delta;
		} else if (event.detail) delta = -event.detail / 3;
		if (event.preventDefault)  event.preventDefault();
		event.returnValue = false;
		_this.wheelStep(delta);
	}
	addHandler(window, 'DOMMouseScroll', wheel); /* Gecko */
	addHandler(window, 'mousewheel', wheel); /* Opera */
	addHandler(document, 'mousewheel', wheel); /* IE */
	
	addHandler(this.list, 'mouseover', function() {
		_this.wheelState = true;
	});
	addHandler(this.list, 'mouseout', function() {
		_this.wheelState = false;
	});
}
imgpre.previewList.prototype.wheelStep = function(delta) {
	this.stepDirection = delta < 0 ? "r" : "l";
	//прокручивать на каждый 2й скролл
	if (this.wheelLength % 2 == 0) if (this.stepDirection == "l" && this.isLeft || this.stepDirection == "r" && this.isRight) this.doStep();
	this.wheelLength++;
}
//end Wheel plugin
