// Ho selezionato qualcosa
function ajaxSelect(e)
{
  var data = $A(arguments);
  data.shift();

  // nomeFile viene valorizzato nell'header e contiene il nome del file in corso
  var source = nomeFile+'?mode=ajax&id='+this.value+'&link='+data[0];
  // Aggiorno la select corrente
  new Ajax.Updater(data[1], source, {asynchronous:true});

  // Svuoto tutte le altre select
  if (data.length > 2)
    for (var index = 2, len = data.length; index < len; ++index)
      $(data[index]).update('<option>- Seleziona-</option>');
}

// Aggiungo l'autocompleter
function addAutocompleter(idTarget,nomeLink,idPadre)
{
  // nomeFile viene valorizzato nell'header e contiene il nome del file in corso
  var source = nomeFile+'?mode=ajax&link='+nomeLink;
  if (idPadre != '')
  {
    new Ajax.Autocompleter
    (
      idTarget+'Testo',
      idTarget+'Update',
      source,{minChars:2,callback: function(element,entry){return entry="&id="+$(idPadre).value}}
    );
  }
  else
  {
    new Ajax.Autocompleter(idTarget+'Testo',idTarget+'Update',source,{minChars:2});
  }
}

// Aggiungo i controlli se il campo è vuoto
function addCheckEmpty()
{
  $$('.notempty').each(function(input)
  {
    if (input.value == '')
      input.addClassName('empty');

    if ((input.type == 'text') || (input.type == 'password'))
    {
      if (input.value == '')
        input.addClassName('empty');
      Event.observe(input, 'blur', updateCheckEmpty.bindAsEventListener(input));
      Event.observe(input, 'keyup', updateCheckEmpty.bindAsEventListener(input));
    }
    else if (input.type == 'select-one')
    {
      if ((input.value == '') || (input.value == '-1') || (input.value == '0'))
        input.addClassName('empty');
      Event.observe(input, 'change', updateCheckEmpty.bindAsEventListener(input));
    }
  });
}

function updateCheckEmpty(e)
{
  if ((this.type == 'text') || (this.type == 'password'))
  {
    if (this.value == '')
      this.addClassName('empty');
    else
      this.removeClassName('empty');
  }
  else if (this.type == 'select-one')
  {
    if ((this.value == '') || (this.value == '-1') || (this.value == '0'))
      this.addClassName('empty');
    else
      this.removeClassName('empty');
  }
}

// Aggiungo i controlli che il campo non sia duplicato
function addCheckDuplicate()
{
  $$('.notduplicate').each(function(input)
  {
    Event.observe(input, 'blur', updateCheckDuplicateBlur.bindAsEventListener(input));
    Event.observe(input, 'keyup', updateCheckDuplicateKeyUp.bindAsEventListener(input));
    input.removeClassName('notduplicate');
  });
}

// Cambio solo la class
function updateCheckDuplicateKeyUp(e)
{
	// nomeFile viene valorizzato nell'header e contiene il nome del file in corso
  // chiavePrimaria viene valorizzato nell'header e contiene l'id del record
	var source = nomeFile+'?mode=duplicate&campo='+this.name+'&valore='+this.value+'&id='+chiavePrimaria;
  var input = this;
  // Aggiorno il link
	new Ajax.Request
  (
    source,
    {
      onSuccess: function(transport)
      {
        if (transport.responseText != '0')
          input.addClassName('duplicate');
        else
          input.removeClassName('duplicate');
      },
      asynchronous:true
    }
  );
}

// Mostro anche l'alert oltre a cambiare la class
function updateCheckDuplicateBlur(e)
{
	// nomeFile viene valorizzato nell'header e contiene il nome del file in corso
  // chiavePrimaria viene valorizzato nell'header e contiene l'id del record
	var source = nomeFile+'?mode=duplicate&campo='+this.name+'&valore='+this.value+'&id='+chiavePrimaria;
  // Aggiorno il link
	new Ajax.Request
  (
    source,
    {
      onSuccess: function(transport)
      {
        if (transport.responseText != '0')
        {
          cssAlert(transport.responseText);
          input.addClassName('duplicate');
        }
        else
          input.removeClassName('duplicate');
      },
      asynchronous:true
    }
  );
}

// Aggiungo i controlli al submit
function addOnSubmit()
{
  for (var i = 0; i < document.forms.length; i++)
		Event.observe(document.forms[i], 'submit', submitCheck.bindAsEventListener(document.forms[i]));
}

// Verifico che tutti i campi siano compilati
function submitCheck(e)
{
  $$('.notempty').each(function(input)
  {
    if ((input.type == 'text') || (input.type == 'password'))
    {
      if (input.value == '')
      {
        alert("Il campo non puo' essere vuoto, compilare il campo");
        input.focus()
        Event.stop(e);
        throw $break;
      }
    }
    else if (input.type == 'select-one')
    {
      if ((input.value == '') || (input.value == '-1') || (input.value == '0'))
      {
        alert("Il campo non puo' essere vuoto, selezionare un opzione");
        input.focus()
        Event.stop(e);
        throw $break;
      }
    }
    else
      alert('none..'+input.type);
  });
}

// Aggiungo l'ajax ai check
function addChecker(selettore,field)
{
  $$(selettore).each(function(img)
  {
    Event.observe(img, 'click', updateCheck.bindAsEventListener(img,field));
  });
}
function updateCheck(e)
{
	var data = $A(arguments);
	data.shift();

	// nomeFile viene valorizzato nell'header e contiene il nome del file in corso
	var source = nomeFile+'?mode=check&id='+this.id+'&field='+data[0];
  var img = this;
	// Aggiorno il link
	new Ajax.Request
  (
    source,
    {
      onSuccess: function(transport){img.setAttribute('src',transport.responseText);},
      asynchronous:true
    }
  );
}

// Hide / Show
function hideShow(idTarget,idLink,testoAperto,testoChiuso)
{
	var changeText = true;
	if ((testoAperto == '') && (testoChiuso == ''))
		changeText = false;

  if ($(idTarget).style.display == "none")
	{
		new Effect.BlindDown($(idTarget),{duration:0.7});
		if (changeText)
    {
      $(idLink).textContent = testoAperto;
			$(idLink).innerHTML = testoAperto;
    }
	}
	else
	{
  	new Effect.BlindUp($(idTarget),{duration:0.4});
		if (changeText)
    {
      // Per IE textContent ( con innerHTML non cambia il testo.. )
      $(idLink).textContent = testoChiuso;
      // Per FF, innerHTML ( in caso di codice html firefox altrimenti codificherebbe il testo passato )
			$(idLink).innerHTML = testoChiuso;
    }
	}
	return false;
}


function addCalendar()
{
  $$('.cal').each(function(img)
  {
    var idCampo = img.id;
    idCampo = idCampo.substr(idCampo.indexOf('-')+1);
    Event.observe(img, 'click', imgCalendar_Click.bindAsEventListener(this, idCampo));
  });
	if ($("calendar-container"))
		new Draggable($("calendar-container"));
}

function addCalendarChange()
{
  if ($('cal-inizio'))
    Event.observe($('cal-inizio'), 'click', imgCalendar_Click.bindAsEventListener(this,$('inizio'),changeDate));
}

function changeDate(data)
{
  $('inizio').value = data.getDate()+"-"+(data.getMonth()+1)+"-"+data.getFullYear();
  document.filtro.submit();
}

function cambiaTab(lista,tabScelto)
{
	for (var i=0; i < lista.length;i++)
		$(lista[i]).hide();
	$(tabScelto).show();
}
function cambiaTabL(lista,listaTab,tabScelto)
{
	for (var i=0; i < lista.length;i++)
	{
		if ($(lista[i]).id == tabScelto)
		{
			$(lista[i]).show();
			$(listaTab[i]).addClassName('sel');
		}
		else
		{
			$(lista[i]).hide();
			$(listaTab[i]).removeClassName('sel');
		}
	}
}

function onLoad()
{
  addCalendarChange();
	addCalendar();
	SortableTable.load();
  addOnSubmit();
  addCheckEmpty();
}


var AjaxInit = {
	onload : function() {
		AjaxInit.actions.each(function(func) {
			func();
		})
	},
	actions : $A([]),
	addOnLoad : function() {
		for(var x = 0; x < arguments.length; x++) {
			var func = arguments[x];
			if(!func || typeof func != 'function') continue;
			AjaxInit.actions.push(func);
		}
	}
}



//if(FastInit)
//  FastInit.addOnLoad(onLoad);
//else
  Event.observe(window, 'load', onLoad);
