var ie5 = (navigator.userAgent.indexOf("MSIE 5") != -1) ? true : false;
var ie6 = (navigator.userAgent.indexOf("MSIE 6") != -1) ? true : false;
var ie7 = (navigator.userAgent.indexOf("MSIE 7") != -1) ? true : false;
var ff1 = (navigator.userAgent.indexOf("Firefox/1") != -1) ? true : false;
var ff2 = (navigator.userAgent.indexOf("Firefox/2") != -1) ? true : false;
var op9 = (navigator.userAgent.indexOf("Opera/9") != -1) ? true : false;

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.prevHDArray = [];
	this.prevPathJpg = "";
	this.prevPathLnk = "";
	this.curPrevId = null;
	this.curPos = 0;
	this.prevPath = "";
	this.prevExt = "";
	this.linkPath = "";
	this.linkExt = "";
	this.isRight = 0;
	this.isLeft = 0;
	this.JSONLoad = false;
	this.cellCount = 0;
	this.curLeft = 0;
	this.frontendCopy = "";
	this.querySearch = "";
	this.theme = "";
	this.themeEng = "";
	this.image_ThemeId = "";
	// Const
	this.prevWidth = 98;
	this.prevHeight = 96;
	this.prevPaddingRight = 10;
	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) {
		if (id != 'likeId') { 
			var curnum = '';
			var cur = this.curPos == index ? ' cur' : ''; 
			if (cur) curnum = '<div class="curnum">' + (curPos + 1) + "/" + this.prevIdArray.length + '</div>';
		}
		else { var cur = ''; var curnum = ''; }
		
		var hd_ico = "";
		if (this.prevHDArray[index] == "1") { hd_ico = "<div class=\"HD_ico\"></div>"; }
		
		if(this.prevIdArray[index] == "empty") aHref = "http://" + VideoPerlHost() + "/catalog/static/wait.html?с=1"; 
		
		var re = /\&amp;/g;
		this.prevNameArray[index] = this.prevNameArray[index].replace(re,"\&");
		
		return '<div><div class="preview1' + cur + '"><div><a class="pv" href="' + aHref + '" onmouseover="pv.getObj(this).display({dynamic : true})"><img src="' + this.prevPathJpg + imgSrc + '" width="120" height="90" alt="" title="" border="0" /></a></div><div class="duration1">'+show_duration(this.prevDurationArray[index])+'</div>' + curnum + '' + hd_ico + '</div><div class="preview_link"><a href="' + aHref + '">' + this.prevNameArray[index] + '</a></div>';
	},
	// ----------- 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.JSONLoad) this.curPrevId = null;
			this.drawList();
			this.wheelInit();
		//} 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.JSONLoad) {
			var _this = this; 
			var _url = 'http://' + VideoPerlHost() + '/ajaxsearch?q=' + this.querySearch + '&theme=' + this.themeEng + '&image_ThemeId=' + this.image_ThemeId + '&page=1&from=' + escape(window.location);
			
			ajax_call_static(_url,function(FromUri,arr){ 
				if (arr.length > 0) { 
					gebi("script_" + _this.id).style.display = "block";
					gebi("videoLike").style.display = "block";
				}
				var f=0;
				for (var i = 0; i < arr.length; i++) {
					if(FromUri != arr[i]["UrlHtml"] && arr[i]["UrlJpg"] != "") {
					for(var j in arr[i]){
						
						if(arr[i]){
						_this.prevIdArray[f] = f;
						_this.prevHtmlArray[f] = "http://r.mail.ru/cln5322/" + VideoPerlHost() + arr[i]["UrlHtml"];
						_this.prevJpgArray[f] = arr[i]["UrlJpg"];
						_this.prevRateArray[f] = (arr[i]["Rate"]) ? arr[i]["Rate"] : "0";
						_this.prevDurationArray[f] = (arr[i]["Duration"]) ? arr[i]["Duration"] : "00:00";
						_this.prevNameArray[f] = (arr[i]["Title"]) ? arr[i]["Title"] : "Без названия";
						_this.prevHDArray[f] = arr[i]["HDexist"];
						}
						}
					f++;
					}
				}
				_this.JSONLoad = 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 VideoPerlHostPreview = VideoPerlHost();
		var VideoContentHostPreview = VideoContentHost();
		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;
			if (!this.frontendCopy) imgSrc = this.prevJpgArray[index];// для всего кроме this.frontendCopy = true
			else imgSrc = this.prevJpgArray[index];// для this.frontendCopy = true
			if (this.prevHtmlArray[index]) aHref = this.prevHtmlArray[index];// для ajax
			else aHref = this.prevPathLnk + this.prevIdArray[index] + '.html';// для обычных альбомов и избранного

			if(this.id == 'likeId'){ aHref = (aHref.indexOf('?') == -1) ? aHref + '?liked=1' : aHref + '&liked=1'; }
			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 class="stripevideos1" style="width: 100%;"><tr>');
		for (var i = 0; i < this.cellCount; i++) {
			html.push('<td><img src="http://img.mail.ru/0.gif" width="120" height="90" alt="" /></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 VideoContentHostPreview = VideoContentHost();
		this.preloadDiv.innerHTML = "";
		for (var i = leftLoad; i <= rightLoad; i++)
		{
			if (typeof this.alreadyLoaded[i] != "undefined") continue;
			index = i;
			if (!this.frontendCopy) imgSrc = this.prevJpgArray[index];// для всего кроме this.frontendCopy = true
			else imgSrc = this.prevJpgArray[index];// для this.frontendCopy = true
			if (this.prevHtmlArray[index]) aHref = this.prevHtmlArray[index];// для ajax
			else aHref = this.prevPathLnk + this.prevIdArray[index] + '.html';// для обычных альбомов и избранного

			this.preloadDiv.innerHTML += '<img src="' + imgSrc + '" width="90" height="68" alt="" border="0" />';
			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=\"#\"></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=\"#\"></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 VideoPerlHostPreview = VideoPerlHost();
		var VideoContentHostPreview = VideoContentHost();
		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);
			if (!this.frontendCopy) imgSrc = this.prevJpgArray[index];// для всего кроме this.frontendCopy = true
			else imgSrc = this.prevJpgArray[index];// для this.frontendCopy = true
			if (this.prevHtmlArray[this.curLeft]) aHref = this.prevHtmlArray[this.curLeft];// для ajax
			else aHref = this.prevPathLnk + this.prevIdArray[this.curLeft] + '.html';// для обычных альбомов и избранного

			if(this.id == 'likeId'){ aHref = (aHref.indexOf('?') == -1) ? aHref + '?liked=1' : aHref + '&liked=1'; }
			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;
			if (!this.frontendCopy) imgSrc = this.prevJpgArray[index];// для всего кроме this.frontendCopy = true
			else imgSrc = this.prevJpgArray[index];// для this.frontendCopy = true
			if (this.prevHtmlArray[curRight]) aHref = this.prevHtmlArray[curRight];// для ajax
			else aHref = this.prevPathLnk + this.prevIdArray[curRight] + '.html';// для обычных альбомов и избранного

			if(this.id == 'likeId'){ aHref = (aHref.indexOf('?') == -1) ? aHref + '?liked=1' : aHref + '&liked=1'; }
			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;
		}
	},
	
		createQuery : function(name,theme,descr,tag) {
		var re,q,i = 0,arr = [];
		if (theme != "") {
						re = /([а-яА-Яa-zA-Z0-9_]+),/;
						if (re.exec(theme))	{ theme = RegExp.$1;}
							else {
								re = /([а-яА-Яa-zA-Z0-9_]+)/;
								if (re.exec(theme))	theme = RegExp.$1;
								}
						}
						
		if (name != "") { arr[i] = name; i++;}
		else if (tag != "") { arr[i] = tag; i++;} 
		else if (descr != "") { arr[i] = this.cutFirst(descr); i++;}
		else if (theme != "") { arr[i] = theme; i++;}
		
		q = arr.join(" ");
		
		q = q.toLowerCase();
		q = str_replace("\"","",q);
		q = str_replace("\'","",q);
		q = str_replace("<","",q);
		q = str_replace(">","",q);
		q = str_replace(">","",q);
		q = str_replace("&quot;","",q);
		q = str_replace("&laquo;","",q);
		q = str_replace("&raquo;","",q);
		
		this.querySearch = q;
	},
	
	countWords :  function(str) {
		var arr = [];
		arr = str.split(" ");
		return arr.length;
	},
	
	cutFirst : function(str){
		var re,q;
		re = /([а-яА-Яa-zA-Z0-9_]+)\s/;
		re.exec(str);
		q = RegExp.$1;
		return q;
	},
	
	encodeUTF : function(string) {
	
	 string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
	
	
	}

}

function showLikeVideo() {
	var container;
	if (container = gebi("script_likeId")) {
		if (container.style.display == "block" ) container.style.display = "none"; 
		else {
			container.style.display = "block";
			if(!imgpre.getObject('likeId').inited) {
				imgpre.getObject('likeId').JSONLoad = true;
				imgpre.getObject('likeId').init();
				imgpre.getObject('likeId').setCentral();
				addHandler(window, "resize", function() {
					imgpre.getObject('likeId').setCentral();
				});
			}
		}
	}
	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