/**
*   file:           nettling.js
*
*   function:       
*   begin:          jun.2010
*   copyright:      © 2010 <i-D> internet + Design GmbH & Co. KG
*                   Erfurter Str. 35
*                   99423 Weimar
*                   Deutschland
*                   Fon:     03643 7785 0
*                   Fax:     03643 7785 29
*                   E-Mail:  office@i-d.de
*                   Web:     http://www.i.d.de/
*   author:         Michael Waack <m.waack@i-d.de>
*
*/


var thumbList = Class.create({
			Thumbs : new Array(),
			
			initialize: function(contentID,divWidth,divHeight,minPerLine,maxPerLine,imgWidth) {

				this.container = $(contentID); 
				this.min = minPerLine;
				this.max = maxPerLine;
				this.width = this.container.offsetWidth;
				this.divWidth = divWidth;
				this.divHeight = divHeight;
				this.isScrolling = false;
				this.aktMargin = 0;
				this.container.style.width = this.width + "px";
				Event.observe(window,"resize",this.resize.bindAsEventListener(this));
				
				var items = $$('#'+contentID +' .thumb');
				this.imgWidth = parseInt(items[0].getStyle('width')) + parseInt(items[0].getStyle('padding-left')) + parseInt(items[0].getStyle('padding-left'));
				for (var i=0; i<items.length; i++) {
					this.add(items[i]);
				}
				
				this.resize();
				var bh = parseInt(document.body.getStyle('height'));
				if (items.length % 6==0) 
					this.detailsHeight = bh + (items.length/6 * 128 + divHeight + 50) + 'px';
				else
					this.detailsHeight = bh + ((items.length/6 +1)* 128 + divHeight + 50) + 'px';
				document.body.setStyle({'height': this.detailsHeight})
				//$('contentThumbs').setStyle({'height': this.detailsHeight});
			},
			// Fügt Thumbnai hinzu
			add: function(item) {
				var ahref = item.childElements()[0];
				var img = ahref.childElements()[0];
				var thumbTitle = ahref.childElements()[1];
				//alert(ahref.childElements()[1].childElements()[0]);
				var newThumb = new Array();
				newThumb['img'] = img;
				newThumb['alt'] = img.title;
				img.title = thumbTitle.down().innerHTML.gsub('"',"'");
				newThumb['src'] = img.src;
				img.alt = thumbTitle.childElements()[0].innerText;
				newThumb['thumbTitle'] = thumbTitle;
				newThumb['ref'] = ahref.href;
				newThumb['item'] = item;
				newThumb['number'] = this.Thumbs.length;
				
				if (item.childElements().length>1) {
					newThumb['prjDetails'] = item.childElements()[1];
					var prjImages = new Array();
					for (var i=item.select('[class="prjImage"]').length-1;i>0;i--) {
						prjImages[i] = item.select('[class="prjImage"]')[i];
						//item.select('[class="prjImage"]')[i].remove();
					}
					newThumb['activePrjNr'] = 0; // Aktuelles projektbild-Nummer
					newThumb['activePrjImg'] = item.select('[class="prjImage"]')[0]; // Aktuelles projektbild
					newThumb['prjImgContainer'] = item.select('[class="prjImgContainer"]')[0];
					newThumb['prjControls'] = item.select('[class="prjControls"]')[0];
					newThumb['prjControls'].setStyle({'top' : '-'+(this.divHeight+20)+"px",'height':this.divHeight+"px"});
					newThumb['prjDescription'] = item.select('[class="prjDescription"]')[0];
					var imgNew = new Element('img', {src: newThumb['activePrjImg'].src,'class':'prjImage'});
					prjImages[0] = imgNew;
					newThumb['prjData'] = prjImages;
					newThumb['prjTitle'] = item.select('[class="prjTitle"]')[0];
					newThumb['prjTitle'].style.cursor = "pointer";
					newThumb['prjTitle'].title = "Klicken blendet die Info aus";
					item.select('[class="aLeft"]')[0].style.visibility="hidden";
					newThumb['scrollLeft'] = item.select('[class="aLeft"]')[0];
					//newThumb['scrollLeft'].hide();
					if(newThumb['prjImgContainer'].childElements().length>1) {
						newThumb['scrollRight'] = item.select('[class="aRight"]')[0];
						Event.observe(newThumb['scrollRight'],"click",this.scrollPrjData.bindAsEventListener(this,newThumb,-1));
					} else {
						item.select('[class="aRight"]')[0].style.visibility = "hidden";
					}
					Event.observe(newThumb['scrollLeft'],"click",this.scrollPrjData.bindAsEventListener(this,newThumb,1));
					Event.observe(newThumb['prjTitle'],"click",this.toggleInfo.bindAsEventListener(this,newThumb));
					Event.observe(newThumb['item'],"mouseover",this.showTitle.bindAsEventListener(this,newThumb));
					Event.observe(newThumb['item'],"mouseout",this.hideTitle.bindAsEventListener(this,newThumb));
					Event.observe(newThumb['prjDetails'],"mousemove",this.showArrows.bindAsEventListener(this,newThumb));
				}
				//ahref.name= "_" + this.Thumbs.length;
				//ahref.name = "_" + this.Thumbs.length;
				ahref.href="javascript:;";//window.location.href + '#_' + this.Thumbs.length;
				newThumb['item'].setStyle({'top':'0px'});
				this.resize();
				//item.style.background='url(' + img.src.replace('.jpg','_on.jpg') + ') no-repeat 3px';
				Event.observe(item,"click",this.openImage.bindAsEventListener(this,newThumb));
				this.Thumbs.push(newThumb);
				
			},
			
			showArrows : function(e) {
				var data = $A(arguments);
				var pos = Event.pointerX(e) - data[1]['prjDetails'].offsetLeft;
				if (this.aktMargin<0 && pos<this.divWidth/2) {
					data[1]['scrollLeft'].style.visibility="visible";
				} else {
					data[1]['scrollLeft'].style.visibility="hidden";
				}
				if (this.aktMargin>(this.divWidth*(data[1]['prjData'].length-1)*-1) && pos>this.divWidth/2) {
					if (data[1]['scrollRight'] !== undefined) {
						data[1]['scrollRight'].style.visibility="visible";
					}
				} else {
					if (data[1]['scrollRight'] !== undefined) {
						data[1]['scrollRight'].style.visibility="hidden";
					}
				}
				
				//data[1]['prjTitle'].update(pos + "  " + this.divWidth);
			},
			showTitle : function(e) {
				var data = $A(arguments);
				data[1]['thumbTitle'].style.display="block";
				data[1]['img'].src=data[1]['alt'];
				
			},
			hideTitle : function(e) {
				var data = $A(arguments);
				if (data.length>1 && this.activeTitle != data[1]['thumbTitle']) {
					data[1]['thumbTitle'].style.display="none";
					data[1]['img'].src=data[1]['src'];
				} 
				else  {
					if (this.activeItem.select('img')[0].classNames() == "activeThumb")
						return;
					this.activeThumbImage.src=this.activeThumbImageSrc;
					this.activeTitle.style.display="none";
				}
			},
			
			toggleInfo : function(e) {
				var data = $A(arguments);
				if (data[1]['prjDescription'].style.visibility=="hidden") {
					data[1]['prjDescription'].style.visibility="visible";
					data[1]['prjTitle'].title = "Klicken blendet die Info aus";
				} else {
					data[1]['prjDescription'].style.visibility="hidden";
					data[1]['prjTitle'].title = "Klicken blendet die Info ein";
				}
				
			}, 
			// Blättern der Projektdetails
			scrollPrjData : function (e) {
//				this.debug.update(this.isScrolling);
				if(this.isScrolling==true)
					return;
				
				this.isScrolling = true;
				var data = $A(arguments);
				
				var direction = data[2]; // -1 nach links, 1 nach rechts
				var prjData = data[1]['prjData'];
				var targetMargin = parseInt(data[1]['prjImgContainer'].getStyle('margin-left'));
				var aktMargin = targetMargin;
				if (direction==-1) {
					targetMargin -= this.divWidth;
				} else {
					targetMargin += this.divWidth;
				}
				if ((this.aktMargin==0 && direction>=0) || 
				((this.divWidth*(data[1]['prjData'].length-1)*-1) >= this.aktMargin && direction == -1)) {
//					this.debug.update(direction);
					this.isScrolling = false;
					return;
				} 					
				var step = 1;
				for (var  i=1;i<100;i++) {
					x = this.divWidth / i;
					if (x<90 && x==parseInt(x)) {
						step = x * direction;
						break;
					}	
				}
				
				this.slide.delay(0.05,aktMargin,targetMargin,step,this,prjData.length-1,data[1]);
			},
			
			slide : function(aktMargin,targetMargin,step,t,len,item) {
				if ((aktMargin > targetMargin && step<0) || (aktMargin < targetMargin && step>0)) {
//					t.debug.update(t.isScrolling);
					aktMargin += step;
					item['prjImgContainer'].setStyle({marginLeft:aktMargin+'px'});
					t.slide.delay(0.05,aktMargin,targetMargin,step,t,len,item);
				} else {
//					t.debug.update(this.isScrolling);
					t.isScrolling = false;
				}
				item['prjDescription'].style.visibility = "hidden";
				t.aktMargin = aktMargin;

			},			
						
			findElement : function(item,cssName) {
				var i;
				for (i=0;i<item.childNodes.length;i++) {
					if (item.className==cssName) {
						return item.childNodes[i];
					}	
				}
				
				
			},
			
			// neuberechnung der positionen, bei window.resize und .add()
			resize: function() {
				// contentdiv breite festlegen damit der umbruch früher kommt
				this.container.style.width = "auto";
				this.width = this.container.offsetWidth;
				this.perLine = parseInt((parseInt(this.width)) / parseInt(this.imgWidth));
				if (this.perLine>this.max) {
					this.perLine = this.max;	
				}
				if (this.perLine<this.min) {
					this.perLine = this.min;	
				}
				
				this.container.style.width = (((this.perLine) * this.imgWidth) ) + "px";
				// Positionen neu berechnen
				var n = this.Thumbs.length;
				for (var i=0;i<n;i++) {
					this.Thumbs[i]['line'] = Math.ceil((i+1) / this.perLine);
				}
				
			},
			
			closeImage : function(e) {
				
				this.activeDiv.morph('height:0px')
				$$('.activeThumb')[0].removeClassName("activeThumb");
				this.activeThumbImage.src=this.activeThumbImageSrc;
				this.activeItem.morph('top:0px')
				this.newOpen.bind(this).delay(1,e);
				//$('contentThumbs').setStyle({'height': ''});
			},
			newOpen : function(e) {
				this.activeDiv.remove();
				this.activeDiv= null;
				if (e['item'] != this.activeItem)
					this.openImage(e);
			},
			/*
			 * Schiebt ein Projekt auf
			 */
			openImage: function(e) {
				var data = $A(arguments);
				if (this.activeDiv!=null) {
					//data[1]['thumbTitle'].hide();
					data[1]['img'].src=data[1]['src'];
					this.closeImage(data[1]);
					return;
				}
				/*
				 * Falls zuvor ein Projekt offen war, titel verbergen
				 */
				if (this.activeTitle!=null) {
					this.activeTitle.hide();
				}
				var index = (data.length==2?1:0);
				
				if (data[index]['prjImgContainer']==null)
					return;
				imgNr = data[index]['line'] * this.perLine;
				data[index]['thumbTitle'].style.display="block";
				this.activeItem = data[index]['item'];
				this.activeTitle = data[index]['thumbTitle'];
				this.activeThumbImage = data[index]['img'];
				this.activeThumbImageSrc = data[index]['src'];
				data[index]['img'].className = 'activeThumb';
				data[index]['img'].src=data[index]['alt']
				data[index]['prjImgContainer'].style.width = (this.divWidth*data[index]['prjData'].length) + "px";
				data[index]['prjImgContainer'].style.height = this.divHeight + 20 + "px";
				data[index]['prjImgContainer'].setStyle({marginLeft:'0px'});
				this.aktMargin = 0;
				if (data[index]['prjDetails']) {
					this.activeDiv = data[index]['prjDetails'];
					this.activeDiv.style.height = "0px";
					this.activeDiv.style.width = "0px";
					this.activeDiv.style.display = "block";
				} else {
					this.activeDiv = new Element('div',{'id':'activeDiv','style': 'float:left;width: 0px; height: 0px;overflow: hidden;'});
					this.activeImage = new Element('img',{'src': data[index]['img'].src ,'width': this.divWidth,'height': this.divHeight });
				}
				this.activeDiv.insert(this.activeImage);
				
				if(imgNr>=this.Thumbs.length) {
					this.Thumbs[this.Thumbs.length-1].item.next().insert({after: this.activeDiv});
				} else {
					this.Thumbs[imgNr].item.insert({before: this.activeDiv});
				}
				data[index]['prjDescription'].style.visibility = "visible";
				//$('activeDiv').morph('width:'+this.divWidth+'px;height:'+this.divHeight+'px')
				this.activeDiv.setStyle({'width':this.divWidth+'px'});
				this.activeItem.setStyle({'position':'relative'});

				//this.moveDown(0,2,114);
				this.activeItem.morph('top:' + (this.imgWidth - 14) + 'px');
				if (data[index]['scrollRight'] !== undefined) {
					data[index]['scrollRight'].style.visibility="hidden";
				}
				//this.activeDiv.scrollTo();
				this.activeDiv.morph('height:'+this.divHeight+'px')
				//this.activeDiv.scrollTo();
				//this.activeTitle.scrollTo();
				var top = (this.activeTitle.cumulativeOffset()[1])-2;
				//console.debug(top);
				window.scrollTo(0,top);
			},
			
//			scrollPage : function () {
//				alert("scroll");
//				this.activeDiv.scrollTo();
//			},

			fadeIn: function() {
				var w = parseInt(this.activeDiv.style.width);
				if (w<this.divWidth) {
					this.activeDiv.style.width = w+2+"px";
					window.setTimeout("fadeIn()",400);
				}
			}
		
		
		});
		
		

		function initThumbs() {
			//(contentID,divWidth,divHeight,minPerLine,maxPerLine,imgWidth)
			var myThumbs = new thumbList('contentThumbs',798,544,6,6,128);
		}
		
		Event.observe(window,"load",initThumbs);
