/********************************************
 * Gestione caricamento e visibilità pagina *
 * ******************************************/

var smartfinder_slide;
var hs = new historyStack();

function loading(show){
	if(show){
		if($('caricamento')){ 
			//$('caricamento').setHTML('<br/><br/><br/><br/><br/><br/><img style="top:100px; left:400px;" src="' + portalURL + '/img_costruzione/loading.gif"');
			$('caricamento').setHTML('<div style="text-align:center; margin:0 auto; margin-top:200px;"><img src="' + portalURL + '/agriventure/img_costruzione/loading.gif" /></div>');
      $('caricamento').style.display="block";
      //$('caricamento').style.height="1000px";
			$('caricamento').style.opacity="0.7"; 
			$('caricamento').style.filter="alpha(opacity=70)";
			$('caricamento').style.MozOpacity="0.7"; 
		}
	}
	else{
		if($('caricamento')){
			$('caricamento').style.display="none";
			//$('caricamento').style.height="0px";
		}
	}
}

/*** Controllo se le coordinate dello smartfinder e del corpo scheda per chiuderlo o aprirlo ************/

function isSlittaCoperta(centrale, slitta)
{
	var oObj = $(centrale).getCoordinates();
	var oSlitta = $(slitta).getCoordinates();
	return (oObj.height + oObj.top) > oSlitta.top;	
}


/**** gestione apertura/chiusura smart-finder ***/
	
function barraSmartFinder(azione, slittaRef)
{
	try
	{
		if(azione == "apri")
		{
			if(slittaRef.open != 'true'){
				if(typeof(slittaRef)!='undefined')
					slittaRef.slideIn();
				$('frecciadx').style.visibility = 'hidden';
				$('frecciasx').style.visibility = 'visible';
			}
		}
		else // chiudi default
		{
			if(slittaRef.open != 'false'){
				if(typeof(slittaRef)!='undefined')
					slittaRef.slideOut();
				$('frecciadx').style.visibility = 'visible';
				$('frecciasx').style.visibility = 'hidden';
			}
		}
	}
	catch(e){console.log( "[E]barraSmartFinder: " + e);}
}

//************** Gestione Detect Flash Plugin ************************//
var detectableWithVB = false;
function detectPlugin(){
  // allow for multiple checks in a single pass
  var daPlugins = detectPlugin.arguments;
  // consider pluginFound to be false until proven true
  var pluginFound = false;
  // if plugins array is there and not fake
  if (navigator.plugins && navigator.plugins.length > 0){
		var pluginsArrayLength = navigator.plugins.length;
		// for each plugin...
		for (pluginsArrayCounter=0; pluginsArrayCounter < pluginsArrayLength; pluginsArrayCounter++ ){
	    // loop through all desired names and check each against the current plugin name
	    var numFound = 0;
	    for(namesCounter=0; namesCounter < daPlugins.length; namesCounter++){
				// if desired plugin name is found in either plugin name or description
				if( (navigator.plugins[pluginsArrayCounter].name.indexOf(daPlugins[namesCounter]) >= 0) || 
				    (navigator.plugins[pluginsArrayCounter].description.indexOf(daPlugins[namesCounter]) >= 0) ){
	    		// this name was found
	    		numFound++;
				}   
    	}
	    // now that we have checked all the required names against this one plugin,
	    // if the number we found matches the total number provided then we were successful
	    if(numFound == daPlugins.length){
				pluginFound = true;
				// if we've found the plugin, we can stop looking through at the rest of the plugins
				break;
    	}
		}
  }
  return pluginFound;
}
if ((navigator.userAgent.indexOf('MSIE') != -1) && (navigator.userAgent.indexOf('Win') != -1)){
    document.writeln('<script language="VBscript">');
    document.writeln('\'do a one-time test for a version of VBScript that can handle this code');
    document.writeln('detectableWithVB = False');
    document.writeln('If ScriptEngineMajorVersion >= 2 then');
    document.writeln('  detectableWithVB = True');
    document.writeln('End If');
    document.writeln('\'this next function will detect most plugins');
    document.writeln('Function detectActiveXControl(activeXControlName)');
    document.writeln('  on error resume next');
    document.writeln('  detectActiveXControl = False');
    document.writeln('  If detectableWithVB Then');
    document.writeln('     detectActiveXControl = IsObject(CreateObject(activeXControlName))');
    document.writeln('  End If');
    document.writeln('End Function');
    document.writeln('</scr' + 'ipt>');
}

function detectFlash(){
	pluginFound = detectPlugin('Shockwave','Flash'); 
  // if not found, try to detect with VisualBasic
  if(!pluginFound && detectableWithVB){
		pluginFound = detectActiveXControl('ShockwaveFlash.ShockwaveFlash.1');
  }
  return pluginFound;
}

function createFlash(movie_width,movie_height,flash_pathname){
  var timeId = new Date().getTime();
  var bgcolor = (document.bgColor != null) ? document.bgColor : "#ffffff";
  return '<div style="text-align: center; z-index:-1;"><OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" CODEBASE="//active.macromedia.com/flash5/cabs/swflash.cab#version=5,0,0,0" ID="'+timeId+'" WIDTH="'+ movie_width +'" HEIGHT="'+ movie_height+'"> <PARAM NAME=movie VALUE="'+ flash_pathname +'"> <PARAM NAME=quality VALUE=high> <PARAM NAME=wmode VALUE=transparent> <PARAM NAME=bgcolor VALUE=' + bgcolor + '><EMBED  src="'+ flash_pathname+'" quality=high bgcolor=' + bgcolor + ' WIDTH="'+ movie_width +'" HEIGHT="'+ movie_height +'" TYPE="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" name="'+timeId+'" wmode="transparent"> </EMBED></OBJECT></div>';
}

function dropFlash(){
	if(detectFlash()){
		return true;
	}
	else{
		return false;
	}
}

function doLink(userAction, userObj){
	switch (userAction)
	{
		case "act01" :{
		// link a scheda interna impostato dall'utente
		//--------------------------------------------------
		ajLoadContent('centraleHome',estraiId(userObj.href), 'sk');
		break;
		}
		default :{
		//inserire codice da eseguire se la action non era quelle gestite
		//attualmente prosegue la navigazione alla pagina indicata
		//--------------------------------------------------
		window.location.href = "#";
		
		}		
  }  
}

window.addEvent('domready', function(){
  // effetto slide della tendina del Gruppo ISP
  var gruppoIsp_slide = new Fx.Slide('gruppo_content');
  gruppoIsp_slide.hide();
  $('gruppo_toggle').addEvent('click', function(e) {
  e = new Event(e);
  gruppoIsp_slide.toggle();
  e.stop();
  });
  
  // effetto slitta smartfinder - freccia che chiude
	smartfinder_slide = new Fx.Slide('iconeSF', {mode : 'horizontal'});
	$('frecciasx').addEvent('click', function(e) {
		e = new Event(e);
		smartfinder_slide.slideOut();
		document.getElementById('frecciadx').style.visibility = 'visible';
		document.getElementById('frecciasx').style.visibility = 'hidden'; 
		e.stop();
	});
	
	// effetto slitta smartfinder - freccia che apre
	$('frecciadx').addEvent('click', function(e) {
		e = new Event(e);
		smartfinder_slide.slideIn();
		document.getElementById('frecciasx').style.visibility = 'visible';
		document.getElementById('frecciadx').style.visibility = 'hidden'; 
		e.stop();
	});
	
	// effetto accordion del box news
	var accordion = new Accordion('h3.atStart', 'div.atStart', {
	opacity: false,
	onActive: function(toggler, element){
		toggler.setStyle('color', '#f57421');
	},
	onBackground: function(toggler, element){
		toggler.setStyle('color', '#f57421');
	}
}, $('accordion'));

/***************************************************************
 *  Effetto tendina "La tua banca"                             *
 *  ***********************************************************/ 

  var tendinaBanche_slide = new Fx.Slide('tendinaLatuabanca');
  tendinaBanche_slide.hide();
  $('laTuaBanca_toggle').addEvent('click', function(e) {
  e = new Event(e);
  tendinaBanche_slide.toggle();
  e.stop();
  });  

});


function stripUrl(cntUrl)
{
	return cntUrl.replace(/\&amp;/g,'&');
}

function getUrlParam(cntUrl,paramName)
{
	paramName = paramName.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regex = new RegExp("[\\?&]" + paramName + "=([^&#]*)");
	var qs = regex.exec(cntUrl);
	if(qs == null)
		return "";
	else
		return qs[1];
}

function gestisciSpallaSx(tp){
  if(tp == 'hp'){
    document.getElementById('divSpallaSx').style.display = 'none';
  }else{
    document.getElementById('divSpallaSx').style.display = 'block';
  }
}


/**
 * Scopo: caricamento del corpo centrale via Ajax
 * @param objContainer
 * @param cntId
 * @param tp
 * @param track  
 * @return
 */

function ajLoadContent(objContainer, cntId, tp, track, hS)
{	
	/****************************************************************************************************************
	 * Parametri della funzione
	 * 
	 * objContainer: id del div contenitore da caricare via Ajax
	 * cntId: id del content onetwo da richiamare         	
	 * tp: parametro che indica il tipo di schema pagina da utilizzare.
	 *   - sk --> scheda
	 *   - nw --> singola news	 
	 * track: indica se tenere traccia o meno del click effettuato dall'utente   	 
	 ****************************************************************************************************************/
  var langFix = 'ita';
  if(tp.indexOf('sk') != -1 || tp.indexOf('nw') != -1){
  	var contentUrl = scriptURL + "/agriventure/nop/include/scheda_inc.jsp?id=" + cntId + "&tp=" + tp;
  	if($(objContainer)){	
  	  loading(true);
  		new Ajax(contentUrl, {
  			method: 'get',
  			evalScripts : true,
  			update : objContainer,
  			onComplete : function(){
            gestisciSpallaSx(tp);
            loading(false);
            if(track != -1)  // se track != -1 --> traccia il click nell'historyStack
              hs.addUrl(contentUrl,tp,'');
            if(isSlittaCoperta('divScheda', 'slittaSF')){	
          		barraSmartFinder('chiudi', smartfinder_slide);
          	}else{
          		barraSmartFinder('apri', smartfinder_slide);
          	}
          },
  			onFailure : function() {alert("Errore caricamento scheda!"); loading(false);}
  				}).request();
  	}
  }
}

function ajLoadCentraleUrl(objContainer, cntUrl, track)
{	
  var contentUrl = "";
	cntUrl = stripUrl(cntUrl);
	var tpValue = getUrlParam(cntUrl,"tp");
  
	// chiamata "Tutte le news"
	if(tpValue == "anews"){
		contentUrl = scriptURL+'/agriventure/nop/'+cntUrl;
	}
  // chiamata all'Url del tool "Ricerca filiale"
  if(tpValue.indexOf("fil") != -1){
		contentUrl = cntUrl;
	}
  
  if($(objContainer))
	{
		loading(true);
		new Ajax(contentUrl, 
		{
			method: 'get',
			evalScripts : true,
			update : objContainer,
			onComplete : function(){
        gestisciSpallaSx();
        loading(false);
        if(track != -1)  // se track != -1 --> traccia il click nell'historyStack
          hs.addUrl(contentUrl, tpValue, '');
        if(isSlittaCoperta('divScheda', 'slittaSF')){	
      		barraSmartFinder('chiudi', smartfinder_slide);
      	}
      	else{
      		barraSmartFinder('apri', smartfinder_slide);
      	}
      }
		}).request();
	}
}

/*******************************************************************************
 * Frammento script di Reply per gestione smartfinder in caso di richiamo del  *
 * tool "Trova filiale".
 * ****************************************************************************/    
function gestisciSmartFinder() {
    if(parent.isSlittaCoperta('divScheda', 'slittaSF')){ 
      parent.barraSmartFinder('chiudi', parent.smartfinder_slide);
   }
   else{
    parent.barraSmartFinder('apri', parent.smartfinder_slide);
   }
}

function gestisciFrecciaBack(stackLenght){
  if (stackLenght > 1){
    document.getElementById('backButton').src = portalURL + "/agriventure/img_costruzione/back.gif";
  }else{
    document.getElementById('backButton').src = portalURL + "/agriventure/img_costruzione/blank.gif";
  }  
}

/*
function estraiId(paramUrl){
  var beginIndex = 0;
  var endIndex = 0;
  beginIndex =  (paramUrl.indexOf("id="))+3;
  endIndex = (paramUrl.indexOf("&"));
  var currId = paramUrl.substring(beginIndex,endIndex);
  return currId;
}
*/

function estraiId(paramUrl){
  var beginIndex = 0;
  var endIndex = 0;
  var currId = "";
  beginIndex =  (paramUrl.indexOf("id="))+3;
  if(paramUrl.indexOf("&") == -1){
    currId = paramUrl.substring(beginIndex);
  }
  else{
    endIndex = (paramUrl.indexOf("&"));
    currId = paramUrl.substring(beginIndex,endIndex);
  }
  return currId;
}

function estraiCntId(paramUrl){
  var beginIndex = 0;
  var endIndex = 0;
  beginIndex =  paramUrl.lastIndexOf("/")+1;
  //endIndex = (paramUrl.indexOf("&"));
  var currId = paramUrl.substring(beginIndex);
  return currId;
}

/*****************************************************************
 * Gestione del BACK APPLICATIVO                                 *
 * **************************************************************/ 

// HistoryStack - BEGIN
function historyStack(){
	var hStack = new Array();
	function addUrl(currUrl,currType,currName){
		hStack.push({url:currUrl, uType:currType, uName:currName});
		gestisciFrecciaBack(hStack.length);
    //if (hStack.length > 1){
		//  document.getElementById('backButton').src = portalURL + "/agriventure/img_costruzione/back.gif";
		//}
	}	
	
	function loadUrl(){
		if (hStack.length >= 2){
			var currHStack = hStack[hStack.length-2];
			switch (currHStack.uType){
				case 'sk':{ 
          // chiamata ajLoadContent di tipo sk
          var currId = estraiId(currHStack.url);
					ajLoadContent('centraleHome', currId, 'sk', -1);
					break;
				}
				case 'nw':{
          // chiamata ajLoadContent di tipo nw
          var currId = estraiId(currHStack.url);
					ajLoadContent('centraleHome', currId, 'nw', -1);
					break;
				}
				case 'anews':{
          // chiamata ajLoadContent di tipo anews
					ajLoadCentraleUrl('centraleHome','/include/scheda_inc.jsp?tp=anews', -1);
					break;
				}
				case 'fil':{
          // chiamata ajLoadContent di tipo fil (tool "Trova filiale")
					ajLoadCentraleUrl('centraleHome',scriptURL + '/agriventure/include/ricercaFiliali.jsp?tp=fil', -1);
					break;
				}
			}
			hStack.pop();
			gestisciFrecciaBack(hStack.length);
		  /*
      document.getElementById('backButton').src = portalURL + "/agriventure/img_costruzione/back.gif";
			if(hStack.length < 2){
			   document.getElementById('backButton').src = portalURL + "/agriventure/img_costruzione/blank.gif";
			}
			*/
		}		
	}
	
	function enableButton(dObj){
		if ($('backButton')&&(hStack.length < 2)){
			$('backButton').style.display = "none";
		}
	}
	
	this.hStack = hStack;
	this.loadUrl = loadUrl;
	this.addUrl = addUrl;
	this.enableButton = enableButton;
} // HistoryStack - END
