// 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.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 = 50;
	this.prevHeight = 50;
	this.prevPaddingRight = 16;
	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.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}; 
	},
	// ----------- 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();
			this.drawList();
		//} catch(e) {alert(this.errorArray[1]);}
	},
	// ----------- Functional -----------
	drawList : function() {
		if (this.prevIdArray.length == 0) {
			gebi("list_" + this.id).innerHTML = 'Ôîòî íåò';
			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.prevPathJpg + this.prevJpgArray[index];
			aHref = this.prevPathLnk + this.prevIdArray[index] + "/";
//			if (this.id == "foto") {
//				this.gebi("pf_" + this.id + i).innerHTML = '<div class="photo-1'+(this.curPos == index ? " on" : "")+'"><a href="' + aHref + '"><img src="' + imgSrc + '" width="'+this.prevWidth+'" height="'+this.prevHeight+'" /></a></div><div class="video-2'+(this.curPos == index ? " on" : "")+'"><a href="'+aHref+'" class="grey t11">'+this.prevNameArray[index]+'</a></div>';
			this.gebi("pf_" + this.id + i).innerHTML = '<div'+(this.curPos == index ? " class=\"on\"" : "")+'><a href="' + aHref + '" style="background-image: url(\'' + imgSrc + '\');" title="'+this.prevNameArray[index]+'">&nbsp;</a></div>';
		}
		this.activeLeftRightAngle();

		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;});
		this.addHandler(window, "resize", function() {imgpre.getObject(id).resizeHandler();});
	},
	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><tr>');
		for (var i = 0; i < this.cellCount; i++) {
			html.push('<td id="pf_' + this.id + i + '">&nbsp;</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;
		this.preloadDiv.innerHTML = "";
		for (var i = leftLoad; i <= rightLoad; i++) {
			if (typeof this.alreadyLoaded[i] != "undefined") continue;
			this.preloadDiv.innerHTML += '<div><a style="background-image: url(\'' + this.prevPathJpg + this.prevJpgArray[i] +'\');">&nbsp;</a></div>';
			this.alreadyLoaded[i] = 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 = '<div class="r">&nbsp;</div>';
				this.isRight = false;
			} else {
				this.goRight.innerHTML = '<div class="r"><a onmousedown="imgpre.getObject(\'' + this.id + '\').scrollInit(\'r\');" onclick="return false;" href="#">&nbsp;</a></div>';
				this.isRight = true;
			}
			// Left
			if (this.curLeft <= 0) {
				this.goLeft.innerHTML = '<div class="l">&nbsp;</div>';
				this.isLeft = false;
			} else {
				this.goLeft.innerHTML = '<div class="l"><a onmousedown="imgpre.getObject(\'' + this.id + '\').scrollInit(\'l\');" onclick="return false;" href="#">&nbsp;</a></div>';
				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;
		if (this.stepDirection == "l") {
			this.curLeft--;
			var row = this.list.firstChild.rows[0];
			row.deleteCell(this.cellCount - 1);
			imgSrc = this.prevPathJpg + this.prevJpgArray[this.curLeft];
			aHref = this.prevPathLnk + this.prevIdArray[this.curLeft];
//			if (this.id == "foto") {
//				row.insertCell(0).innerHTML = '<div class="photo-1'+(this.curPos == this.curLeft ? " on" : "")+'"><a href="' + aHref + '"><img src="' + imgSrc + '" width="'+this.prevWidth+'" height="'+this.prevHeight+'" /></a></div><div class="video-2'+(this.curPos == this.curLeft ? " on" : "")+'"><a href="'+aHref+'" class="grey t11">'+this.prevNameArray[this.curLeft]+'</a></div>';
			row.insertCell(0).innerHTML = '<div'+(this.curPos == this.curLeft ? " class=\"on\"" : "")+'><a href="' + aHref + '" style="background-image: url(\'' + imgSrc + '\');" title="'+this.prevNameArray[this.curLeft]+'">&nbsp;</a></div>';
		} else if (this.stepDirection == "r") {
			this.curLeft++;
			var curRight = this.curLeft + this.cellCount - 1;
			var row = this.list.firstChild.rows[0];
			row.deleteCell(0);
			imgSrc = this.prevPathJpg + this.prevJpgArray[curRight];
			aHref = this.prevPathLnk + this.prevIdArray[curRight];
//			if (this.id == "foto") {
//				row.insertCell(-1).innerHTML = '<div class="photo-1'+(this.curPos == curRight ? " on" : "")+'"><a href="' + aHref + '"><img src="' + imgSrc + '" width="'+this.prevWidth+'" height="'+this.prevHeight+'" /></a></div><div class="video-2'+(this.curPos == curRight ? " on" : "")+'"><a href="'+aHref+'" class="grey t11">'+this.prevNameArray[curRight]+'</a></div>';
			row.insertCell(-1).innerHTML = '<div'+(this.curPos == curRight ? " class=\"on\"" : "")+'><a href="' + aHref + '" style="background-image: url(\'' + imgSrc + '\');" title="'+this.prevNameArray[curRight]+'">&nbsp;</a></div>';
		}
		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;
		}
	}
}
