// multiple images javascript

// couple things to add:
// 1) function to switch selected detail image based on GET['altImg']
function updateAltImageHREF (theHREF, altImgID) {
	if ((theHREF.search('altImg') >= 0)) {
		var getVars = theHREF.split('&');
		var lp = 0;
		getVars.each ( function getSplit (inp) {
			if (inp.split('=')[0] == 'altImg') {
				getVars[lp] = 'altImg=' + altImgID;
			}
			lp++;
		});
		
		theHREF = getVars.join('&');
	} else {
		theHREF += "&altImg=" + altImgID;
	}
	
	return theHREF;
}

function thumbnailClick(e) {
	// hide border around other thumbs
	$('detail_thumbnails').childElements().each ( function zulu(obj) {
		obj.style.borderColor = "#FFFFFF";
	});
	// add border to the container
	var thumbLink = e.findElement('a');
	thumbLink.blur();
	thumbLink.up('div').style.borderColor = "#000000";
	$('ProdImage').name = thumbLink.down('img').src.replace(this.thumbDirectory, this.sourceDirectory);	
	$('ProdImage').up('a').href = updateAltImageHREF($('ProdImage').up('a').href, thumbLink.id.split('_')[1]);
	Event.stop(e);
}

function swapDetailImage(newImageSrc) {
	$('ProdImage').src = newImageSrc;
}

function thumbnailHover(e) {	
	// image swap
	if (e.element().readAttribute('src') != null) {
		swapDetailImage (e.element().src.replace(this.thumbDirectory, this.sourceDirectory));
	} else {
	    swapDetailImage (e.element().down('img').src.replace(this.thumbDirectory, this.sourceDirectory));
    }
	Event.stop(e);
}

function thumbnailUnHover(e) {
	var oldImageSource = $('ProdImage').name;
    swapDetailImage (oldImageSource);
    
	Event.stop(e);
}

function setNewImageSource (imageID, newImageSource) {
	$(imageID).src = newImageSource;	
}

document.observe ('dom:loaded', function multiple_image_load() {
	// image thumbnails	
	var lp = 0;
	
	$$('.thumbPopup').each ( function zed(x) {
	    if (location.search.search('altImg') >= 0) {
		    var theSplit = location.search.split('&');
			theSplit.each ( function findIt (inp) {
				var thisPair = inp.split('=');
				if (thisPair[0] == 'altImg') {
					$('alt_' + thisPair[1]).up('div').style.borderColor = "#000000";
					swapDetailImage ($('alt_' + thisPair[1]).down('img').src.replace(theManager.thumbDirectory, theManager.sourceDirectory));
				}
			});
		} else {			
			if (lp == 0) {
				x.up('div').style.borderColor = "#000000";
			}
		}
		lp++;
		
		// install listeners
		x.observe('click', thumbnailClick.bindAsEventListener(theManager));
		/*
		x.down('img').observe('mouseover', thumbnailHover);
		x.down('img').observe('mouseout', thumbnailUnHover);
		*/
		x.observe('mouseover', thumbnailHover.bindAsEventListener(theManager));
		x.observe('mouseout', thumbnailUnHover);
		// image preload	
		var preloaderImage = new Image();	
		preloaderImage.src = x.down().src.replace(theManager.thumbDirectory, theManager.sourceDirectory);
	});	
});