/****************************************************************************************
*****************************************************************************************
*** Slideshow stuff *********************************************************************
*****************************************************************************************
*****************************************************************************************/

/*var DELAY_INITIAL = 2000;
var DELAY_GAP = 2000;

var USING_CUTOUT = true;
var CUTOUT_SRC			= "../images/slide_cutout_3" 		+ (Browser.isIE()?"_ie":"") + ".png";
var CUTOUT_SELECTED_SRC	= "../images/slide_cutout_selected" + (Browser.isIE()?"_ie":"") + ".png";
var VIEWER_CUTOUT_SRC	= "../images/viewer_cutout" 		+ (Browser.isIE()?"_ie":"") + ".png";

var CELL_IMAGE_ID = "ssID";
var CELL_ID = "ssCellID";*/

/* preload hack */
/*var ssImgPreload1 = new Image();
	ssImgPreload1.src = CUTOUT_SRC;

var ssImgPreload2 = new Image();
	ssImgPreload2.src = CUTOUT_SELECTED_SRC;

var ssImgPreload3 = new Image();
	ssImgPreload3.src = VIEWER_CUTOUT_SRC;
*/

var SlideShow = {
	delayInitial: 2000,
	delayGap: 2000,

	_usingCutout:1,//0 or 1
	cutout: "images/red/slide_cutout" + (Browser.isIE()?"_ie":"") + "_small.png",
	cutoutSelected:	"images/red/slide_cutout_selected" + (Browser.isIE()?"_ie":"") + "_small_blue.png",
	viewerCutout:	"images/red/viewer_cutout" 		+ (Browser.isIE()?"_ie":"") + "_medium.png",
	

	isUsingCutout: function() {
		return this._usingCutout == 1;
	},

	setUsingCutout: function(using) {
		this._usingCutout = using?1:0;
	},


	setupVisualCutout: function(imgRef, isSlide) {
		if (!this.isUsingCutout()) return;
		if (Browser.needsPNGHack()) {
			//ok load up two AlphaImageLoaders
			//first is the original image, 
			//the second is the slide_mask
	
			imgRef.style.filter = 
				IE.PNG._toAlphaLoaderString(imgRef.src) + 
				IE.PNG._toAlphaLoaderString(isSlide?this.cutout:this.viewerCutout) + 
				(isSlide?IE.PNG._toAlphaLoaderString(this.cutoutSelected):"");
				//alert(this.cutout);
			if (isSlide) {
				imgRef.filters[2].enabled = false;
			}		
			imgRef.src = Assets.blankGIF;
	
		} else {
			//everyone else seems to support png, so put the original image
			//as the background image and then the slide-mask as the src
			imgRef.style.backgroundImage = 'url(' + imgRef.src + ')';
			imgRef.style.backgroundRepeat = "no-repeat";
			imgRef.style.backgroundPositionX = "0px";
			imgRef.style.backgroundPositionY = "0px";			
			imgRef.src = (isSlide?this.cutout:this.viewerCutout);
			Debug.print(imgRef.id +  "  isSlide : " + isSlide);
		}
	},

	cellImageID: "ssID",
	cellID: "ssCellID",

	getCells: function(holder) {
		
		var cells = [];

		if (holder == null) return cells;

		if (holder.nodeName == "TABLE") {

			for (var i = 0; i < holder.rows.length; i++) {
				var row = holder.rows[i];
				for (var j = 0; j < row.cells.length; j++) {
					var cell = row.cells[j];
					cells.push(cell);
					//alert(cell);
				}
			}
		} else {
			//one of those new fangled div ones

			for (i = 0; i < holder.childNodes.length; i++) {
				var child = holder.childNodes[i];		
				if (child.nodeName != "DIV") continue;

				cells.push(child);					
			}  
		}

		return cells;
	},

	getCellLink: function(cell) {
		return	findChildByTag(cell, "A");
	},


	slideshows: [],
	createSlideShow: function(viewerId) {
		var ss = new SlideShow.Viewer(viewerId);
		this.slideshows.push(ss);
	},

	deleteAllSlideShows: function() {
		for (var i=0; i < this.slideshows.length; i++) {
			this.slideshows[i].finalize();
		}
	}
};


/*****************************
***  Slide *******************
*****************************/

SlideShow.Slide = Class.create();
SlideShow.Slide.prototype = {

	initialize: function (index, label, smallUrl, bigUrl, productHref, productText) {
		this.id = SlideShow.cellImageID + index;
		this.cellId = SlideShow.cellID + index;
		this.label = label;
		this.productText = productText;
	
		//preload small
		this.smallUrl = smallUrl;
		var smallCache = new Image();
		smallCache.src = this.smallUrl;

		//preload big		
		this.bigUrl = bigUrl ||	Util.fromSmall(smallUrl);		
		var bigCache = new Image();
		bigCache.src = this.bigUrl;

		this.productHref = productHref;
		this.enabled = 1;
	},

	getRef: function() {
		return document.getElementById(this.id);	
	},

	getCellRef: function() {
		return document.getElementById(this.cellId);
	},

	update: function() {	
		//do something about being disabled.
		var ref = this.getRef();
		//ref.style.visibility = this.enabled==1?"visible":"hidden";	
		ref.parentNode.parentNode.style.visibility = this.enabled==1?"visible":"hidden";
	},

	setSelected: function (selected) {
		var cn = "ssSlide" + (selected?"Showing":"");

		this.getCellRef().className = cn;
		
		var slideRef = this.getRef();
		slideRef.className = cn;
	
		if (!SlideShow.isUsingCutout()) return;
	
		if (Browser.needsPNGHack()) {
			slideRef.filters[1].enabled = !selected;
			slideRef.filters[2].enabled = selected;		
		} else {
			slideRef.src = selected?SlideShow.cutoutSelected:SlideShow.cutout;
		}	
	},

	setEnabled: function(enabled) {
		this.enabled = (enabled==true?1:0);
		this.update();
	},

	isEnabled: function() {
		return this.enabled == 1;
	}
}

/*****************************
***  SlideRunner *************
*****************************/

SlideShow.Runner = Class.create();
SlideShow.Runner.prototype = {
	initialize: function(slideshow) {
		this.slideshow = slideshow;
		this.lastTimerId = 0;
		this.funcEvent = this.slideshow.showNextSlide.bind(this.slideshow);
		this.increment = 1;
	},

	start: function() {		
		this.lastTimerId = setTimeout(this.funcEvent, SlideShow.delayInitial);	
	},

	pause: function() {
		clearTimeout(this.lastTimerId);
		this.lastTimerId = 0;
	},	

	next: function() {
		this.lastTimerId = setTimeout(this.funcEvent, SlideShow.delayGap);
	}
}

/*****************************
***  SlideShow ***************
*****************************/

SlideShow.Viewer = Class.create();
SlideShow.Viewer.prototype = {

	initialize:function (viewerId) {
		this.viewerId = viewerId;
		this.slides = new Array();

		this.lastSlideIndex = -1;
		this.lastViewed = 0;
		this.runner = new SlideShow.Runner(this);
		this.build();
	},

	build: function() {			

			var holder = document.getElementById("ssThumbs");
			if (holder == null) return;
		
			SlideShow.setupVisualCutout(this.getViewer(), false);
		
			var slideCells = SlideShow.getCells(holder);

			//alert("complied a list of " + slideCells.length + " cell");

			//loop invariant
			var funcOut = this.runner.start.bind(this.runner);
		
			for (var k = 0; k < slideCells.length; k++) {
				cell = slideCells[k];
				var para = findChildByTag(cell, "P");
				var text = "";
				try {
					text = findFirstTextChild(para).nodeValue;
				} catch (excp) {
					text = "";
				}
				//assuming a link, then a img tag
				var link =	SlideShow.getCellLink(cell);
				if (link) {
					var imgRef = findChildByTag(link, "IMG");
					if (imgRef) {
						var slide = this.add(imgRef.alt, imgRef.src, (imgRef.longDesc || null), link.href, text);
						imgRef.id = slide.id;
						
						
						
						EventUtil.addListener(link, "mouseover", this.showSlideById.bindWith(this, [imgRef.id]));
						EventUtil.addListener(link, "mouseout", funcOut);

						
						cell.id = slide.cellId;
		
						Debug.print("found slide " + imgRef.id);
						//Debug.print("longdesc " + imgRef.longDesc);
						
						SlideShow.setupVisualCutout(imgRef, true);
						
					} else {
						Debug.print("Cannot find image for slide " + k);
					}
				} else {
					Debug.print("Cannot find link for slide " + k);
				}	
			} 
		
			//doPNGSupportDescendentImages(table);


		
			for (i=0; i < this.slides.length; i++) {
				this.slides[i].update(); 
			}			
			
			this.runner.increment = (holder.className.indexOf("minus") != -1)?-1:1;			
			this.runner.funcEvent();
			
			
			var initialSlide = this.getIndexFromLabel(this.getViewerLabel().firstChild.nodeValue);
			this.getSlide(initialSlide).setSelected(true);			
			this.showSlideByIndex(initialSlide);

			
			//this.nextIndex();
	},

	getViewer: function() {
		return document.getElementById(this.viewerId);
	},

	getViewerLabel: function() {
		return document.getElementById("ssLabel");
	},

	getViewerText: function() {
		return document.getElementById("ssText");
	},

	getViewerLabelNoMatches: function() {
		return document.getElementById("ssLabelNoMatches");
	},

	getSlide : function(index) {
		var out = null;
		if (index >= 0 && index < this.slides.length) {
			out = this.slides[index];
		}
		return out;
	},

	//add

	add: function(label, smallUrl, bigUrl, productHref, productText) {
		var newSlide = new SlideShow.Slide(this.slides.length, label, smallUrl, bigUrl, productHref, productText);
		this.slides.push(newSlide);	
		return newSlide;
	},

	//viewed

	clearLastViewed: function() {
		if (this.lastViewed == -1) return;

		var slide = this.slides[this.lastViewed];

		slide.setSelected(false);

		this.lastViewed = -1;
	},

	setLastViewed: function(index) {
		if (index == -1) return;

		var slide = this.slides[index];

		slide.setSelected(true);

		this.lastViewed = index;
	},

	//id and index

	getIndexFromId: function(id) {
		var slideIndex = -1;
		for (var i = 0; i < this.slides.length; i++) {
			if (this.slides[i].id == id) {
				slideIndex = i;
				break;
			}
		}
		return slideIndex;
	},

	getIndexFromLabel: function(label) {
		var slideIndex = -1;
		for (var i = 0; i < this.slides.length; i++) {
			if (this.slides[i].label == label) {
				slideIndex = i;
				break;
			}
		}
		return slideIndex;	
	},

	//enabled

	isSlideEnabled: function(index) {	
		var slide = this.getSlide(index);
		var out = ((slide!=null)?slide.isEnabled():false);
		Debug.print("Slide " + index + " is enabled? " + out);
		return out;
	},

	setSlideEnabled: function(index, enabled) {	
		var slide = this.getSlide(index);
		if (slide != null) {
			slide.setEnabled(enabled);
		}
	},

	setAllEnabled: function() {
		for (var i = 0; i < this.slides.length; i++) {
			this.slides[i].setEnabled(true);
		}
	},

	//show

	showSlideById: function(ssID) {
		this.runner.pause();
		var slideIndex = this.getIndexFromId(ssID);
		if (this.isSlideEnabled(slideIndex)) {
			this.showSlideByIndex(slideIndex);	
		}
	},

	showSlideByIndex: function(index) {	
		var viewer = this.getViewer();
		//do bounds check??
		var slide = this.getSlide(index);
		if (slide == null) return;

		viewer.src = slide.bigUrl;
		viewer.alt = slide.label;
		viewer.parentNode.href = slide.productHref;	
		viewer.style.visibility = "visible";

		if (SlideShow.isUsingCutout()) {
			SlideShow.setupVisualCutout(viewer, false);
		}

		var label = this.getViewerLabel();

		label.style.display = "block";
		label.innerHTML = slide.label;

		var labelNoMatches = this.getViewerLabelNoMatches();
		if (labelNoMatches) {
			labelNoMatches.style.display = "none";
		}

		var text = this.getViewerText();
		if (text) {
			text.innerHTML = slide.productText;
		}

		this.clearLastViewed();
		this.setLastViewed(index);
		//now do something about the source thumb nail

	},

	checkShowingSlideEnabled: function() {	
		//wind back one then forward, but checking for 
		//enabled ones.
		this.lastSlideIndex--;
		this.showNextSlide();
		this.runner.pause();
	},

	nextIndex: function() {
		if (this.runner.increment < 0 && this.lastSlideIndex <= 0) {
			this.lastSlideIndex = this.slides.length-1;			
		} else if (this.runner.increment > 0 && this.lastSlideIndex >= this.slides.length-1) {
			this.lastSlideIndex = 0;
		} else {
			this.lastSlideIndex += this.runner.increment;
		}		
	},

	showNextSlide: function() {	
		this.nextIndex();

		var currentIndex = this.lastSlideIndex;

		//Debug.print("Checking if slide : " + this.lastSlideIndex + " is enabled ");
		while (this.isSlideEnabled(this.lastSlideIndex) == false) {		
			this.nextIndex();
			//going round in circles here!
			//no slides are enabled so hide the viewer and show the 
			//noMatches label
			if (currentIndex == this.lastSlideIndex) {
				this.getViewer().style.visibility = "hidden";
				this.getViewerLabel().style.display = "none";

				var label = this.getViewerLabelNoMatches();
				if (label) {
					label.style.display = "block";
				}

				return;
			}
		}

		this.showSlideByIndex(this.lastSlideIndex);
		this.runner.next();	
	}
}

/*****************************
***  Mask ********************
*****************************/

SlideShow.Mask = Class.create();
SlideShow.Mask.prototype = {

	initialize: function(nameListString) {
		var firstComma = nameListString.indexOf(",");
		this.id = nameListString.substring(0, firstComma);

		var list = nameListString.substr(firstComma+1);

		var lastComma = list.lastIndexOf(",");
		var mutex = list.substr(lastComma+1);
		mutex = mutex.substring("mutex(".length, mutex.length-1);
		this.mutexes = (mutex.length != 0?mutex.split(","):new Array());

		list = list.substring(0, lastComma);
		this.names = list.split(",");	
		this.enabled = 0;    
	},

	isEnabled: function() {
		return this.enabled == 1;
	},

	setEnabled: function(enabled) {
		this.enabled = (enabled == true?1:0);
	}
}

/*****************************
***  SlideMasker *************
*****************************/

SlideShow.Masker = Class.create();
SlideShow.Masker.prototype = {

	initialize:function(slideshow) {
		this.slideshow = slideshow;	
		this.masks = new Array();
		this.showingNames = new Array();
	},

	//a name list string is a list of comma delimited strings 
	//with no spaces between comma and list items.
	add: function(nameListString) {	 	 
		 var m = new SlideShow.Mask(nameListString);
		 this.masks.push(m);
		 return m.id;
	},

	getMask: function(maskId) {	
		for (var i=0; i < this.masks.length; i++) {
			if (this.masks[i].id == maskId) {
				return this.masks[i];
			}
		}	
		return null;
	},

	applyMask: function(maskId) {
		var m = this.getMask(maskId);
		if (m) {
			m.setEnabled(true);
			if (m.mutexes.length != 0) {
				for (var i=0; i < m.mutexes.length; i++) {	   			
					var mm = this.getMask(m.mutexes[i]);
					if (mm.isEnabled()) {
						mm.setEnabled(false);
						//and now for the naughty bit where we unset the 'presser'
						document.getElementById(m.mutexes[i]).className = "contentChooserBlockNormal";
					}
				}
			}
		}
		this.updateMask();
	},

	removeMask: function(maskId) {
		var m = this.getMask(maskId);
		if (m) {
		   m.setEnabled(false);
		}
		this.updateMask();
	},

	updateMask: function() {
		//okay this is the magic routine that goes through 
		//all the masks and finds the master list of enabled names


		//clear the list
		this.showingNames = null;

		//loop
		for (var i=0; i < this.masks.length; i++) {
			var m = this.masks[i];
			//if not enabled, don't bother
			if (m.isEnabled() == false) continue;

			//if this is the first mask, set the list names to be
			//the masks lists, thenwe remove items when not found
			if (this.showingNames == null) {
				//duplicate
				this.showingNames = m.names.slice(0);
				continue;
			} 		

			for (var j=0; j < this.showingNames.length; j++) {
				var name = this.showingNames[j];
				if (name == null) continue;//could have been blanked before

				//if its in the masks list, is allowed, next..
				var index = m.names.getIndexOfValue(name);
				if (index != -1) continue;

				//damn. not in the mask list. so remove it from the showingNames.
				this.showingNames[j] = null;
			}		
		}

		//so by now should have a list of names that we are allowesd to show.

		//there will be 3 cases: no list(show all), some(limited), none(stop slide show spinning).


		//no list(show all)
		if (this.showingNames == null) {
			this.slideshow.setAllEnabled();
			return;
		}

		var anyShowing = false;

		this.slideshow.runner.pause();

		//some(limited)
		for (var k=0; k < this.slideshow.slides.length; k++) {
			var slide = this.slideshow.slides[k];
			var sIndex = this.showingNames.getIndexOfValue(slide.label);
			slide.setEnabled(sIndex != -1);

			if (sIndex != -1) anyShowing = true;
		}

		this.slideshow.checkShowingSlideEnabled();

		if (anyShowing) {
			this.slideshow.runner.start();
		}//else none(stop slide show spinning).
	}
}

