/*
	# Produzido por: Aurl Infomática
	# Site: http://www.aurlinformatica.com.br
	# Autor: Aurélio de Morais
*/

function galleryImage(divBox,divBoxImg,optionList){
	var objBox=document.getElementById(divBox);
	var objBoxClass='boxImage';
	var imgMini=260;//miniatura normal 
	var imgZoomW1=150;//minutura zoom 1
	var imgZoomW2=70;//minutura zoom 2
	var imgMargin=5;
	var indiceInit=0;//indice inicial
	
	var setaLeft;
	var setaRight;
	var setaPlay;
	var setaStop;
	var palcoPrincipal=0;
	var arrayImg;
	var isLightbox=false;
	
	var imgZoomH=imgMini;//altura do zoom
	var i=0;
	var x=0;
	var n;
	var imgs=new Array();
	var imgW=new Array();
	var imgH=new Array();
	var imgLink=new Array();
	var palcoImgW=imgZoomW1+imgMargin+imgMini+imgMargin+imgZoomW1 	+imgZoomW2;//largura do palco das imagens	/
	var palcoW=palcoImgW+0;//largura do palco geral => imagens + botões
	var objBoxImg=document.getElementById(divBoxImg);//objBox.firstChild;//obj #boxList
	var indice=0;//indice matriz geral das imagens
	var controlMove='';
	var intervalo;
	var setaPlayStatus='off';
	var ax;
	var ix;
	var ixLoad;

	// *************************** carrega a lista de parametros ************************** //
	/* sintaxe: op1:value1|opt2:value2
	* variaveis
			setaLeft = nome-layer						- nome a layer do botao (opcional)
			setaLeft = nome-layer						- nome a layer do botao (opcional)
			setaPlay = nome-layer						- nome a layer do botao (opcional)
			setaStop = nome-layer						- nome a layer do botao (opcional)
			imgMini = number							- valor em pixels da imagem normal (opcional)
			imgZoomW1 = number							- valor em pixels da imagem menor 1 (opcional)
			imgZoomW2 = number							- valor em pixels da imagem menor 2 - alpha (opcional)
			imgMargin = number							- valor em pixels da margem entre as imagens (opcional)
			palcoPrincipal = number						- largura do palco principal onde será posicionado o box das imagens (opcional)
			arrayImg = matriz(img1|img2|title)			- matriz os dados das imagens (opcional)
			isLightbox = true/false						- habilita ou não o recurso de lightbox
			indiceInit = number							- indice correspondente a imagem do centro ao carregar
	*/
	var optStr=new Array('setaLeft','setaRight','setaPlay','setaStop','imgMini','imgZoomW1','imgZoomW2','imgMargin','palcoPrincipal','arrayImg','isLightbox','indiceInit');
	if(optionList!=undefined){
		for (i=0;i<optStr.length;i++){
			if(eval('optionList.'+optStr[i])!=undefined){
				if(i<4){
					eval(optStr[i]+' = document.getElementById(optionList.'+optStr[i] +')');
				}else{
					eval(optStr[i]+' = optionList.'+optStr[i]);
				}
			}
		}
		palcoImgW=imgZoomW1+imgMargin+imgMini+imgMargin+imgZoomW1 	+imgZoomW2;//largura do palco das imagens	/
		palcoW=palcoImgW+0;//largura do palco geral => imagens + botões
		imgZoomH=imgMini;//altura do zoom
	}
	// *************************** ***************************** ************************** //

	//ajusta o tamanho das imagens
	var resizeImg=function(objImg,limite){
		//alert(  objImg.width+'      '+ objImg.height )
		if(objImg.width>limite || objImg.height>limite){
			var w;
			var h;
			if(objImg.width>=objImg.height){
				h = parseInt((objImg.height/objImg.width)*limite)
				w = limite;
				objImg.style.height=h+'px';
				objImg.style.width=w+'px';
			}else{
				w = parseInt((objImg.width/objImg.height)*limite);
				h = limite;
				objImg.style.width=w+'px';
				objImg.style.height=h+'px';
			}
			return w+'|'+h;
		}else{
			return objImg.width+'|'+objImg.height;
		}
	}
	var positionObjs=function(control){//alinha os objetos
		var p1=0;
		var pI=0;
		var pF=0;
		var w=0;
		var h=0;
		var z=0;
		var posCenter=Math.round(palcoImgW/2);//posicao do centro
		var indL1;
		var indL2;
		var indR1;
		var indR2;

		if (control=='load'){//posiciona os primeiros objetos
				//incializar os valores das posições
				if(indice<0){ indice=imgs.length-1; }else if(indice>imgs.length-1){ indice=0; }
				indL1= (indice-1<0 ? imgs.length-1 : indice-1);
				indR1= (indice+1>imgs.length-1 ? 0 : indice+1);
				indL2= 0;
				indR2= 0;
				
				//posiciona do objeto do centro
				p1 = (posCenter - parseInt(imgW[indice]/2) );
				imgs[indice].style.left=p1+'px';
				imgs[indice].style.top=(parseInt(imgZoomH/2))+'px';
				imgs[indice].style.marginTop='-'+(  parseInt(imgH[indice]/2)  )+'px';
				imgs[indice].style.visibility='visible';
				
				z = imgZoomW1/imgMini;
				//posiciona o objeto da esquerda
				w = imgW[indL1]*z;
				h = imgH[indL1]*z;
				imgs[indL1].firstChild.style.width= w+'px';
				imgs[indL1].firstChild.style.height= h+'px';
				imgs[indL1].style.left=(posCenter - imgZoomW1 - Math.round(imgW[indL1]/2) - imgMargin)+'px';
				imgs[indL1].style.top=(parseInt(imgZoomH/2))+'px';
				imgs[indL1].style.marginTop='-'+(  parseInt(h/2)  )+'px';
				imgs[indL1].style.visibility='visible';
				
				//posiciona o objeto da direita
				w = imgW[indR1]*z;
				h = imgH[indR1]*z;
				imgs[indR1].firstChild.style.width= w+'px';
				imgs[indR1].firstChild.style.height= h+'px';
				imgs[indR1].style.left=(posCenter +  Math.round(imgW[indice]/2) + imgMargin	 )+'px';
				imgs[indR1].style.top=(parseInt(imgZoomH/2))+'px';
				imgs[indR1].style.marginTop='-'+(  parseInt(h/2)  )+'px';
				imgs[indR1].style.visibility='visible';

				//oculta os demais objetos
				for(i=0;i<imgs.length;i++){
					if(i!=indice && i!=indL1 && i!=indR1){// && i!=indL2 && i!=indR2
						imgs[i].style.visibility='hidden';
						//resizeImg(imgs[i].firstChild,imgZoomW2);//ajusta como minuatura as demais imagens
					}
				}
				
		}else{//scroll dos demais objetos para 'left' ou 'right'
				indL1= (indice-1<0 ? imgs.length-1 : indice-1);
				indL2= (indL1-1<0 ? imgs.length-1 : indL1-1);
				indR1= (indice+1>imgs.length-1 ? 0 : indice+1);
				indR2= (indR1+1>imgs.length-1 ? 0 : indR1+1);
				//alert(indL1+'          '+indice+'      '+indR1);

				p1 = (posCenter - Math.round(imgW[indice]/2) );
				//objeto do centro
				pI = p1;
				if (control=='left')pF = posCenter-Math.round(imgMini/2)-imgMargin-imgZoomW1;
				if (control=='right')pF = posCenter+Math.round(imgMini/2)+imgMargin;
				moveObj('center',indice,pI,pF,imgZoomW1, -1 );//-1 porque sempre diminui

				//objeto da esquerda 1
				pI = parseInt(imgs[indL1].style.left.replace('px',''));
				if (control=='left')pF=pI-imgMini-imgMargin;
				if (control=='right')pF=posCenter - Math.round(imgW[indL1]/2); //pI+imgMini+imgMargin;
				if (control=='left')moveObj('left',indL1,pI,pF,imgZoomW2,-1);
				if (control=='right')moveObj('right',indL1,pI,pF,imgMini,1);

				//objeto da esquerda 2
				if (control=='right'){
					pI = posCenter - Math.round(imgMini/2) - imgMargin - imgZoomW1 - imgMargin - imgZoomW2;
					pF = pI + imgZoomW2 + imgMargin;
					moveObj('left2',indL2,pI,pF,imgZoomW1,1);
				}

				//objeto da direita 1
				pI = Math.round(imgs[indR1].style.left.replace('px','')); 
				if (control=='left')pF=posCenter-Math.round(imgW[indR1]/2);//pI-imgMini-imgMargin;
				if (control=='right')pF=pI+imgMini+imgMargin;
				if (control=='left') moveObj('left',indR1,pI,pF,imgMini,1);
				if (control=='right') moveObj('right',indR1,pI,pF,imgZoomW2,-1);

				//objeto da direita 2
				if (control=='left'){
					pI = posCenter + Math.round(imgMini/2) + imgMargin + imgZoomW1 + imgMargin + imgZoomW2;
					pF = posCenter + Math.round(imgMini/2) + imgMargin ;
					moveObj('right2',indR2,pI,pF,imgZoomW1,1);
				}

				//reajusta os valores dos indices
				if (control=='left'){indice++;}else{indice--;}
				if(indice<0){
					indice=imgs.length-1;
				}else if(indice>imgs.length-1){
					indice=0;
				}
		}
	}
	
	var moveObj=function(area,ind,posI,posF,limite,fator,ic,activeZoom,opacity,nLoop,tf){//move os objetos //fator=indica valores positivos ou negativos // aumenta ou diminui
		var iPerc=0.25;//percentual de aceleração
		var desloc=5;//deslocamento
		var i=0;
		var n=0;//0.05;
		var a=0;//
		var limiteTmp=0;
		var tf2;
		var liImg=0;
		var w=0;
		var h=0;
		if (tf==undefined)tf='';
		
		
		if(activeZoom==undefined)activeZoom=0;
		if(ic==undefined){//inicializado somente a primeira vez
			ic=0;
			if ((area=='left2' && fator==1) || (area=='right2' && fator==1) ){//reajusta as miniaturas não exibidas
				var tmp=resizeImg(imgs[ind].firstChild,parseInt(imgZoomW2));
				//alert(tmp)
				imgs[ind].firstChild.style.opacity = 0;
				imgs[ind].firstChild.style.filter = "alpha(opacity=" + 0 + ")";
			}
		}else{
			ic+=iPerc;//% de aceleracao do objeto
		}
		if(nLoop==undefined){//inicializado somente a primeira vez
			//conta quantas vezes será feito o loop
			nLoop=0;
			var x_posI=posI;
			var x_ic=0;
			while(true){
				nLoop++;
				if(x_posI>posF){//right
					x_posI -= (desloc * (1+x_ic)); 
					if(x_posI<=posF)break;
				}else if(x_posI<posF){//left
					x_posI += (desloc * (1+x_ic));
					if(x_posI>=posF)break;
				}else{
					break;
				}
				x_ic+=iPerc;
			}
			//alert(nLoop)
		}
		if(area=='left2' && fator==1){		n=nLoop/(imgZoomW1-imgZoomW2); 	a=(imgZoomW1-imgZoomW2)/nLoop;		desloc=a;	}
		if(area=='left2' && fator==-1){		n=nLoop/(imgZoomW2);		 	a=(imgZoomW2)/nLoop;				desloc=a;	}
		if(area=='right2' && fator==1){		n=nLoop/(imgZoomW2);			a=(imgZoomW2)/nLoop;				desloc=a;	}
		if(area=='right2' && fator==-1){	n=nLoop/(imgZoomW1-imgZoomW2);	a=(imgZoomW1-imgZoomW2)/nLoop;		desloc=a;	}
		if(area=='left' && fator==1){		n=nLoop/(imgMini-imgZoomW1);	a=(imgMini-imgZoomW1)/nLoop;		desloc=a;	}
		if(area=='right' && fator==1){		n=nLoop/(imgZoomW1-imgZoomW2); 	a=(imgZoomW1-imgZoomW2)/nLoop;		desloc=a;	}
		if(area=='left' && fator==-1){		n=nLoop/(imgZoomW1-imgZoomW2); 	a=(imgZoomW1-imgZoomW2)/nLoop;		desloc=a;	}
		if(area=='right' && fator==-1){		n=nLoop/(imgMini-imgZoomW1); 	a=(imgMini-imgZoomW1)/nLoop;		desloc=a;	}
		if(area=='center'){					n=nLoop/(imgMini-imgZoomW1); 	a=(imgMini-imgZoomW1)/nLoop;		desloc=a;	}
		
		//posicionamentos dos elementes
		if(posI>posF){//right
			posI -= (desloc * (1+ic)); 
			if(posI<=posF)posI=posF;
			controlMove='lock';//trava o controle de movimento
		}else if(posI<posF){//left
			posI += (desloc * (1+ic))  ;
			if(posI>=posF)posI=posF;
			controlMove='lock';//
		}else{//sao iguais os valores//interrompe o deslocamento
			tf+='1';
			controlMove='';//destrava o controle de movimento
		}
		
		if(true){//tf
			w = imgs[ind].firstChild.style.width.replace('px','');if(w=='' || w==undefined){w=imgW[ind];}else{w=parseInt(w);}
			h = imgs[ind].firstChild.style.height.replace('px','');if(h=='' || h==undefined){h=imgH[ind];}else{h=parseInt(h);}
			w=w*(1 + (n*fator) ); h=h*(1 + (n*fator) );		
			//if(area=='left2' && fator==1)alert(w+'       '+h +'         '+(7.35==h))
			
			if(area=='left2' && fator==1){		if(opacity==undefined)opacity=0; if(opacity<=100)opacity+=a;		}
			if(area=='left' && fator==-1){		if(opacity==undefined)opacity=100; if(opacity>=0)opacity-=a;		}
			if(area=='right' && fator==-1){		if(opacity==undefined)opacity=100; if(opacity>=0)opacity-=a;		}
			if(area=='right2' && fator==1){		if(opacity==undefined)opacity=0; if(opacity<=100)opacity+=a;		}

			//imagem maior
			if(imgMini==limite){limiteTmp = imgW[ind]>imgH[ind] ? imgW[ind] : imgH[ind];}else{limiteTmp = limite;}
			liImg = (w>h?w:h); //if(fator==-1){liImg = (w>h?w:h);}else{liImg = (w<h?w:h);}
			
			//se true => atingiu o limite
			tf2=false;
			tf2=(fator==-1 && liImg<limiteTmp) ||  (fator==1 && liImg>limiteTmp);
			if(tf2){
				if(w>=h){
					h = Math.round((h/w)*limiteTmp); w = limiteTmp;
				}else{
					w = Math.round((w/h)*limiteTmp); h = limiteTmp;
				}
				tf+='2';
			}
			
			
			if(true){
				w=Math.round(w);h=Math.round(h);
				imgs[ind].firstChild.style.width= w+'px';
				imgs[ind].firstChild.style.height= h+'px';
				imgs[ind].firstChild.style.opacity = (opacity / 100);
				imgs[ind].firstChild.style.filter = "alpha(opacity=" + opacity + ")";
			}
			imgs[ind].style.left=Math.round(posI)+'px';
			imgs[ind].style.top=(Math.round(imgZoomH/2))+'px';
			imgs[ind].style.marginTop='-'+(  Math.round(h/2)  )+'px';
			imgs[ind].style.visibility='visible';

			if(tf.indexOf('1')==-1 || tf.indexOf('2')==-1){
				setTimeout(function(){	moveObj(area,ind,posI,posF,limite,fator,ic,activeZoom,opacity,nLoop,tf); },30);
			}
		}
	}
	
	if(setaLeft!=undefined){
		setaLeft.onmouseover=function(){
			intervalo = setInterval(function(){
				if(controlMove=='')controlMove='left';
			},150);
		}
		setaLeft.onmouseout=function(){
			controlMove='';
			clearInterval(intervalo);
		}
	}
	if(setaRight!=undefined){
		setaRight.onmouseover=function(){
			intervalo = setInterval(function(){
				if(controlMove=='')controlMove='right';
			},150);
		}
		setaRight.onmouseout=function(){
			controlMove='';
			clearInterval(intervalo);
		}
	}
	if(setaPlay!=undefined){
		setaPlay.onclick=function(){
			if(setaPlayStatus=='off'){
				setaPlayStatus='on';
				intervalo = setInterval(function(){
					if(controlMove=='')controlMove='left';
				},150);
			}
		}
	}
	if(setaStop!=undefined){
		setaStop.onclick=function(){
			setaPlayStatus='off';
			controlMove='';
			clearInterval(intervalo);
		}
	}
	
	var timeControlMove=function(){
		setTimeout(function(){
				if(controlMove=='left'){
					//indice--;
					positionObjs('left');
				}else if(controlMove=='right'){
					//indice++;
					positionObjs('right');
				}
				
				timeControlMove();
		},350);
	}
	
	var openBox=function(ind){
	}
		
	//adiciona as div left e right para auto scroll
	var objAutoLeft = document.createElement('div');
	objAutoLeft.setAttribute('id','autoLeft');
	objBox.appendChild(objAutoLeft);
	var objAutoRight = document.createElement('div');
	objAutoRight.setAttribute('id','autoRight');
	objBox.appendChild(objAutoRight);
	//posiciona as setas left e right
	x = imgZoomW1+Math.round(imgZoomW2/2);
	objAutoLeft.style.top= '0px';
	objAutoLeft.style.left='0px';
	objAutoLeft.style.height=imgMini+'px';
	objAutoLeft.style.width=x+'px';
	objAutoLeft.style.border='1px solid green';
	
	objAutoRight.style.top='0px';
	objAutoRight.style.left=(palcoW-x)+'px';
	objAutoRight.style.height=imgMini+'px';
	objAutoRight.style.width=x+'px';
	objAutoRight.style.border='1px solid green';
	
	objAutoLeft.onmouseover=function(){
		intervalo = setInterval(function(){
			if(controlMove=='')controlMove='right';
		},150);
	}
	objAutoLeft.onmouseout=function(){
		controlMove='';
		clearInterval(intervalo);
	}
	objAutoRight.onmouseover=function(){
		intervalo = setInterval(function(){
			if(controlMove=='')controlMove='left';
		},150);
	}
	objAutoRight.onmouseout=function(){
		controlMove='';
		clearInterval(intervalo);
	}


	/* **************************** inicializa os comandos da função ************************************ */
	var init=function(){
			objBox.className=objBoxClass;
			objBox.style.width=palcoW+'px';
			objBox.style.height=imgZoomH+'px';
			//alert('-'+Math.round(palcoPrincipal/2)+'px');
			if(palcoPrincipal>0)objBox.style.marginLeft='-'+Math.round(palcoW/2)+'px';
			objBoxImg.style.width=palcoImgW+'px';//obj #boxList
			objBoxImg.style.height=imgZoomH+'px';//obj #boxList
			objBoxImg.style.marginLeft=Math.round((palcoW-palcoImgW)/2)+'px';
			
			//leitura das imagens // preload
			if (arrayImg==undefined){//faz a busca dentro da div
					x=0;
					var ixx = new Array();
					ixLoad=0;
					arrayImg = new Array();
					for(i=0;i<objBoxImg.childNodes.length;i++){
						if(objBoxImg.childNodes[i].href){
							//ixx[i] = new Image();
							//ixx[i].src = objBoxImg.childNodes[i].firstChild.src;
							//ixx[i].onload=function(){
								ixLoad++;
							//}
							arrayImg[x] =objBoxImg.childNodes[i].firstChild.src+"|";
							arrayImg[x]+=objBoxImg.childNodes[i].href+"|";
							arrayImg[x]+=objBoxImg.childNodes[i].title+"|";
							arrayImg[x]+=objBoxImg.childNodes[i].firstChild.width+"|";
							arrayImg[x]+=objBoxImg.childNodes[i].firstChild.height;
							x++;
						}
					}
			}else{//utiliza a matriz para as imagens
					var ixx = new Array();
					var html='';
					ixLoad=0;					
					//a forma de escrita abaixo é para funcionar o jquery-lightbox
					for(i=0;i<arrayImg.length;i++){
						//alert(arrayImg[i])
						ixx[i] = new Image();//arrayImg[i].split('|')[3] , arrayImg[i].split('|')[4]
						ixx[i].src = arrayImg[i].split('|')[0];
						ixx[i].onload=function(){
							ixLoad++;
						}
						html+="<a href='"+arrayImg[i].split('|')[1]+"' rel='"+divBox+"_galeria_fotos' class='lightbox'>"
						html+="<img src='"+arrayImg[i].split('|')[0]+"' title='"+arrayImg[i].split('|')[2]+"' width='"+arrayImg[i].split('|')[3]+"' width='"+arrayImg[i].split('|')[4]+"' />"
						html+="</a>";
					}
					objBoxImg.innerHTML=html;
					
			}

			//aguarda o loading completo das imagens através da var 'ix1' para inicializar as demais funções
			var ixc=setInterval(function(){//onLoading
				//document.getElementById('idMsg').innerHTML+=ixLoad+' | ';
				if(ixLoad>=arrayImg.length ){
						x=0
						for(i=0;i<arrayImg.length;i++){
							if(objBoxImg.childNodes[i].href){
								imgs[x] = objBoxImg.childNodes[i];
								imgLink[x] = imgs[x].href;
								if(!isLightbox)imgs[x].href='javascript:void[0];'//desabilita o link das imagens
								n = resizeImg(imgs[x].firstChild,imgMini);//reajusta a altura dos objetos
								//alert(  imgs[x].firstChild.width+' / '+ imgs[x].firstChild.height+'          '+ n)
								imgW[x] = parseInt(n.split('|')[0]);
								imgH[x] = parseInt(n.split('|')[1]);
								
								imgs[x].style.position='absolute';
								imgs[x].style.visibility='hidden';
								x++;
							}
						}
					
						clearInterval(ixc);
						indice=indiceInit;
						positionObjs('load');
						timeControlMove();
						if(isLightbox)$(".lightbox").lightbox();
						boxLoading('hide');
				}
			},50);
			

	}
	
	var boxLoading=function(sh){
		if(sh=='hide'){
			var objLoad = document.getElementById(divBox+'_loading')
			objLoad.style.visibility='hidden';
		}else{
			var html="<table border=0 width=100% height=100%><tr><td align=center valign=middle>";
			html+="<img src='http://colheitademadeira.tempsite.ws/imageSite/carregando-imagens.gif'>";
			html+="</td></tr></table>";
			
			var objLoad = document.createElement('div');
			objLoad.setAttribute('id',divBox+'_loading');
			objLoad.className='load';
			objLoad.style.width=(palcoW+20)+'px';
			objLoad.style.height=(imgZoomH+20)+'px';
			objLoad.innerHTML=html;
			objBox.appendChild(objLoad);
		}
	}

	var returnKey=function(e){
		var k = (window.event)?event.keyCode:e.which;  
		return k;
	}

	this.loading=function(){
		boxLoading();
	}
	this.left=function(){
		if(controlMove==''){ controlMove='left';setTimeout("controlMove=''",351) }
	}
	this.right=function(){
		if(controlMove==''){ controlMove='right';setTimeout("controlMove=''",351) }
	}
	this.load=function(){
		//boxLoading();
		init();
	}
	this.start=function(){
		//boxLoading('hide');
	}
	document.body.onkeyup=function(){
		if(returnKey(event)==37){//left
			if(controlMove==''){ controlMove='left';setTimeout("controlMove=''",351) }
		} 
		if(returnKey(event)==39){//right
			if(controlMove==''){ controlMove='right';setTimeout("controlMove=''",351) }
		}
	}

}