/**
 * Return an Object cursor{x, y} with the current cursor-position 
 * for all current browsers
 * 
 * @e event
 * @return cursor-object 
 */


Prototype.Browser = {
	IE:     !!(window.attachEvent && !window.opera),
	Opera:  !!window.opera,
	WebKit: document.childNodes && !document.all && !navigator.taintEnabled,
	Gecko:  (document.getBoxObjectFor != null),
	MobileSafari: !!navigator.userAgent.match(/Apple.*Mobile.*Safari/)
};

Object.extend(Prototype.Browser, {
     WebKit419: Prototype.Browser.WebKit && (Prototype.BrowserFeatures.XPath),
     WebKit420: Prototype.Browser.WebKit && (!Prototype.BrowserFeatures.XPath),
     IE6:      Prototype.Browser.IE && (typeof window.XMLHttpRequest == "undefined"),
     IE7:      Prototype.Browser.IE && (typeof window.XMLHttpRequest == "object")
});

/*
function getCursorPosition(e) {
    e = e || window.event;
    var cursor = {x:0, y:0};
    if (e.pageX || e.pageY) {
        cursor.x = e.pageX;
        cursor.y = e.pageY;
    } 
    else {
        var de = document.documentElement;
        var b = document.body;
        cursor.x = e.clientX + 
            (de.scrollLeft || b.scrollLeft) - (de.clientLeft || 0);
        cursor.y = e.clientY + 
            (de.scrollTop || b.scrollTop) - (de.clientTop || 0);
    }
    return cursor;
}

var lastCursorPosition = {x:0, y:0};

Event.observe(document, 'mousemove', function(event) {
	 lastCursorPosition = getCursorPosition(event);
});

function isMouseOver () {
	var cursor = lastCursorPosition;
	if (lastCursorPosition.x < this.positionLeft || lastCursorPosition.x > this.positionRight 
		|| lastCursorPosition.y < this.positionTop || lastCursorPosition.y > this.positionBottom) {
		return false;
	}
	return true;
}
*/


var ImageSlide = Class.create({
	
	//currently active item, count from 0
	items: [],
	currentItem: 0,
	navigation: [],
	pe: false,
	inProgress: false,
	
	
	/**
	 * Initialize class
	 *
	 * @container: html-parent-container, usually with class fce-imageslide
	 */
	initialize: function(container) {
		this.container  = container;
		this.height = 0;
		this.items = this.container.select('ul.images>li');
		this.itemCount = this.items.size();
		
		this.items.each(function (item, index) {
			imgTag = item.select('img').first();
			//preload all images
			preloadImage = new Image();
			preloadImage.src = imgTag.readAttribute('src');
			
			//search for image with greatest height
			if (Prototype.Browser.IE) {
				regExp = new RegExp(/\<img.*height[^\d]+(\d+)/i);
				match = regExp.exec(item.innerHTML);
				tempHeight = match[1];
			} else {
				tempHeight = imgTag.readAttribute('height');
			}
			this.height = (tempHeight > this.height) ? tempHeight : this.height;
			
			//display first image
			if (index == this.currentItem) {
				item.show();
			}
		}.bind(this));
		//FG, this is a hotfix, please change 
		if (this.container.hasClassName('imageslider')) {
			this.container.setStyle({height: this.height + 'px'});
		}

		if (this.itemCount > 1) {
			this.navigation = this.container.select('ul.navigation>li');
			this.navigation.each(function (item, index) {
				item.observe('click', function(event) {
					elementClicked = event.element().tagName.toLowerCase() == 'li' ? event.element() : event.element().up('li');
					this.currentItem = this.navigation.indexOf(elementClicked);
					this.pe.stop();
					this.showItem(this.currentItem);
				}.bindAsEventListener(this));
			}.bind(this));
			
			//startPeriodicalExecuter
			this.pe = new PeriodicalExecuter(function(pe) {
				this.nextItem();
			}.bind(this), 5);
		}
	},
	
	nextItem: function () {
		this.items[this.currentItem].fade();
		this.currentItem = (this.currentItem + 1) % this.itemCount;
		this.items[this.currentItem].appear();
		
		if (this.navigation.size() > 0) {
			this.navigation.invoke('removeClassName', 'act');
			this.navigation[this.currentItem].addClassName('act');
		}
	},
	
	stopRotation: function () {
		this.pe.stop();
	},
	
	destroy: function () {
		this.navigation.each( function (item) {
			item.stopObserving('click');
		});
		this.pe.stop();
	},
	
	showItem: function (itemPos) {
		inProgress = false; 
		this.items.each(function (item) {
			if (item.inProgress) {
				inProgress = true;
			}
		});
		
		if (! inProgress) {
			this.items.each(function (item, index) {
				item.inProgress = true;
				if (index == itemPos) {
					item.appear({
						afterFinish: function() {
							item.inProgress = false;
						}.bind(item)
					});
				} else {
					item.fade({
						afterFinish: function() {
							item.inProgress = false;
						}.bind(item)
					});
				}
			}.bind(this));
			
			if (this.navigation.size() > 0) {
				this.navigation.invoke('removeClassName', 'act');
				this.navigation[itemPos].addClassName('act');
			}
		}
	}
});

var OptionSelect = Class.create({
	
	//currently active item, count from 0
	items: [],
	targetContainersBig: [],
	targetContainersSmall: [],
	currentItem: 0,
	initialIsOption: false,
	
	
	
	/**
	 * Initialize class
	 *
	 * @container: html-parent-container, usually with class fce-imageslide
	 */
	initialize: function(container) {
		this.container  = container;
		this.targetContainersBig = $$('.tx-jsgallery-pi1-productdetails-images-big > ul');
		this.targetContainersSmall = $$('.tx-jsgallery-pi1-productdetails-images-small > ul');
		this.items = this.container.select('ul.options>li');
		this.itemCount = this.items.size();
		
		this.items.each(function (item, index) {
			imgTag = item.select('img').first();
			//preload all images
			preloadImage = new Image();
			preloadImage.src = imgTag.readAttribute('src');
			
			//search for image with greatest height
			if (Prototype.Browser.IE) {
				regExp = new RegExp(/\<img.*height[^\d]+(\d+)/i);
				match = regExp.exec(item.innerHTML);
				tempHeight = match[1];
			} else {
				tempHeight = imgTag.readAttribute('height');
			}
			this.height = (tempHeight > this.height) ? tempHeight : this.height;
			
			item.observe('click', function(event) {
				elementClicked = event.element().tagName.toLowerCase() == 'li' ? event.element() : event.element().up('li');
				this.currentItem = this.items.indexOf(elementClicked);
				this.setActive(this.currentItem+1);
				this.toggleDisplayStateBig(this.currentItem+1);
				this.toggleDisplayStateSmall(this.currentItem+1);
				running.destroy();
				running = new ImageSlide($$('.tx-jsgallery-pi1-productdetails-images')[0]);
			}.bindAsEventListener(this));
		}.bind(this));
	},
	
	setActive: function (index) {
		this.items.each(function (item) {
			if(item.hasClassName('act')) {
				item.toggleClassName('act');
			}
			if(this.items.indexOf(item) == index) {
				item.addClassName('act');
			}
		}.bind(this));
	},
	
	toggleDisplayStateBig: function (index) {
		this.targetContainersBig.each(function (item) {
			if(this.targetContainersBig.indexOf(item) == index) {
				if(item.hasClassName('images')) {
					return;
				}
				item.toggleClassName('images');
				item.writeAttribute('style', '');
				item.down('img').writeAttribute('style', 'display: none;');
				item.down('img').appear();
			}
			else {
				if(item.hasClassName('images')) {
					item.toggleClassName('images');
					//item.down('div').setStyle({ display: 'none' });
					item.down('div').writeAttribute('style', 'display: none;');
					item.down('img').fade({afterFinish: function() {
						item.writeAttribute('style', 'display: none;');
						item.down('div').writeAttribute('style', '');
					}});
				}
			}
		}.bind(this));
	},

	toggleDisplayStateSmall: function (index) {		
		this.targetContainersSmall.each(function (item) {
			if(this.targetContainersSmall.indexOf(item) == index) {
				if(item.getStyle('display') != 'none') {
					return;
				}
				item.toggleClassName('navigation');
				item.appear();
			}
			else {
				if(item.hasClassName('navigation')) {
					item.toggleClassName('navigation');
					item.fade();
				}
			}
		}.bind(this));
	}
});

var AutoClearInput = Class.create({
	inputField: false,
	defaultValue: '',
	
	/**
	 * Initialize class
	 *
	 * @inputField: html input field, usually with class "autoclearinput"
	 */
	initialize: function(inputField) {
		this.inputField = inputField;
		this.defaultValue = $(this.inputField).readAttribute('title');
		
		this.inputField.observe('focus', this.focus.bindAsEventListener(this));
		this.inputField.observe('blur', this.blur.bindAsEventListener(this));
	},
	
	focus: function (event) {
		if ($F(this.inputField) == this.defaultValue) {
			$(this.inputField).clear();
		}
	},
	
	blur: function (event) {
		if ($F(this.inputField) == '') {
			$(this.inputField).value = this.defaultValue;
		}
	}
});

Event.observe(document, "dom:loaded", function (event) {
		//imageslider
	$$('.imageslider,.tx-jsgallery-pi1-productdetails-images').each(function (item) {
		running = new ImageSlide(item);
	});
		//Product options
	$$('.tx-jsgallery-pi1-productdetails-options').each(function (item) {
		new OptionSelect(item);
	});
	
		//autoClearInput
	$$('.input-autoclear').each(function (item) {
		new AutoClearInput(item);
	});	
});

/*
var EnableHoverClass = Class.create({
	container: null,
	hoverClass: 'hover',
	className: '',
	
	initialize: function (container, className) {
		this.container = container;
		if (className != '') {
			this.className = className;
			this.hoverClass = className + '-' + this.hoverClass;
		}
		this.container.observe('mouseover', this.focus.bindAsEventListener(this));
		this.container.observe('mouseout', this.blur.bindAsEventListener(this));
	},
	
	focus: function (event) {
		this.container.addClassName(this.hoverClass);
	},
	
	blur: function (event) {
		this.container.removeClassName(this.hoverClass);
	}
});

if (Prototype.Browser.IE6) {
	Event.observe(document, "dom:loaded", function (event) {
		$$('.tx-jsgallery-pi1-productlist-item').each(function (item) {
			new EnableHoverClass(item, 'tx-jsgallery-pi1-productlist-item');
		});
	});
}
*/
/** 
 * SPECIAL JOSEF SEIBEL
 */
var JSGalleryProductFinder = Class.create({
	//parent container
	container: null,
	
	//type (could be list or slider)
	type: 'slider',
	
	//link for opening/closing productfinder
	pfLink: null,
	
	//container for productfinder selectors
	pfContainer: null,
	
	//pfForm is the form-tag of the productfinder
	pfForm: null,
	
	//pfSubmit is the submit-button of the productfinder
	// infact, the submit-button is a normal link getting it's function from javascript
	pfSubmit: null,
	
	initialize: function(container) {
		this.container = container;
		
		this.pfLink = container.select('.tx-jsgallery-pi1-navigation-productfinder-link').first();
		this.pfLink.observe('click', this.show.bindAsEventListener(this));
		
		this.pfContainer = container.select('.tx-jsgallery-pi1-productfinder').first();
		this.pfForm = container.select('form').first();
		this.pfSubmit = container.select('.tx-jsgallery-pi1-submit>a').first();
		
		this.type = this.pfContainer.select('input[name="tx_jsgallery_pi1[view]"]').first().getValue();
		if (this.type == 'list') {
			this.pfSubmit.observe('click', this.submitForm.bindAsEventListener(this));
		} else {
			this.pfSubmit.observe('click', this.submitXHR.bindAsEventListener(this));
			this.submitXHR();
		}
	},
	
	show: function (event) {
		try {
			Effect.toggle(this.pfContainer, 'slide');
			//Effect.toggle(this.pfContainer, 'blind');
		} catch (e) {
			console.log(e);
		}
		//this.pfContainer.toggle();
	},
	
	submitForm: function (event) {
		this.pfForm.submit();
	},
	
	submitXHR: function () {
		this.pfForm.request({
			onComplete: function (result) {
				$('JSproductSlider').SetVariable('string_filter',result.responseText);
			}.bind(this)
		});

		linkSwitchView = $$('.tx-jsgallery-pi1-navigation-linkswitchview>a').first();
		linkSwitchViewQuery = linkSwitchView.readAttribute('href').parseQuery();
			//reset pf-params
		Object.keys(linkSwitchViewQuery).each(function (key) {
			if (key.startsWith('tx_jsgallery_pi1[pf]')) {
				delete(linkSwitchViewQuery[key]);
			}
		});
		
		
		pfQuery = this.pfForm.serialize(true);
		Object.keys(pfQuery).each(function (key) {
			if (key.startsWith('tx_jsgallery_pi1[pf]')) {
				linkSwitchViewQuery[key] = pfQuery[key];
			}
		});
		
		newHref = linkSwitchView.readAttribute('href').substring(0, linkSwitchView.readAttribute('href').indexOf('?'));
		linkSwitchView.writeAttribute('href', newHref + '?' + Object.toQueryString(linkSwitchViewQuery))
	}
});

Event.observe(window, "load", function (event) {
	$$('.tx-jsgallery-pi1-navigation-productfinder').each(function (item) {
		new JSGalleryProductFinder(item);
	});
});


Event.observe(window, 'unload', function (event) {
});


