function createPop(e, content){
   if($('pop')) $('pop').remove();
   getBody().insert(new Element('div', {id:'pop', 'style': 'display:none;'}).update(content));

   var x = (Event.pointerX(e) + $('pop').getWidth() < document.viewport.getWidth()) ? (Event.pointerX(e) + 10) : (Event.pointerX(e) - $('pop').getWidth() - 10);
   var y = (Event.pointerY(e) + $('pop').getHeight() < document.viewport.getHeight()) ? (Event.pointerY(e) + 10) : (Event.pointerY(e) - $('pop').getHeight() - 10);
   $('pop').setStyle('display:block;top:'+ y +'px;left:'+ x +'px');
}

function popHelp(that, e, txt){
   new Ajax.Request('?',{
      parameters:{ajax:'ajax.html', fun:'pophelp', txt:txt},
      onSuccess: function(res){
	 createPop(e, res.responseText);
	 Event.observe(that, 'mouseout', function(){
	    try {$('pop').remove();} catch(er){}
	    Event.stopObserving(that, 'mouseout');
	 });
      }
   });
}

function popImg(that, e, img){
   createPop(e, '<img class="popImg" src="'+ img +'" />');
   Event.observe(that, 'mouseout', function(){
      try {$('pop').remove();} catch(er){}
      Event.stopObserving(that, 'mouseout');
   });
}

function popGlo(that, e, id){
   new Ajax.Request('?',{
      parameters:{ajax:'ajax.html', fun:'popglo', idglo:id},
      onSuccess: function(res){
	 createPop(e, res.responseText);
	 Event.observe(that, 'mouseout', function(){
	    try {$('pop').remove();} catch(er){}
	    Event.stopObserving(that, 'mouseout');
	 });
      }
   });
}

function fillSimilar(that, e, voidText){
   var e = e ? e : window.event;
   var that = $(that);
   switch(e.type){
      case 'blur':
	 if(!that.value){
	    that.addClassName('inputVoid');
	    that.value = voidText;
	 }
      break;
      case 'focus':
	 if(that.hasClassName('inputVoid')){
	    that.removeClassName('inputVoid');
	    that.value = '';
	 }
      break;
      case 'keyup':
	 if(that.value.length) new Ajax.Request('?', {
	    parameters: {ajax:'ajax.html', fun:'fill', type:(that.id=='nome_glo')?'g':'p', key:that.value},	   
	    onSuccess: function(res){
	       var res = res.responseText;	      
	       if(res.length){
		  var myPos = that.cumulativeOffset(); 
		  if(!$('pop'))document.body.appendChild(
		     new Element('div', {id:'pop', 'class':'popFill', 'style':'top:'+ (myPos[1]+27) +'px;left:'+ (myPos[0]) +'px;width:'+ (that.getWidth()-12)+'px'})
		  );
		  $('pop').update(res);
	       }
	       else if($('pop')) $('pop').remove();
	    }
	 });
	 else if($('pop')) $('pop').remove();
      break;
   }
}

function uploadFoto(e, idp, tit){
   var txt = '<form method="post" enctype="multipart/form-data" '+ (isIE()?'style="width:300px;"':'' ) + '>'+
   '<a href="javascript:void(0);" onclick="$(\'pop\').remove()" class="closeUpload" title="chiudi">X</a>'+
   '<b>Carica la tua "'+ unescape(tit) +'"</b><br/>'+
   '<input type="hidden" name="id_pianta" value="'+ idp +'" />'+
   '<input type="file" class="inputFile" name="userfile" /> '+
   '<input type="submit" class="inputButt" value="invia" />'+
   '</form>'
   createPop(e, txt);   
}

function deleteFoto(idp){
   if(confirm('Eliminare la foto caricata?')) new Ajax.Request('?',{
      parameters:{ajax:'ajax.html', fun:'deleteFoto', id_pianta:idp},
      onSuccess: function(res){ document.location.href = document.location.search; }
   });
}

function moveResults(v){
   var f = $('search');
   $('search').from.value = v;
   $('search').submit();
}

/**** virtual *****/
function virtual_go(amb, frm, esp, dim){
    var f = $('vsearch');
    f.lnk_ambiente.value = amb;
    f.lnk_forma.value = frm ;
    f.lnk_esposizione.value = esp ;
    f.lnk_dimensione.value = dim ;
    f.submit();
}

/**** aggiungi ****/
function checkNewPlant(f){ 
   try {
      var el = $(f).elements;
      if(!el['nc'].value){
	 alert('Indicare un nome per la pianta da inserire');
         return false;
      }
      else return true;
   }
   catch(er) {alert(er); return false;}
}


/******************* mappa ***************************/
var pMap;
var pId;
var pMrk;
function geoReferPlant(that, idup){
   var that = $(that);
   pId = idup;
   var thatPos = that.cumulativeOffset();
   $('pMap').setStyle('top:'+ (thatPos[1]+40) +'px;left:'+ (thatPos[0]-2) +'px;display:block;');
   if(!pMap){
      pMap = new google.maps.Map($('pMap'), {
         zoom:5, 
	 center: new google.maps.LatLng(41.902277,12.590332),
         mapTypeId: google.maps.MapTypeId.HYBRID,
         mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU}
      });
      pMap.controls[google.maps.ControlPosition.BOTTOM].push($('butGeoSrc'));
      $('butGeoSrc').appear();
   }
   if(pMrk) pMrk.setMap(null);
   if(arguments[2]){
      var pLL = new google.maps.LatLng(arguments[2][0], arguments[2][1]);
      pMap.setZoom(15);
      pMap.setCenter(pLL);
      pMrk = new google.maps.Marker({id:idup, position:pLL, draggable:true, title:'Trascina per modificare la posizione', cursor:'move'});
      pMrk.setMap(pMap);
      google.maps.event.addListener(pMrk, 'dragend', function(){pMapSave(pMrk)});
   }
}

function pGetGeoRequest(f){
   try{
      if(f.luogo.value.length > 3) {
	 new Ajax.Request(ajax_base, {
	    parameters: {ajax:'geoblog', fun:'getGeoRequest', geo:f.luogo.value},
	    onSuccess: function(res){
	       if(res.responseText){
		  var go = res.responseText.evalJSON();
		  pMap.setCenter(new google.maps.LatLng(go[1], go[0]));
		  pMap.setZoom(go[2]);
	       }
	    }
	 });
      }
   }
   catch(er){return false;}
   return false;
}

function pMapInsert(that){
   var img = $(that);   
   if(img.hasClassName('butsDel')){
      img.removeClassName('butsDel');
      img.title = 'clicca per georefereziare la pianta';
      $('pMapStatus').update('sposta la mappa e clicca sul "+" per georefereziare la pianta');
      $('pMap').removeClassName('crosshair');
      google.maps.event.clearListeners(pMap, 'click');
   }
   else {
      img.addClassName('butsDel');
      img.title = 'annulla inserimento';
      $('pMapStatus').update('clicca sulla mappa per inserire il punto');
      $('pMap').addClassName('crosshair');
      if(pMrk) pMrk.setMap(null);
      google.maps.event.addListener(pMap, 'click', function(p){
	 pMapInsert(that);
	 p = p.latLng;
	 pMrk = new google.maps.Marker({id:pId, position: p, draggable:true, title:'Trascina per modificare la posizione', cursor:'move'});
	 pMrk.setMap(pMap);
	 google.maps.event.addListener(pMrk, 'dragend', function(){pMapSave(pMrk)});
	 pMapSave(pMrk);
      });
   }
}

function pMapInsertHome(home){
   if(!home[0]) alert('Non hai ancora georeferenziato il tuo profilo.\nClicca su "modifica dati" in alto a destra.');
   else {
      if(pMrk) pMrk.setMap(null);
      var pLL = new google.maps.LatLng(home[0], home[1]);
      pMap.setZoom(15);
      pMap.setCenter(pLL);
      pMrk = new google.maps.Marker({id:pId,position:pLL,draggable:true,title:'Trascina per modificare la posizione', cursor:'move'});
      pMrk.setMap(pMap);
      google.maps.event.addListener(pMrk, 'dragend', function(){pMapSave(pMrk)});
      pMapSave(pMrk);
   }
}

function pMapSave(p){
   new Ajax.Request('?', {
      parameters:{ajax:'ajax.html', fun:'refPlant', idup:p.id, coords:Object.toJSON(p.getPosition())},
      onSuccess: function(res){
	 alert('Pianta georeferenziata!');
	 $('geoTd'+ p.id).removeClassName('geoNo');
	 $('geoTd'+ p.id).firstChild.onclick = function(){ geoReferPlant(this, p.id, [p.getPosition().lat(), p.getPosition().lng()]); }
	 $('geoTd'+ p.id).firstChild.title = 'Pianta georoferenziata: '+ p.getPosition().lat() +', '+ p.getPosition().lng();
      }
   });
}

function pMapClose(){ $('pMap').hide(); }

Event.observe(window, 'load', function(){
   	if(typeof(window.imgNotify)=='function'){
   imgNotify('div.lmp_thumb img');
   imgNotify('img.users');
}
   //relax
   if($$('div.princ-art').length){
      $$('.titolo')[0].insert({bottom:'<a id="relax" title="versione amica degli occhi" href="javascript:relax()" style="display:none;"></a>'});
      $('relax').appear(); 
   }      
});


function relax(){
   var relax_divs = ['top','midl','midm','midr','bot'];
   var midm = $('midm');
   var relaxed = 0;
   Effect.multiple(relax_divs, Effect.Fade, {afterFinish:function(){relaxed++;}});

   var waitComplete = setInterval(function(){
      if(relaxed == relax_divs.length){
	 clearInterval(waitComplete);
	 setTimeout(function(){
	    if(!midm.hasClassName('relax')){
	       midm.addClassName('relax');
	       Effect.Appear('midm');
	    }
	    else {
	       midm.removeClassName('relax');	  
	       Effect.multiple(relax_divs, Effect.Appear);
	    }
	 },500);
      }
   }, 1000);
}

function getGallery(id){
   var myVal = unescape($('thbP'+ id).value).evalJSON();
   if(!$('galBack')){
      getBody().insert(new Element('div', {id:'galBack', 'style':'display:none;cursor:pointer;', 'title':'Chiudi'}));
      Event.observe($('galBack'), 'click', closeGallery);
   }
   if(!$('galImgC')) getBody().insert(new Element('div', {id:'galImgC', 'style':'top:'+ ((document.viewport.getHeight()/2)+ document.viewport.getScrollOffsets()[1]) 
      +'px;left:'+ (document.viewport.getWidth()/2) +'px'
      }).update('<img id="galImgC-img" alt="" src="/customizer/sysimg/void.gif" /><div id="galImgC-dida"></div>'));

   var gBk = $('galBack');
   var gIc = $('galImgC');
   $(getBody()).addClassName('galleryBody');
   
   gBk.setOpacity(.5);
   gBk.setStyle('height:'+ (document.viewport.getHeight() + document.viewport.getScrollOffsets()[1]) +'px;width:'+ document.viewport.getWidth() +'px;display:block;');

   gIc.morph('top:'+ (((document.viewport.getHeight()-myVal[2])/2)+ document.viewport.getScrollOffsets()[1]) +'px;left:'+ ((document.viewport.getWidth()-myVal[1])/2) +'px;');

   $('galImgC-img').src = '/customizer/sysimg/void.gif';
   $('galImgC-img').morph('height:'+ myVal[2] +'px;width:'+ myVal[1] +'px;');
   $('galImgC-img').src = myVal[0];
   $('galImgC-dida').update(
      ($('thbP'+ (id-1)) ? '<a class="iconeA galP" href="javascript:getGallery('+ (id-1) +')" title="Vai alla precedente">Prec.</a>':'')+
      ($('thbP'+ (id+1)) ? '<a class="iconeA galN" href="javascript:getGallery('+ (id+1) +')" title="Vai alla successiva">Succ.</a>':
      '<a class="iconeA galN" href="javascript:closeGallery()" title="Chiudi">Chiudi</a>')+
      '<div>'+ unescape(myVal[3]) +'</div>'
   );
}

function closeGallery(){
   $('galBack').remove();      
   $('galImgC').remove();     
   $(getBody()).removeClassName('galleryBody');
}

