/* Detailed Product Information Page - Photo Switcher - ETWP Edition
---- MJJames - Based upon the YAHOO! PhotoBox Example
*/

/*extern YAHOO */

YAHOO.namespace("newmind.etwp.container");
YAHOO.namespace("newmind.etwp");

YAHOO.newmind.etwp.photoswitcher = function(){ //some default stuff
	var iLargeWidth, iThumbWidth, oLargeContext;
	return{
		setImageSizes : function(oSizes){
			iLargeWidth = oSizes.largewidth;
			iThumbWidth = oSizes.thumbwidth;
			oLargeContext = oSizes.largecontext;
		},
		
		getImageSizes : function(){
			return{
					largewidth : iLargeWidth, 
					thumbwidth : iThumbWidth ,
					largecontext : oLargeContext
			};
		}
	};
}();

// Removes product image and replaces with slideshow html
YAHOO.newmind.etwp.photoswitcher.remove = function() {

	// 2008-11-26 DWR: Altered this such that the original product image will be the first image
	// in the photo switcher (required by Oxygen call #6156) - see getImages method also
	var objMainImage = document.getElementById("productImage");
	if (objMainImage)
	{
		var strImgSrc = objMainImage.src;
		var strImgAlt = objMainImage.alt;
		var objImageList = document.getElementById("imgSwapCtrl");
		if (objImageList)
		{
			var strTempId = "productImage" + Math.floor(Math.random() * 100000);
			var strNewItem = "<img id=\"" + strTempId + "\" />";
			var strList = objImageList.innerHTML;
			strList = "<li><a href=\"#\">" + strNewItem + "</a></li>" + strList;
			objImageList.innerHTML = strList;
			var objMainImage = document.getElementById(strTempId);
			objMainImage.src = strImgSrc;
			objMainImage.alt = strImgAlt;
		}
	}
        
	var olddiv = document.getElementById('productImage');
	var div = olddiv.parentNode;
	div.removeChild(olddiv);

	var mySlideShow = new YAHOO.widget.Module("mySlideShow"); //create a module for the slideshow
	mySlideShow.setBody("<a href=\"#\"><img src=\"#\" id=\"mySlideShow_img\" /></a>"); 
    
	mySlideShow.render(div); // render in our element
};


YAHOO.newmind.etwp.getImages = function(elementID) {
    
	// 2008-11-26 DWR: Updated to prevent duplicate images being displayed (especially if the
	// main product image also appears in additional images)
	var aryImages = []; //our main array
	var photos = []; // our photos
	var el = new YAHOO.util.Element(elementID); 
	var images = el.getElementsByTagName('img'); // pull out imgs from element
	        	
	for (i = 0; i < images.length; i++){
		aryImages[i] = {
			src : images[i].src.replace("ProductThumbsAdditional", "ProductMain"),
			caption : images[i].alt
		}; 
	}

	var aryOut = [];
	for (i = 0; i < aryImages.length; i++){
		var bDupe = false;
		for (j = 0; j < aryOut.length; j++){
			if (aryImages[i].src === aryOut[j].src){
				bDupe = true;
				break;
			}
		}
		if (!bDupe){
			aryOut.push(aryImages[i]);
		}
	}

	return aryOut;
};

 YAHOO.newmind.etwp.getImage = function(elementID){
    
    var aryImages = []; //our main array
    var photos = [];  // our photos
    var el = new YAHOO.util.Element(elementID); 
    aryImages[0] = {
						src :  el.src,
						caption :  el.alt
					};
    return aryImages;
        
};

YAHOO.newmind.etwp.removeDiv = function(elementID){
   var olddiv = document.getElementById(elementID);
   var div = olddiv.parentNode;
   div.removeChild(olddiv);

};

        
// Overrides the handler for the "modal" property with special animation-related functionality 

YAHOO.widget.ImageBox = function(el, userConfig) { 
    if (arguments.length > 0) { 
        YAHOO.widget.ImageBox.superclass.constructor.call(this, el, userConfig); 
    } 
} ;

// Inherit from YAHOO.widget.Overlay 
YAHOO.extend(YAHOO.widget.ImageBox, YAHOO.widget.Panel); 

YAHOO.widget.ImageBox.prototype.configModal = function(type, args, obj) { 
    var modal = args[0]; 
 
    if (modal) { 
        this.buildMask(); 
 
        if (typeof this.maskOpacity === 'undefined') { 
            this.mask.style.visibility = "hidden"; 
            this.mask.style.display = "block"; 
            this.maskOpacity = YAHOO.util.Dom.getStyle(this.mask,"opacity"); 
            this.mask.style.display = "none"; 
            this.mask.style.visibility = "visible"; 
        } 
 
        if (! YAHOO.util.Config.alreadySubscribed( this.beforeShowEvent, this.showMask, this ) ) { 
            this.beforeShowEvent.subscribe(this.showMask, this, true); 
        } 
        if (! YAHOO.util.Config.alreadySubscribed( this.beforeHideEvent, this.hideMask, this) ) { 
            this.beforeHideEvent.subscribe(this.hideMask, this, true); 
        } 
        if (! YAHOO.util.Config.alreadySubscribed( YAHOO.widget.Overlay.windowResizeEvent, this.sizeMask, this ) ) { 
            YAHOO.widget.Overlay.windowResizeEvent.subscribe(this.sizeMask, this, true); 
        } 
    } else { 
        this.beforeShowEvent.unsubscribe(this.showMask, this); 
        this.beforeHideEvent.unsubscribe(this.hideMask, this); 
        YAHOO.widget.Overlay.windowResizeEvent.unsubscribe(this.sizeMask); 
    } 
}; 
 
    
YAHOO.newmind.etwp.showImageLarge = function(e){
	var oSizes = YAHOO.newmind.etwp.photoswitcher.getImageSizes();
    src = this.src;
    src = src.replace("action=ProductThumbsAdditional","action=ProductThumbsAdditionalLarge"); //if it s a multi image its this
    src = src.replace("action=ProductMain","action=ProductThumbsAdditionalLarge"); // if its a single image
    alt = this.title.replace(NewMind.ETWP.GetResource('NewMind.env.lang.resources.productdetail["photoswitcher"]["clicktoenlarge"]', ' - Click to Enlarge'), "");
    var productImageLarge = new YAHOO.widget.ImageBox("productImageLarge", { 
                                                                    effect:{effect:YAHOO.widget.ContainerEffect.FADE,duration:0.45},  
                                                                    underlay:"none", 
                                                                    close:true, 
                                                                    visible:true, 
                                                                    draggable: false, 
																	iframe: true,
                                                                    modal:false, 
                                                                    context: oSizes.largecontext,
                                                                    zindex: 1000,
                                                                    width: oSizes.largewidth } ); //create a module for the slideshow
                                                                    
    productImageLarge.setHeader(alt);
    productImageLarge.setBody("<img src=\"" + src + "\" id=\"productImageLarge_img\" />"); 
    productImageLarge.setFooter("");
    productImageLarge.render(document.body); // render in our element
               
    YAHOO.newmind.etwp.container.photoboxLarge.render();
    YAHOO.newmind.etwp.container.photoboxLarge.show();
    
    productImageLarge.show();
};

       
// begin photoswitcher sub class //


	// BEGIN PHOTOBOX SUBCLASS //
	YAHOO.widget.PhotoBox = function(el, userConfig) {
		if (arguments.length > 0) {
			YAHOO.widget.PhotoBox.superclass.constructor.call(this, el, userConfig);
		}
	};
	
	// Inherit from YAHOO.widget.Panel
	YAHOO.extend(YAHOO.widget.PhotoBox, YAHOO.widget.Panel);

	// Define the CSS class for the PhotoBox
	YAHOO.widget.PhotoBox.CSS_PHOTOBOX = "photobox";

	// Define the HTML for the footer navigation
	YAHOO.widget.PhotoBox.NAV_FOOTER_HTML = "<a id=\"$back.id\" href=\"javascript:void(null)\" class=\"back\"><img src=\"/images/slideshow/image_left.gif\" /></a><a id=\"$next.id\" href=\"javascript:void(null)\" class=\"next\"><img src=\"/images/slideshow/image_right.gif\" /></a>";

	// Initialize the PhotoBox by setting up the footer navigation
	YAHOO.widget.PhotoBox.prototype.init = function(el, userConfig) {
		YAHOO.widget.PhotoBox.superclass.init.call(this, el); 
		
		this.beforeInitEvent.fire(YAHOO.widget.PhotoBox);

		YAHOO.util.Dom.addClass(this.innerElement, YAHOO.widget.PhotoBox.CSS_PHOTOBOX);
		
		if (userConfig) {
			this.cfg.applyConfig(userConfig, true);
		}
		
		this.setFooter(YAHOO.widget.PhotoBox.NAV_FOOTER_HTML.replace("$back.id",this.id+"_back").replace("$next.id",this.id+"_next"));
		
		this.renderEvent.subscribe(function() {
			var back = document.getElementById(this.id + "_back");
			var next = document.getElementById(this.id + "_next");

			YAHOO.util.Event.addListener(back, "mousedown", this.back, this, true);
			YAHOO.util.Event.addListener(next, "mousedown", this.next, this, true);

		}, this, true);

		this.initEvent.fire(YAHOO.widget.PhotoBox);
	};

	// Set up the PhotoBox's "photos" property for setting up the list of photos
	YAHOO.widget.PhotoBox.prototype.initDefaultConfig = function() {
		YAHOO.widget.PhotoBox.superclass.initDefaultConfig.call(this);
		
		this.cfg.addProperty("photos", { handler:this.configPhotos, suppressEvent:true });
	};

	// Handler executed when the "photos" property is modified
	YAHOO.widget.PhotoBox.prototype.configPhotos = function(type, args, obj) {
		var oSizes = YAHOO.newmind.etwp.photoswitcher.getImageSizes();
		var photos = args[0];
		
		if (photos) {
			this.images = [];

			if (! (photos instanceof Array)) {
				photos = [photos];
			}

			this.currentImage = 0;

			if (photos.length === 1) {
				this.footer.style.display = "none";
			}

			for (var p=0;p<photos.length;p++) {
				var photo = photos[p];
				var img = new Image();
				img.src = photo.src;
				img.title = photo.caption + NewMind.ETWP.GetResource('NewMind.env.lang.resources.productdetail["photoswitcher"]["clicktoenlarge"]', ' - Click to Enlarge');
				img.id = this.id + "_img";
				img.width = oSizes.thumbwidth.replace("px", "");
				this.images[this.images.length] = img;
			}

			this.setImage(0);
			
		}
	};

	// Sets the current image displayed in the PhotoBox to the corresponding image in the photo dataset, 
	// and determines whether back and forward arrows should be diplsayed, based on the position in the dataset
	YAHOO.widget.PhotoBox.prototype.setImage = function(index) {
		var oSizes = YAHOO.newmind.etwp.photoswitcher.getImageSizes();
		var photos = this.cfg.getProperty("photos");

		if (photos) {
			if (! (photos instanceof Array)) {
				photos = [photos];
			}
			
			var back = document.getElementById(this.id + "_back");
			var next = document.getElementById(this.id + "_next");
			var img =  document.getElementById(this.id + "_img");
			var title = document.getElementById(this.id + "_title");

			this.currentImage = index;

			var current = this.images[index];

			var imgNode = document.createElement("IMG");
			imgNode.setAttribute("src",current.src);
			imgNode.setAttribute("title",current.title + NewMind.ETWP.GetResource('NewMind.env.lang.resources.productdetail["photoswitcher"]["clicktoenlarge"]', ' - Click to Enlarge'));
			imgNode.setAttribute("width", oSizes.thumbwidth.replace("px", ""));
			imgNode.setAttribute("id",current.id);
			
			img.parentNode.replaceChild((this.browser === "safari"?imgNode:current), img);
			
			//this.body.style.height = "auto";

			//title.innerHTML = current.title;

			if (this.currentImage === 0) {
				back.style.display = "none";
			} else {
				back.style.display = "block";
			}

			if (this.currentImage === (photos.length-1)) {
				next.style.display = "none";
			} else {
				next.style.display = "block";
			}
		}
		YAHOO.util.Event.addListener("mySlideShow_img", "click", YAHOO.newmind.etwp.showImageLarge); //re add handler
	};
	
	// Navigates to the next image
	YAHOO.widget.PhotoBox.prototype.next = function() {	
		if (typeof this.currentImage === 'undefined') {
			this.currentImage = 0;
		}

		this.setImage(this.currentImage+1);
	};

	// Navigates to the previous image
	YAHOO.widget.PhotoBox.prototype.back = function() {
		if (typeof this.currentImage === 'undefined') {
			this.currentImage = 0;
		}

		this.setImage(this.currentImage-1);
	};
	
	
	// END PHOTOBOX SUBCLASS //
	
	YAHOO.newmind.etwp.photoswitcher.init = function(e, args, initArgs){
		//do some checking
		initArgs = initArgs || {largewidth: undefined, thumbwidth: undefined};
		initArgs.largewidth = ((initArgs === undefined) | (initArgs.largewidth === undefined)) ? '400px' : initArgs.largewidth;
		initArgs.thumbwidth = ((initArgs === undefined | initArgs.thumbwidth === undefined)) ? '145px' : initArgs.thumbwidth;
		initArgs.largecontext = ((initArgs === undefined | initArgs.largecontext === undefined)) ? ["colsWrapper", "tl", "tl"] : initArgs.largecontext;

		
		YAHOO.newmind.etwp.photoswitcher.setImageSizes(initArgs);

		YAHOO.newmind.etwp.photoswitcher.performCheck(); //see what we need to do
	};

	YAHOO.newmind.etwp.photoswitcher.create = function() {
		var initArgs = YAHOO.newmind.etwp.photoswitcher.getImageSizes();
	    YAHOO.newmind.etwp.photoswitcher.remove(); // delete our product image and replace with SlideShow HTML
	
		YAHOO.newmind.etwp.container.photobox = new YAHOO.widget.PhotoBox("mySlideShow", 
		{ 
			fixedcenter:false,
			constraintoviewport:false,
			underlay:"none",
			close:false,
			visible:true,
			draggable:false,
			photos: YAHOO.newmind.etwp.getImages('productExtraImages'), //// get out images, store them in an array and then remove the html
			width: initArgs.thumbwidth || '145px'
		} );
		
		YAHOO.newmind.etwp.container.photoboxLarge = new YAHOO.widget.PhotoBox("productImageLarge", 
		{ 
			fixedcenter:true,
			constraintoviewport:false,
			underlay:"none",
			close:true,
			visible:true,
			draggable:false,
			context: initArgs.largecontext,
			photos: YAHOO.newmind.etwp.getImages('productExtraImages'), //// get out images, store them in an array and then remove the html
			width: initArgs.largewidth || '400px'
		} );
		
		YAHOO.newmind.etwp.removeDiv("productExtraImages");
		
	    YAHOO.newmind.etwp.container.photobox.show();
		YAHOO.newmind.etwp.container.photobox.render();
		
	};
	
	YAHOO.newmind.etwp.photoswitcher.performCheck = function(){
		var initArgs = YAHOO.newmind.etwp.photoswitcher.getImageSizes();
        if (document.getElementById("imgSwapCtrl") !== null){
	        YAHOO.newmind.etwp.photoswitcher.create(initArgs); //wait until we are ready
	    }
	    else{
		    YAHOO.newmind.etwp.container.photoboxLarge = new YAHOO.widget.PhotoBox("productImageLarge", 
		    { 
			    fixedcenter:true,
			    constraintoviewport:false,
			    underlay:"none",
			    close:true,
			    visible:true,
			    draggable:false,
				context: initArgs.largecontext,
			    photos: YAHOO.newmind.etwp.getImage('productImage'), //// get out images, store them in an array and then remove the html
				width: initArgs.largewidth || '400px'
		    } );
            YAHOO.util.Event.addListener("productImage", "click", YAHOO.newmind.etwp.showImageLarge); //re add handler
        }
    };
	
//YAHOO.util.Event.addListener(window, "load", YAHOO.newmind.etwp.photoswitcher.init({largewidth: '400px', thumbwidth: '175px' }));
