// JavaScript Document
// min. Dojo v1.3 required

//dojo.require("dojo.NodeList-fx");
//dojo.require("dijit.Dialog");
//dojo.require("dijit.form.Form");
//dojo.require("dijit.form.MultiSelect");
//dojo.require("dijit.form.Button");
//dojo.require("dijit.form.TextBox");
//dojo.require("dijit.form.ValidationTextBox");
//dojo.require('dojo.io.iframe');
dojo.require('dojo.fx.easing');

dojo.addOnLoad(function(){
	// START Suchfeld Standardwert setzen/loeschen
	dojo.connect(dojo.byId('term'), 'onfocus', function() {
		if(this.value=='' || this.value==this.defaultValue) {
			this.value='';
		}
	});
	dojo.connect(dojo.byId('term'), 'onblur', function() {
		if(this.value=='') {
			this.value=this.defaultValue;
		};
	});
	// ENDE Suchfeld Standardwert setzen/loeschen
	//Gax.changeColor.dtlColors = new Gax.changeColor.init();

	var pImg = dojo.byId('productimg');
	var hImg = dojo.byId('hoverimg');
	var video = dojo.byId('video');
	if(video){ var sources=video.getElementsByTagName('source'); }
	if(pImg) {
		dojo.connect(pImg, 'onmousemove', mbuffer );
		dojo.connect(hImg, 'onmousemove', mbuffer );
		dojo.connect(pImg, 'onmouseover', function(){
			dojo.animateProperty({
				node:this,
				duration:150,
				properties:{ 'opacity':0.6 }
			}).play();
			hImg.style.display='block';
		});
		dojo.connect(hImg, (!dojo.isMozilla ? "onmousewheel" : "DOMMouseScroll"), function(e){
			e.preventDefault();
			var scroll = e[(!dojo.isMozilla ? "wheelDelta" : "detail")] * (!dojo.isMozilla ? 1 : -1);
				if(scroll<0){
					if(Gax.hImgDim<200){ Gax.hImgDim+=14; }
				} else {
					if(Gax.hImgDim>40){ Gax.hImgDim-=14; }
				}
				setClip(e);
		});
		dojo.connect(dojo.byId('zoom'), 'onmouseleave', function(){
			dojo.animateProperty({
				node:pImg,
				duration:150,
				properties:{ 'opacity':1 }
			}).play();
			hImg.style.display='none';
		});
		dojo.connect(dojo.byId('ansichten'), 'onclick', function(e){
			if(e.target.nodeName.toLowerCase() == 'img' && !e.target.id) {
				pImg.src = e.target.src.replace(/-105px/,'-360px');
				hImg.src = e.target.src.replace(/-105px/,'-720px');
				dojo.byId('zoom').style.display='block';
				if(video){
					video.style.display='none';
				}
			}
		});
		//if((vswitch=dojo.byId('vswitch'))){
		var vswitch=dojo.byId('vswitch');
		if(vswitch){
			dojo.connect(vswitch,'onclick', function(e){
				dojo.byId('zoom').style.display='none';
				if(video){
					video.style.display='block';
				}
			});
		}
		var colorField=dojo.byId('color');
		if( colorField ) { // assignment!
			dojo.connect(colorField, 'onchange', function(e){
				/* deaktiviert
				dojo.destroy("invalid");
				if(Gax.colors[this.value]) {
					dojo.place('<p class="notice" id="invalid">Die Farbe '+Gax.colors[this.value]+' ist in Kürze lieferbar.</p>',
						'pd','after'
					);
				}
				dojo.byId('itemprice').value=getMaxPrice();
				*/
				
				var allImg = dojo.query('#zoom img, #ansichten img');
				var sizeRegEx=/_\d{3}-/;
				var colorRegEx=/_\d{3}\./g;
				var fieldVal;
				// bilder aendern
				for (var i=allImg.length-1; i>=0; i--) {
					fieldVal = this.value.split('#');
					fieldVal = fieldVal[0].split('§');
					/*allImg[i].src = allImg[i].src.replace(/_..._/,'_'+colorVal[0]+'_');
					console.log(allImg[i].src.replace(/_..._/,'_'+colorVal[0]+'_'));*/
					allImg[i].src = allImg[i].src.replace(sizeRegEx,'_'+fieldVal[0]+'-');
					//console.log(allImg[i].src);
				}
				
				// videodatei aendern
				if(dojo.isMozilla){
					// Firefox 3.6.4 load() Method is broken
					video_alt=dojo.byId('video');
					video=video_alt.cloneNode(true);
					vParent=video_alt.parentNode;
					dojo.destroy(video_alt);
					srcs=video.innerHTML;
					newsrcs=srcs.replace(colorRegEx,'_'+fieldVal[0]+'.');
					video.removeAttribute('src');
					video.innerHTML=newsrcs;
					dojo.place(video, vParent, 'first');
				}
				
				for(var jj=0, sl=sources.length; jj<sl; jj++){
					sourceType=dojo.attr(sources[jj],'type');
					sourceAttr=dojo.attr(sources[jj],'src');
					//dojo.attr(sources[jj],'src',sourceAttr.replace(colorRegEx,'_'+fieldVal[0]+'.'));
					sources[jj].src=sourceAttr.replace(colorRegEx,'_'+fieldVal[0]+'.');
				}
				$f('fplayer').play(sources[1].src);
				video.load();
			});
		}
		// Preis anpassen
		dojo.connect(dojo.byId('size'),'onchange', function(e){
			//dojo.byId('itemprice').value=getMaxPrice();
			dojo.byId('itemprice').value=this.options[this.selectedIndex].text.substr(-6);
		});
		// Farbauswahl wieder aktivieren
		dojo.query('#color :disabled').forEach(function(node,idx,list) {
			if(dojo.hasAttr(node.parentNode,'disabled')) {
				dojo.attr(node.parentNode,'disabled',false);				
			}
			if(dojo.hasAttr(node,'disabled')) {
				Gax.colors[node.value]=node.text;
				dojo.attr(node,'disabled',false);
			}
		});
	}
	dojo.query('#cartbox.active, #measurebox').onmouseenter( function(e){
		this.style.cursor='pointer';
	});
	dojo.query('#cartbox.active').onclick( function(e){
		window.location=this.getElementsByTagName('a')[0].href;
	});
	dojo.query('#measurebox').onclick( function(e){
		window.location=this.getElementsByTagName('a')[0].href;
	});
});

function mbuffer(e) {
	if(Gax.zCounter>=5 || Gax.zCounter==0) {
		zoomer(e);
		Gax.zCounter =0;
	}
	Gax.zCounter++;
}
function zoomer(e) {
	// bugfix - event nur wenn position wirklich anders ausführen
	if (e.pageX != Gax.cx || e.pageY != Gax.cy) {
		//console.log(e);		//console.log(getMPos(e));
		setClip(e);
	}
	Gax.cx =e.pageX;
	Gax.cy =e.pageY;
}

function setClip(e) {
	var mPos = getMPos(e);
	var zdiv =dojo.byId('zoom');
	var zimg =dojo.byId('hoverimg');
	var hImgDim=Gax.hImgDim, imgScaleF=zimg.offsetWidth/zdiv.offsetWidth;
	var clipLeft=(mPos.mX-zdiv.offsetLeft);
	// div#container hat 30px border-top
	var clipTop=((mPos.mY-zdiv.offsetTop-30));
	
	zimg.style.display='block';
	zimg.style.clip=clipString(
		Math.round(clipTop*imgScaleF)-hImgDim,
		Math.round(clipLeft*imgScaleF)-hImgDim,
		hImgDim*2);
	
	/*
	if(dleft<=hImgDim && dtop>hImgDim && dtop <(sImgH-hImgDim)){
		// links anstoßen
		zimg.style.left=0;
		zimg.style.top=-dtop+'px';
	}
	else if(dleft>=sImgW-hImgDim && dtop>hImgDim && dtop <(sImgH-hImgDim)){
		// rechts anstoßen 
		zimg.style.left=sImgW-(2*hImgDim)+'px';
		zimg.style.top=dtop-hImgDim+'px';
	}
	else if(dtop<=hImgDim && dleft>hImgDim && dleft <(sImgW-hImgDim)){
		// oben anstoßen
		zimg.style.top=0;
		zimg.style.left=-dleft+'px';
	}
	else if(dtop>=sImgH-hImgDim && dleft>hImgDim && dleft <(sImgW-hImgDim)){
		// unten anstoßen
		zimg.style.top=sImgH-(2*hImgDim)+'px';
		zimg.style.left=dleft-hImgDim+'px';
	}
	else if(dleft>hImgDim && dleft <(sImgW-hImgDim) && dtop>hImgDim && dtop <(sImgH-hImgDim)){*/
		// rest innerhalb
	zimg.style.left=-clipLeft+'px';
	zimg.style.top=-clipTop+'px';
	//}
}

function clipString(top,left,dim) {
	var t = top+'px';
	var r =dim+left+'px';
	var b =dim+top+'px';
	var l = left+'px';
	return 'rect('+t+', '+r+', '+b+', '+l+')';
}

function getMPos(e) {
	var posx = 0;
	var posy = 0;
	if (!e) var e = window.event;
	if (e.pageX || e.pageY) {
		posx = e.pageX;
		posy = e.pageY;
	}
	else if (e.clientX || e.clientY) 	{
		posx = e.clientX + document.body.scrollLeft
			+ document.documentElement.scrollLeft;
		posy = e.clientY + document.body.scrollTop
			+ document.documentElement.scrollTop;
	}
	// posx and posy contain the mouse position relative to the document
	return {'mX':posx,'mY':posy}
}
function percentPx(s,l) {
	p = (parseInt(s)*100)/parseInt(l);
	px = parseInt(s)*p;
	return parseInt(px);
}

function getMaxPrice(){
	var prices=[];
	dojo.query('#pd #size, #pd #color').forEach(function(node, idx, arr){
		var price=parseFloat(node.options[node.selectedIndex].text.substr(-6).replace(',','.'));
		if(!isNaN(price)){
			prices.push(price);
		}
	});
	prices.push(0);
	console.log(prices);
	if(prices.length>1 && prices[0]!==0){
		return Math.max(prices[0],prices[1]);
	} else {
		return dojo.byId('itemprice').value;
	}
}

var Gax = {
	colors:new Object,
	hImgDim:120
	,iframeW: 500
	,iframeH: 250
	,zCounter:0
	,showDialog: function(el,url) {
		// el=Element
		var title = Gax.getText(el);
		var dialog = new dijit.Dialog({
			'title':title, "href": url, 'id': 'dlg',
			'onLoad': function(){
				dijit.byId('dlg').domNode.appendChild(
					//var stag = dojo.create('script');
					//dojo.attr(stag,{innerHtml:"alert('JAAA');"})
				);
			}
		});
		dialog.show();
	}
	,showIframeDialog: function(el,w,h) {
		// el=Element, w+h=Number
		var title = Gax.getText(el);
		var dialog = new dijit.Dialog({'title':title});
		//dialog.content();
		var iframe = dojo.create('iframe', {
			'src': el.href
		});
		if(w && h) {
			dojo.attr(iframe,{'width':w, 'height':h});
		} else {
			dojo.attr(iframe,{'width':Gax.iframeW, 'height':Gax.iframeH});
		}
		dialog.attr('content',iframe);
		dialog.show();
	}
	/*,createIframe: function(url) {
		var iframe = dojo.io.iframe.create({
			'uri': url,
			'fname': "post"
		 });
		return iframe;
	}*/
	,getText: function(node) {
		// node=Element
		if(node.textContent) {
			return node.textContent;
		} else if (node.innerText) {
			return node.innerText;
		} else {
			return node.innerHtml;
		}
	}
	,changeImg: function(imgPath){
		dojo.byId('produktbild').src=imgPath;
	}
	,changeColor: {
		init:	function(){
			this.colSel = dojo.byId('colorinfo'); // <select> element
			this.colors = dojo.query('#colors img');
			this.colors.style('cursor','pointer');
			this.views = dojo.query('#ansichten img');
			this.views.style('cursor','pointer');
			this.productImg = dojo.query('img#produktbild');
			this.imgSList = this.views.concat(this.productImg); // all product images
			dojo.connect(this.colSel, 'onchange', this.colSel, Gax.changeColor.update ); // <select> event binding
			this.colors.connect('onclick', Gax.changeColor.update ); // <img> event binding
			this.views.connect('onclick', function(){
				var newView = dojo.attr(this, 'data-view');
				Gax.changeColor.dtlColors.productImg[0].src =
					Gax.changeColor.newAttrStr('src', Gax.changeColor.dtlColors.productImg[0], newView, 3);
			}); // <img> event binding
		}
		,update: function() {
			var newColor = this.value || dojo.attr(this, 'data-color');
			dojo.byId('colorinfo').value = newColor;
			Gax.changeColor.dtlColors.imgSList.forEach(function(el) {
				if(dojo.hasAttr(el,'src')) {
					el.src = Gax.changeColor.newAttrStr('src',el, Gax.colorinf[newColor], 1);
				}
			});
		}
		,newAttrStr: function(attr,elem,newVal,part) {
			var currAttr = elem.getAttribute(attr);	// gibt bis IE7 die function zurück
			var txtArr = currAttr.split('_');
			txtArr[part]=newVal;
			return txtArr.toString().replace(/\,/g,'_');
		}
	}
}
