//<![CDATA[


Event.observe(window, 'load', function() { 
       initializeGM(); 
       
      //  alert (" observe Onload loadAddbookmark adid" + adid  ); 
       loadAddbookmark(  adid  ); 
        	
 }); 


function myAdBookmark (  adid  ) 
{

        // alert (" func  myAdBookmark adid: " + adid   );         
        var action ="add";         
        var url = '/action/bookmarkdiv.php'; 
        var pars =  'action='+ action + '&adid='+ adid; 
        new Ajax.Updater( {success: 'myBookmark' }, url,
        {
         
         method:'post',
         parameters: pars, 
         
         onCreate: function() {
     		    // alert(' onCreate a request has been initialized  ... ');	
            // Element.show ('adloadingbm' ); 	 
            // $("adloadingbm").innerHTML= " <img src='/images/indicator.gif'> "; 		 
     
     		}, 
     		 onComplete: function () {
     		   // alert('  onComplete a request has been terminated!');
     		  // Element.hide ('loading_'+ divid); 	
                  
     
     		}, 
     		
         onSuccess: function( transport ) {
                   var response = transport.responseText || "no response text"; 
		             //  alert ("\n AddBookmark onSuccess:   " + response);        
		   
		  
/*		           
                //  alert('onSuccess response: ' + response);
                 Element.hide ('adloadingbm' ); 
                var tmp=response.slice(0,3);
                tmp=tmp.toLowerCase();
                if (tmp =="err") {
                     // var err = getLabel(response);
                      var err = 'ERROR! ';
                   
                        alert( "\n " + err + " \n (" + response + " ) "  ); // Error! \n 
                    
                   //     Effect.Fade("loading_" + divid, {duration: 5});
                     //$( "loading_" + divid ).fade();
                      
               } else {             
      
                  $("myBookmark").innerHTML = response;  
                  //  Effect.Fade(divid, {duration: 5});
                  // $(divid).fade({ duration: 3.0 });  
                  Element.addClassName('myBookmark','selected-fav');
                  $('myBookmark').removeClassName('fav');
*/

/*
var linewid=response.toQueryParams();
if (  linewid.isJSON() ) {
}
//  alert ("\n  linewidresult:   " + linewid.result + ' id: '+ linewid.id);
if ( linewid.result=="OK" )  {

}

                    
                  
      }
               
               */
         },
         onFailure: function(){ alert('Something went wrong...') }
  });
  
}


function loadAddbookmark (  adid  ) 
{

    // alert (" Onload loadAddbookmark adid" + adid  ); 
   
    var action ="get";
    
    var url = '/action/bookmarkdiv.php'; 
    var pars =  'action='+ action + '&adid='+ adid; 
   new Ajax.Updater( {success: 'myBookmark' }, url,
   {
    
    method:'post',
    parameters: pars, 
    
    onCreate: function() {
		  // alert('a request has been initialized  ... ');	
      // Element.show ('loading_'+ divid); 	 
      // $(divid).innerHTML= " <img src='/images/indicator.gif'> "; 		 

		}, 
		 onComplete: function () {
		  // alert('a request has been terminated!');
		  // Element.hide ('loading_'+ divid); 	
      // Element.hide ('loading_'+ divid); 

		}, 
		
    onSuccess: function( transport ) {
            
           var response = transport.responseText || "no response text";
           //  alert('onSuccess response: ' + response);
           var tmp=response.slice(0,3);
           tmp=tmp.toLowerCase();
           if (tmp =="err") {
                // var err = getLabel(response);
                 var err = 'ERROR! ';
              
                  alert( "\n " + err + " \n (" + response + " ) "  ); // Error! \n 
                  $("loading_" + divid).innerHTML=  "<img src='/images/warning.png'>";
              //     Effect.Fade("loading_" + divid, {duration: 5});
                //$( "loading_" + divid ).fade();
                 
          } else {             
 
            // $(divid).innerHTML = response;  
             //  Effect.Fade(divid, {duration: 5});
             // $(divid).fade({ duration: 3.0 });  
             Element.addClassName('myBookmark','selected-fav');
             $('myBookmark').removeClassName('fav');
                       
             
          }
    },
    onFailure: function(){ alert('Something went wrong...') }
  });
}

function getBidLabel(label,val)
{
    switch(label)
    {  
        case "error":
          return "Errore ... ";
        case "error1":
         return "MESSAGGIO NON INVIATO \n Il codice digitato non corrisponde a quello visualizzato. \n Verifica il codice, inseriscilo correttamente e premi il tasto \"Invia\" \n";
        case "error11":
	    return "\n Il codice digitato non corrisponde a quello visualizzato. \n Verifica il codice, inseriscilo correttamente e premi il tasto \"Invia\" oppure regenera nuovo codice e riprovare\n";
         case "error2":
         return "MESSAGGIO NON INVIATO \n codice annuncio non trovato ";
        case "error3":
         return "MESSAGGIO NON INVIATO \n Errore durante invio di email, \n Riprovare ancora ";
         case "error5":
	          return "MESSAGGIO NON INVIATO \n Errore durante invio di email, \n Email in Blacklist Internazionale";
          case "error12":
         return "MESSAGGIO NON INVIATO \n Il campo \"email\" non è stato compilato corettamente, correggi email e riprova ancora ";
        case "error13":
         return "MESSAGGIO NON INVIATO \n Il campo \"nome\" non è stato compilato ";
        case "error14":
         return "MESSAGGIO NON INVIATO \n Il campo \"codice di verifica\" non è stato compilato";
        case "error15":
         return "MESSAGGIO NON INVIATO \n Il campo \"messaggio\" non è stato compilato ";
        case "error25":
         return "MESSAGGIO NON INVIATO \n Il campo \"id annuncio adid\"  è vuoto ";
         case "error144":
         return "MESSAGGIO NON INVIATO \n Il campo \"Importo della Proposta\" è vuoto ";
       case "error145":
         return " Non è possibile formulare \"proposte d'acquisto\" ribassando di oltre il 15% il prezzo del venditore!";   // return "  \"Importo della Proposta\" " + val+"  è troppo basso ";
       case "error146":
         return " Non è possibile formulare \"proposte d'acquisto\" al rialzo !";  
       case "error1456":
         return " Non è possibile formulare piu   \"proposte d'acquisto\" ";  
         
        case "no response text":  
         return "MESSAGGIO NON INVIATO \n Server non risponde, riprovare ancora ";
    }        
}
 
function docontact (email, name, msg, imgtxt)
{
 
    if (!name) {
       alert ('Inserire Nome');
       $("name").focus();
       return false; 
    }  
     
    if ( ! email.strip() ) {
        alert ('Inserire Email');
        $('contactemail').focus();  
        return false;
    }

    
    email=email.replace(/\s+$|^\s+/g,""); //trim string
    arr = email.match("^[0-9a-zA-Z]([0-9a-zA-Z\._\-]*)@(([0-9a-zA-Z\-]+\.)+)([0-9a-zA-Z\-]+)$");
    if (!arr) {         
        alert ('Indirizzio Email non corretto' ); 
        $('contactemail').focus();   
        return;
    }
   
    
    if ( !msg.strip() ) {
       alert ('Inserire il tuo messaggio');
       $('message').focus();  
       return false;
    }  
    
    if (  !imgtxt.strip() )
    {
       alert ('Inserire il codice di controllo');
       $('imgcontrol').focus();  
       return false;
    }
   
   // alert ( $('acceptprivacy').checked   +   $('acceptrule').checked);
   
   if ( ! $('acceptprivacy').checked  ||  !$('acceptrule').checked  )  {
       alert (' Bisogna accetare  Informativa sulla Privacy e Regole di utilizzo del Servizio  ');
       
       return false;
   }
    
 
   var adid=$F('adid')  ;
   var zticket=$F('zticket')  ;
   var url = '/action/psscontact.php';
   var pars = 'email='+email+'&adid='+adid+'&zticket='+zticket+'&name='+ encodeURI(escape(name))+'&msg='+ encodeURI(escape(msg)) +'&imgtxt='+ encodeURI(escape(imgtxt)); 
  
   
  new Ajax.Request(url,
  {
     method:'post',
     parameters: pars, 
    
    onCreate: function() {
		// alert('a request has been initialized!');
		    Element.show ('contactloading');	 

		}, 
		onFailure: function ( transport ) {
      var response = transport.responseText || "no response text";
     //  alert('a request onFailure:  ' + response );
          
         Element.hide ('contactloading');
        
         $('_errorcontactdiv').innerHTML= "Failure: Errore durante INVIO EMAIL riprovare (404) ";          
         alert ("\n Failure: (404) Server momentaneamente non disponible , riprovare ancora, grazie ");
    },
    onException: function ( transport ) {
      var response = transport.responseText || "no response text"; 
      // alert('a request onException:  ' + response );
      	if ( response == "no response text") {
      	    Element.hide ('contactloading');
            $('_errorcontactdiv').innerHTML= "Exception: Errore durante invio, riprovare , grazie";
            alert ("\n Exception: Errore durante invio, riprovare , grazie");
      	
        }
    } ,
                
	 
   onComplete: function( transport ) {
        var response = transport.responseText || "no response text"; 
		//alert('a request completed');
		// $('contactloading').innerHTML= "";
	 Element.hide ('contactloading' );  
		 
	                    
  } ,
             
  onSuccess: function( transport ) {

// manca ! popupWindow            
           
           Element.hide ('contactloading' );
           var response = transport.responseText;
           // alert ("\n response " + response );
           
           if (response=='error11' || response=='error25' || response=='error' || response=='error1' || response=='error2' || response=='error3' || response=='error12' ||response=='error13' ||response=='error14' ||response=='error15' ) 
           { 
                   var err = getBidLabel(response);
                   alert( "\n " + err + " \n (" + response + ")" ); // Error! \n
                   
                   
           }  
           else if ( response.substring(0,2) == "OK" ) 
           {
               
               
                $("name").value="";
                $("contactemail").value="";
                $('message').value="";
                $('imgcontrol').value=""; 
                $('contactform').innerHTML = response; //  decodeURI(response); 
                new Effect.Highlight('contactform' , { startcolor: '#EFB586', endcolor: '#A7DFA9' });
              //  Effect.Fade('contactform', {duration: 22}); 
               // Element.hide('contactform');
               alert ("\n" + response.substring(2,response.length ) ); // Success!  
             
                //  response == 'no response text' || 
           }  else { 
              
                $("name").value="";
                $("contactemail").value="";
                $('message').value="";
                $('imgcontrol').value=""; 
               $('contactform').innerHTML = response; //  decodeURI(response); 
               new Effect.Highlight('contactform' , { startcolor: '#EFB586', endcolor: '#A7DFA9' });
               // Effect.Fade('contactform', {duration: 22}); 
               // Element.hide('contactform');
               alert ("\n" + response.substring(2,response.length ) ); // Success! 
           }
           
        
        
            
    }
  });
     
}
 
 
function regencaptcha () {
 
   var rid=Math.random()*11;
   // alert (' rid: ' +rid);
   var answer = confirm('Regenerare il  codice di verifica?')
   if ( answer  ) {
          
       $('imgcaptcha').src="/action/imgtext.php?rid=" + rid; 
       // $('captcha').innerHTML = "<img border=2 src='/action/imgtext.php?rid=" + rid + "'>";
       $('imgcontrol').value = ""; 
       
       return true;
   
   } else 
     return false;

}


function isFloat ( e )
{
  var tem=e;
  // alert (e + ' - isFloat ' ); 
  var comma=false;
  for(i=0; i < e.length; i++ ) {
     var c = e.charAt(i);
     if (c == "," && i>0) // se primo char è un num e non ,
        comma=true;
     
     if ( (i==0 || !i) && c=='0')
         return false;    
  }
  
  if (!comma )
     e +=',0';
  
  // alert (e + '   isFloat Ok' + tem ); 
     
  var reFloat = /^((\d+(,\d*)?\d+))$/
  if( !reFloat.test( e ) )
	{
	   return false;
	} else 
	   return true;
}


  
function makebid(email,bidprice) {

       var error = false;
       //  alert  (   ' orig:  ' +  $("originalprice").value   );
            if (!email) {
                alert ('Inserire Email');
                $("bidemail").focus();
            return false;
            }

            login=email.replace(/\s+$|^\s+/g,""); //trim string
            arr = login.match("^[0-9a-zA-Z]([0-9a-zA-Z\._\-]*)@(([0-9a-zA-Z\-]+\.)+)([0-9a-zA-Z\-]+)$")
            if (!arr) {
                alert('Email non è valida'); 
                $("bidemail").focus(); 
                return;
            }
           
            if ( !bidprice ) {
                alert ('inserire l\'importo della proposta');
                $("bidprice").focus();
                return false;
            } 
            
            // if ( !isInteger ( bidprice ) ) {  || bidprice < 10
            if ( !isFloat( bidprice )  ) {  
                alert (' Importo della Proposta non è valido (es: 12,300 oppure 12300 ) o è troppo basso ');
                $("bidprice").focus();
                return false;
            }
          
          
         if (  $("originalprice") != undefined ) {
              var origprice = $("originalprice").value;
              origprice=1*origprice;
         } else {
               var origprice=bidprice;
         }
         
          if ( origprice  > 0  )  {
                diff = Math.round( origprice - (  origprice  *  ( 15/100 ) )  );
             // $diff=  (int)$show->PRICE  - round((int)$show->PRICE  * ( 15/100 ) ) ;   
             //   alert  ( ' bid: ' + bidprice + ' orig:  ' +   origprice  + ' dif: ' + diff );
                if ( bidprice < diff ) {
                    var err = getBidLabel('error145', bidprice);
                    // alert( "\n " + err + " \n  bidprice < " + diff + ' ' ); // Error! \n
                     alert( "\n " + err + " \n "  ); // Error! \n
                    return false; 
                
                }
                
               /* 
                var origprice = $("originalprice").value;
                if ( bidprice > origprice ) 
                {
                    var err = getBidLabel('error146', bidprice); 
                    alert( "\n " + err + " \n  " +  bidprice + ' > ' + origprice  ); // Error! \n
                    return false; 
                
                }
                */
            
           } 
           
           
  //   onkeypress="return checkNumeric(event, true)" 
  //   onchange="return checkFloatValue(this.value, 'd_content_{attributeid}', 'zinvalidfield', event); {_check_f_js}"
            
            var adid=$('adid').value;            
            var url = '/action/makebid.php';
            var pars = 'bidprice='+bidprice+'&email='+ encodeURIComponent(email)+'&adid='+adid+ '&title='+ encodeURIComponent($F('titleh')) ;
            
		
            
  var myAjax =  new Ajax.Request( url,
  {
     method:'post',
     parameters: pars, 
     onCreate: function(){
		// alert('a request has been initialized!');
		 Element.show ('bidloading');
		// $('spanloading').innerHTML= "<img src='/images/indicator.gif'>";			 

		}, 
    onComplete: function( transport ) {
            
           Element.hide ('bidloading');
           var response = transport.responseText || "no response text";
           
        	 var ss=response.slice(0,3);
        	 ss=ss.toLowerCase();
          //  alert  ( ' response slice: ' + ss +  '  response: '+ response );
        	// if (response.indexOf("error")!=-1) {  
        	if ( ss !="ok-" ) { // error: 
            	// if ( response=='error25' || response=='error' ) { 
            	var err = getBidLabel(response);              
            	error=true;
            	$("bidemail").value="";
              $("bidprice").value="";
              Element.hide('bidform');
              if  ( response=='error5' ) // erorre Blaklistato 
                  Element.hide('bidbutton');
                  
              alert( "\n " + err + " \n (" + response + ")" ); // Error! \n
          
          }  else {       
           
                    
             $("bidemail").value="";
             $("bidprice").value="";
             Element.hide('bidform');  //$('bidform').remove();
             Element.hide('bidbutton');
             $('bidspan').innerHTML = "Tua proposta: &euro; <b>" + bidprice +"</b> è stata inviata"; // response; 
             alert ("\n" + response ); // Success! 
             // set cookies adid + bidprice in session php            
  }                         
           
    },
    onSuccess: function()  { /* alert('Success') */  } ,
    onFailure: function()  { alert('Something went wrong...') } ,
    on403: function()  { alert('403 forbiden Something went wrong...') } ,
    on404: function()  { alert('404  no found Something went wrong...') }   
    
  });
  
 /* onSuccess: onSuccess, 
        onFailure: onError,
        on403: on403, on404: on404
        */
// div id=bidbutton

}

function checkNumeric(e, withCommas )
{
	var unicode = e.charCode? e.charCode : e.keyCode;
	
   // charCode 39 = left key && keyCode 39=' !!!  
   
 //    alert ( ' func checkNumeric: ' + unicode );  
   if (e.charCode==39) // se ' esce
       return false;
       
	if (unicode!=8 && unicode != 39 && unicode != 37 && unicode != 9)
	{ //if the key isn't the backspace key, left, right key (which we should allow)

		if((unicode<48||unicode>57) && unicode != 46 )
		{
			if(unicode == 44 && withCommas)
				return true;
			
			return false; //disable key press
		}

		// check if the key is not a '.' but a 'DEL' which we should allow
		 if( unicode == 46 && e.keyCode==0 ) // disattiva PUNTO "."
		    return false;

// ctr +c 99 ctr + v 118	
	}
	
	// $(divid).style.background='white';
	return true;
}

    

  function ShowPic(img) {
      // alert (img);
        $("mainimg").src = img; 
   }
 
 function showImg() {
 
        Element.hide ("areavideo");  $('tabvid').removeClassName('TabActive'); $('tabvid').addClassName('Tab');
        Element.hide ("areamap");   $('tabmap').removeClassName('TabActive');  $('tabmap').addClassName('Tab');
        Element.show ("areaimg");   $('tabimg').removeClassName('Tab'); $('tabimg').addClassName('TabActive');
 }

 function showMap ( ) {
      
      Element.hide("areavideo");  $('tabvid').removeClassName('TabActive'); $('tabvid').addClassName('Tab');
      Element.hide ("areaimg");  $('tabimg').removeClassName('TabActive'); $('tabimg').addClassName('Tab');  
      Element.show("areamap");   $('tabmap').removeClassName('Tab'); $('tabmap').addClassName('TabActive');
 }

 function showVideo( ) {
     Element.hide ("areaimg");  $('tabimg').removeClassName('TabActive'); $('tabimg').addClassName('Tab');
     Element.hide ("areamap");  $('tabmap').removeClassName('TabActive'); $('tabmap').addClassName('Tab');
     Element.show("areavideo"); $('tabvid').removeClassName('Tab'); $('tabvid').addClassName('TabActive');
 }

    
     function initializeGM ( ) { 
         
        var map = null;
        var geocoder = null;        
        var myg= mygeodata.Placemark[0];
        var country = myg.AddressDetails.Country.CountryNameCode;
        var address =  myg.address;
        var lat =  myg.Point.coordinates[1]; 
        var lng = myg.Point.coordinates[0]; 
   // myg.population
        if (GBrowserIsCompatible()) {
          
          
           map = new GMap2( $("gmap_canvas") );  
           map.clearOverlays();
           if( map.getZoom() == 5)
              var centerbox=2;
              else if( map.getZoom() == 9)
              var centerbox=0.1;
              else
              var centerbox = 0;
           map.addControl(new GSmallMapControl());
			     map.addControl(new GMapTypeControl());
          // map.setCenter(new GLatLng(lat,lng), 5);
           point = new GLatLng(lat +centerbox ,lng);
           map.setCenter(point, 14);  
           map.panTo(point);                 
           
           var gmarkers = [];
			var baseIcon = new GIcon();
			var icon = new GIcon(); 
			icon.image = "/img/ico/puntatore.png";
       icon.shadow = "/img/ico/shade.png";
			icon.iconSize = new GSize(32, 68);
			icon.shadowSize = new GSize(67, 35);
			icon.iconAnchor = new GPoint(15, 35);
			icon.infoWindowAnchor = new GPoint(15, 0);

	
 


           var marker = new GMarker(point,icon); 
           map.addOverlay(marker);
           marker.openInfoWindowHtml( "\n <b>" + title + "<br> \n" + country + " " + address + " </b>");
          //  GEvent.addListener(marker, "mouseover", function() { ew.openOnMarker(marker,miniatura); });
			   	 

           geocoder = new GClientGeocoder();
  
      }
    }
    
 
 function flagThisAd ( adid )  {
  //    alert(' flagit  !!!');
      
  var email = $('flagmail').value.strip(); 
  var adid =$('fadid').value;
  var fdata=$('flagthisad').serialize(true);
//   alert(' fdata ' + fdata.d_type );
 
 // if ( fdata.d_type == undefined ) {
 if ( typeof(fdata.d_type) == 'undefined') {    
         alert ('Selezionare il motivo della segnalazione'); 
        $('d_type_1').focus();        
        return;
 }
 
   if (!email) {
        alert ('Inserire Email');
        $('flagmail').focus();  
        return;
    }
    
     
    arr = email.match("^[0-9a-zA-Z]([0-9a-zA-Z\._\-]*)@(([0-9a-zA-Z\-]+\.)+)([0-9a-zA-Z\-]+)$");
    if (!arr) {         
        alert ('Indirizzio Email non corretto'  ); 
        $('flagmail').focus();   
        return;
    }  
    
    var url = '/action/mailtoadmin.php';
    var pars = 'email='+email+'&adid='+ adid+'&msg='+ encodeURI(escape(fdata.d_type)); 
  //  alert ( pars );  
   new Ajax.Request(url,
  {
     method:'get',
     parameters: pars, 
     onCreate: function(){
      	//	  alert('a request has been initialized!');
      		// Element.show ('loadingmadmin');
            Element.show ('signspamloading'); 
            Element.show ('adflagloading');
            Element.hide ('sendadflagbutton');		 

		}, 
		 onComplete: function () {
    		  // alert('a request has been terminated!');
    		  // Element.hide('signspamloading');
    		   Element.hide ('adflagloading');
    		   Element.show ('sendadflagbutton'); 

		}, 
		
     onSuccess: function( transport ) {
            var response = transport.responseText || "no response text";
            
           //   var response = transport.responseText || "no response text";
           //  'Prototype JavaScript'.startsWith('Pro');
          var resjson=response.toQueryParams();  
                  
         // alert (" response: " + response + ' \n \n  result: ' +  resjson.result + '  \n resultdesc: '  + resjson.resultdesc    ); 
          
          if ( resjson.result == "OK" )  {
                     alert ( decodeURIComponent ( resjson.resultdesc)  );              
                     $('flagmail').value=""; 
                    // Effect.Fade('signspamform', {duration: 22}); 
                     Effect.SlideUp('signspamform', { duration: 3.0 })
                     // Element.hide('signspamform');
                 
                } else {        
                     alert( resjson.resultdesc ); 
                 }
          
            /*  if ( !resjson.isJSON() ){ 
              alert ("\n flagThisAd onSuccess:   " + response + " \n   isJSON " + resjson.isJSON() );
          } else {
                 //  alert ("\n  linewidresult:   " + linewid.result + ' id: '+ linewid.id);
                
                if ( resjson.result == "OK" )  {
                     
                     Element.hide('signspamform');
                     alert ( resjson.resultdesc  );              
                     $('flagmail').value=""; 
                     Effect.Fade('signspamform', {duration: 22}); 
                 
                } else {        
                     alert( resjson.resultdesc ); 
                 }
           }
          */ 
    },
    onFailure: function(){ alert('Something went wrong...') }
  });
  
 
  
   


  }
  


//]]>    