
if (typeof(mobile) == "undefined") var mobile = {};

mobile.ImageHelper = {};

// Gracefully preloads images into page
mobile.ImageHelper.preloadImages = function() { 
	if(document.images) {
		if(!document.preloads) {
			document.preloads = new Array();
		}
    	var i;
    	var j = document.preloads.length;
    	var args = mobile.ImageHelper.preloadImages.arguments;
    	for(i=0; i < args.length; i++) {
    		if (args[i].indexOf("#") != 0) { 
    			document.preloads[j] = new Image; 
    			document.preloads[j++].src = args[i];
    		}
    	}
	}
}

//load imgs later
mobile.ImageHelper.loadAllImages = function(imageSet) {
	//console.log(imageSet);
	//console.log(imageSet.size());
	
	//remove event listener (observe only once)
	document.stopObserving("mobile:late", mobile.ImageHelper.loadAllImagesCurry);
	Event.stopObserving(window, "scroll", mobile.ImageHelper.loadAllImagesCurry);
	
	var baseTimeout = (Prototype.Browser.IE)?200:50;
	
	imageSet.each(function(img, index){
		var timeout = baseTimeout*(index+1);
		//console.log(timeout);
		setTimeout((function(){
			var imgRel = img.getAttribute("rel");
			//console.log(imgRel);
			if(imgRel !=="" && imgRel != img.src){
				img.observe("load", function() {
					
					var link = img.up("a");
					link.removeClassName("loaded-later");
					img.setStyle({"visibility":"visible"});
				});
				img.src = imgRel;
			}
		}).bind(img), timeout);
	});
}

//load img later on mobile:late or scroll or on reload when viewport top > 0
mobile.ImageHelper.imageLateLoader = function(imageSet){
	if (document.viewport.getScrollOffsets().top > 0) {
		mobile.ImageHelper.loadAllImages(imageSet);
	} else {
		//we need a variable for stopObserving
		mobile.ImageHelper.loadAllImagesCurry = mobile.ImageHelper.loadAllImages.curry(imageSet);
		document.observe("mobile:late", mobile.ImageHelper.loadAllImagesCurry);
		Event.observe(window, "scroll", mobile.ImageHelper.loadAllImagesCurry);
		
	}
}

/* used for the images on preview(HB) and DES(ÖB and HB) */
mobile.ImageSwitcher = Class.create({
	
	_imageElement: null,
	_thumbnailListElement: null,
	_options: null,
	_currentThumbnail: null,
	_selectionTimeout: null,
	
	initialize: function(imageElement, thumbnailListElement, options) {
		this._imageElement = $(imageElement);
		this._thumbnailListElement = $(thumbnailListElement);
		
		this._options = Object.extend({
			selectEvent: "mouseover",
			tagName: "a",
			timeout: 100
		}, options);
		
		this._thumbnailListElement.observe(this._options.selectEvent, this._thumbnailSelectHandler.bindAsEventListener(this));
	},
	
	_thumbnailSelectHandler: function(event) {
		var element = Event.element(event);
		var targetElement = (element.tagName.toLowerCase() == this._options.tagName.toLowerCase()) ? element : element.up(this._options.tagName);
		if (targetElement && targetElement.descendantOf(this._thumbnailListElement)) {
			if (this._currentThumbnail != targetElement && targetElement.rel) {
				if (this._selectionTimeout) {
					clearTimeout(this._selectionTimeout);
				}
				this._selectionTimeout = setTimeout(this._switchImage.bind(this, targetElement), this._options.timeout);
			}
		}
	},
	
	_switchImage: function(targetElement) {
		this._currentThumbnail = targetElement;
		this._imageElement.src = this._currentThumbnail.rel;
	}
	
	
});

/**
 * @author uloydl
 * 
 * HTML like this is required
 * 
 * <div class="thumb-wrap">
 * 		<a href="whatever" rel="gallery-img-url">
 * 			<img src="thumbnail-url" />
 * 		</a>
 * </div>
 * 
 * On mouseover creates a wrapper with loading gif 
 * Displays the wrapper
 * Loades the img from gallery-url
 * 
 * setImageWrapperAlignment should be overwritten if needed
 * 
 */
mobile.ImageHelper.InventoryGallery = Class.create({
	
	_DISPLAY_DELAY: 400,	// ms to keep pointer over image to show galleryImg.
	_mouseoverTimeout: null,
	_currentThumbnailElement: null,
	
	/**
	 * Constructor. Attaches mouseover event to the document node. 
	 * Delegate event to document node, only nodes with the given css class are processed
	 * @param {String} imgWithGalleryPreview The CSS class name for the links with a thubnailimage.
	 */
	initialize: function(imgWithGalleryPreview) {
	
		//delegate event to document node, only nodes with the given css class are processed
		
		mobile.observe("."+imgWithGalleryPreview, "mouseover", function(event){
			this._startDisplayGalleryImg(event);
		}.bind(this)); 
		
		if (mobile.BrowserCheck.IE6) {
			this.iframeShim = new IframeShim();
		}
	},
	
	/**
	 * Handler starting display the gallery preview img, will be bound to mouseover event.
	 * Will start a timeout which can be cancelled by a mouseout event, to prevent flickering
	 * Will call {@link #_displayGalleryImg} when timeout is complete.
	 * @param {Object} event
	 */
	_startDisplayGalleryImg: function(event){
		//if (event) console.log("start event %o", event.element());
		this._stopDisplayGalleryImg(event);
		// Prototype 1.6.0.3 event bug workaround:
		//    In IE we explicitly have to clone the event element.
		//    FF ist just fine with a reference.
		var theEvent = Prototype.Browser.IE ? Object.clone(event) : event;
		this._mouseoverTimeout = setTimeout(this._displayGalleryImg.bind(this, theEvent), this._DISPLAY_DELAY);
	},
	
	/**
	 * Handler stopping a running mouseover timeout.
	 * To be bound to mouseout events.
	 */
	_stopDisplayGalleryImg: function(event) {
		//if (event) console.log("stop event %o", event.element());
		if (this._mouseoverTimeout) {
			clearTimeout(this._mouseoverTimeout);
			this._mouseoverTimeout = null;
		} 
	},
	
	/**
	 * Displays an gallery img belonging to a given thumbnail img element.
	 * Retrieves the galleryImg, positions the img beside the tumbnail img
	 * chooses the proper alignment depending on viewport position.
	 * @param {Event} event
	 */
	_displayGalleryImg: function(event){
		var element = Event.findElement(event, "a");
		
		//get the wrapper for the gallery img
		var imageWrapperElement = this._getImageWrapper();
		
		if (!imageWrapperElement.down(".gallery-img") || (imageWrapperElement.down(".gallery-img") && imageWrapperElement.down(".gallery-img").src != element.rel) ){
			//align the wrapper
			this.setImageWrapperAlignment(element);
			//show wrapper with a loading gif
			imageWrapperElement.show();
			//load the gallery img
			this._loadGalleryImage(element);
			//attach a mouseleave/mouseout event to the tumbnail wrapper
			element.up(".thumb-wrap").observe(Prototype.Browser.IE ? "mouseleave" : "mouseout", this._closeImageWrapper.bindAsEventListener(this, imageWrapperElement));
		} else {
			this.setImageWrapperAlignment(element);
			imageWrapperElement.show();
		}
		this._currentThumbnailElement = element;
	},
	
	/**
	 * Getter for gallery img wrapper. Element will be created ({@link #_createImageWrapper})
	 * and attached to DOM if it doesn't exist so far.
	 * @return The gallery img wrapper. 
	 */
	_getImageWrapper: function(){
		if (!this._imageWrapperElement) {
			this._imageWrapperElement = this._createImageWrapper();
		}
		return this._imageWrapperElement;
	},
	
	/**
	 * Creates the gallery img wrapper HTML element with a loding gif and attaches it to the DOM.
	 * If there we have a wrapper from an other instance of this class we use it
	 * Will also initialize the mouseleave event listening for closing the info box.
	 * @return The gallery img wrapper.
	 */
	_createImageWrapper: function(){
		
		var wrapperExists = documentBody.down(".imageWrapper");
		if (wrapperExists){
			return wrapperExists;
		} else {
			var element = new Element('div', {className: 'imageWrapper'});
			element.setStyle({position:"absolute", zIndex:"10", border:"2px solid #ccc", backgroundColor:"#fff"});
			element.innerHTML = '<img style="margin: 85px 129px" class="loading-gif" alt="" src="'+mobile.PageParams.imagePath+'loading_big.gif"/>';
			if (!(mobile.BrowserCheck.IE6 && documentBody.down('.ie6-position-fixed'))) {
				documentBody.insert({bottom: element});
			} else {
				// attach to page div if we have a ie6 position-fixed emulation.
				documentBody.down('.page').insert({bottom: element});
			}
			element.observe(Prototype.Browser.IE ? "mouseleave" : "mouseout", this._closeImageWrapper.bindAsEventListener(this, element));
			return element;
		}
	},
	
	/**
	 * Closes (hides) a currently open gallery img.
	 * To be bound to a mouseleave event.
	 * @param {Event} event
	 * @param {Element} element
	 */
	_closeImageWrapper: function(event, element) {
		// Includes a "mouseleave" emulation for FF:
		if (Prototype.Browser.IE || (event.relatedTarget && event.relatedTarget != event.currentTarget && !event.relatedTarget.childOf(event.currentTarget))) {
			element.hide();
			if (this.iframeShim) {
				this.iframeShim.hide();
			}
			event.stop();
		}
		this._stopDisplayGalleryImg();
	},
	
	/**
	 * Loads a gallery img into the wrapper
	 * Removes other gallery imgs
	 * Hides the loading gif
	 * To be bound to a mouseleave event.
	 * @param {Element} element (a HTML-Element with thumbnail img)
	 */
	_loadGalleryImage: function(element){
		
		this._imageWrapperElement.down("img.loading-gif").show();
		
		var previewImage = new Element("img", {className: 'gallery-img'});
		
		if (this._imageWrapperElement.down(".gallery-img")) this._imageWrapperElement.select(".gallery-img").invoke("remove");
		
		previewImage.onload = function(){
			this._imageWrapperElement.down("img.loading-gif").hide();
			this._imageWrapperElement.insert(previewImage, {bottom: previewImage});
			
		}.bind(this);
		
		previewImage.src = element.rel; 
		
	},
	
	/**
	 * Aligns the gallery img beside the thumbnailimg
	 * the gallery img is aligned to the wrapper element of the thumbnail, has to have the css class .thumb-wrap
	 * if you need a different alignment overwrite this method!
	 * @param {Element} element (a HTML-Element with thumbnail img)
	 */
	setImageWrapperAlignment: function(element) {
		var imageWrapper = this._getImageWrapper();
		var alignToElement = element.up(".thumb-wrap");
		
		var elementOffset = alignToElement.cumulativeOffset();
		var elementDimensions = alignToElement.getDimensions();
		//console.log("elementOffset: %o, elementDimensions: %o",elementOffset ,elementDimensions);
		
		imageWrapper.setStyle({top: elementOffset.top  + "px"});
		imageWrapper.setStyle({left: (elementOffset.left + elementDimensions.width + 10)  + "px"});
		
		if (this.iframeShim) {
			this.iframeShim.positionUnder(imageWrapper);
			this.iframeShim.show();
		}
		
	}
	
});
