// Default
function addHandler(object, event, handler, useCapture) {
	if (object.addEventListener) {
		object.addEventListener(event, handler, useCapture ? useCapture : false);
	} else if (object.attachEvent) {
		object.attachEvent('on' + event, handler);
	}
}

// Object
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.prevPathArray = [];
	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 = 85;
	this.prevHeight = 65;
	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 -----------
	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}; 
	},
	// ----------- Init -----------
	findElements : function() {
		this.noscript = web.$(this._noscript + this.id);
		if (this.noscript == null) {
			alert(this.errorArray[1] + " : " + this.errorArray[2]);
			return;
		}
		this.script = web.$(this._script + this.id);
		if (this.script == null) {
			alert(this.errorArray[1] + " : " + this.errorArray[3]);
			return;
		}
		this.list = web.$(this._list + this.id);
		if (this.list == null) {
			alert(this.errorArray[1] + " : " + this.errorArray[4]);
			return;
		}
		this.goRight = web.$(this._goRight + this.id);
		if (this.goRight == null) {
			alert(this.errorArray[1] + " : " + this.errorArray[5]);
			return;
		}
		this.goLeft = web.$(this._goLeft + this.id);
		if (this.goLeft == null) {
			alert(this.errorArray[1] + " : " + this.errorArray[6]);
			return;
		}
		this.compare = web.$(this._compare + this.id);
		if (this.compare == null) {
			alert(this.errorArray[1] + " : " + this.errorArray[10]);
			return;
		}
	},
	init : function() {
		//try {
			this.inited = true;
			this.findElements();
			
			var id = this.id;
			this.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;});
			this.addHandler(window, "resize", function() {
				if (imgpre.getObject(id).resizeTimer[id]) {
					clearTimeout(imgpre.getObject(id).resizeTimer[id]);
					imgpre.getObject(id).resizeTimer[id] = null;
				}
				imgpre.getObject(id).resizeTimer[id] = setTimeout("imgpre.getObject('"+id+"').resizeHandler()", this.resizeInterval);
			});
			
			this.browserDefine();
			if (this.xmlLoad) this.curPrevId = null;
			this.drawList();
		//} catch(e) {alert(this.errorArray[1]);}
	},
	// ----------- Functional -----------
	drawList : function() {
		if (this.prevIdArray.length == 0) {
			web.$("list_" + this.id).innerHTML = '<div>Фото нет<\/div>';
			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 imgSrc, aHref, index;
		for (var i = 0; i < this.cellCount; i++) {
			index = this.curLeft + i;
			if (typeof this.prevJpgArray[index] == "undefined") continue;
			imgSrc = this.prevJpgArray[index];// для всего
			aHref = (this.prevPathArray.length > index) ? this.prevPathArray[index] : this.prevPathLnk;
			aHref = aHref + this.prevIdArray[index];
      if (this.prevPathLnk_postfix) aHref = aHref + this.prevPathLnk_postfix;
			fTitle = this.prevNameArray[index];
			if (this.id == 'videoId') {
				web.$("pf_" + this.id + i).innerHTML = '<div class="u-pre-video"><a href="'+aHref+'"><i>'
					+ '<img src="'+imgSrc+'" alt="">'
					+ (this.curPrevId == this.prevIdArray[index] ? '' : '<b></b>')
					+ '<span>'+fTitle+'</span>'
					+ '</i></a></div>';
      } else if (this.id == 'panoramaId') {
				web.$("pf_" + this.id + i).innerHTML = '<div class="u-pre-video"><a href="'+aHref+'"><i>'
					+ '<img src="'+imgSrc+'" alt="">'
					+ (this.curPrevId == this.prevIdArray[index] ? '' : '<b></b>')
					+ '<span>'+fTitle+'</span>'
					+ '</i></a></div>';
			} else if (this.id == 'listIndexId') {
				web.$("pf_" + this.id + i).innerHTML = '<a href="' + aHref + '"><img src="' + imgSrc + '" alt="'+(fTitle ? fTitle.replace('"', '&quot;') : '')+'" title="'+(fTitle ? fTitle.replace('"', '&quot;') : '')+'" />'+(fTitle ? '<br />' + fTitle : '') + '</a>';
				if (this.prevFullNameArray && this.prevFullNameArray[index]) web.$("pf_" + this.id + i).innerHTML += 
					'<a href="'+aHref+'" class="hover" style="visibility:hidden;">'+this.prevFullNameArray[index]+'</a>';
				web.$("pf_" + this.id + i).onmouseover = function() {
					var hover = this.firstChild.nextSibling;
					if (hover) hover.style.visibility = 'visible';
				}
				web.$("pf_" + this.id + i).onmouseout = function() {
					var hover = this.firstChild.nextSibling;
					if (hover) hover.style.visibility = 'hidden';
				}
			} else if (this.id == 'listIndexIdBlog') {
			  web.$("pf_" + this.id + i).innerHTML = '<div><a href="' + aHref + '"><img src="' + imgSrc + '" alt="" />'+(fTitle ? '<br />' + fTitle : '') + ' все его записи</a></div>'; 
			} else 
				web.$("pf_" + this.id + i).innerHTML = '<a href="' + aHref + '"><img src="' + imgSrc + '" alt="'+(fTitle ? fTitle.replace('"', '&quot;') : '')+'" title="'+(fTitle ? fTitle.replace('"', '&quot;') : '')+'" />'+(fTitle ? '<br />' + fTitle : '') + '</a>';
			if (this.curPrevId == this.prevIdArray[index])
				web.$("pf_" + this.id + i).parentNode.className = "on";
		}
		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));
		this.cellCount = this.cellCount > this.prevIdArray.length ? this.prevIdArray.length : this.cellCount;
		var html = [];

		if (this.cellCount < this.prevIdArray.length) {
			html.push('<table class="w100"><tr>');
			this.goRight.style.display = this.goLeft.style.display = "";
		} else {
			html.push('<table><tr>');
			this.goRight.style.display = this.goLeft.style.display = "none";
		}

		for (var i = 0; i < this.cellCount; i++) {
			index = this.curLeft + i;
			html.push('<td><div id="pf_' + this.id + i + '">&nbsp;</div></td>');
		}
		html.push('</tr></table>');
		html = html.join('');
		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;
			this.preloadDiv.innerHTML += '<img src="' + this.prevJpgArray[i] + '" alt="" />';
			this.alreadyLoaded[i] = true;
		}
	},
	activeLeftRightAngle : function() {
		this.goRight.style.display = this.goLeft.style.display = "";
		// Right
		if (this.curLeft + this.cellCount + 1 > this.prevIdArray.length) {
			if (this.id == 'videoId' || this.id == 'panoramaId')
				this.goRight.style.display = "none";
			else
				this.goRight.innerHTML = "";
			this.isRight = false;
		} else {
			if (this.id == 'videoId' || this.id == 'panoramaId')
				this.goRight.style.display = "block";
			else if (this.id == 'galId')
				this.goRight.innerHTML = "<a onmousedown=\"imgpre.getObject('" + this.id + "').scrollInit('r');\" onclick=\"return false;\" href=\"#\" title=\"Вперед\"><img src=\"/img/html/0.gif\" alt=\"\" /></a>";
			else
				this.goRight.innerHTML = "<a onmousedown=\"imgpre.getObject('" + this.id + "').scrollInit('r');\" onclick=\"return false;\" href=\"#\" title=\"Вперед\"></a>";
			this.isRight = true;
		}
		// Left
		if (this.curLeft <= 0) {
			if (this.id == 'videoId' || this.id == 'panoramaId')
				this.goLeft.style.display = "none";
			else
				this.goLeft.innerHTML = "";
			this.isLeft = false;
		} else {
			if (this.id == 'videoId' || this.id == 'panoramaId')
				this.goLeft.style.display = "block";
			else if (this.id == 'galId')
				this.goLeft.innerHTML = "<a onmousedown=\"imgpre.getObject('" + this.id + "').scrollInit('l');\" onclick=\"return false;\" href=\"#\" title=\"Назад\"><img src=\"/img/html/0.gif\" alt=\"\" /></a>";
			else
				this.goLeft.innerHTML = "<a onmousedown=\"imgpre.getObject('" + this.id + "').scrollInit('l');\" onclick=\"return false;\" href=\"#\" title=\"Назад\"></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 imgSrc, aHref, index, ctd;
		
		if (this.stepDirection == "l") {
			this.curLeft--;
			var row = this.list.firstChild.rows[0];
			row.deleteCell(this.cellCount - 1);

			imgSrc = this.prevJpgArray[this.curLeft];
			aHref = (this.prevPathArray.length > this.curLeft) ? this.prevPathArray[this.curLeft] : this.prevPathLnk;
			aHref = aHref + this.prevIdArray[this.curLeft];
			if (this.prevPathLnk_postfix)
				aHref = aHref + this.prevPathLnk_postfix;
			fTitle = this.prevNameArray[this.curLeft];

			if (this.id == 'videoId') {
				row.insertCell(0).innerHTML = '<div class="u-pre-video"><a href="'+aHref+'"><i>'
					+ '<img src="'+imgSrc+'" alt="">'
					+ (this.curPrevId == this.prevIdArray[this.curLeft] ? '' : '<b></b>')
					+ '<span>'+fTitle+'</span>'
					+ '</i></a></div>';
			} else if (this.id == 'panoramaId') {
				row.insertCell(0).innerHTML = '<div class="u-pre-video"><a href="'+aHref+'"><i>'
					+ '<img src="'+imgSrc+'" alt="">'
					+ (this.curPrevId == this.prevIdArray[this.curLeft] ? '' : '<b></b>')
					+ '<span>'+fTitle+'</span>'
					+ '</i></a></div>';
			} else if (this.id == 'listIndexId') {
				ctd = row.insertCell(0);
				ctd.innerHTML = '<div><a href="' + aHref + '"><img src="' + imgSrc + '" alt="'+(fTitle ? fTitle.replace('"', '&quot;') : '')+'" title="'+(fTitle ? fTitle.replace('"', '&quot;') : '')+'" />'+(fTitle ? '<br />' + fTitle : '') + '</a>' +
					(this.prevFullNameArray && this.prevFullNameArray[this.curLeft] ? '<a href="'+aHref+'" class="hover" style="visibility:hidden;">'+this.prevFullNameArray[this.curLeft]+'</a>' : '') + '</div>';
				ctd.firstChild.onmouseover = function() {
					var hover = this.firstChild.nextSibling;
					if (hover) hover.style.visibility = 'visible';
				}
				ctd.firstChild.onmouseout = function() {
					var hover = this.firstChild.nextSibling;
					if (hover) hover.style.visibility = 'hidden';
				}
		  } else if (this.id == 'listIndexIdBlog') {
			  row.insertCell(0).innerHTML = '<div><a href="' + aHref + '"><img src="' + imgSrc + '" alt="" />'+(fTitle ? '<br />' + fTitle : '') + ' все его записи</a></div>';
			} else 
				row.insertCell(0).innerHTML = '<div><a href="' + aHref + '"><img src="' + imgSrc + '" alt="" />'+(fTitle ? '<br />' + fTitle : '') + '</a></div>';

			if (this.curPos == this.curLeft)
				row.cells[0].className = 'on';

		} else if (this.stepDirection == "r") {
			this.curLeft++;
			var row = this.list.firstChild.rows[0];
			row.deleteCell(0);
			var curRight = this.curLeft + this.cellCount - 1;

			imgSrc = this.prevJpgArray[curRight];
			aHref = (this.prevPathArray.length > curRight) ? this.prevPathArray[curRight] : this.prevPathLnk;
			aHref = aHref + this.prevIdArray[curRight];
			if (this.prevPathLnk_postfix)
				aHref = aHref + this.prevPathLnk_postfix;
			fTitle = this.prevNameArray[curRight];

			if (this.id == 'videoId') {
				row.insertCell(-1).innerHTML = '<div class="u-pre-video"><a href="'+aHref+'"><i>'
					+ '<img src="'+imgSrc+'" alt="">'
					+ (this.curPrevId == this.prevIdArray[curRight] ? '' : '<b></b>')
					+ '<span>'+fTitle+'</span>'
					+ '</i></a></div>';
			} else if (this.id == 'panoramaId') {
				row.insertCell(-1).innerHTML = '<div class="u-pre-video"><a href="'+aHref+'"><i>'
					+ '<img src="'+imgSrc+'" alt="">'
					+ (this.curPrevId == this.prevIdArray[curRight] ? '' : '<b></b>')
					+ '<span>'+fTitle+'</span>'
					+ '</i></a></div>';
			} else if (this.id == 'listIndexId') {
				ctd = row.insertCell(-1);
				ctd.innerHTML = '<div><a href="' + aHref + '"><img src="' + imgSrc + '" alt="'+(fTitle ? fTitle.replace('"', '&quot;') : '')+'" title="'+(fTitle ? fTitle.replace('"', '&quot;') : '')+'" />'+(fTitle ? '<br />' + fTitle : '') + '</a>' +
					(this.prevFullNameArray && this.prevFullNameArray[curRight] ? '<a href="'+aHref+'" class="hover" style="visibility:hidden;">'+this.prevFullNameArray[curRight]+'</a>' : '') + '</div>';
				ctd.firstChild.onmouseover = function() {
					var hover = this.firstChild.nextSibling;
					if (hover) hover.style.visibility = 'visible';
				}
				ctd.firstChild.onmouseout = function() {
					var hover = this.firstChild.nextSibling;
					if (hover) hover.style.visibility = 'hidden';
				}
			} else if (this.id == 'listIndexIdBlog') {
			  row.insertCell(-1).innerHTML = '<div><a href="' + aHref + '"><img src="' + imgSrc + '" alt="" />'+(fTitle ? '<br />' + fTitle : '') + ' все его записи</a></div>';
			} else 
				row.insertCell(-1).innerHTML = '<div><a href="' + aHref + '"><img src="' + imgSrc + '" alt="" />'+(fTitle ? '<br />' + fTitle : '') + '</a></div>';

			if (this.curPos == curRight)
				row.cells[row.cells.length-1].className = 'on';

		}
		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;
		}
	}
}

