// ©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); 
}

// --------------------------------------------------------------------------------
// sezione VIDEO
// --------------------------------------------------------------------------------

function playVideoInterfaceRnd(divContainer,directory,width,height,fixedDelay){
// il video con suffisso FIRST.ext verrà girato più probabilmente (es: "video MAIN.mp4")
// il video con suffisso LAST.ext verrò girato meno probabilmente (es: "video LAST.mp4")
// fixedDelay è il valore FISSO di pausa tra un video e l'altro e anche il valore di RANDOM calcolato.
// l'immagine poster deve essere una .jpg o .png - si può aggiungere anche una .gif per iphone
// inserire i video in una cartellina, allegare anche un "nomeQualunque.jpg" (jpg/png/gif) come posterImg
// nota: questa funzione NON prevede il "loop" ed è sempre "autoplay" per ragioni intrinseche alla logica
  
  this.videoArray = new Array();
  this.divContainer = divContainer;
  this.directory = directory;
  this.width = width;
  this.height = height;
  this.fixedDelay = fixedDelay;
  this.posterImg = undefined;
  this.videoMain = undefined;
  this.videoLast = undefined;
  this.videoclip = undefined;
  this.videoMedia = this.divContainer+"_media";
  this.template = undefined;
  var me = this;
  
  var scanDir = new ajax("code/scanDir.php","dir=../"+this.directory);

  scanDir.http_request.onreadystatechange = function(){
    if (scanDir.http_request.readyState == 4) {
      if (scanDir.http_request.status == 200) {
        me.inizialize();
      }
    }
  }
  
  this.inizialize = function(){
    // costruzione lista video
    files = (scanDir.http_request.responseText).split(";");
    checkName = new Array();
    for(scan=0;scan<files.length;scan++){
       videoName = files[scan].split(".")[0];
       // controlla se il file è un immagine e salta da lista video, e se è immagine poster (jpg o png) aggiunge a variabile this.posterImg
       if(files[scan].toLowerCase().indexOf(".jpg") != -1 || files[scan].toLowerCase().indexOf(".png") != -1 || files[scan].toLowerCase().indexOf(".gif") != -1){
         if(files[scan].toLowerCase().indexOf(".jpg") != -1 || files[scan].toLowerCase().indexOf(".png") != -1){
            this.posterImg = files[scan];
         }
       } else {
        // controlla se è mainRnd
        if(files[scan].toLowerCase().indexOf("main.") != -1 && this.videoMain == undefined){
          this.videoMain = videoName;
        } else {
          // controlla se è lastRnd
          if(files[scan].toLowerCase().indexOf("last.") != -1 && this.videoLast == undefined){
            this.videoLast = videoName;
            this.videoLastCounter = 0;
          } else {
            // inserisci video
            if(checkName[checkName.length-1] != videoName){
              this.videoArray.push(videoName);
            }
          } 
        }
      }
      checkName.push(videoName);
    }
     
    // flash autonomo per piattaforme non html5
    if( !!document.createElement('video').canPlayType != true){
      // parte object
      this.template = '<object '+
      'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" '+
      'codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" '+
      'width="'+this.width+'" '+
      'height="'+this.height+'"'+
      'hspace="0" '+
      'vspace="0" '+
      'align="top"> '+
      '<param name="FlashVars" value="targetWidth='+this.width+'&targetHeight='+this.height+'&directory=../'+this.directory+'&videoMain='+this.videoMain+'&videoLast='+this.videoLast+'&fixedDelay='+this.fixedDelay+'&posterImg='+this.posterImg+'&videoArray='+this.videoArray.join(';')+'" />'+
      '<param name="allowScriptAccess" value="sameDomain" /> '+
      '<param name="loop" value="false" /> '+
      '<param name="scale" value="noscale" />'+
      '<param name="quality" value="high" /> '+
      '<param name="salign" value="lt" /> '+
      '<param name="wmode" value="transparent" /> '+
      '<param name="bgcolor" value="#ffffff" /> '+
      '<param name="movie" value="code/playVideoInterfaceRnd.swf" /> '+
      // parte embed
      '<embed type="application/x-shockwave-flash" pluginspage="https://www.macromedia.com/go/getflashplayer" '+
      'width="'+this.width+'" '+
      'height="'+this.height+'" '+
      'hspace="0" '+
      'vspace="0" '+
      'align="top" '+
      'FlashVars = "targetWidth='+this.width+'&targetHeight='+this.height+'&directory=../'+this.directory+'&videoMain='+this.videoMain+'&videoLast='+this.videoLast+'&fixedDelay='+this.fixedDelay+'&posterImg='+this.posterImg+'&videoArray='+this.videoArray.join(';')+'" '+
      'loop="false" '+
      'scale="noscale" '+
      'quality="high" '+
      'salign="lt" '+
      'wmode="transparent" '+
      'bgcolor="#ffffff" '+
      'allowScriptAccess="sameDomain" '+
      'src="code/playVideoInterfaceRnd.swf"/></object>';
      document.getElementById(this.divContainer).innerHTML = this.template;
      return;                
    }
    
    // salta con piattaforme incompatibili con video interfaccia
    if(navigator.platform == "iPhone"){
        this.template = '<img src="'+this.directory+'/'+this.posterImg.split('.')[0]+'.gif" width="'+this.width+'" height="'+this.height+'" onerror="src='+this.directory+"/"+this.posterImg+'" />';
        document.getElementById(this.divContainer).innerHTML = this.template;
        return;
    }
    this.playRnd();
  }
  
  this.playRnd = function(){
    // ritarda funzione
    if(this.flagDelay==undefined){
      // scambia con immagine fissa (stesso file del poster)
      this.template = '<img src="'+this.directory+'/'+this.posterImg+'" width="'+this.width+'" height="'+this.height+'" />';
      document.getElementById(this.divContainer).innerHTML = this.template;
      this.flagDelay = true;
      trigger = parseInt(Math.floor(Math.random()*fixedDelay));
      window.setTimeout(function(){me.playRnd();},this.fixedDelay+trigger);
      return;
    } else {
      this.flagDelay = undefined;
    }
    // lancia video rnd
    totalRnd = this.videoArray.length;
    if(this.videoMain != undefined){
      totalRnd +=10;
    }
    rnd = parseInt(Math.floor(Math.random()*totalRnd));
    if(rnd<this.videoArray.length){
      this.videoclip = this.videoArray[rnd];
      // seconda estrazione per video last (amentare il valor moltiplicato per minor probabilità)
      if(this.videoLast != undefined){
        if(this.videoLastCounter > totalRnd){
           rndLast = parseInt(Math.floor(Math.random()*3));
           if(rndLast==0){
             this.videoLastCounter = 0;
             this.videoclip = this.videoLast;
           }
        } else {
           this.videoLastCounter++;
        }
      }
    } else {
      this.videoclip = this.videoMain;
    }
    
    this.template =''+
    '<video id="'+this.videoMedia+'" width="'+this.width+'" height="'+this.height+'" ';
    if(this.posterImg.toLowerCase().indexOf(".jpg") != -1 || this.posterImg.toLowerCase().indexOf(".png") != -1 ){
   	this.template += 'poster="'+this.posterImg+'" ';
    }
    this.template += ' >';
    '<source src="'+this.directory+'/'+this.videoclip+'.mp4" type="video/mp4;"> '+
    '<source src="'+this.directory+'/'+this.videoclip+'.m4v" type="video/m4v;"> '+
    '<source src="'+this.directory+'/'+this.videoclip+'.ogg" type="video/ogg;"> '+
    '<source src="'+this.directory+'/'+this.videoclip+'.webm" type="video/webm;"> '+
    'Il tuo navigatore non supporta ancora video Html5'+
    '</video>';
    document.getElementById(this.divContainer).innerHTML = this.template;
    document.getElementById(this.videoMedia).play();
    
    // controlla finale video 
    this.enterFrame = window.setInterval(function(){me.checkEnd();},100); 
  }
  
  // funzione di riaccensione immagine o video al termine dello spezzone video random
  this.checkEnd = function(){
      if(document.getElementById(this.videoMedia).ended != false){
         window.clearInterval(this.enterFrame);
         this.playRnd();
      }
  }

  
}  


function playVideoInterface(divContainer,videoclip,width,height,loop){
// videoclip dev'essere comprensivo dell'estensione (verrà tolta in automatico)
// l'immagine poster DEVE AVERE LO STESSO NOME del video e deve essere una .jpg o .png - si può aggiungere anche una .gif per iphone
// nota: questa funzione NON prevede "autoplay" per ragioni intrinseche alla logica
   
  this.divContainer = divContainer;
  this.videoclip = (videoclip.split("."))[0];
  this.posterImg = this.videoclip.split("/")[this.videoclip.split("/").length-1];
  this.width = width;
  this.height = height;
  this.loop = loop;
  this.videoMedia = this.divContainer+"_media";
  this.directory = this.videoclip.split("/"+this.posterImg)[0];
  this.template
  var me = this;
  
  var checkPoster = new ajax("code/findIfJpgOrPng.php","dir=../"+this.directory+"&targetFile="+this.posterImg);

  checkPoster.http_request.onreadystatechange = function(){
    if (checkPoster.http_request.readyState == 4) {
      if (checkPoster.http_request.status == 200) {
         me.inizialize();
      }
    }
  }
  
  this.inizialize = function(){
   // ricevi immagine poster da funzione ajax
   this.posterImg = this.directory+"/"+checkPoster.http_request.responseText;
     
   this.template =''+
   '<video id="'+this.videoMedia+'" width="'+this.width+'" height="'+this.height+'" ';
   if(this.posterImg.toLowerCase().indexOf(".jpg") != -1 || this.posterImg.toLowerCase().indexOf(".png") != -1 ){
   	this.template += 'poster="'+this.posterImg+'" ';
   }
   if(this.loop=="loop"){
      this.template += 'loop ';
   }
   this.template += '>'+
  
   '<source src="'+this.videoclip+'.mp4" type="video/mp4;"> '+
   '<source src="'+this.videoclip+'.m4v" type="video/m4v;"> '+
   '<source src="'+this.videoclip+'.ogg" type="video/ogg;"> '+
   '<source src="'+this.videoclip+'.webm" type="video/webm;"> '+
   'Il tuo navigatore non supporta ancora video Html5'+
   '</video>';

   if(navigator.platform == "iPhone"){
      this.template = '<img src="'+this.posterImg.split('.')[0]+'.gif" width="'+this.width+'" height="'+this.height+'" onerror="src='+this.posterImg+'" />';
   }
 
   if( !!document.createElement('video').canPlayType != true){
      // parte object
      this.template = '<object '+
      'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" '+
      'codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" '+
      'width="'+this.width+'" '+
      'height="'+this.height+'"'+
      'hspace="0" '+
      'vspace="0" '+
      'align="top"> '+
      '<param name="FlashVars" value="targetWidth='+this.width+'&targetHeight='+this.height+'&targetSource=../'+this.videoclip+'.flv&targetLoop='+this.loop+'" />'+
      '<param name="allowScriptAccess" value="sameDomain" /> '+
      '<param name="loop" value="false" /> '+
      '<param name="scale" value="noscale" />'+
      '<param name="quality" value="high" /> '+
      '<param name="salign" value="lt" /> '+
      '<param name="wmode" value="transparent" /> '+
      '<param name="bgcolor" value="#ffffff" /> '+
      '<param name="movie" value="code/playVideoInterface.swf" /> '+
      // parte embed
      '<embed type="application/x-shockwave-flash" pluginspage="https://www.macromedia.com/go/getflashplayer" '+
      'width="'+this.width+'" '+
      'height="'+this.height+'" '+
      'hspace="0" '+
      'vspace="0" '+
      'align="top" '+
      'FlashVars = "targetWidth='+this.width+'&targetHeight='+this.height+'&targetSource=../'+this.videoclip+'.flv&targetLoop='+this.loop+'" '+
      'loop="false" '+
      'scale="noscale" '+
      'quality="high" '+
      'salign="lt" '+
      'wmode="transparent" '+
      'bgcolor="#ffffff" '+
      'allowScriptAccess="sameDomain" '+
      'src="code/playVideoInterface.swf"/></object>';                
   }
  
   document.getElementById(this.divContainer).innerHTML = this.template;
   document.getElementById(this.videoMedia).play();
   
  }
  
  // PER FIREFOX FINCHE' NON HA IL LOOP!!!
  if( navigator.userAgent.toLowerCase().indexOf("mozilla") != -1 && navigator.userAgent.toLowerCase().indexOf("firefox") != -1 && this.loop=="loop"){
    this.enterFrame = window.setInterval(function(){me.checkEnd();},50);
    this.checkEnd = function(){
       if(document.getElementById(this.videoMedia).ended == true){
          document.getElementById(this.videoMedia).play();
       }
    }
  }
  
}  
  
  
function playVideo(divContainer,videoclip,width,height,autoplay,loop,controls){
// videoclip dev'essere comprensivo dell'estensione (verrà tolta in automatico)
// l'immagine poster DEVE AVERE LO STESSO NOME del video e deve essere una .jpg o .png - si può aggiungere anche una .gif per iphone
  
  this.divContainer = divContainer;
  this.videoclip = (videoclip.split("."))[0];
  this.width = width;
  this.height = height;
  this.controls = controls;
  this.autoplay = autoplay;
  this.loop = loop;
  this.template;
  this.videoMedia = this.divContainer+"_media";
  var me = this;
  
  this.template =''+
  '<video id="'+this.videoMedia+'" width="'+this.width+'" height="'+this.height+'" poster="'+this.videoclip+'.jpg" ';
  
  if(this.autoplay=="autoplay"){
    //this.template += 'autoplay '; DISABILITATO PER COMPATIBILITA'
    if(this.controls=="controls"){
      this.template += 'controls ';
    }
  } else {
     this.template += 'controls ';
  }
  if(this.loop=="loop"){
    this.template += 'loop ';
  }
  this.template += '>'+
  '<source src="'+this.videoclip+'.mp4" type="video/mp4;"> '+
  '<source src="'+this.videoclip+'.m4v" type="video/m4v;"> '+
  '<source src="'+this.videoclip+'.ogg" type="video/ogg;"> '+
  '<source src="'+this.videoclip+'.webm" type="video/webm;"> '+
  'Il tuo navigatore non supporta ancora video Html5'+
  '</video>';

  if( !!document.createElement('video').canPlayType != true){
    // parte object
    this.template = '<object '+
    'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" '+
    'codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" '+
    'width="'+this.width+'" '+
    'height="'+this.height+'"'+
    'hspace="0" '+
    'vspace="0" '+
    'align="top"> '+
    '<param name="FlashVars" value="targetWidth='+this.width+'&targetHeight='+this.height+'&targetSource=../'+this.videoclip+'.flv&targetLoop='+this.loop+'&targetControls='+this.controls+'&targetAutoplay='+this.autoplay+'" />'+
    '<param name="allowScriptAccess" value="sameDomain" /> '+
    '<param name="loop" value="false" /> '+
    '<param name="scale" value="noscale" />'+
    '<param name="quality" value="high" /> '+
    '<param name="salign" value="lt" /> '+
    '<param name="wmode" value="transparent" /> '+
    '<param name="bgcolor" value="#ffffff" /> '+
    '<param name="movie" value="code/playVideo.swf" /> '+
    // parte embed
    '<embed type="application/x-shockwave-flash" pluginspage="https://www.macromedia.com/go/getflashplayer" '+
    'width="'+this.width+'" '+
    'height="'+this.height+'" '+
    'hspace="0" '+
    'vspace="0" '+
    'align="top" '+
    'FlashVars = "targetWidth='+this.width+'&targetHeight='+this.height+'&targetSource=../'+this.videoclip+'.flv&targetLoop='+this.loop+'&targetControls='+this.controls+'&targetAutoplay='+this.autoplay+'" '+
    'loop="false" '+
    'scale="noscale" '+
    'quality="high" '+
    'salign="lt" '+
    'wmode="transparent" '+
    'bgcolor="#ffffff" '+
    'allowScriptAccess="sameDomain" '+
    'src="code/playVideo.swf"/></object>';         
  }
  
  document.getElementById(this.divContainer).innerHTML = this.template;
  if(this.autoplay=="autoplay"){
  		document.getElementById(this.videoMedia).play();
  }
  
  // PER FIREFOX FINCHE' NON HA IL LOOP!!!
  if( navigator.userAgent.toLowerCase().indexOf("mozilla") != -1 && navigator.userAgent.toLowerCase().indexOf("firefox") != -1 && this.loop=="loop"){
    this.enterFrame = window.setInterval(function(){me.checkEnd();},50);
    this.checkEnd = function(){
       if(document.getElementById(this.videoMedia).ended == true){
          document.getElementById(this.videoMedia).play();
       }
    }
  }
  
}  
  
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------

// --------------------------------------------------------------------------------
// sezione ANIMAZIONI
// --------------------------------------------------------------------------------
function mouseFade(mouseItem,targetDiv,fadeVelocity){
// controllo fade in/out al passare del mouse sopra un oggetto (anche esterno)
// settare mouseItem = la SORGENTE del lancio, che rileva il mouseOver e mouseOut
// targetDiv è la destinazione del contenitore della grafica da dissolvere in/out
// fadeVelocity (epresso in millisecondi) la velocità di dissolvenza
   
   this.targetDiv = targetDiv;
   this.mouseItem = mouseItem;
   this.fadeVelocity = fadeVelocity;
   this.fade = Number(document.getElementById(targetDiv).style.opacity);
   var me = this;
   
   document.getElementById(this.mouseItem).onmouseover = function() {
      me.fadeIn();  
   }
   document.getElementById(this.mouseItem).onmouseout = function() {
      me.fadeOut();  
   }
   
   this.fadeIn = function(){ 
      if(this.fade <1){
         this.fade += 0.1;
         document.getElementById(this.targetDiv).style.opacity = this.fade;
         document.getElementById(this.targetDiv).style.filter = "alpha(opacity="+this.fade*100+")";
         this.enterFrameFadeIn = setTimeout(function(){me.fadeIn();},this.fadeVelocity);
         clearTimeout(this.enterFrameFadeOut );
      } else { 
         clearTimeout(this.enterFrameFadeIn ); 
      }
   }
   
   this.fadeOut = function(){
      if(this.fade >0){
         this.fade -= 0.1;
         document.getElementById(this.targetDiv).style.opacity = this.fade;
         document.getElementById(this.targetDiv).style.filter = "alpha(opacity="+this.fade*100+")"; 
         this.enterFrameFadeOut = setTimeout(function(){me.fadeOut();},this.fadeVelocity); 
         clearTimeout(this.enterFrameFadeIn );
      } else {
         clearTimeout(this.enterFrameFadeOut ); 
      }
   }
 
}

