// ©Marco Coan - basic function for animation - start on Augost2010

// --------------------------------------------------------------------------------
// sezione AJAX
// --------------------------------------------------------------------------------

function ajax(filePHP,data) {
// ajax - filePHP = file php da richiamare (incluso path) - data = dati da inviare a seconda del php richiamato (variabile=valore)
  
    this.filePHP = filePHP;
    this.data = data;
  
    if (window.XMLHttpRequest) { 
      this.http_request = new XMLHttpRequest();
      if (this.http_request.overrideMimeType) {
        this.http_request.overrideMimeType('text/xml');
      }
    } else if (window.ActiveXObject) { // IE
      try {
        this.http_request = new ActiveXObject("Msxml2.XMLHTTP");
      } catch (e) {
        try {
          this.http_request = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e) {}
      }
    }
    // LANCIA RICHIESTA...
    this.http_request.open('POST', this.filePHP, true);
    this.http_request.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    this.http_request.send(this.data); 
}


function mouseScreenPosition(e) {
      var x, y;
      if (!e) e = window.event;
      if (e.pageX || e.pageY){
         x = e.pageX;
         y = e.pageY;
      }
      else if (e.clientX || e.clientY){
         x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
         y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
      }
      return Array(x,y);
}


function mouseDivPosition(e,targetDiv) {
		// ATTENZIONE! targetDiv è il nome semplice dell'elemento, NON un getElementById ad un elemento
		var coords = { x: 0, y: 0};
		var CalculatedTotalOffsetLeft = 0;
		var CalculatedTotalOffsetTop = 0 ;
		var Element = document.getElementById(targetDiv);
        if(!e) { // then we have a non-DOM (probably IE)  browser
       			 e = window.event;
					 if(Element.offsetParent) {
						  while(1) {
							 CalculatedTotalOffsetLeft += Element.offsetLeft;
							 CalculatedTotalOffsetTop += Element.offsetTop;
							 if(!Element.offsetParent) { break; }
							 Element = Element.offsetParent;
						  }
					 }
					 coords.x = (e.clientX+ document.body.scrollLeft + document.documentElement.scrollLeft)-CalculatedTotalOffsetLeft;
                coords.y = (e.clientY+ document.body.scrollTop + document.documentElement.scrollTop)-CalculatedTotalOffsetTop;
        } else {     // we assume  DOM modeled  javascript
                while (Element.offsetParent) {
							CalculatedTotalOffsetLeft += Element.offsetLeft ;     
							CalculatedTotalOffsetTop += Element.offsetTop ;
							Element = Element.offsetParent ;
                }
                coords.x = e.pageX - CalculatedTotalOffsetLeft ;
                coords.y = e.pageY - CalculatedTotalOffsetTop ;
        }
        return Array(coords.x,coords.y);
}



function mouseItem(e) {
	if(!e) { // then we have a non-DOM (probably IE)  browser
		e = window.event;
		return e.srcElement;
	} else {
		return e.target;
	}
}



function menuUp(lanchDiv,menuDiv,offsetPos) {
	this.lanchDiv = document.getElementById(lanchDiv);
	this.menuDiv = document.getElementById(menuDiv);
	this.offsetPos = offsetPos;
	this.delay = 0;
	var me = this;
	//this.menuDiv.style.top = this.lanchDiv.offsetHeight+"px";
	
	
	this.lanchDiv.onmouseover = function() {
	me.delay = 0;
      me.enter();  
   }
	this.lanchDiv.onmouseout = function() {
		me.delay = 0;
      	me.exit();  
   }

   this.enter = function(){
   	window.clearTimeout(this.onExitFrame);
   	if(this.menuDiv.offsetTop > this.lanchDiv.offsetHeight - this.offsetPos){
			if(this.delay < 2){
					this.delay++;
				} else {
   			this.menuDiv.style.top = (this.menuDiv.offsetTop-1-(this.menuDiv.offsetTop-(this.lanchDiv.offsetHeight-this.offsetPos))/2) + "px";
   		}
   		this.onEnterFrame = window.setTimeout(function(){me.enter();},20);
   	} else {
   		window.clearTimeout(this.onEnterFrame);
   	}
   }
   
    this.exit = function(){
    
    	window.clearTimeout(this.onEnterFrame);
   	if(this.menuDiv.offsetTop < this.lanchDiv.offsetHeight){
   		if(this.delay < 2){
   			this.delay++;
   		} else {
   			this.menuDiv.style.top = (this.menuDiv.offsetTop+1+(this.lanchDiv.offsetHeight-this.menuDiv.offsetTop)/2) + "px";
   		}
   		this.onExitFrame = window.setTimeout(function(){me.exit();},20);
   	} else {
   		window.clearTimeout(this.onExitFrame);
   	}
   }
   
	
}













function gallery(targetDiv, targetDivWidth, targetDivHeight, targetMaskThumb, thumbWidth, thumbHeight, thumbMargin, textPadding, targetFolder, slideTime){
	
	// Si possono associare file txt o html con lo stesso nome della fotografia
	// Si puÚ associare una regola stile nel template per i files html inclusi come descrizione
	// utilizzando la classe .anteprimaGallery come master

	var me = this;
	this.targetDiv = targetDiv; // id del div grande
	this.targetDivWidth = targetDivWidth; // width div grande
	this.targetDivHeight = targetDivHeight; // height div grande
	this.targetMaskThumb = targetMaskThumb; // id della maschera principale in cui scorrono le thumb
	this.thumbWidth = thumbWidth; // larghezza delle thumb
	this.thumbHeight = thumbHeight; // altezza delle thumb (e quindi della maschera principale in cui scorrono le thumb)
	this.thumbMargin = thumbMargin; // margind destro thumb
	this.textPadding = textPadding;
	this.nameDiv = targetDiv; // nome univoco della gallery (AUTOMATICO)
	this.offsetScroll = 1;
	this.velocityScroll = 100;
	this.counter = 0;
	this.text = "";
	this.targetFolder = targetFolder;
	this.slideTime = slideTime;
	this.slideArray = new Array();
	this.slideText = new Array();
	this.enterFrame = undefined;
	this.enterFrameOutAutoText = undefined;

	document.write("<div class='anteprimaGallery' id='gallery_"+this.targetDiv+"'></div>");
	this.masterDiv = document.getElementById("gallery_"+this.targetDiv);
	
	// creazione div grande
	var createGalleryDiv = document.createElement("div");
	createGalleryDiv.setAttribute("id", this.targetDiv);
	createGalleryDiv.style.width = this.targetDivWidth+"px";
	createGalleryDiv.style.height = this.targetDivHeight+"px";
	createGalleryDiv.style.overflow = "hidden";
	createGalleryDiv.style.position = "relative";
	createGalleryDiv.style.margin = "0";
	// ---------------------------------------------------------------------------------------------------------
	// INTERVENIRE QUI PER IL MARGIN BOTTOM TRA LA FOTO GRANDE E LA PICCOLA EVENTUALMENTE INSERENDO VALORE FISSO
	// ---------------------------------------------------------------------------------------------------------
	createGalleryDiv.style.marginBottom = this.thumbMargin+"px";
	// ---------------------------------------------------------------------------------------------------------
	this.masterDiv.appendChild(createGalleryDiv);
	this.galleryDiv = document.getElementById(this.targetDiv);
	// creazione div testo
	var createTextDiv = document.createElement("div");
	createTextDiv.setAttribute("id", "text_"+this.targetDiv);
	createTextDiv.style.background = "url(code/galleryTextBackground.png)";
	createTextDiv.style.color = "#fff";
	createTextDiv.style.zIndex = this.counter+10;
	createTextDiv.style.width = this.targetDivWidth-this.textPadding*2+"px";
	createTextDiv.style.position = "absolute";
	createTextDiv.style.top = this.targetDivHeight+"px";
	createTextDiv.style.left = this.textPadding+"px";
	this.galleryDiv.appendChild(createTextDiv);
	this.textDiv = document.getElementById("text_"+this.targetDiv);
	
	var scanDir = new ajax("code/scanDir.php","dir=../"+this.targetFolder);

	scanDir.http_request.onreadystatechange = function(){
	  if (scanDir.http_request.readyState == 4) {
		if (scanDir.http_request.status == 200) {
			var rispostaPhp = (scanDir.http_request.responseText).split(";");
			for(scan = 0; scan <rispostaPhp.length; scan++){
				if(rispostaPhp[scan].toLowerCase().indexOf(".txt") != -1 || rispostaPhp[scan].toLowerCase().indexOf(".htm") != -1 || rispostaPhp[scan].toLowerCase().indexOf(".html") != -1){
					me.slideText.push(rispostaPhp[scan]);
				} else {
					if(rispostaPhp[scan].toLowerCase().indexOf(".jpg") != -1 || rispostaPhp[scan].toLowerCase().indexOf(".gif") != -1 || rispostaPhp[scan].toLowerCase().indexOf(".gif") != -1){
						me.slideArray.push(rispostaPhp[scan]);	
					}
				}
			}
			if(me.targetMaskThumb){ me.thumball(); }
			me.changeSlide();
		}
	  }
	}
  
  // FUNZIONI DI SCROLLING
  this.scrollLeft = function(scrollDiv,maskDiv) {
		if(scrollDiv.offsetLeft>-scrollDiv.offsetWidth+maskDiv.offsetWidth){
			scrollDiv.style.left = scrollDiv.offsetLeft-this.offsetScroll/10 +"px";
			if(scrollDiv.offsetLeft<-scrollDiv.offsetWidth+maskDiv.offsetWidth){
				scrollDiv.style.left = -scrollDiv.offsetWidth+maskDiv.offsetWidth +"px";
			}
			this.enterFrameScrolling = window.setTimeout(function(){me.scrollLeft(scrollDiv,maskDiv);},me.velocityScroll);
		};
	}
	this.scrollRight = function(scrollDiv,maskDiv) {
		if(scrollDiv.offsetLeft+this.offsetScroll/10 <0){
			scrollDiv.style.left = scrollDiv.offsetLeft+this.offsetScroll/10 +"px";
		} else {
			scrollDiv.style.left = "0";
		}
		this.enterFrameScrolling = window.setTimeout(function(){me.scrollRight(scrollDiv,maskDiv);},me.velocityScroll);
	}
	this.scrollStop = function(){
		if(this.enterFrameScrolling){
				window.clearTimeout(this.enterFrameScrolling);
				this.enterFrameScrolling = undefined;
		}
	}
	//
	
  	this.thumball = function(){
		// creazione maschera thumb
		var createThumbMaskDiv = document.createElement("div");
		createThumbMaskDiv.setAttribute("id", this.targetMaskThumb);
		createThumbMaskDiv.style.width = this.targetDivWidth+"px";
		createThumbMaskDiv.style.height = this.thumbHeight+"px";
		createThumbMaskDiv.style.overflow = "hidden";
		createThumbMaskDiv.style.position = "relative";
		// ---------------------------------------------------------------------------------------------------------
		// INTERVENIRE QUI PER IL MARGIN BOTTOM TRA IL DIV CONTENITORE MINIATURE ED IL RESTO DELLA PAGINA HTML
		// ---------------------------------------------------------------------------------------------------------
		createThumbMaskDiv.style.marginBottom = this.thumbMargin+"px";
		// ---------------------------------------------------------------------------------------------------------
		this.masterDiv.appendChild(createThumbMaskDiv);
		this.maskTuhmbContainer = document.getElementById(this.targetMaskThumb);
		// creazione contenitore miniature
		var createThumbContainer = document.createElement("div");
		createThumbContainer.setAttribute("id", this.targetMaskThumb+"_thumbs");
		createThumbContainer.style.position = "absolute";
		createThumbContainer.style.left = "0";	
		createThumbContainer.style.top = "0";	
		createThumbContainer.style.height = this.thumbHeight+"px";
		this.maskTuhmbContainer.appendChild(createThumbContainer);
		this.thumbContainer = document.getElementById(this.targetMaskThumb+"_thumbs");
		// creazione miniature
		this.thumbContainer.style.width = "0";
		for (scan=0;scan<=this.slideArray.length-1;scan++){
			var miniDiv = document.createElement("div");
			miniDiv.setAttribute("id", this.nameDiv+"_thumb_"+scan);
			miniDiv.style.width = this.thumbWidth+"px";
			miniDiv.style.overflow = "hidden";
			miniDiv.style.position = "relative";
			// normal
			miniDiv.style.float = "left";
			// ie
			miniDiv.style.styleFloat = "left";
			//firefox
			miniDiv.style.cssFloat = "left";
			miniDiv.style.margin = "0";
			if(scan<this.slideArray.length-1){
				miniDiv.style.marginRight = this.thumbMargin+"px";
			}
			var tempHtml = "<img src='"+this.targetFolder+"/"+this.slideArray[scan]+"' width='"+this.thumbWidth+"' alt='"+this.slideArray[scan]+"' title='"+this.slideArray[scan]+"'  />";
			miniDiv.innerHTML = tempHtml;
			miniDiv.targetLink = this.slideArray[scan];
			miniDiv.onclick = function() {
				me.changeSlide(this.targetLink);
			}
			miniDiv.onmouseover = function() {
			}
			miniDiv.onmouseout = function() {
			}
			this.thumbContainer.appendChild(miniDiv);
			if(scan<this.slideArray.length-1){
				this.thumbContainer.style.width = this.thumbContainer.offsetWidth + this.thumbWidth + this.thumbMargin +"px";
			} else {
				this.thumbContainer.style.width = this.thumbContainer.offsetWidth + this.thumbWidth +"px";
			}
		}	
		
		// controllo mouse
		this.maskTuhmbContainer.onmousemove = function(e){
			var mouseLoc = mouseDivPosition(e,me.targetMaskThumb);
			var offsetRilevamento = me.maskTuhmbContainer.offsetWidth/3;
			//window.status = mouseLoc+" - "+me.maskTuhmbContainer.offsetLeft;
			if(mouseLoc[0] < offsetRilevamento){
				me.offsetScroll = offsetRilevamento - mouseLoc[0];
				me.velocityScroll = 1+(mouseLoc[0]/5);
				if(me.enterFrameScrolling == undefined){
					me.scrollRight(me.thumbContainer,me.maskTuhmbContainer);
				}
			} else {
				if(mouseLoc[0] > me.maskTuhmbContainer.offsetWidth-offsetRilevamento){
					me.offsetScroll = offsetRilevamento - (me.maskTuhmbContainer.offsetWidth - mouseLoc[0]);
					me.velocityScroll = 1+( (me.maskTuhmbContainer.offsetWidth - mouseLoc[0])/5);
					if(me.enterFrameScrolling == undefined){
						me.scrollLeft(me.thumbContainer,me.maskTuhmbContainer);
					}
				} else {
					me.scrollStop();
				}
			}
		}
		this.maskTuhmbContainer.onmouseout = function() {
			me.scrollStop();
		}
	}
	
  
  this.changeSlide = function(image){
		// se image = undefined Ë slide puro, se image = immagine.jpg cerca immagine e carica (per thumball)
		if(image){
			this.image = image;
		}
		tempDiv = document.createElement("div");
		tempName = "slideshow_"+this.counter;
		oldName = "slideshow_"+(this.counter-1);
		tempDiv.setAttribute("id",tempName);
		this.counter++;
		tempDiv.style.position = "absolute";
		tempDiv.style.zIndex = this.counter;
		this.textDiv.style.zIndex = this.counter+10;
		tempDiv.style.opacity = "0";
		tempDiv.style.filter = "Alpha(opacity=0)";
		
		if(this.image){
			for(scan = 0; scan<this.slideArray.length-1; scan++){
				if(this.slideArray[0] != this.image){
					this.slideArray.push(this.slideArray.shift());
				} else {
					break;
				}
			}
		}
		tempHtml = "<img src='"+this.targetFolder+"/"+this.slideArray[0]+"' />";
		tempDiv.innerHTML = tempHtml;
		this.text = this.slideArray[0].split(".")[0];
		this.slideArray.push(this.slideArray.shift());
		this.galleryDiv.appendChild(tempDiv);
		this.newDiv = document.getElementById(tempName);
		this.oldDiv = document.getElementById(oldName);
		if(this.enterFrame){
			window.clearTimeout(this.enterFrame);
		}
		this.image = undefined;
		this.fadeIn();
		this.changeText();
	}
	
	
	
	this.fadeInText = function(){
		if(this.textDiv.offsetTop > this.targetDivHeight-this.textDiv.offsetHeight){
			if(this.textDiv.offsetTop-2 > this.targetDivHeight-this.textDiv.offsetHeight){
				this.textDiv.style.top = this.textDiv.offsetTop-2+"px";
			} else {
				this.textDiv.style.top = this.targetDivHeight-this.textDiv.offsetHeight+"px";
			}
			this.enterFrameChangeText = window.setTimeout(function(){me.fadeInText();},10);
		} else {
			window.clearTimeout(this.enterFrameOutAutoTextTimer);
			this.enterFrameOutAutoTextTimer = window.setTimeout(function(){me.fadeOutAutoText();},me.slideTime/2);	
			this.enterFrameOutAutoText = "on";
		}
	}
	this.fadeOutText = function(){
		if(this.textDiv.offsetTop < this.targetDivHeight){
			if(this.textDiv.offsetTop+2 < this.targetDivHeight){
				this.textDiv.style.top = this.textDiv.offsetTop+2+"px";
			} else {
				this.textDiv.style.top = this.targetDivHeight+"px";
			}
			this.enterFrameChangeText = window.setTimeout(function(){me.fadeOutText();},10);
		} else {
			this.changeText();
		}
	}
	
	this.fadeOutAutoText = function(){
		if(this.textDiv.offsetTop < this.targetDivHeight && this.enterFrameOutAutoText != undefined){
			this.textDiv.style.top = this.textDiv.offsetTop+1+"px";
			window.setTimeout(function(){me.fadeOutAutoText();},10);
		}
	}
	
	this.changeText = function(){
		this.enterFrameOutAutoText = undefined;
		window.clearTimeout(this.enterFrameChangeText);
		window.clearTimeout(this.enterFrameOutAutoTextTimer);
		this.movementText = undefined;
		if(this.textDiv.offsetTop < this.targetDivHeight){
			this.fadeOutText();
			return;
		}
		// esegue test se trova un file txt o html associato
		var textTarget = undefined;
		for(scanText=0;scanText<this.slideText.length;scanText++){
			if	(this.slideText[scanText].indexOf(this.text) != -1) {
				textTarget = this.targetFolder+"/"+this.slideText[scanText];
				break;
			}
		}
		// se trova il file lo carica ed esegue il fadeInText - se non lo trova esegue subito con nome file come testo
		if(textTarget){
			var scanText = new ajax("code/readTextFile.php","page=../"+textTarget);
			scanText.http_request.onreadystatechange = function(){
			  if (scanText.http_request.readyState == 4) {
				if (scanText.http_request.status == 200) {
					me.text = scanText.http_request.responseText;
					me.textDiv.innerHTML = "<div style='padding:20px;'>"+me.text+"</div>";
					me.fadeInText();
				}
			  }
			}
		} else {
			this.textDiv.innerHTML = "<div style='padding:20px;'>"+this.text+"</div>";
			this.fadeInText();
		}
	}
	
	this.fadeIn = function(){
		alpha = Number(this.newDiv.style.opacity);
		if(alpha<1){
			// fade in
			this.newDiv.style.opacity = alpha+0.05;
			this.newDiv.style.filter = "Alpha(opacity="+((alpha+0.05)*100)+")";
			// fade out
			if(this.oldDiv){
				this.oldDiv.style.opacity = 1-(alpha+0.05);
				this.oldDiv.style.filter = "Alpha(opacity="+(100-(alpha+0.05)*100)+")";
			}
			this.enterFrame = window.setTimeout(function(){me.fadeIn();},50);
		} else {
			// cancella il vecchio oldDiv
			if(this.oldDiv){
				this.galleryDiv.removeChild(this.oldDiv);
			}
			window.clearTimeout(this.enterFrame);
			this.enterFrame = window.setTimeout(function(){me.changeSlide();},this.slideTime);
			this.oldDiv.style.opacity = 100;
			this.oldDiv.style.filter = "Alpha(opacity=100)";

		}
	}
}



