// Redirect  ( semplice alias )
var regPage = '';
function redirect(url)
{
	document.location.href = url;
}
// Refresh della pagina ( semplice alias )
function refresh()
{
	document.location.reload();
}

function isInternetExplorer()
{
	return /msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent);
}

function getLoader()
{
	var load = new Element('img', { src: '/img/v/loader.gif'});
	return load;
}
// 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];

  var img = getLoader();
  this.parentNode.appendChild(img);

  // Aggiorno la select corrente
  new Ajax.Updater(data[1], source,
      {
        onComplete: function()
        {
          $(img).remove();
        },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 value="-1">- Seleziona-</option>');
}
function ajaxSelect_file(e)
{
  var data = $A(arguments);
  data.shift();

  // nomeFile viene valorizzato nell'header e contiene il nome del file in corso
  var source = data[0]+'?mode=ajax&id='+this.value+'&link='+data[1];

  var img = getLoader();
  this.parentNode.appendChild(img);

  // Aggiorno la select corrente
  new Ajax.Updater(data[2], source,
      {
        onComplete: function()
        {
          $(img).remove();
        },asynchronous:true
      });

  // Svuoto tutte le altre select
  if (data.length > 3)
    for (var index = 3, len = data.length; index < len; ++index)
      $(data[index]).update('<option value="-1">- 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 l'ajax ai check
function addChecker(selettore,field)
{
  $$(selettore).each(function(img)
  {
    Event.observe(img, 'click', updateCheck.bindAsEventListener(img,field));
  });
}

function getSelected(type,name)
{
  return $$('input:checked[type="'+type+'"][name="'+name+'"]').pluck('value');
}

function setSelected(type,name,valueToCheck)
{
  $$('input:[type="'+type+'"][name="'+name+'"]').find( function(radio){return radio.value==valueToCheck}).checked = true;
}

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

// Aggiungo l'ajax alle immagini
function addLinks(selettore,href)
{
  $$(selettore).each(function(link)
  {
    link.onclick = function()
    {
      window.location.href = href+"&id="+link.id;
      return false;
    };
  });
}

// Seleziono/deseleziono tutto
function checkAll(master,target)
{
	var lista = document.getElementsByTagName("input");
	var check = document.getElementById(master).checked;

	for(i=0; i < lista.length; i++)
  		if(lista.item(i).getAttribute("type") == 'checkbox')
        if (lista.item(i).getAttribute("name") == target)
          lista.item(i).checked = check;
}

// Aggiungo le conferme in delete
function addDel()
{
  $$('.del').each(function(link)
  {
    link.onclick = function()
    {
      return confirm('Sei sicuro di voler cancellare questo record?');
    };
  });
}

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

    Event.observe(input, 'blur', updateCheckEmpty.bindAsEventListener(input));
    Event.observe(input, 'keyup', updateCheckEmpty.bindAsEventListener(input));
    input.removeClassName('notempty');
  });
}

function updateCheckEmpty(e)
{
  if (this.value != '')
    this.removeClassName('empty');
  else
    this.addClassName('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
    }
  );
}

function updateChain(elem,link,nome)
{
	var trovato = false;
	// Elimino tutte le select successive a questa
	$(elem.parentNode).childElements().each(function(sel)
	{
		if (sel == elem)
			trovato = true;
		else
			if (trovato)
				elem.parentNode.removeChild(sel);
	});
	if ((elem.value == '-1') || (elem.value == '') || (elem.value == 0))
		return;

  var img = getLoader();
  $(elem.parentNode).appendChild(img);

	// Aggiungo una nuova select con i dati che ottengo da ajax
	var source = nomeFile+'?mode=ajax&id='+elem.value+'&link='+link;
	new Ajax.Request
	(
		source,
		{
			onSuccess: function(transport)
			{
				$(img).remove();

				var reply = transport.responseText;
				if ((reply != '') && (reply != ' '))
				{
					var sel = new Element('select', { name: nome });
					$(elem.parentNode).appendChild(sel);
					$(sel).update(reply);
					$(sel).onchange = function(){updateChain(sel,link,nome);};
				}
			},
			asynchronous:true
		}
	);
}

function sendData(url,callBack,debug)
{
	var param = new Array();
  $$('.post').each(
    function(inp,i)
    {
      if (inp.type == 'radio')
        param[i] = inp.name + '='+encodeURIComponent(getSelected(inp.type,inp.name));
      else
        param[i] = inp.name + '='+encodeURIComponent(inp.value);
    });

  var parame = param.join('&');
  var source = url;
  if (url.indexOf('?'))
    source += '&'+parame;
  else
    source += '?'+parame;

  if (debug)
    alert(source);
	// Aggiorno il link
	new Ajax.Request(source,{onSuccess: callBack,asynchronous:true});
}

function buttonClick(campo)
{
  $(campo).click();
}

function cssAlert(testo)
{
  var close = '<br /><br /><center><span class="alertClose" onClick="Control.Alert.current.close();">Chiudi</span></center>';
	new Control.Alert(testo+close);
}

// Aggiungo i controlli al submit
function addOnSubmit()
{
  $$(document.forms).each(function(form)
  {
    Event.observe(form, 'submit', submitCheck.bindAsEventListener(form));
  });
}
// Verifico che tutti i campi siano compilati
function submitCheck(e)
{
  $$('.notempty').each(function(input)
  {
		var tipo = $(input).getAttribute('type');
    if (tipo == 'text')
    {
      if (input.value == '')
      {
        alert("Il campo non può essere vuoto, compilare il campo");
        input.focus()
        Event.stop(e);
        throw $break;
      }
    }
    else if (tipo == 'select-one')
    {
      if ((input.value == '') || (input.value == '-1') || (input.value == '0'))
      {
        alert("Il campo non può essere vuoto, selezionare un opzione");
        input.focus()
        Event.stop(e);
        throw $break;
      }
    }
    else
      alert('none..'+input.type);
  });
}


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 addTooltip()
{
	$$('.tip').each(function (link)
	{
		var testo = '';
		$A(link.getElementsByTagName('em')).each(function(em){testo += em.innerHTML});
		new ToolTip.Text(link,testo);
	});

  // $$('.tip').each(function(link) { var tooltip = new Control.Tip(link); });
}

function addField()
{
  $$('.field').each(function(inp)
  {
    var vecchioVal = inp.value;
    Event.observe(inp, 'blur', updateFieldBlur.bindAsEventListener(inp,vecchioVal));
    Event.observe(inp, 'focus', updateFieldFocus.bindAsEventListener(inp,vecchioVal));
  });
}

function updateFieldBlur(e,oldVal)
{
	if (this.value == '')
	{
		this.value = oldVal;
		$(this).writeAttribute('type','text');
	}
}
function updateFieldFocus(e,oldVal)
{
	if (this.value == oldVal)
		this.value = '';
	if (this.name.toLowerCase() == 'password')
	{
		var input = this;
		Try.these(
			function() { return $(input).writeAttribute('type','password'); },
			function()
			{
				var dimensione = $(input).size;
				var newInp = new Element('input',{type:'password',name:'password',id:'newPassword',className:'field',size:dimensione});
				$(input).parentNode.replaceChild(newInp,input);
				setTimeout('$(\'newPassword\').focus()',100);
				return true;
			}
	  );
	}
}

function addTooltipProdotti()
{
	$$('.off').each(function(off)
  {
		var id = off.id;
		id = id.substring(4);
		new ToolTip.Ajax(off,'prodotti.php?mode=ajax&target=preview&id='+id);
	  //var tooltip = new Control.AjaxTip(off,'prodotti.php?mode=ajax&target=preview&id='+id);
	});
}

function addAutocompleterSearch()
{
	if ($('search'))
	{
		var source = '/prodotti.php?mode=ajax&target=search';
		var img = getLoader();
		$('search').parentNode.appendChild(img);
		$(img).hide();
		new Ajax.Autocompleter('search','searchUpdate',source,{minChars:2,indicator:img,updateElement: updateSearch});
	}
}
function updateSearch(li)
{
	if (li.id != '-1')
	{
		var nomeCat = li.innerHTML;
		nomeCat = pulisci(nomeCat);
		redirect("/categorie/"+encodeURIComponent(nomeCat)+'_'+li.id+".html");
	}
}

function pulisci(testo)
{
	testo = testo.replace("/","_");
	testo = testo.replace("&amp;","e");
	testo = testo.replace("&nbsp;","_");
	// Regexp: [^a-z ]+
	var reg = new RegExp("[^a-z A-Z]+","g")
	testo = testo.replace(reg,"_");
	testo = testo.replace("&","e");
	testo = testo.replace(",","_");
	testo = testo.replace(" ","_");
	return testo;
}

function addWelcomeMessage()
{
	if ($('idRegione_zon'))
	{
		Event.observe('idRegione_zon', 'change', ajaxSelect_file.bindAsEventListener($('idRegione_zon'),'/profile.php','provincia_utente','idProvincia_zon'));
	}
}

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

function changeDate(data)
{
	var dataT = data.getDate()+"-"+(data.getMonth()+1)+"-"+data.getFullYear();
	var url = document.location;

	var par = url.search.toQueryParams();
	par.data = dataT;

	redirect(url.protocol+'//'+url.hostname+url.pathname+'?'+Object.toQueryString(par));
}

function addShowZone()
{
	if ($('linkZone'))
		Event.observe($('linkZone'), 'click', openClose.bindAsEventListener($('linkZone'),'showZone'));
}

function openClose(link,div)
{
	if ($(div).innerHTML == '')
	{
		// Se è vuoto, allora aggiungo un loader e carico via ajax i dati
		var img = getLoader();
		$(div).appendChild(img);

		var source = '/ajax.php?mode=zone';
		new Ajax.Updater($(div),source,
			{
				asynchronous:true,
				onComplete: function ()
				{
					Event.observe($('masterZone'), 'click', checkAllZone.bindAsEventListener($('masterZone')));
				}
			});
	}

	if ($(div).style.display == "none")
		new Effect.BlindDown($(div),{duration:0.6});
	else
  	new Effect.BlindUp($(div),{duration:0.4});
	return false;
}


// Seleziono/deseleziono tutto
function checkAllZone()
{
	var lista = document.getElementsByTagName("input");
	var check = this.checked;
	var target = "enable[";

	for(i=0; i < lista.length; i++)
  		if(lista.item(i).getAttribute("type") == 'checkbox')
        if (lista.item(i).getAttribute("name").include(target))
          lista.item(i).checked = check;
}

// 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 onLoad()
{
	addTooltip();
	addCalendar();
	addField();
	addTooltipProdotti();
	addAutocompleterSearch();
	addGuestTip();
	addWelcomeMessage();
	addChangeDate();
	addShowZone();

	Object.extend(Element.Methods, {
		sendData: function(form, options)
		{
			form = $(form), options = Object.clone(options || { });

			var params = options.parameters, action = form.readAttribute('action') || '';
			if (action.blank()) action = window.location.href;
			options.parameters = form.serialize(true);

			if (params) {
				if (Object.isString(params)) params = params.toQueryParams();
				Object.extend(options.parameters, params);
			}

			if (form.hasAttribute('method') && !options.method)
				options.method = form.method;
			if (options.action != null)
				action = options.action;

			return new Ajax.Request(action, options);
		}
	});
	Element.addMethods();
}

function popupLogin()
{
	var url = '/ajax.php?mode=login';
	regPage = new ToolTip.Message('',{ajaxUrl:url,keepPosition: false,overlay : { opacity: 0.3 },onAjaxComplete:onLoadRegister});
}

function submitForm(form,funct)
{
	$(form).request(
	{
		onSuccess: function(transport)
		{
			var reply = transport.responseText;
			if (funct)
				funct(reply);
			else
				regPage.updateContent(reply);
		},
		asynchronous:true
	});
}

function onLogin(testo)
{
	var info = testo.evalJSON(true);
	if (info.info != undefined)
	{
		$('loginInfo').show();
		$('loginInfo').down().update(info.info);
	}
	if (info.redirect != undefined)
		refresh();

}

function submitRegister()
{
	$('register').request(
	{
		onSuccess: function(transport)
		{
			console.log(transport.responseText);
			// Estraggo tramite json le informazioni che mi passa
			up = transport.responseText.evalJSON(true);

			// Se mi da qualche info c'è stato qualche errore, lo mostro
			if (up.info != undefined)
			{
				$('reg_info').show();
				$('reg_info').update(up.info);
			}
			else if (up.refresh = true)
				redirect("/login.html");
		},
		asynchronous:true
	});
}
function registrationPage()
{
	openPage('/ajax.php?mode=register');
}

function openPage(url)
{
	if ((regPage == '') || (!regPage.isVisible()))
		regPage = new ToolTip.Message('',{ajaxUrl:url,keepPosition: false,overlay : { opacity: 0.3 },onAjaxComplete:onLoadRegister});
	else
		regPage.ajaxUpdate(url);
}
function closePage()
{
	if ((regPage == '') || (!regPage.isVisible()))
		return;
	else
		regPage.hideTooltip();
}
function onLoadRegister()
{
	addAutoGrown();
	if ($('idRegione'))
	{
		nomeFile = '/profile.php';
		Event.observe('idRegione', 'change', ajaxSelect.bindAsEventListener($('idRegione'),'provincia_utente','idProvincia','idComune','idFrazione'));
		Event.observe('idProvincia', 'change', ajaxSelect.bindAsEventListener($('idProvincia'),'comune_utente','idComune','idFrazione'));
		Event.observe('idComune', 'change', ajaxSelect.bindAsEventListener($('idComune'),'frazione_utente','idFrazione'));
	}
	FB_RequireFeatures(["XFBML"], function()
	{
		FB.XFBML.Host.autoParseDomTree = false;
		FB.XFBML.Host.addElement(new FB.XFBML.LoginButton($("puls_fbLogin")));
	});
}

function addGuestTip()
{
	if ((!loggato) && ($('testoRegistrati')))
	{
		var pcontainer = $('testoRegistrati');
		$$('.nonreg,.carr,.carr_p,.carr_m').each(function(span)
		{
			// new ToolTip.Base(span,pcontainer);
			span.onclick = popupLogin;
		});
	}

	if (IE6)
	{
		// Mostro solo 1 volta
		var visita = Cookie.get('visita'); //null
		if (visita != '1')
		{
			Cookie.set('visita','1',3600);
			var html = "<b>Stai utilizzando Internet Explorer 6 per navigare su www.SpesaFacile.com.</b><br />";
			html += "<br />Spesafacile funziona meglio se aggiorni il tuo browser a Internet Explorer 7 o utilizzi un altro browser<br />";
			html += "<br /><br />";
			html += '<a href="http://www.microsoft.com/windows/downloads/ie/getitnow.mspx">Aggiorna ad Internet Explorer 7</a><br/>';
			html += '<a href="http://www.firefox.com/">Passa a Firefox</a><br/>';

			cssAlert(html);
		}
	}
}



FastInit.addOnLoad(onLoad);
