function getCookie(NameOfCookie)
{
 if (document.cookie.length > 0) 
{ begin = document.cookie.indexOf(NameOfCookie+"="); 
if (begin != -1) 
{ begin += NameOfCookie.length+1; 
end = document.cookie.indexOf(";", begin);
if (end == -1) end = document.cookie.length;
return unescape(document.cookie.substring(begin, end)); } 
}
return null; 
}



function setCookie(NameOfCookie, value, expiredays) 
{ var ExpireDate = new Date ();
ExpireDate.setTime(ExpireDate.getTime() + (expiredays * 60 * 1000));
document.cookie = NameOfCookie + "=" + escape(value) + 
((expiredays == null) ? "" : "; expires=" + ExpireDate.toGMTString())+";path=/";
}



function delCookie (NameOfCookie) 
{ if (getCookie(NameOfCookie)) {
document.cookie = NameOfCookie + "=" +
"; expires=Thu, 01-Jan-70 00:00:01 GMT";
}

}

Event.observe(window, 'load', function() {
	InteractiveScroll.init();
//	InteractiveScroll.setCallbackFunction(giveMeMyProducts);
})

var InteractiveScroll = {
	init: function() {
		if ($(document).getElementsByClassName('interactiveScroll')) {
			this.scrollList = $($(document).getElementsByClassName('interactiveScroll')[0]);
			if (!this.scrollList) return;

    		if(this.scrollBar) {this.scrollBar.remove();};
			if(this.result) {this.result.remove();};
			if(this.scrollContainer) {this.scrollContainer.remove();};

			this.products = $A(this.scrollList.getElementsByTagName('li'));
			this.setPropertyClass('properties');
			this.createContainer();
			this.createScrollBar();
			this.createResultContainer();
			this.setScrollWidth();
			this.findPricesAndProperties();
			this.findUnits();
			this.sortProducts();
			this.recalculate();
			my=getCookie('eurodom'+id);
			if(my) {this.moveSliderTo(my);};
			this.scrollContainer.observe('scroll', InteractiveScroll.doResize.bindAsEventListener(InteractiveScroll));
			Event.observe(window, 'resize', InteractiveScroll.doResize.bindAsEventListener(InteractiveScroll));
			InteractiveScroll.doResize();
		    used=getCookie('eurodom_used_scroll');
		    if(!used) {jQuery('#scrollcomment').fadeIn('slow');};
		}
	},
	doResize: function(e) {
		this.recalculate();
		this.doDelayCallback()
	},
	setPropertyClass: function(className) {
		this.propertyClass = className;
	},
	getPropertyClass: function(className) {
		return this.propertyClass;
	},
	callbackFunction: function() {},
	setCallbackFunction: function(fn) {
		this.callbackFunction = fn;
	},
	evalCallbackFunction: function() {
		if (!this.delayCallback) {
			this.callbackFunction(this.getSelectedProductsForCallback());
		}
	},
	createContainer: function() {
		this.scrollContainer = $(document.createElement('div'));
		this.scrollContainer.addClassName('interactiveScrollContainer');
		this.scrollList.parentNode.insertBefore(this.scrollContainer, this.scrollList);
		this.scrollList.parentNode.removeChild(this.scrollList);
		this.scrollContainer.appendChild(this.scrollList);
	},
	createScrollBar: function() {
		this.scrollBar = this.createDivWithSpan('scrollBar', this.scrollContainer);
		this.arrowLeft = this.createDivWithSpan('arrowLeft', this.scrollBar);

		this.toleft = this.createDivWithSpan('toleft', this.scrollBar);
//		this.toleft.innerHTML = "1111";
		this.slider = this.createDivWithSpan('slider', this.scrollBar);
		this.slider.firstChild.appendChild(document.createElement('span'));
		this.arrowRight = this.createDivWithSpan('arrowRight', this.scrollBar);

		this.slider.style.position = 'relative';
		this.movingSlider = false;
		this.scrollList.style.left = 0;
		this.scrollList.style.position = 'relative';
		this.arrowLeft.observe('click', InteractiveScroll.moveScrollDown.bindAsEventListener(InteractiveScroll));
		
		this.toleft.observe('click', InteractiveScroll.moveScrollDown.bindAsEventListener(InteractiveScroll));
		
		
		this.arrowRight.observe('click', InteractiveScroll.moveScrollUp.bindAsEventListener(InteractiveScroll));
		this.scrollBar.observe('click', InteractiveScroll.scrollPage.bindAsEventListener(InteractiveScroll));

		InteractiveScroll.moveSlider = InteractiveScroll._moveSlider.bindAsEventListener(InteractiveScroll);
		this.slider.observe('click', function(e){Event.stop(e);});
		this.slider.observe('mousedown', InteractiveScroll.startMovingSlider.bindAsEventListener(InteractiveScroll));
		Event.observe(document, 'mouseup', InteractiveScroll.stopMovingSlider.bindAsEventListener(InteractiveScroll));

		this.scrollContainer.observe('DOMMouseScroll', InteractiveScroll.scrollWheel.bindAsEventListener(InteractiveScroll));
		this.scrollContainer.observe('mousewheel', InteractiveScroll.scrollWheel.bindAsEventListener(InteractiveScroll));
	},
	
	
//вот эта хрень
	
	scrollPage: function(e) {
	
		if ((Position.cumulativeOffset(this.slider)[0] + this.slider.getWidth()) < Event.pointerX(e)) {
			this.slider.style.left = this.sliderOffsetLimit(this.getSliderOffset() + this.slider.getWidth()*0.9) + 'px';
		} else {
			this.slider.style.left = this.sliderOffsetLimit(this.getSliderOffset() - this.slider.getWidth()*0.9) + 'px';
		}
		this.moveSliderTo(this.sliderToProducts(this.getSliderOffset()));

		this.evalCallbackFunction();
		Event.stop(e);
	},
	
	scrollPageLeft: function(e) {
		this.slider.style.left = this.sliderOffsetLimit(this.getSliderOffset() - this.slider.getWidth()*0.9) + 'px';
		this.moveSliderTo(this.sliderToProducts(this.getSliderOffset()));
		this.evalCallbackFunction();
		Event.stop(e);
	},
	
	scrollPageRight: function(e) {
		this.slider.style.left = this.sliderOffsetLimit(this.getSliderOffset() + this.slider.getWidth()*0.9) + 'px';
		this.moveSliderTo(this.sliderToProducts(this.getSliderOffset()));
		this.evalCallbackFunction();
		Event.stop(e);
	},
	
	
	createDivWithSpan: function(className, parent) {
		var result = $(document.createElement('div'));
		result.addClassName(className);
		result.appendChild(document.createElement('span'));
		parent.appendChild(result);
		return result;
	},
	createResultContainer: function() {
		
		
		
		
		this.result = $(document.createElement('div'));
		this.result.addClassName('result');
		
		
		this.br = $(document.createElement('br'));
		this.br.style.clear = "both";
		
		this.scrollContainer.appendChild(this.br);
//		this.scrollContainer.appendChild(this.result);
		
		
		this.table = $(document.createElement('table'));
		this.table.addClassName('tableresult');
		
		this.scrollContainer.appendChild(this.table);
//		this.tr = this.table.insertRow();
		this.tr = this.table.insertRow(-1); //кто не проверяет код во всех браузерах, тот лох
		
		this.td1 = this.tr.insertCell(0);
		this.td1.setAttribute("valign", "top");
		this.td1.style.padding = "0px 0px 0px 7px"; //4 0 0 7
		this.larr = $(document.createElement('a'));
		this.larr.style.color = "#666";
		this.larr.style.display = "block";
		this.larr.style.margin = "3px 0px 0px 0px";
		this.larr.style.textDecoration = "none";
		this.larr.setAttribute("href", "#");
		
		//тут лево
		this.larr.innerHTML = "&larr;";
		this.td1.appendChild(this.larr);
		
		
		
		

		this.td2 = this.tr.insertCell(1);
		this.td2.setAttribute("valign", "top");
		this.td2.appendChild(this.result);
		
		
		this.td3 = this.tr.insertCell(2);
		this.td3.setAttribute("valign", "top");
		this.td3.style.padding = "0px 0px 0px 10px"; //4 0 0 7
		this.rarr = $(document.createElement('a'));
		this.rarr.style.color = "#666";
		this.rarr.style.display = "block";
		this.rarr.style.margin = "3px 0px 0px 0px";
		this.rarr.style.textDecoration = "none";
		this.rarr.setAttribute("href", "#");
		//тут право
		this.rarr.innerHTML = "&rarr;";
		this.td3.appendChild(this.rarr);
		
		

		
		
		
		this.larr.observe('click', InteractiveScroll.scrollPageLeft.bindAsEventListener(InteractiveScroll));
		this.rarr.observe('click', InteractiveScroll.scrollPageRight.bindAsEventListener(InteractiveScroll));

		
	},
	startMovingSlider: function(e) {
		if (Event.isLeftClick(e)) {
			this.movingSlider = true;
			this.startingMouseX = Event.pointerX(e);
			this.startingSliderOffset = this.getSliderOffset();
			Event.observe(document, 'mousemove', InteractiveScroll.moveSlider);
			Event.observe(document, 'selectstart', InteractiveScroll.stopSelect);
			Event.stop(e);
		}
	},
	stopSelect: function(e) {
		Event.stop(e);
	},
	_moveSlider: function(e) {
		if (this.movingSlider) {
			this.slider.style.left = this.sliderOffsetLimit(this.startingSliderOffset + Event.pointerX(e) - this.startingMouseX) + 'px';
			this.moveSliderTo(this.sliderToProducts(this.getSliderOffset()));
		}
	},
	getSliderOffset: function() {
		return parseInt(this.slider.style.left);
	},
	moveSliderTo: function(offset) {
		setCookie('eurodom'+id,offset,2);
		setCookie('eurodom_used_scroll','1',1*60*24*30);
		this.setScrollListOffset(offset);
		this.recalculate();
		jQuery('#scrollcomment').fadeOut('slow');
	},
	setScrollListOffset: function(offset) {
		if (offset == null) offset = -parseInt(this.scrollList.style.left);
		this.scrollList.style.left = '-' + this.scrollOffsetLimit(offset) + 'px';
	},
	sliderOffsetLimit: function(offset) {
		var maxOffset = this.scrollBar.getWidth() - this.arrowLeft.getWidth() - this.arrowRight.getWidth() - this.slider.getWidth();
		if (offset < 0) return 0;
		if (offset > maxOffset) return maxOffset;
		return offset;
	},
	stopMovingSlider: function(e) {
		if (this.movingSlider == true) {
			this.movingSlider = false;
			Event.stopObserving(document, 'mousemove', InteractiveScroll.moveSlider);
			Event.stopObserving(document, 'selectstart', InteractiveScroll.stopSelect);
			this.evalCallbackFunction();
		}
	},
	moveScrollUp: function(e) {
		this.moveScrollBy(1);
		Event.stop(e);
	},
	moveScrollDown: function(e) {
		this.moveScrollBy(-1);
		Event.stop(e);
	},
	moveScrollBy: function(step) {
		for(var i = 0; i < this.products.length; i++) {
			if (this.isInRange(this.products[i])) {
				if (!currentProduct) {
					var currentProduct = this.products[i];
				} else if (Position.cumulativeOffset(this.products[i])[0] < Position.cumulativeOffset(currentProduct)[0]) {
					currentProduct = this.products[i];
				}
			}
		}
		if (step > 0) {
 			if ($(currentProduct).next(step-1)) this.moveScrollToProduct($(currentProduct).next(step-1));
		} else {
			if ($(currentProduct).previous(-step-1)) this.moveScrollToProduct($(currentProduct).previous(-step-1));
		}
	},
	moveScrollToProduct: function(product) {
		var currentOffset = 0;
		for(var i = 0; i < this.products.length; i++) {
			if (Position.cumulativeOffset(this.products[i])[0] < Position.cumulativeOffset(product)[0]) {
				currentOffset += this.getProductWidth(this.products[i]);
			}
		}
		this.moveSliderTo(currentOffset);
		this.recalculate();
		this.evalCallbackFunction();
	},
	scrollOffsetLimit: function(offset) {
		if (offset < 0) return 0;
		if (offset > this.scrollList.getWidth() - this.scrollContainer.getWidth()) return this.scrollList.getWidth()-this.scrollContainer.getWidth();
		return offset;
	},
	recalculate: function() {
		if (this.checkScrollWidth()) {
			this.setScrollListOffset();
			this.setSliderPosition();
			this.calculateResult();
			return true;
		} else {
			return false;
		}
	},
	checkScrollWidth: function() {
	  if (this.scrollList.getWidth() < this.scrollContainer.getWidth()) {
		this.scrollList.style.left = '0px';

		if(this.scrollList.hasClassName('noHide')) {
			this.scrollBar.style.display='none';
			this.larr.style.display='none';
			this.rarr.style.display='none';
			} else 
			{ 
			this.larr.style.display='block';
			this.rarr.style.display='block';
			this.scrollContainer.style.height = '0px';
		};
		
		this.evalCallbackFunction();
	    return false;
		  } else {

		if(this.scrollList.hasClassName('noHide')) {
			this.scrollBar.style.display='block';
			} else 
			{ 
			this.scrollContainer.style.height = 'auto';
		};
	   return true;
	  }
 },
	setSliderPosition: function() {
		this.slider.style.width = this.productsToSlider(this.scrollContainer.getWidth()) + 'px';
		this.slider.style.left = this.productsToSlider(-parseInt(this.scrollList.style.left)) + 'px';
	},
	productsToSlider: function(width) {
		return ((this.scrollBar.getWidth()-this.arrowLeft.getWidth()-this.arrowRight.getWidth()) * [(width / this.scrollList.getWidth()),1].min());
	},
	sliderToProducts: function(width) {
		return (this.scrollList.getWidth() * width / (this.scrollBar.getWidth()-this.arrowLeft.getWidth()-this.arrowRight.getWidth()));
	},
	findPricesAndProperties: function() {
		for(var i = 0; i < this.products.length; i++) {
			this.products[i].price = this.getPrice(this.products[i]);
			this.products[i].properties = this.getProperties(this.products[i]);
		}
	},
	getPrice: function(element) {
		return parseInt(this.getPriceText(element)) || 0;
	},
	getPriceText: function(element) {
//		return $(element).getElementsByClassName('price').size() ? $(element).getElementsByClassName('price')[0].innerHTML : '';
		return $(element).getElementsByClassName('price').length ? $(element).getElementsByClassName('price')[0].innerHTML : '';
	},
	getProperties: function(element) {
		return $(element).getElementsByClassName(this.getPropertyClass()).length ? $(element).getElementsByClassName(this.getPropertyClass())[0].innerHTML.split(', ') : [];
//		return $(element).getElementsByClassName(this.getPropertyClass()).size() ? $(element).getElementsByClassName(this.getPropertyClass())[0].innerHTML.split(', ') : [];
	},
	findUnits: function() {
		for(var i = 0; i < this.products.length; i++) {
			if (this.units = this.getPriceText(this.products[i]).match(/[0-9,\.-]*(.*)/)[1]) break;
		}
	},
	resortProducts: function(sortBy) {
		sortBy = sortBy ? sortBy : 'price';
		if (sortBy == 'price') {
			this.scrollList.removeClassName('sortByProperties');
			this.scrollList.addClassName('sortByPrice');
		} else {
			this.scrollList.addClassName('sortByProperties');
			this.scrollList.removeClassName('sortByPrice');
			this.setPropertyClass(sortBy);
		}
		this.findPricesAndProperties();
		this.sortProducts();
		this.recalculate();
	},
	sortProducts: function() {
		if (this.scrollList.hasClassName('sortByProperties')) {
			var products_sorted = this.sortProductsByProperties();
		} else if (this.scrollList.hasClassName('sortByPrice')) {
			var products_sorted = this.sortProductsByPrice();
		} else {
			var products_sorted = this.sortBoth();
		}
		this.products.invoke('remove');
		for(var i = 0; i < products_sorted.length; i++) {
			this.scrollList.appendChild(products_sorted[i])
		}
		this.products = products_sorted;
	},
	sortProductsByPrice: function() {
		return this.products.sortBy(function(value,index){return value.price});
	},
	sortProductsByProperties: function() {
		return this.products.sortBy(function(value,index){return (value.properties.length>0 ? value.properties.sort().join('') : 'ÑÑÑÑÑÑÑÑÑÑÑ');});
	},
	sortBoth: function() {
		return this.products.sortBy(function(value,index){return (value.price/1000000)+(value.properties.length>0 ? value.properties.sort().join('') : 'ÑÑÑÑÑÑÑÑÑÑÑ');});
	},
	setScrollWidth: function() {
		var width = 0;
		for(var i = 0; i < this.products.length; i++) {
			width += this.getProductWidth(this.products[i]);
		}
		this.scrollList.style.width = width + 'px';
	},
	getProductWidth: function(product) {
		return $(product).getWidth() + parseInt(product.getStyle('margin-left')) + parseInt(product.getStyle('margin-right'));
	},
	calculateResult: function() {
		var prices = [];
		var properties = [];
		for(var i = 0; i < this.products.length; i++) {
			if (this.isInRange(this.products[i])) {
				if (!this.scrollList.hasClassName('sortByProperties') && this.products[i].price) {prices.push(this.products[i].price);}
				if (this.scrollList.hasClassName('sortByProperties') && this.products[i].properties) {properties = properties.concat(this.products[i].properties);}
			}
		}
		this.result.innerHTML = '';
		if ($A(prices).max() > 0) {
			this.result.innerHTML += '<div class="price">'+(($A(prices).min() != $A(prices).max()) ? $A(prices).min() + '&mdash;' : '') + $A(prices).max() + this.units + ' <span id="scrollcomment" style="display:none;background:gold">&uarr; потяните скроллер</span></div>';
		}
		if (properties) {
			properties = properties.uniq().sort();
			this.result.innerHTML += '<div class="properties">'+properties.join(', ')+'</div>';
		}
	},
	isInRange: function(element) {
		return Position.within(this.scrollContainer, Position.cumulativeOffset(element)[0]+element.getWidth()/2, Position.cumulativeOffset(element)[1]);
	},
	getSelectedProductsForCallback: function() {
		var result = [];
		var result2 =[];
		for(var i = 0; i < this.products.length; i++) {
			if (this.isInRange(this.products[i])) result.push(this.products[i].getAttribute('id'));
			result2.push(this.products[i].getAttribute('id'));
		}
		if(result=='') result=result2;
		return result;
	},
	scrollWheel: function(e){
		var delta = 0;
		if (e.wheelDelta) {
			delta = e.wheelDelta/120;
			if (window.opera) delta = -delta;
		} else if (e.detail) {
			delta = -e.detail/3;
		}
		this.doDelayCallback()
		this.moveScrollBy(delta > 0 ? -1 : 1);
		Event.stop(e);
	},
	doDelayCallback: function() {
		if (!this.delayCallback && !this.doStartTimeout) {this.doStartTimeout = true;}
		this.delayCallback = true;
		if (!this.delayCallback || this.doStartTimeout) {
			this.doStartTimeout = false;
			setTimeout(function(){InteractiveScroll.delayCallback = false; InteractiveScroll.evalCallbackFunction();}, 1000);
		}
	}
}


function giveMeMyProducts(products) {
	var cbl = document.getElementById('callbackLogger');
	cbl.innerHTML += (cbl.innerHTML ? '<br /><br />' : '') + 'Products =';
	for (var i=0; i < products.length; i++) {
		cbl.innerHTML += ((i == 0 ? ' ': ', ') + products[i]);
	};
}

