var a;

var GetCat = function(sel) {
  try { 
	sel.disabled = true;
    c = parseInt(sel.options[sel.selectedIndex].value); 
    t = sel.options[sel.selectedIndex].innerHTML;
    $('rechercheSpinner').setStyles({display:'inline'});
    new Ajax('catinfo.xml?id='+(c+1)+'&t='+(new Date().getTime()), { 
	  method:'post', onComplete:function(_a,_b) {
	    try { 
		    
		  a  = Json.evaluate(_a); 
          
		  h  = '<form method="post" action="depot-recherche.html" id="rechercheForm" name="rechercheForm">';
		  h += '<input type="hidden" name="cat" id="cat" value="'+sel.selectedIndex+'" />';
		  
		  for(i=0;i<a.total;i++) {
			  
			h += '<div class="rechercheCat">';
			h += '<b>'+a[i].nom+'</b><br/>';
		    h += '<select id="c['+(i)+']" name="c['+(i)+']" style="font-size:12px;margin-top:5px;">';
		    h += '<option value="0">--- '+a[i].nom+' ---</option>';
		    
		    for(j=0;j<a[i].total;j++) {
			    
			 h += '<option value="'+a[i].values[j]+'">'+a[i].values[j]+'</option>';    
		    }
		    h += '</select>';
		    h += '</div>';
		  }
		  
		  h += '<input type="button" value="Rechercher" onMouseDown="RechercheGo();" />'; 
          h += '</form>';
          
		  $('rechercheSpinner').setStyles({'display':'none'});
		  $('rechercheCats').setHTML(h);
		  sel.disabled = false;
		  
		} catch(e) { console.warn(e.message); }
      }
    }).request();
  } catch(e){ debug(e);}
  
}

// -------------------------------------------------------------------------------

var RechercheGo = function() {

  //self.location = 'depot-recherche.html?'+$('rechercheForm').toQueryString();	
  $('rechercheForm').submit();
	
}

// -------------------------------------------------------------------------------

var SetDepotCat = function(sel) {
	
  try { 
    c = parseInt(sel.options[sel.selectedIndex].value); 
    location.href = 'depot-annonces.html?etape=2&cat='+c;
  } catch(e){debug(e);}
	
}

// -------------------------------------------------------------------------------

var ReadXML = function(xml) {
	
  return Json.evaluate(xml2json(xml));
	
}

// -------------------------------------------------------------------------------

var CaptchaUpdate = function() {
	
 $('captchaImage').src = 'captcha.jpg?v='+((new Date).getTime());	
	
}

// -------------------------------------------------------------------------------

var HighlightContact = function() {
	
  contactFx.cancel();
  new Fx.Scroll(document.body, {duration:'long', transition:Fx.Transitions.Elastic.easeOut, onComplete:function(){
    $('contactContainer').setStyles({'color':'#00f'});
    contactFx.start({'color':'#000'});	
  }}).scrollTo(0,$('contact').getPosition().y);	

}

// -------------------------------------------------------------------------------

var HighlightDialog = function() {
	
  dialogFx.cancel();
  $('authForm').ticket.setStyles({'border-color':'#f00'});
  dialogFx.start({'border-color':'#888'});	

}

// -----------------------------------------------------------------------------------

var SearchClientReset = function() {

	frm=window.document.forms.formNouveau;
	frm.clientFullname.value = '';
	//frm.clientID.value = 0;
	SearchClientClose();

}

// -----------------------------------------------------------------------------------

var SearchClientClose = function() {
	
	frm=window.document.forms.formNouveau;
	$('clientSearch').setStyle('display','none');
	
}

// -----------------------------------------------------------------------------------

var SearchClientFound = function(id,name) {

	frm=window.document.forms.formNouveau;
	frm.clientFullname.disabled = true;
	frm.clientFullname.value = name;
	frm.clientID.value = id;
	SearchClientClose();

}

// -----------------------------------------------------------------------------------

var SearchClient = function(nom) {

	frm=window.document.forms.formNouveau;
	if(nom.length<2) return(SearchClientClose() && false);
	try { scAj.cancel(); }catch(e){}
	
	//frm.clientFullname.disabled = true;
	
	scAj = new Ajax('espace-admin/client-search.html?name='+nom, {
	method:'post'
	,
	onRequest: function() {
	 $('clientSearchResults')
	  .setHTML('');
	 $('clientSearch')
	  .setStyle('display','block')
	  .setStyle('background','#fff url("images/24-0.gif") center center no-repeat');
	 /*$('clientSearchResults')
	  .setStyle('display','none');*/
	}
	,
	onComplete:function(res){ 
	 frm.clientFullname.disabled = false;
	 $('clientSearch')
	  .setStyle('display','block')
	  .setStyle('background','#fff'); 
	 $('clientSearchResults')
	  .setHTML(res)
	  .setStyle('display','block');
	}
	});
	
	scAj.request();

}

// -----------------------------------------------------------------------------------

var ParticulierAuth = function(toDo,annonceID) {
	
 var actionName = '';
 switch(toDo) {
   case 'modifier' : actionName = 'modifier'; break;
   case 'update' : actionName = 'm&ecirc;tre &agrave; jour'; break;
   case 'supprimer' : actionName = 'supprimer'; break;
   default : actionName = '';
 }
 	 
 if(actionName=='') return false;	
 
 if( $('authScreen') == null ) {
	
   new Element('div').setProperties({
     'id' : 'authScreen'
   }).setHTML(''
     +'<div class="dialog">'
     +' <form method="post" action="" name="authForm" id="authForm" onsubmit="return(false)">'
     +' <div class="dialogTitle">Authentification</div>'
     +' <div class="dialogBody">'
     +'  <table width="100%">'
     +'   <tr>'
     +'    <td colspan="2" style="text-align:left;">'
     +'     Pour pouvoir <span id="actionName">executer cette action sur</span> votre annonce, veuillez entrer ci-dessous le num&eacute;ro de ticket'
     +'     re&ccedil;u lors de l\'inscription de votre annonce :'
     +'    </td>'
     +'   </tr>'
     +'   <tr>'
     +'    <td style="text-align:left;"><input type="text" id="ticket" name="ticket" value="" style="width:370px;" /></td>'
     +'   </tr>'
     /*
     +'   <tr>'
     +'    <td style="text-align:left;">Aide : <a href="javascript:void(0)" onmousedown="ParticulierAuthMail('+annonceID+');>';
     +'Ticket perdu ? cliquez ici pour le recevoir par mail</a></td>'
     +'   </tr>'
     */
     +'  </table>'
     +' </div>'
     +' <div class="dialogFooter">'
     +'  <input type="button" onmousedown="ParticulierAuthClose();" value="Annuler" />'
     +'  <input type="submit" id="authGo" value="Authentification" style="font-weight:bold;" />'
     +' </form>'
     +' </div>'
     +'</div>'
   ).injectInside($E('body'));	
   
 }
 
 $$('.dialogTitle')[0].setHTML('Authentification : '+actionName+'');
 $$('.dialog')[0].moveToCenter();
 $('actionName').setHTML(actionName);
 $('authGo').removeEvents().addEvent('mousedown',function(){
   ParticulierAuthGo(this.toDo,this.annonceID);
 }.bind({toDo:toDo,annonceID:annonceID}));
 $('authScreen').setStyles({ 'top' : window.getScrollTop()+'px' ,'display' : 'block'});
 $E('body').setStyles({'overflow':'hidden'});
	
}

// -----------------------------------------------------------------------------------

var ParticulierAuthGo = function(toDo,annonceID) {

 if($('authForm')) {
	 
   var frm = $('authForm');
   dialogFx = new Fx.Styles($('authForm').ticket, {duration:1000, wait:false, transition:Fx.Transitions.Bounce.easeInOut });
   if(frm.ticket.value=='' || frm.ticket.value.replace(/[^a-z0-9]/gi,'').length!=32 ) {
	 alert('Le ticket entré n\'est pas valide');
     HighlightDialog();
     return false;
   }
      
   //self.location =  wwwroot+'ticket/'+(frm.ticket.value)+'/'+toDo+'.html';
   var ticket = frm.ticket.value.replace(/[^a-z0-9]/gi,'');
   new Ajax(wwwroot+'ticket.isValid.php?ticket='+ticket+'&id='+annonceID, { 
	 method:'get', 
	 onComplete:function(resp) {
	   switch(resp) {
		 case 'err': alert('Une erreur est survenue pendant la vérification de votre ticket'); break;
		 case 'no' : alert('Le ticket entré n\'est pas celui correspondant à cette annonce'); break;
		 case 'yes' : 
		 default:
		   self.location =  wwwroot+'ticket/'+(ticket)+'/'+toDo+'.html'; 
		   break;
	   }
	 }
   }).request();
   return false;
   
 }
 
 return false;
	
}

var ParticulierAuthMail = function(annonceID) {
	
 new Ajax(wwwroot+'ticket.sendMail.php?id='+annonceID, { 
   method:'get', 
   onComplete:function(resp) {
	 alert("Le mail a été correctement envoyé.\nVérifiez votre boite mail pour recevoir votre ticket");
     ParticulierAuthClose();
   }
 });
	
}

// -----------------------------------------------------------------------------------

var ParticulierAuthClose = function() {
  
 if( $('authScreen') == null ) { return false; }
  
 var authScreen = $('authScreen');
 authScreen.setStyles({
  'display' : 'none'
 });
 
 $E('body').setStyles({'overflow':'auto'});
 
}

// -----------------------------------------------------------------------------------

Element.implement({
  moveToCenter:function(){
    var size = this.getSize();
    var docSize = document.getSize();
    
    var elTop = parseInt(docSize.y / 2) - 120; //parseInt(size.y / 2);
    var elLeft = parseInt(docSize.x / 2) - (parseInt(this.getStyle('width'))/2); // parseInt(size.x / 2);

    this.setStyles({
        'position' :'absolute',
        'top' : elTop,
        'left' : elLeft
    });
  }
});