// Extends prototype and scriptacolous class for scroll operation
Element.addMethods({
	scrollTo: function(element, left, top){
		var element = $(element);
		if (arguments.length == 1){
			var pos = element.cumulativeOffset();
			window.scrollTo(pos[0], pos[1]);
		} else {
			element.scrollLeft = left;
			element.scrollTop  = top;
		}
		return element;
	}
});

Effect.Scroll = Class.create();
Object.extend(Object.extend(Effect.Scroll.prototype, Effect.Base.prototype), {
	initialize: function(element) {
		this.element = $(element);
		if(!this.element) throw(Effect._elementDoesNotExistError);
		this.start(Object.extend({x: 0, y: 0}, arguments[1] || {}));
	},
	setup: function() {
		var scrollOffsets = (this.element == window)
								? document.viewport.getScrollOffsets()
								: Element._returnOffset(this.element.scrollLeft, this.element.scrollTop) ;
		this.originalScrollLeft = scrollOffsets.left;
		this.originalScrollTop  = scrollOffsets.top;
	},
	update: function(pos) {
		this.element.scrollTo(Math.round(this.options.x * pos + this.originalScrollLeft), Math.round(this.options.y * pos + this.originalScrollTop));
	}
});

function scrollGallery(galleryId, direction) {
	direction = (direction == 'right')?+1:-1;
	var scrollingDiv = $("galleryContainer"+galleryId);
	new Effect.Scroll(scrollingDiv, {x: GALLERY_STEP * direction, duration: 0.5});
	var position = scrollingDiv.scrollLeft + GALLERY_STEP * direction;
	if (position == 0)
		$("galleryArrowLeft"+galleryId).style.visibility = 'hidden';
	else
		$("galleryArrowLeft"+galleryId).style.visibility = 'visible';
	if (position == scrollingDiv.scrollWidth - GALLERY_STEP)
		$("galleryArrowRight"+galleryId).style.visibility = 'hidden';
	else
		$("galleryArrowRight"+galleryId).style.visibility = 'visible';
}

function toogleImageGallery(oImg) {
	var isBw = (oImg.src.indexOf("bw_thumb") > 0);
	if (isBw)
		oImg.src = oImg.src.replace("bw_thumb", "thumb");
	else
		oImg.src = oImg.src.replace("thumb", "bw_thumb");
}

function initGalleries() {
	galleryImages = document.getElementsByClassName('product_gallery_image');
	galleryRows = document.getElementsByClassName('product_gallery_row');
	if (galleryRows[0])
		new PeriodicalExecuter(checkGalleryImages, 0.250);

}

function checkGalleryImages(pe) {
	if (galleryRows[0].style.display != 'none')
		return;
	for (var i=0; i<galleryImages.length; i++)
		if (!galleryImages[i].complete)
			return;
	// Show galleries and stop...
	for (var j=0; j<galleryRows.length; j++)
		galleryRows[j].style.display = 'block';
	$('productGalleryWaiting').style.display = 'none';
	pe.stop();
}
