/* $Id: product.js,v 1.111 2011-09-27 12:16:33 bfitrzyk Exp $ */
var viewerBrowserZIndex = 120;

function popup()
{
  window.open('/sklep/porownaj_produkty.xml','comparer','width=950,height=800,scrollbars=yes,status=yes,resizable=yes');
}

$(document).ready(function(){
	$("#transBackground").css("height", $(document).height());
	if ($("#go_to_comparer"))
	{
		$("#go_to_comparer").click(function()
		{
			popup();
			return false;
		});
	}

	initProductTabs();
	initSetHighlighting();
	initPriceUpdate();
});

$(window).bind("resize", function(){
	$("#transBackground").css("height", $(window).height());
});

function preloadFromArray(arrayOfPaths) {
    $(arrayOfPaths).each(function(){
    	(new Image()).src = this;
    });
}

// uzycie
// preloadFromElementArray(['img/imageName.jpg','img/anotherOne.jpg','img/blahblahblah.jpg']);

function initProductTabs()
{
	// activating tabs -> can use tab links or external content links with class '.activate_tab'
	var tabs = $("#product-tabs .tabs li a");
	tabs.click(function(event){
		event.preventDefault();
		var rel = $(this).attr("rel");
		activateTab($(this), "#" + rel);
	});

	var activationLinks = $(".activate-tab");
	activationLinks.click(function(event){
		event.preventDefault();
		var rel = $(this).attr("rel");
		var tab = tabs.parent().find("a[rel='" + rel + "']");
		activateTab(tab, "#" + rel);
		$.scrollTo("#product-tabs", 300);
	});
}

function activateTab(tab, contentId)
{
	var tabs = $("#product-tabs .tabs li a");
	tabs.removeClass("active");
	tab.addClass("active");

	var tabsContent = $("#product-tabs .tab-content");
	tabsContent.addClass("hidden");
	$(contentId).removeClass("hidden");
}

/* zestawy - podswietlanie wybranego */
function initSetHighlighting()
{
	highlightSet();
	$("#attrs ul li input:radio").click(function(){
		highlightSet();
	});
}

function highlightSet()
{
	$("#attrs ul li").removeClass("active");
	$("#attrs ul li input:radio:checked").parent().addClass("active");
}

/* zestawy - dynamiczna aktualizacja ceny */
function initPriceUpdate()
{
	var oldPriceContainer = $("#old-price");
	var newPriceContainer = $("#new-price");
	
	if (oldPriceContainer.length > 0 && newPriceContainer.length > 0)
	{
		var oldPrice = parseFloat(oldPriceContainer.html().replace(',','.'));
		var newPrice = parseFloat(newPriceContainer.html().replace(',','.'));

		$("#attrs ul li input:radio").change(function()	{
			var modifierPrice = 0;
			var value = $("#attrs ul li input:radio:checked").parent().find("label > .modifier_price").html();
			if (value != null) modifierPrice = parseFloat(value.replace(',','.'));
	
			if (!isNaN(oldPrice))
			{
				oldPriceContainer.html(oldPrice + modifierPrice).priceFormat();
			}
	
			newPriceContainer.html(newPrice + modifierPrice).priceFormat();
		});
	}
}

/* formatowanie ceny - jquery plugin */
(function($) {
    $.fn.priceFormat = function() {
        $(this).each(function(i) {
        	if(isNaN(parseFloat($(this).html().replace(',','.')))) return;

        	var price = parseFloat($(this).html().replace(',','.')).toFixed(2);
        	price = price.replace(".", ","); // format to polish - toLocaleString() is not working
        	$(this).html(price);

        	//Math.round(original*100)/100

        });
        return this;
    }
})(jQuery);

function imageBrowser(productName, productAvailable)
{
	var img = $JM("product_img");
	if(!img) return;

	var header;
	var imgBrowser;
	var browse; // browse layer
	var ieFrame;
	var wrapper;
	var imagesList;
	var interval;
	var imagesArray = new Array();
	var tmpPhotos = new Array();
	var preloadPaths = new Array();
	var otherPhotos = $JM("product_other_photos");
	var productInfo = $JM("product_info");
	var headerTitle = "";						// "Przegl\u0105darka zdj\u0119\u0107: ";
	var changing = false;
	var currentImgWidth = 500;
	var currentImgHeight = 225;

	var baseLongWidth = 700;
	var baseWidth = 300;
	var baseLongHeight = 450;
	var baseHeight = 225;

	var thumbnailsVisible = 5;
	var zoomW = 480;
	var zoomH = 400;

	generateBrowser();
	return;

	function getImageDimensions(srcPath)
	{
		var newImg = new Image();
		newImg.src = srcPath;//
		var dimensions = new Array();
		dimensions['height'] = newImg.height;
		dimensions['width'] = newImg.width;
		return dimensions;
	}

	function generateBrowser()
	{
		imgBrowser = createElement("div",{"id":"image_browser"});
		imgBrowser.onmousedown = function() { this.style.zIndex = viewerBrowserZIndex++; }
		//if(getCookie("browser_resize") == -1) addClass(imgBrowser,"long");
		$JM('imgbrowserparent').appendChild(imgBrowser);

		// thumbnails list
		var images = otherPhotos?otherPhotos.getElementsByTagName("a"):[];

		//Original:
//		imgBrowser.style.left = (productInfo.offsetLeft + 33) + "px";
//		imgBrowser.style.top = (productInfo.offsetTop + 33) + "px";

		//New for zoom:
		var pageContainer = $JM('container');
		imgBrowser.style.left = parseInt(pageContainer.offsetLeft,10) + 16 + "px";
		imgBrowser.style.top = (parseInt(productInfo.offsetTop,10) + parseInt(pageContainer.offsetTop,10) + 20) + "px";

		ieFrame = createElement("iframe",{"src":"/images/misc/empty.gif","frameBorder":"0"});
		imgBrowser.appendChild(ieFrame);

		img.onclick = function()
		{
			// show info about window
			//if(!getCookie("browser_info"))
			{
			//	setCookie("browser_info","1","/");
			//	myAlert("Otowrzy\u0142e\u015B okienko przegl\u0105dania zdj\u0119\u0107 produktu. Aby zamkn\u0105\u0107 okienko naci\u015Bnij przycisk X w jego g\u00F3rnym prawym rogu");
			}
			$('#transBackground').fadeIn();
			this.blur();
			var minimize = header.className.indexOf("minimize") == -1;
			var visible = imgBrowser.className.indexOf("visible") != -1;
			// check if not already visible
			if(visible && minimize) return false;

			if(!minimize) minMaxButton.onclick();
			if(visible)
				return false;

			preloadFromArray(preloadPaths);

			imgBrowser.style.visibility = "visible";
			addClass(imgBrowser,"visible");
			return false;
		}


		// header
		header = createElement("div",{"className":"header"});
		header.innerHTML = headerTitle + "Podstawowe zdj\u0119cie";
		imgBrowser.appendChild(header);

		// big img
		currentImgWidth = (containsClass(imgBrowser,"long")?baseLongWidth:baseWidth);
		currentImgHeight = (containsClass(imgBrowser,"long")?baseLongHeight:baseHeight);
		var image = createElement("div",{"className":"image","title":""},{"backgroundImage":"url('/converter?widthMax="+currentImgWidth+"&heightMax="+currentImgHeight+"&img="+img.pathname+"')"});

		//Preloader
		$(images).each(function(){
			preloadPaths.unshift(this.pathname);
			preloadPaths.push("/converter?widthMax="+currentImgWidth+"&heightMax="+currentImgHeight+"&img="+this.pathname);
	    });

		var zoomLayer = createElement("img",{"src":"/images/misc/blank.gif","title":""},{});
		var tmpDims = getImageDimensions("/converter?widthMax="+currentImgWidth+"&heightMax="+currentImgHeight+"&img="+img.pathname);
		var adjustXZoomPosition = 0;


		if (tmpDims['width'] <= 0)
		{
			tmpDims['width'] = currentImgWidth;
		}

		adjustXZoomPosition = Math.ceil((currentImgWidth + 132 - tmpDims['width']) / 2) - 1;

		if(images.length > thumbnailsVisible){
			zoomH += 19;
		}
		var zoomHref = createElement("a",{href:(img.pathname.charAt(0)!='/')?'/'+img.pathname:img.pathname,className:"cloud-zoom",title:"",rel:"adjustY:-52,adjustX:"+adjustXZoomPosition+",zoomWidth:"+zoomW+",zoomHeight:"+zoomH},{});

		image.style.width = tmpDims['width'] + "px"
		zoomLayer.style.width = tmpDims['width'] + "px";
		zoomHref.style.width = tmpDims['width'] + "px";

		zoomHref.appendChild(zoomLayer);
		$(zoomHref).click(function(event){
			event.preventDefault();
		});

		image.appendChild(zoomHref);
		imgBrowser.appendChild(image);

		// close
		var closeButton = createElement("span",{"className":"close","title":"Zamknij okienko ze zdj\u0119ciami","innerHTML":"Powrót"});
		$('#transBackground').click(closeButton.onclick = function() { $('#transBackground').fadeOut();removeClass(imgBrowser,"visible"); imgBrowser.style.visibility = "hidden"; return false; });
		imgBrowser.appendChild(closeButton);

		// full size
		// przy zoomie raczej zbedny
		// ale przywrocony na prosbe
		var fullSize = createElement("span",{"className":"fullsize","title":"Zobacz oryginalny obrazek","innerHTML":"Pe\u0142ny rozmiar"});
		fullSize.onclick = function(e)
		{
			var tmp = image.style.backgroundImage;
			tmp = tmp.slice(tmp.indexOf("img=")+4,-1);
			if(tmp.slice(-1) == "\"") tmp = tmp.slice(0,-1);
			if (tmp.charAt(0)!='/') tmp='/'+tmp;
			window.open(tmp,"_blank");

			//Anulowanie propagacji
			if (!e) var e = window.event;
			e.cancelBubble = true;
			if (e.stopPropagation) e.stopPropagation();
			return false;
		}
		//Uwaga na propagacje zdarzenia!
		//image.onclick = fullSize.onclick;
		imgBrowser.appendChild(fullSize);

		if(images.length > 1){
			var prevButton = createElement("span",{"id":"prevImageButton","className":"prev","title":"Poprzednie zdj\u0119cie","innerHTML":"Poprzednie"});
			imgBrowser.appendChild(prevButton);
			var nextButton = createElement("span",{"id":"nextImageButton","className":"next","title":"Nast\u0119pne zdj\u0119cie","innerHTML":"Nast\u0119pne"});
			imgBrowser.appendChild(nextButton);
		}

		if(images.length > 0)
		{
			browse = createElement("div",{"className":"browse"});
			imgBrowser.appendChild(browse);
			wrapper = createElement("div",{"className":"wrapper"});
			browse.appendChild(wrapper);
			imagesList = createElement("ul",false,{"width":((images.length*82)+10)+"px"});
			wrapper.appendChild(imagesList);

			// add thumbnails
			for( var i = 0; i < images.length; i++ )
			{
				var li = createElement("li");
				var a = createElement("a",{className:(i>0?"":"active"),"href":images[i].href,"title":"Powi\u0119ksz zdj\u0119cie: "+images[i].innerHTML,"innerHTML":images[i].innerHTML},
				{"backgroundImage":"url('/converter?widthMax=65&heightMax=45&img="+images[i].pathname+"')"});
				//alert(escape());
				imagesArray[i]=a;
				li.appendChild(a);
				imagesList.appendChild(li);
			}

			if(images.length == 1){
				var noMorePics = createElement("p",{"className":"noMorePics"});
				noMorePics.innerHTML = "Brak dodatkowych zdj\u0119\u0107 produktu";
				wrapper.appendChild(noMorePics);
			}

			serviceBrowser();
		}

		// services
		servicePhotos();

		// create scroll (only if there is more than 6 images)
		var refServiceScrollBar = null;
		if(images.length > thumbnailsVisible)
		{
			var scrollBar = createElement("div",{"className":"scrollbar"});
			// 400 is base, if more images, then scroller is mniejszy :)
			var scrollWidth = (baseWidth - (images.length - 6)*20);
			if(scrollWidth < 30) scrollWidth = 30;
			var scroll = createElement("span",{"className":"scroll","title":"Z\u0142ap i przesu\u0144"},{"width":scrollWidth+"px"});
			var leftScroll = createElement("span",{"className":"left_scroll arrow","title":"Przesu\u0144 w lewo"});
			var rightScroll = createElement("span",{"className":"right_scroll arrow","title":"Przesu\u0144 w prawo"});
			scrollBar.appendChild(leftScroll);
			scrollBar.appendChild(rightScroll);
			scrollBar.appendChild(scroll);
			browse.appendChild(scrollBar);
			refServiceScrollBar = new serviceScrollBar(scrollBar,scroll,leftScroll,rightScroll);
			if(containsClass(imgBrowser,"long") && images.length <= 8)
				addClass(scrollBar,"hidden");
		}

		// buttons
		if(productAvailable == 1)
		{
			var buttons = createElement("div",{"className":"buttons"});
			imgBrowser.appendChild(buttons);

			var btnCart = createElement("a",{"title":"Dodaj "+productName+" do koszyka","innerHTML":"Dodaj do koszyka","className":"add","href":"#","onclick":function()
						{
				$JM("form_cart").getElementsByTagName("input")[3].click();
							return false;
						}});

			buttons.appendChild(btnCart);
		}

		// minmax button (PCH: turned off)
		/*
		var minMaxButton = createElement("span",{"className":"minmax","title":"Zwi\u0144 Panel","innerHTML":"Zwi\u0144"});
		minMaxButton.minProperty = true;
		minMaxButton.imgBrowserHeight = imgBrowser.offsetHeight;
		minMaxButton.tmpHeader = "";
		minMaxButton.onclick = function()
		{
			if(this.minProperty)
			{
				var b = this.imgBrowserHeight;
				var interval = setInterval(function() {
				b -= 10;
				if(b <= header.offsetHeight + 1)
				{
					clearInterval(interval);
					b = header.offsetHeight + 1;
					addClass(header,"minimize"); addClass(minMaxButton,"maxmin");
					minMaxButton.tmpHeader = header.innerHTML; header.innerHTML = headerTitle.slice(0,-2);
					minMaxButton.title = "Poka\u017C panel";
					imgBrowser.style.clip = "auto";
				}
				imgBrowser.style.clip = "rect(0px 735px "+b+"px 0px)"; // hard coded 735
				}, 10);
			}
			else
			{
				var b = header.offsetHeight + 1;
				removeClass(header,"minimize");
				var interval = setInterval(function() {
				b += 10;
				if(b >= minMaxButton.imgBrowserHeight)
				{
					clearInterval(interval);
					b = minMaxButton.imgBrowserHeight; removeClass(minMaxButton,"maxmin");
					header.innerHTML = minMaxButton.tmpHeader; minMaxButton.title = "Zwi\u0144 panel";
					imgBrowser.style.clip = "auto";
				}
				imgBrowser.style.clip = "rect(0px 735px "+b+"px 0px)";
				}, 10);
			}
			this.minProperty = !this.minProperty;
		};
		*/
		// turn off minmax
		//imgBrowser.appendChild(minMaxButton);


		// resize button (PCH: turned off)
		/*
		var resizeButton = createElement("span",{"className":"resize","title":"Rozszerz panel","innerHTML":"Rozszerz"});
		resizeButton.property = (getCookie("browser_resize") == -1) ? -1 : 1;
		//!!!
		resizeButton.onclick = function()
		{
			if(this.property == 1)
			{
				addClass(imgBrowser,"long");
				if(images.length > 6 && images.length <= 8)
				{
					addClass(scrollBar,"hidden");
					refServiceScrollBar.moveS(0);
				}
				image.style.backgroundImage = image.style.backgroundImage.replace("widthMax=400","widthMax=700").replace("heightMax=250","heightMax=450");
			}
			else
			{
				removeClass(imgBrowser,"long");
				if(scrollBar && images.length > 6) removeClass(scrollBar,"hidden");
				image.style.backgroundImage = image.style.backgroundImage.replace("widthMax=700","widthMax=400").replace("heightMax=450","heightMax=250");
			}

			currentImgWidth = (containsClass(imgBrowser,"long")?700:400);
			currentImgHeight = (containsClass(imgBrowser,"long")?450:250);
			minMaxButton.imgBrowserHeight = imgBrowser.offsetHeight;

			this.property *= -1;
			setCookie("browser_resize",this.property,"/","Wed, 01-Jan-20 00:00:01 GMT");
			if(refServiceScrollBar != null)
				refServiceScrollBar.updateScale();

		};
		*/

		// turn off resize
		//imgBrowser.appendChild(resizeButton);

		ieFrame.style.height = (imgBrowser.offsetHeight) + "px";
		ieFrame.style.width = (imgBrowser.offsetWidth) + "px";

		// dragable
		makeDragAble(imgBrowser);
	}

	// -- create single element
	function createElement(name,params,style)
	{
		var el = document.createElement(name);
		if(params) for(var i in params) el[i]=params[i];
		if(style) for(var i in style) el.style[i]=style[i];
		return el;
	}

	// -- other photos list
	function servicePhotos()
	{
		var photos = otherPhotos?otherPhotos.getElementsByTagName("a"):[];
		var browserPhotos = imgBrowser.getElementsByTagName("a");
		for( var i = 0; i < photos.length; i++ )
			photos[i].onclick = function(e)
			{
				this.blur();
				changeOtherPhotosSelected(this);

				var url = "/converter?widthMax=335&heightMax=170&img="+this.pathname;
				// check if photo is active
				if(img.style.backgroundImage.indexOf(url) != -1)
					return false;

				// change image
				changing = true;
				img.style.backgroundImage = "url('/images/misc/loading.gif')";

				// set bg in main
				if(tmpPhotos[url]==undefined)
				{
					var tmp = new Image();
					tmp.src = url;
					tmpPhotos[url] = tmp;

					tmp.onload = function() { img.style.backgroundImage = "url('" + this.src + "')"; changing = false; }
				}
				else
					img.style.backgroundImage = "url('" + tmpPhotos[url].src + "')";;
				// and set this in browser
				for( var i = 0; i < imagesArray.length; i++ )
					if(imagesArray[i].href == this.href) imagesArray[i].onclick();

				if(e != undefined || window.event != undefined)
				{
					e=e||window.event;
					stopBubbling(e);
				}

				return false;
			}
	}

	function getSelectedPhotosIndex()
	{
		var photos = otherPhotos.getElementsByTagName("a");
		for( var i = 0; i < photos.length; i++ )
		{
			if(containsClass(photos[i], "active"))
				return i;
		}
		return -1;
	}

	function changeOtherPhotosSelected(el)
	{
		var photos = otherPhotos.getElementsByTagName("a");
		for( var i = 0; i < photos.length; i++ )
		{
			if(photos[i].href == el.href) addClass(photos[i], "active");
			else removeClass(photos[i], "active");
		}
	}

	// -- img browser
	function serviceBrowser()
	{
		var opacity = 90; // thumbnails opacity (0-100)
		for( var i = 0; i < imagesArray.length; i++ )
		{
			//setOpacity(imagesArray[i],i==0?100:opacity);
			// visualisations
			//imagesArray[i].onmouseout = function() { if(this.className.indexOf("active")==-1) setOpacity(this,opacity); }
			//imagesArray[i].onmouseover = function() { setOpacity(this,100); }
			imagesArray[i].onmousedown = function() { this.blur(); }
			imagesArray[i].counter = i;
			// show image
			imagesArray[i].onclick = function(e)
			{
				if(e != undefined || window.event != undefined)
				{
					e=e||window.event;
					stopBubbling(e);
				}
				return setImage(this,this.counter);
			}
		}

		// biggest image
		var image = imgBrowser.getElementsByTagName("div").item(1);

		var nextButton = document.getElementById("nextImageButton");
		var prevButton = document.getElementById("prevImageButton");
		var imagesArrayLength = imagesArray.length;

		//inicjalizacja guzików
		if (nextButton){
		nextButton.style.display = (imagesArrayLength > 1)?"block":"none";
		nextButton.onclick = function()
			{
				if (imagesArrayLength > 1)
				{
					var i = getActiveThumbnailIndex();
					if (i < imagesArrayLength - 1)
					{
						setImage(imagesArray[i],++i)
					}
				}
			}
		}

		if (prevButton){
			prevButton.style.display = "none";
			prevButton.onclick = function()
			{
				if (imagesArrayLength > 1)
				{
					var i = getActiveThumbnailIndex();
					if (i > 0)
					{
						setImage(imagesArray[i],--i)
					}
				}
			}
		}

		// prepare href
		function setImage(element, index)
		{
			element.blur();
			image.style.backgroundImage = "url('/images/misc/loading.gif')";

			var href = element.href.slice(element.href.indexOf("/",7));
			if(imagesArray[index]['converter'+currentImgWidth] == null)
				imagesArray[index]['converter'+currentImgWidth] = "/converter?widthMax="+currentImgWidth+"&heightMax="+currentImgHeight+"&img=" + imagesArray[index].pathname;
			var selected = imagesArray[index];
			if(tmpPhotos[selected['converter'+currentImgWidth]]==undefined)
			{
				var tmp = new Image();
				tmp.src = selected['converter'+currentImgWidth];
				tmpPhotos[selected['converter'+currentImgWidth]] = tmp;
				tmp.onload = loadedComplete;
			}
			else
				loadedComplete();

			function loadedComplete()
			{
				image.style.backgroundImage = "url('"+selected['converter'+currentImgWidth]+"')";

				while (image.hasChildNodes())
				{
					image.removeChild(image.firstChild);
				}

				var zoomLayer = createElement("img",{"src":"/images/misc/blank.gif","title":""},{});

				var tmp = image.style.backgroundImage;
				tmp = tmp.slice(tmp.indexOf("img=")+4,-1);
				if(tmp.slice(-1) == "\"") tmp = tmp.slice(0,-1);
				if (tmp.charAt(0)!='/') tmp='/'+tmp;

				var tmpDims = getImageDimensions("/converter?widthMax="+currentImgWidth+"&heightMax="+currentImgHeight+"&img="+tmp);
				var adjustXZoomPosition = 0;

				if (tmpDims['width'] <= 0)
				{
					tmpDims['width'] = currentImgWidth;
				}

				adjustXZoomPosition = Math.ceil((currentImgWidth + 132 - tmpDims['width']) / 2) - 1;
				var zoomHref = createElement("a",{href:tmp,className:"cloud-zoom",title:"",rel:"adjustY:-52,adjustX:"+adjustXZoomPosition+",zoomWidth:"+zoomW+",zoomHeight:"+zoomH},{});

				image.style.width = tmpDims['width'] + "px"
				zoomLayer.style.width = tmpDims['width'] + "px";
				zoomHref.style.width = tmpDims['width'] + "px";

				zoomHref.appendChild(zoomLayer);

				$(zoomHref).click(function(event){
					event.preventDefault();
				});
				image.appendChild(zoomHref);

				$(".cloud-zoom").CloudZoom();

				var tmp = selected.title.split(":");
				header.innerHTML = headerTitle + tmp[1];
			}

			setActiveThumbnail(selected);
			return false;
		}

		// set active thumbnail
		function setActiveThumbnail(selected)
		{

			for( var i = 0; i < imagesArray.length; i++ )
			{
				if( imagesArray[i] == selected )
				{
					imagesArray[i].className += " active";
					//setOpacity(imagesArray[i],100);
					// set image in under layer (indexOf prevent cycles)
					if(changing == false)
						img.style.backgroundImage = "url('/converter?widthMax=335&heightMax=170&img="+imagesArray[i].pathname+"')";
				}
				else
					removeClass(imagesArray[i],"active");
			}

			var i = getActiveThumbnailIndex();
			nextButton.style.display = (imagesArrayLength > 1 && i < imagesArrayLength - 1)?"block":"none";
			prevButton.style.display = (imagesArrayLength > 1 && i > 0)?"block":"none";

			changeOtherPhotosSelected(selected);

		}

		function getActiveThumbnailIndex()
		{
			for( var i = 0; i < imagesArray.length; i++ )
			{
				if(containsClass(imagesArray[i], "active"))
					return i;
			}
			return -1;
		}

	}

	// -- scroller
	function serviceScrollBar(scrollBar, scroll, leftScroll, rightScroll)
	{
		var scrollStatus = false;
		var startX = 0;
		var buttonX;

		var imagesListWidth = parseInt(imagesList.style.width);
		var scrollWidth = scrollBar.offsetWidth; // 6 border
		var scale;
		var revScale;
		updateScale();

		// drag events
		addEvent(scroll,"mousedown",dragScrollOn);
		addEvent(scroll,"mouseup",dragScrollOff);
		addEvent(document,"mouseup",dragScrollOff);
		addEvent(document,"mousemove",dragScrollMove);

		addEvent(scroll,"click",stopBubbling);
		// arrow events
		addEvent(leftScroll,"mousedown",arrowScrollRight);
		addEvent(rightScroll,"mousedown",arrowScrollLeft);
		addEvent(leftScroll,"mouseup",arrowScrollStop);
		addEvent(rightScroll,"mouseup",arrowScrollStop);
		addEvent(leftScroll,"mouseout",arrowScrollStop);
		addEvent(rightScroll,"mouseout",arrowScrollStop);
		addEvent(leftScroll,"mouseout",function(){removeClass(this,"hover")});
		addEvent(rightScroll,"mouseout",function(){removeClass(this,"hover")});
		addEvent(leftScroll,"mouseover",function(){addClass(this,"hover")});
		addEvent(rightScroll,"mouseover",function(){addClass(this,"hover")});
		addEvent(rightScroll,"click",stopBubbling);
		addEvent(leftScroll,"click",stopBubbling);
		// scrollbar events
		addEvent(browse,"click",scrollBarScroll);
		addEvent(browse,'DOMMouseScroll',scrollBarRoll);
		addEvent(browse,'mousewheel',scrollBarRoll);

		// dont select text while moving
		addEvent(document,"selectstart",function() { if(scrollStatus); return false; });

		this.updateScale = function() { updateScale(); }
		function updateScale()
		{
			scrollWidth = scrollBar.offsetWidth;
			scale = ( imagesListWidth - imagesList.parentNode.offsetWidth )
					/ (scrollWidth - scroll.offsetWidth);
			revScale = (1/scale)*5;
		}

		// - drag events
		function dragScrollOn(e)
		{
			e = e||event;
			scrollStatus = true;
			// remember start pos
			startX = e.clientX;
			buttonX = this.offsetLeft;
		}
		function dragScrollOff() { scrollStatus = false; }
		function dragScrollMove(e)
		{
			e = e||event;
			if(scrollStatus)
				moveScroll(buttonX + (e.clientX - startX));
		}

		// - arrow events
		function arrowScrollStop()
		{
			clearInterval(interval);
			return false;
		}

		function arrowScrollLeft() { arrowScroll(true); }
		function arrowScrollRight() { arrowScroll(false); }

		function arrowScroll(direction)
		{
			var pos = scroll.offsetLeft;
			interval = setInterval(function()
			{
				pos = direction?pos+revScale:pos-revScale ;
				moveScroll(pos);
			}, 10 );
			return false;
		}

		// - scrollbarevents
		function scrollBarScroll(e)
		{
			e = e||event;
			var xPos = e.layerX || e.x;
			moveScroll(xPos-((scroll.offsetWidth/2)+2));
		}

		// - scrollbarevents
		function scrollBarRoll(e)
		{
			e = e||event;
			var eventDirection = 1;
			var pos = scroll.offsetLeft;

			if(!e.detail)
			{
				if(!e.wheelDelta) return;
				eventDirection = event.wheelDelta * -1;
				if(window.opera) eventDirection = -eventDirection
			}
			else
				eventDirection = e.detail;

			var direction;
			if(eventDirection < 0) direction = false;
			else if(eventDirection > 0) direction = true;

			var pos = scroll.offsetLeft;
			var scrollScale = revScale + 5;
			pos = direction ? pos+scrollScale : pos-scrollScale;
			moveScroll(pos);

			if (e.preventDefault) e.preventDefault();
			e.returnValue = false;
			return false;
		}

		// scroll moving
		this.moveS = function(pos) //public
		{
			moveScroll(pos);
		}

		function moveScroll(newPos)
		{

			// margin left
			if(newPos <= 0 )
				scroll.style.left = 0;
			// margin right
			else if( newPos + scroll.offsetWidth >= scroll.parentNode.offsetWidth - 6 ) // 6px border
				scroll.style.left = (scroll.parentNode.offsetWidth-scroll.offsetWidth-6) + "px";
			else
			{
				try{
				scroll.style.left = newPos + "px";
				}
				catch(e)
				{
					alert(newPos);
				}
			}
			synchronize();
		}
		// synchronize scroll position with thumbnails
		function synchronize()
		{
			imagesList.style.left = (-1*((parseInt(scroll.style.left) * scale))) + "px";
		}
	}
	// cancel propagate event
	function stopBubbling(e){e=e||event;e.cancelBubble = true}
}

/* review TODO: add buffer */
function reviewService()
{
	var reviewBox = $JM("product_review");
	if(!reviewBox) return;

	/* show hide box */
	var form = reviewBox.getElementsByTagName("form").item(0);

	var showAllOpinions = $JM("review_show_all");
	if(showAllOpinions) showAllOpinions.currentOffset = 0;

	var showFormButton = $JM("review_form_show");

	var loading = null;
	var sent = false;

	var buffer = new Array();

	showFormButton.vProp = false;
	showFormButton.onclick = function()
	{
		this.blur();
		if(!this.vProp) addClass(form,"visible");
		else removeClass(form,"visible");
		this.vProp = !this.vProp;
		return false;
	}

	var hideFormButton = $JM("review_form_hide");
	hideFormButton.onclick = function()
	{
		removeClass(form,"visible");
		return false;
	}

	/* ajax paging */
	ajaxReviewSubmit();
	ajaxReviewPager();

	function ajaxReviewSubmit()
	{
		$(form).submit(function() {
			$(this).ajaxSubmit({
				url: '/sklep/review_add_ajax.xml',
				type: 'POST',
				beforeSubmit: beforeSubmit,
				success: afterSubmit
			});
			return false;
		});
		
		/*
		form.onsubmit = function()
		{
			var url = "/sklep/review_add_ajax.xml?name=" + escape(unicode_to_utf8( $JM('form_review_name').value ))
			+ "&email=" + escape(unicode_to_utf8($JM('form_review_email').value))
			+ "&body=" + escape(unicode_to_utf8($JM('form_review_body').value))
			+ "&captcha=" + escape(unicode_to_utf8($JM('form_review_captcha').value))
			+ "&product_id=" + productId + "&captcha_key=" + MIL_CAPTCHA_KEY
			+ "&form-id=review";

			// TODO: T#12428, PCH, 2010-10-08, Zdemontowac warunek po uruchomieniu live
			if ($JM('form_review_note')){
				url += "&note=" + escape($JM('form_review_note')[$JM('form_review_note').selectedIndex].value);
			}



			if(!checkFormReview(this))
				return false;

			setTimeout(function()
			{
				if(sent) return;
				loading = document.createElement("div");
				loading.style.width = (form.offsetWidth - 3) + "px";
				loading.style.height = (form.offsetHeight - ((form.offsetHeight/2) - 40) - 23) + "px";
				loading.style.paddingTop = ((form.offsetHeight/2) - 40) + "px";
				loading.innerHTML = "Zapisywanie danych";
				form.appendChild(loading);
			},500);

			return !ajaxRequest(url, "POST", null, afterSubmit);
		}
		*/
		
		function beforeSubmit(formData, jqForm, options)
		{
			if (!checkFormReview(this))
				return false;

			setTimeout(function() {
				if (sent)
					return;
				loading = document.createElement("div");
				loading.id = "review-saving";
				loading.style.width = (form.offsetWidth - 3) + "px";
				loading.style.height = (form.offsetHeight - ((form.offsetHeight/2) - 40) - 23) + "px";
				loading.style.paddingTop = ((form.offsetHeight/2) - 40) + "px";
				loading.innerHTML = "Zapisywanie danych";
				form.appendChild(loading);
			}, 500);
			
			return true;
		}

		function afterSubmit(responseText, statusText, xhr, $form)
		{
			sent = true;
			if (loading && loading.parentNode) {
				loading.parentNode.removeChild(loading);
			}
			if (responseText.slice(0,2).toUpperCase() != "OK") {
				myAlert(responseText);
				reloadCaptcha();
				return;
			}
			cleanForm($form);
			removeClass(form,"visible");
			showInfo();

			//GA
			if (trackCustomVarReview) {
				trackCustomVarReview();
			}
		}

		function cleanForm($form)
		{
			clearError();
			$(':input', $form).not(':button, :submit, :reset, :hidden').val('').removeAttr('checked').removeAttr('selected');
			$('span.filerow', $form).each(function() {
				var input = $(this).hide().find('input.file');
				input.replaceWith('<input type="file" name="' + input.attr('name') + '" class="file"/>')
			});
			//$('#review-note-select').stars('select', 0);
			reloadCaptcha();
		}
		
		function reloadCaptcha()
		{
			$JM('form_review_captcha_img').src = $JM('form_review_captcha_img').src + "&rand=" + Math.random();
		}

		function showInfo()
		{
			var saved = document.createElement("div");
			addClass(saved,"review_saved");
			saved.innerHTML = $JM('form_saved_message').innerHTML;

			form.parentNode.insertBefore(saved,form);

			var close = document.createElement("a");
			addClass(close,"close");
			close.href = location.href;
			close.title = "Zamknij komunikat";
			close.innerHTML = "Zamknij";
			close.onclick = function() { var tmp = this.parentNode; tmp.parentNode.removeChild(tmp); return false; }

			saved.appendChild(close);
		}
	}

	function ajaxReviewPager()
	{
		ajaxReviewPagerService($JM("reviews_pager"));
		ajaxReviewPagerService($JM("reviews_pager_bottom"));

		// all options
		if(!showAllOpinions) return;
		showAllOpinions.onclick = function()
		{
			if(this.clicked) return false;
			this.clicked = true;
			this.blur();
			var link = this;
			var content = $JM("reviews_content");

			var url = (this.href.indexOf("/sklep/reviews.xml") != -1) ? this.href :
			"/sklep/reviews.xml?" + this.search + (this.href.indexOf("product_id") != -1 ?
			"" : "&product_id=" + productId);

			if(containsClass(link,"show"))
			{
				link.className = "";
			}
			else
			{
				link.className = "show";
				url = url.replace("show=all","_offset=" + this.currentOffset);
			}

			if(buffer[url])
			{
				content.innerHTML = buffer[url];
				ajaxReviewPager();
				link.clicked = false;
				return false;
			}

			var timeout = setTimeout(function() { addClass(link,"loading") }, 15);

			return !ajaxRequest(url, "GET", content, function(req)
			{
				clearTimeout(timeout);
				removeClass(link,"loading");
				if(!containsClass(link,"show")) link.innerHTML = "Zobacz opinie z podzia\u0142em na strony";
				else link.innerHTML = "Zobacz wszystkie opinie";
				buffer[url] = req.responseText;
				ajaxReviewPager();
				link.clicked = false;
			});
		}
	}

	function ajaxReviewPagerService(pager)
	{
		if(!pager) return;
		var content = $JM("reviews_content");
		var pageLinks = pager.getElementsByTagName("a");
		for( var i = 0; i < pageLinks.length; i++ )
		{
			pageLinks[i].href = pageLinks[i].href.replace("/sklep/reviews.xml",location.pathname);
			pageLinks[i].onclick = function()
			{
				if(containsClass(this,"ranking_review")) return true;
				var link = this;
				var url = (this.href.indexOf("/sklep/reviews.xml") != -1) ?
				this.href : ("/sklep/reviews.xml" + this.search + (this.href.indexOf("product_id") != -1 ?
				"" : ("&product_id=" + productId)));

				if(buffer[url])
				{
					content.innerHTML = buffer[url];
					ajaxReviewPager();
					return false;
				}

				setTimeout(function() {addClass(link,"loading")}, 15);

				var searchParams = new String(this.search);
				var matcher = searchParams.match(/_offset=([0-9]*)/);
				if(matcher && matcher[1]) showAllOpinions.currentOffset = matcher[1];

				ajaxRequest(url, "GET", content, function(req)
				{
					ajaxReviewPager();
					buffer[url] = req.responseText;
				});
				return false;
			}
		}
	}
}

// nice movie browser
function movieBrowser()
{
	var movieList = $JM("product_movies");
	if(!movieList) return;

	var movies = movieList.getElementsByTagName("a");
	if(movies.length == 0) return;
	var productInfo = $JM("product_info");

	var viewer = $JMc("div");
	viewer.id = "movie_viewer";
	viewer.style.zIndex = viewerBrowserZIndex;
	viewer.onmousedown = function() { this.style.zIndex = viewerBrowserZIndex++; }

	var ieFrame = document.createElement("iframe");
	ieFrame.src = "/images/misc/empty.gif";
	ieFrame.setAttribute("frameBorder","0");
	viewer.appendChild(ieFrame);

	var movie = $JMc("div");
	movie.id = "flv_movie_container";
	var header = $JMc("div");
	header.className = "header";
	viewer.appendChild(header);

	var closeButton = $JMc("span");
	closeButton.className = "close";
	closeButton.onclick = function() { $('#transBackground').fadeOut();removeClass(viewer,"visible"); viewer.style.visibility = "hidden";clearActive(); movie.innerHTML = ''; return false; }
	viewer.appendChild(closeButton);

	viewer.appendChild(movie);

	var list = $JMc("ul");
	viewer.appendChild(list);

	$JM("movieviewerparent").appendChild(viewer);

	viewer.style.left = (productInfo.offsetLeft + 33) + "px";
	viewer.style.top = (productInfo.offsetTop + 33) + "px";

	for(var i = 0; i < movies.length; i++)
	{
		if(movies[i].className.indexOf("player_vcms") > -1 || movies[i].href.slice(-3) == "flv")
		{
			prepareMovie(movies[i],i);
		}
	}

	//ieFrame.style.height = productInfo.offsetHeight + "px";
	ieFrame.style.height = (viewer.offsetHeight) + "px";
	ieFrame.style.width = (viewer.offsetWidth) + "px";

	makeDragAble(viewer);

	function prepareMovie(movie,index)
	{
		movie.index = index;

		var item = $JMc("li");
		list.appendChild(item);

		var link = $JMc("a");
		link.index = index;
		link.href = movie.href;
		link.innerHTML = movie.innerHTML;


		if (movie.className.indexOf("player_vcms") > -1)
		{
			movie.onclick = showMovieVcms;
			link.onclick = showMovieVcms;
		}
		else
		{
			movie.onclick = showMovie;
			link.onclick = showMovie;
		}

		item.appendChild(link);
	}

	function showMovie()
	{
		$('#transBackground').fadeIn();
		this.blur();
		clearActive();

		addClass(list.getElementsByTagName("a")[this.index],"active");
		addClass(movies[this.index],"active");

		var so = new SWFObject("/swf/flvplayer.swf" , "flv_movie", 400, 300, "8");
		//var so = new SWFObject("/swf/VPlayerApp.swf" , "flv_movie", 400, 300, "8");
		so.addParam("quality", "best");
		so.addParam("wmode", "transparent");
		so.addParam("flashVars", "nobor=1&path=" + this.href);
		so.write(movie.id);
		viewer.style.visibility = "visible";
		addClass(viewer,"visible");
		header.innerHTML = "Przeglądarka filmów: " + this.innerHTML;
		return false;
	}

	function showMovieVcms()
	{
		$('#transBackground').fadeIn();
		this.blur();
		clearActive();

		addClass(list.getElementsByTagName("a")[this.index],"active");
		addClass(movies[this.index],"active");

		var movieId = parseInt(this.hash.replace("#",""));

		movie.innerHTML = '<object id="mediaPlayer-' + movieId + '" width="499" height="350" type="application/x-shockwave-flash" name="videoPlayer-' +  movieId + '" data="http://player.videocms.pl/militaria/Player.swf">'
						+ '<param name="movie" value="http://player.videocms.pl/militaria/Player.swf"/>'
						+ '<param name="allowfullscreen" value="true"/>'
						+ '<param name="allowscriptaccess" value="always"/>'
						+ '<param name="bgcolor" value="#000000"/>'
						+ '<param name="wmode" value="transparent"/>'
						+ '<param name="flashvars" value="xmlConfig=http://militaria.videocms.pl/wp-content/plugins/videocms/config_xml.php?params=' + movieId + ',2"/>'
						+ '</object>';

		var el = $JMc("SCRIPT");
		el.type = "text/javascript";
		el.src = "http://militaria.videocms.pl/wp-content/plugins/videocms/embed_js.php?params=" + movieId;
		movie.appendChild(el);
		viewer.style.visibility = "visible";
		addClass(viewer,"visible");
		header.innerHTML = "Przeglądarka filmów: " + this.innerHTML;
		return false;
	}

	function clearActive()
	{
		var links = list.getElementsByTagName("a");
		for(var i = 0; i < links.length; i++)
		{
			removeClass(links[i],"active");
			removeClass(movies[i],"active");
		}
	}
}

function showListedMovie(idx){
	if (!idx) idx = 0;
	window.location.hash = "#container";
	$("#product_movies a:eq("+idx+")").click();
}

function makeDragAble(element)
{
	element.moving = false;

	// drag
	var header;
	var divs = element.getElementsByTagName("div");
	for( var i = 0; i < divs.length; i++)
		if(containsClass(divs[i],"header"))
		{
			header = divs[i];
			break;
		}

	addEvent(header,"mousedown", dragImgBrowserStart);
	addEvent(document,"mouseup", function(){element.moving = false;
	//setOpacity(element,100);
	});
	addEvent(document,"mousemove",dragImgBrowser);
	addEvent(document,"selectstart",function(){ if(element.moving) return false; });

	function dragImgBrowserStart(ev)
	{
		var e = ev||event;
		element.moving = true;
		element.startX = e.pageX ? e.pageX - element.offsetLeft : e.offsetX;
		element.startY = e.pageY ? e.pageY - element.offsetTop  : e.offsetY;
		//setOpacity(element,80);
	};

	function dragImgBrowser(ev)
	{
		if(!element.moving) return;
		var e = ev||event;

		var leftOffset = (e.pageX ? e.pageX : e.clientX+(document.documentElement.scrollLeft?document.documentElement.scrollLeft:document.body.scrollLeft)) - element.startX;
		var topOffset  = (e.pageY ? e.pageY : e.clientY+(document.documentElement.scrollTop?document.documentElement.scrollTop:document.body.scrollTop)) - element.startY;
		if(leftOffset >= 0) { element.style.left = leftOffset + "px"; }
		if(topOffset >= 0) { element.style.top  = topOffset + "px"; }
	}
}

var currentDragAble = null;
function makeDragAble(element)
{
	var thisElem = element;
	thisElem.moving = false;

	// drag
	var header;
	var divs = thisElem.getElementsByTagName("div");
	for( var i = 0; i < divs.length; i++)
		if(containsClass(divs[i],"header"))
		{
			header = divs[i];
			break;
		}

	addEvent(header,"mousedown", dragImgBrowserStart);
	addEvent(document,"mouseup", function(){ if(currentDragAble) currentDragAble.moving = false; });
	addEvent(document,"mousemove",dragImgBrowser);
	addEvent(document,"selectstart",function(){ if(currentDragAble && currentDragAble.moving) return false; });

	function dragImgBrowserStart(ev)
	{
		var e = ev||event;
		currentDragAble = this.parentNode;
		currentDragAble.moving = true;
		currentDragAble.startX = e.pageX ? e.pageX - currentDragAble.offsetLeft : e.offsetX;
		currentDragAble.startY = e.pageY ? e.pageY - currentDragAble.offsetTop  : e.offsetY;
		//setOpacity(currentDragAble,80);
	};

	function dragImgBrowser(ev)
	{
		var e = ev||event;
		if(!currentDragAble || !currentDragAble.moving) return;

		var leftOffset = (e.pageX ? e.pageX : e.clientX+(document.documentElement.scrollLeft?document.documentElement.currentDragAbleeft:document.body.scrollLeft)) - currentDragAble.startX;
		var topOffset  = (e.pageY ? e.pageY : e.clientY+(document.documentElement.scrollTop?document.documentElement.scrollTop:document.body.scrollTop)) - currentDragAble.startY;
		if(leftOffset >= 0) { currentDragAble.style.left = leftOffset + "px"; }
		if(topOffset >= 0) { currentDragAble.style.top  = topOffset + "px"; }
	}
}

// recommended products
function productRecommendPager(productId, divProductsId, divPagerId)
{
	var pager = $JM(divPagerId);
	var content = $JM(divProductsId);
	if(!pager)
	{
		return;
	}
	var pageLinks = pager.getElementsByTagName("a");
	for( var i = 0; i < pageLinks.length; i++ )
	{
		pageLinks[i].href = pageLinks[i].href.replace("/sklep/product_recommend.xml",location.pathname);
		pageLinks[i].onclick = function()
		{
			setTimeout(function() {addClass(pager,"loading")}, 15);
			this.href = this.href.replace(new RegExp('&oi_[^&]+', 'g'), "");
			url = (this.href.indexOf("/sklep/product_recommend.xml") != -1) ? this.href :
			"/sklep/product_recommend.xml" + this.search + (this.href.indexOf("product_id") != -1 ?
			"" : "&product_id=" + productId);
			ajaxRequest(url, "GET", content, function() {
				productRecommendPager(productId, divProductsId, divPagerId);
			});
			return false;
		}
	}
}

// nice fix
function updateClientShopping()
{
	// :]
	var maxWidth = 0;
	var elems = $JM("client_shopping").getElementsByTagName("p");
	for( var i = 0; i < elems.length; i++ )
		if(elems[i].className.indexOf("points") != -1)
			if(elems[i].offsetWidth > maxWidth) maxWidth = elems[i].offsetWidth;
	for( var i = 0; i < elems.length; i++ )
		if(elems[i].className.indexOf("points") != -1) elems[i].style.width = (maxWidth-53) + "px";
}

function notifyService()
{
	var notifyButton = $JM("notify_button");
	if(!notifyButton) return;
	var notifyForm = $JM("product_notify");
	var notifyCancel = $JM("notify_cancel");

	notifyButton.onclick = function()
	{
		if(containsClass(notifyForm,"visible"))
			removeClass(notifyForm,"visible");
		else
		{
			addClass(notifyForm,"visible");
			notifyForm.getElementsByTagName("form").item(0).className = "";
			location.hash = "p_p";
		}
		return false;
	}
	notifyCancel.onclick = function()
	{
		removeClass(notifyForm,"visible");
		return false;
	}
	var notifyCloseInfo = $JM("notify_close_info");
	if(notifyCloseInfo)
		notifyCloseInfo.onclick = function()
		{
			var parent = this.parentNode;
			parent.parentNode.removeChild(parent);
			removeClass(notifyForm,"visible");
			return false;
		}

}

function updateProductShop(select, getFromCookie)
{
	var cookieName = "default_shop";
	var key = "";
	var selects = select.parentNode.parentNode.getElementsByTagName("select");
	var button = $JM('shop_info_button');
	if(selects[0].value == "" && getFromCookie)
	{
		var shopId = getCookie(cookieName);
		if(shopId) selects[0].value = shopId;
	}
	if(selects.length == 0 || selects[0].value == "")
	{
		$JM('product_shop_info').innerHTML = "";
		addClass(button,'hidden');
		return;
	}
	removeClass(button,'hidden');
	//button.onclick();

	// save shop settings in cookie value
	var date = new Date();
	setCookie(cookieName, selects[0].value, "/", "Wed, 01-Jan-20 00:00:01 GMT");

	for(var i = 0; i < selects.length; i++)
	{
		if(i > 0) key += "_";
		key += selects[i].value;
	}
	$JM('product_shop_info').innerHTML = (shopAttributes[key] == 2) ? 'Status nieznany' : ((shopAttributes[key] == 1) ? 'Dost\u0119pny' : 'Niedost\u0119pny');
	$JM('product_shop_info').className = (shopAttributes[key] == 2) ? 'unknown_stock' : ((shopAttributes[key] == 1) ? 'on_stock' : 'out_off_stock');
}

function showHideTableShopAvailability(button)
{
	button.blur();
	var table = $JM("shop_table");
	if(containsClass(table,"visible")) { button.innerHTML = "Poka\u017c tabel\u0119 dost\u0119pno\u015bci"; removeClass(table,"visible"); }
	else { button.innerHTML = "Ukryj tabel\u0119 dost\u0119pno\u015bci"; addClass(table,"visible"); }
	return false;
}

/* 2011-04-06, PCH,
 * Typy pol i nazwy odpowiadaja zdefiniowanym w product_attributes.xsl
 * formWish = formularz dodajacy do wishlisty
 * formCart = formularz dodajacy do koszyka
 * przepisujemy pola z koszykowego do hiddenow w wishlistowym
 * */
function addProductToWishList(formWish,formCart)
{
	if (!formWish && !formCart)
		return true;

	var elems = formCart.elements
	var field,name,value;
	for (var i=0;i<formCart.length;i++){
		if (elems[i].name && elems[i].name.indexOf("oi_pa_")==0){
			value=null;

			if (elems[i].type=='text'){
				value = elems[i].value;
			}
			else if ((elems[i].type=='checkbox' || elems[i].type=='radio') && elems[i].checked){
				value = elems[i].value;
			}
			else if (elems[i].type=='select-one'){
				value = elems[i].options[elems[i].selectedIndex].value;
			}

			if (value!=null){
				field = document.createElement('input');
				field.setAttribute("type", "hidden");
				field.setAttribute("name", elems[i].name);
				field.setAttribute("value", value);
				formWish.appendChild(field);
			}
		}
	}
	return true;
}

function popupLayerProductRecommend()
{
	var pr = document.getElementById("product_recommend");
	if (pr)
	{
		addClass(pr,"visible");
		document.location.hash = "#product_recommend";
	}
}

function popupLayerShopInfo()
{
	var select = $JM('shops').getElementsByTagName('select')[0];
	var button = $JM('shop_info_button');
	var shopsInfo = $JM('shops_info').getElementsByTagName('div');

	for(var i = 0; i < shopsInfo.length; i++)
		if(containsClass(shopsInfo[i],"content"))
			shopsInfo[i].getElementsByTagName("span")[0].onclick = hideShopInfo;

	button.onclick = function()
	{
		this.blur();
		return showShopInfo(select.value);
	}

	this.showShop = function(element,id)
	{
		element.blur();
		return showShopInfo(id);
	}

	function showShopInfo(id)
	{
		if(id == '') return false;
		for(var i = 0; i < shopsInfo.length; i++)
		{
			if(shopsInfo[i].id == "shop_info_" + id)
			{
				shopsInfo[i].style.left = (button.offsetLeft + 20) + "px";
				shopsInfo[i].style.top = (button.offsetHeight + 30) + "px";
				if(containsClass(shopsInfo[i],"visible")) _hideShopInfo(shopsInfo[i]);
				else addClass(shopsInfo[i], "visible");
			}
			else _hideShopInfo(shopsInfo[i]);
		}
		return false;
	}

	function _hideShopInfo(elem)
	{
		removeClass(elem, "visible");
		elem.style.left = "-3000px";
	}

	function hideShopInfo()
	{
		_hideShopInfo(this.parentNode.parentNode);
	}
}
var popupLayerObject;
