/* Server per accodare ad ogni richiesta ajax un parametro con timestamp per evitare caching da parte dei browser */
function urlTimestamp()
{
  var d = new Date();
  return 'ts=' + encodeURIComponent(d.getTime());
}

/* Apre le opzioni di ricerca avanzata per la form principale di ricerca offerte */
function openAdvSearch ()
{
  $('#open').hide();
  $('#close').show();
  if ( $('#aree').length == 0 )
    $('#advancedsearch').slideDown('fast');
  else
    $('#aree').hide( 'fast', function() { $('#advancedsearch').slideDown('fast') } );
}

/* Chiude le opzioni di ricerca avanzata per la form principale di ricerca offerte */
function closeAdvSearch ()
{
  $('#close').hide();
  $('#open').show();
  if ( $('#aree').length == 0 )
    $('#advancedsearch').slideUp('normal');
  else
    $('#advancedsearch').slideUp( 'normal', function() { $('#aree').show() } );
}

/* Apre i "tabs" in home page nel riquadro "offerte di lavoro per categoria, area funzionale, regione" */
function openArea(areaId)
{
  $('.a_aree').css('color', 'green');
  $('.a_aree').css('text-decoration', 'none');
  $('#area-visibile').html($('#'+areaId).html());
  $('#a_'+areaId).css('color', 'orange');
  $('#a_'+areaId).css('text-decoration', 'underline');
}

/* Funzione utilizzata per riempire facebox con un contenuto html */
function loadInFacebox(myHTML) {
  if ( $('div#facebox').is(':hidden') || $('div#facebox').length == 0 )
    $.facebox(myHTML);
  else
    $('div#facebox div.content').html(myHTML);
}

/* Funzione utilizzata nella view offerta per visualizzare il numero delle candidature tramite chiamata ajax */
function getNumCandidature(offertaId)
{
  if ( offertaId == null || isNaN(offertaId) )
    return;

  var myUrl   = contextPath + '/getNumCandidature';
  var myPars  = 'offerta_id=' + encodeURIComponent(offertaId);
  myPars     += '&' + urlTimestamp();

  var numCand = $.ajax({
                   url: myUrl,
                   data: myPars,
                   async: false
                 }).responseText;

  if ( numCand < 0 )
    $.facebox('Il server &egrave; temporaneamente sovraccarico. Ritenta in un altro momento');
  else
    $('#numero_candidature a').fadeOut('slow',function(){$('#numero_candidature').html('<h3 style="border-bottom: none;">' + numCand + '</h3>')});
}

/* Funzione che conta i caratteri inseriti in una textarea  */
function ResidualLength( txId, max )
{
  var a = max - $('#'+txId).val().length;
  if ( a < 0)
  {
    $('#'+txId).val($('#'+txId).val().substring(0, $('#'+txId).val().length + a));
    a = 0;
    alert('Attenzione e\' stata raggiunta la lunghezza massima consentita di ' + max + ' caratteri');
  }
  $('#'+txId+'_ResidualLength').html('massimo numero di caratteri ' + max + '<br />residui ' + a);
}

/* Mostra un oggetto se e' nascosto, lo nasconde se e' visibile */
function mostranascondi(objId)
{
  if($('#'+objId).is(':hidden'))
    $('#'+objId).show();
  else
    $('#'+objId).hide();
}

/* Nasconde un oggetto - Funzione mantenuta per compatibilita' vecchia versione */
function nascondi(x)
{
  $('#'+x).hide();
}

/* Apre popup - Funzione mantenuta per compatibilita' vecchia versione */
function popup(url,w,h,sb)
{
  var d = new Date();
  myWin = window.open(url,'popupwindow'+escape(d.getTime()),'left='+((screen.width/2)-(w/2))+',top='+((screen.height/2)-(h/2)-40)+',screenX='+((screen.width/2)-(w/2))+',screenY='+((screen.height/2)-(h/2)-40)+',Width='+w+',height='+h+',alwaysRaised=yes,history=no,resizable=yes,status=no,scrollbars=' + sb +',menubar=no,toolbar=no,location=no')
  myWin.opener = self;
  myWin.focus();
}

/* Encoding Email: inserisce nel testo un link di tipo mailto.
// ------------------------------------------------------------------------------------------
// mailToId    : l'id di un elemento span (o altro) che conterra' la mail.
// emUsername  : la parte prima della chiocciola della mail
// emDomain    : la parte dopo la chiocciola della mail
// emText      : il testo del link; se null viene usata la stessa mail come anchor text */

function mailTo(mailToId, emUsername, emDomain, emText)
{
  if (!document.getElementById(mailToId)) return false;
  var spanobj = document.getElementById(mailToId);
  var anch = document.createElement("a");
  var email = emUsername + "@" + emDomain;
  var mailto = "mailto:" + email;
  anch.setAttribute("href",mailto);
  spanobj.appendChild(anch);
  if ( emText == null )
    emText = email;
  var txt = document.createTextNode(emText);
  anch.appendChild(txt);
  return true;
}

/* Encoding Email: inserisce nel testo un link di tipo mailto.
// Modificato rispetto al precedente per usare la classe e non l'id, e jquery.
// ------------------------------------------------------------------------------------------
// mailToClass : classe di un elemento span (o altro) che conterra' la mail.
// emUsername  : la parte prima della chiocciola della mail
// emDomain    : la parte dopo la chiocciola della mail
// emText      : il testo del link; se null viene usata la stessa mail come anchor text */

function jMailTo(mailToClass, emUsername, emDomain, emText)
{
  if ( emText == null )
    emText = emUsername + '@' + emDomain;

  $('.' + mailToClass).html('<a href="mailto:' + emUsername + '@' + emDomain + '">' + emText + '</a>');
}


/* Funzione usata in _include/homesearch.jsp (maschera di ricerca offerte)
 * Prepara una url pulita e con url rewrite per il campo testuale
 */

function offertaClearSearch(contextPath)
{
  var formAction  = $('#inputbase').attr('action');
  var firstChar   = '?';

  //Caso speciale: se c'e' un'offerta id, gli altri campi sono inutili (vedi ricerca nell'AH che non considera gli altri campi)
  //Redirect alla ricerca
  if ( ! isBlank($('#fld_query_filter_id').val(), true) )
  {
    location = contextPath + '/controller?action=search_basesearch&id=' + encodeURIComponent($('#fld_query_filter_id').val());
    return;
  }

  //Caso speciale: se c'e' un termine di ricerca, viene costruita una url per l'url rewrite
  if ( ! isBlank($('#fld_query_querystring_1').val(), true) || ! isBlank($('#fld_query_filter_regione').val(), true) )
  {
    var querystring = '';
    if ( ! isBlank($('#fld_query_querystring_1').val(), true) )
      querystring = encodeURIComponent(trim(trim(trim($('#fld_query_querystring_1').val()).replace(/_/g, ' ')).replace(/ /g, '-')).replace(/-+/g, '-'));

    if ( querystring == '-' )
      querystring = '';

    var regione = '';
    if ( ! isBlank($('#fld_query_filter_regione').val(), true) )
    {
      if ( querystring != '' )
        regione = '_';
      regione = regione + encodeURIComponent(trim($('#fld_query_filter_regione').val()).replace(/ /g,'-'), true);
    }
    formAction = contextPath + '/' + querystring + regione + '-s.htm';
  }
  else
  {
    formAction += '?action=search_basesearch';
    firstChar = '&';
  }

  var querystring = '';

  $.each($('#inputbase :input'), function() {
    if ( ! isBlank(this.value, true) && this.name != 'query_querystring_1' && this.name != 'action' && this.name != 'query_fieldname_1' && this.name != 'regione' )
    {
        if ( ( this.type == 'checkbox' || this.type == 'radio' ) && this.checked )
        {
          querystring += firstChar + this.name + '=' + encodeURIComponent(this.value);
          firstChar = '&';
        }
        if ( this.type != 'checkbox' && this.type != 'radio' && this.type != 'submit' && this.type != 'reset' )
        {
          querystring += firstChar + this.name + '=' + encodeURIComponent(this.value);
          firstChar = '&';
        }
    }
  });

  location = formAction + querystring;
}

/* Funzione di servizio che verifica se una variabile e' vuota o nulla
*/

function isBlank ( myVar, trimIt )
{
  if ( myVar == null )
    return true;

  if ( typeof(myVar) == 'object' )
    return false;

  if ( trimIt )
    myVar = trim(myVar);

  if ( myVar == '' )
    return true;

  return false;
}

function trim ( myVar )
{
  while (myVar.substring(0,1) == ' ')
  {
    myVar = myVar.substring(1, myVar.length);
  }
  while (myVar.substring(myVar.length-1, myVar.length) == ' ')
  {
    myVar = myVar.substring(0,myVar.length-1);
  }
  return myVar;
}

/* Apre un popup facebox informativo */
function openInfo(myArea)
{
    var infoBox = '<h2 class="title icon_info">Informazione</h2><div style="padding: 10px 0px 20px 0px;">@text@</div>';
    var info    = null;

    if ( myArea == 'tag-offerta' )
    {
      info  = 'I TAG sono delle etichette, parole chiave che vengono associate a dei contenuti. ';
      info += 'Puoi associare pi&ugrave; TAG ad una offerta in modo che sia subito ricercabile ';
      info += 'nelle prime posizioni per le parole chiave inserite.<br />';
      info += 'Se un candidato ricerca uno dei TAG inseriti, la tua offerta sar&agrave; resa disponibile ';
      info += 'anche se la parola non &egrave; contenuta nel testo dell\'offerta.';
    }

    if ( myArea == 'prodotti-listino' )
    {
      info  = 'Per qualsiasi domanda chiamaci gratis su Skype oppure telefonarci al numero indicato.<br />';
      info += 'I ns operatori sono disponibili dal lunedi al venerdi,<br />';
      info += '9:00 - 13:00 e 15:00 -18:00';
    }

    if ( myArea == 'tag-curriculum' )
    {
      info  = 'I TAG sono delle parole chiave (etichette) che vengono associate a dei contenuti. ';
      info += 'Puoi associare pi&ugrave; TAG ad un CV in modo che sia subito ricercabile ';
      info += 'nelle prime posizioni per le parole chiave inserite.<br />';
      info += 'Le aziende inseriscono TAG specifici nelle offerte, non visibili al pubblico. ';
      info += 'Se uno di essi corrisponde a quello abbinato al tuo CV, sarai avvisato ';
      info += 'automaticamente delle offerte relative. ';
    }

    if ( myArea == 'pdc-acquista-crediti' )
    {
      info  = '<b>Cosa sono i crediti?</b><br />';
      info += 'I crediti vengono utilizzati per visualizzare i profili dei candidati, ';
      info += 'per garantire maggiore visibilit&agrave; alle offerte inserite e per ';
      info += 'promuoverle con  SMS Target ad utenti selezionati.<br /><br />';
      info += 'Acquista i crediti per utilizzare da subito ';
      info += 'i servizi che pi&ugrave; ti interessano.';
    }

    if ( info != null )
      loadInFacebox ( infoBox.replace('@text@', info) );

    return;
}

/* Funzione usata in _include/homesearch.jsp (maschera di ricerca offerte)
* Se il browser non accetta cookie, restituisce false e si ferma
* Se esiste il cookie "avvisoofferta"  che indica se almeno una ricerca e' gia' stata fatta, restituisce true
* Se il cookie non esiste, lo imposta e mostra un popup javascript con le istruzioni per l'avviso email, e restituisce comunque true
* LA CHIAMATA DI QUESTA FUNZIONE RICHIEDE JQUERY E FACEBOX
*/

function avvisoOffertaEmail(contextPath)
{
  if ( ! navigator.cookieEnabled )
    return false;

  //Se querystring e' valorizzato ma ha meno di tre caratteri, esce
  if ( ! isBlank($('#search-querystring').html(),true) && $('#search-querystring').html().length < 3 )
    return false;

  //Almeno uno dei due campi, regione, o query string, deve essere valorizzato
  if ( isBlank($('#search-querystring').html(),true) && isBlank($('#search-regione-id').html(),true) )
    return false;

  var cookies     = document.cookie.split(';');

  for ( var i = 0; i < cookies.length; i++ )
  {
    var tmpArray = cookies[i].split('=');
    if ( tmpArray[0].replace(/^\s+|\s+$/g, '') == "avvisoOffertaEmail" )
      return true;
  }

  scriviCookieAvvisoOffertaEmail();
  openAvvisoOffertaEmail(contextPath);

  return true;
}

function scriviCookieAvvisoOffertaEmail()
{
  var today = new Date();
  today.setTime( today.getTime() );
  //var expires_date = new Date( today.getTime() + (365 * 24 * 60 * 60 * 1000) ); //Un anno
  var expires_date = new Date( today.getTime() + (7 * 24 * 60 * 60 * 1000) ); //Una settimana
  var path = "/";

  //Altri mondi di scrivere il cookie danno malfunzionamenti su IE7, attenzione
  document.cookie = "avvisoOffertaEmail=true;expires=" + expires_date.toGMTString() + ";path=" + path + ";";
}

function openAvvisoOffertaEmail(contextPath)
{
  //Almeno uno dei due campi, regione, o query string, deve essere valorizzato
  if ( ( ! isBlank($('#search-querystring').html(),true) && $('#search-querystring').html().length < 3 )
      || ( isBlank($('#search-querystring').html(),true) && isBlank($('#search-regione-id').html(),true) ) )
  {
    txt =  '<p style="text-align: center; font-weight: bold; padding: 10px 0px;">Impossibile effettuare l\'iscrizione agli avvisi offerta.</p>';
    txt += '<p style="padding: 5px 0px;">';
    txt += 'Per salvare un avviso email occorre cercare per regione, oppure inserire un termine di ricerca di almeno tre caratteri, o entrambi.';
    txt += '</p>';
    $.facebox(txt);
    return;
  }

  $.facebox({ ajax: contextPath + '/' + '_include/avvisoofferta.jsp' });
}

/* Funzione usata in _include/homesearch.jsp (maschera di ricerca offerte)
* Invoca il salvataggio dell'avviso offerta
*/

function salvaAvvisoEmail(contextPath)
{
    $('#avvisoemail_result').hide();
    $('#avvisoemail_result').html();
    $('#avvisoemail_button').hide();
    $('#avvisoemail_loading').show();

    var url = contextPath + '/controller';
    var pars = 'action=avvisoemail_insertfrombox'
             + '&avvisoemail_email=' + encodeURIComponent($('#avvisoemail_email').val())
             + '&avvisoemail_accept=' + encodeURIComponent($('#avvisoemail_accept').is(':checked'))
             + '&avvisoemail_regione_id=' + encodeURIComponent($('#search-regione-id').html())
             + '&avvisoemail_querystring=' + encodeURIComponent($('#search-querystring').html())
             + '&' + urlTimestamp();

    $.ajax({
     type: 'POST',
     url: url,
     data: pars,
     success: function(ResponseText){
      var arr_response = ResponseText.split('|');
      if(arr_response[0]=='error')
      {
        $('#avvisoemail_result').html('<img src="img/alert-ico.gif" />&nbsp;'+arr_response[1]);
        $('#avvisoemail_result').fadeIn();
      }
      if(arr_response[0]=='failed')
      {
        $('#avvisoemail_result').html('<img src="img/alert-ico.gif" />&nbsp;'+arr_response[1]);
        $('#avvisoemail_result').fadeIn();
        $('#avvisoemail_box_list').load(contextPath + '/_include/avvisoemail_box_list.jsp?' + urlTimestamp());
      }
      if(arr_response[0]=='ok') {
        txt =  '<p style="text-align: center; font-weight: bold; padding: 40px 0px;">Iscrizione effettuata</p>';
        txt += '<p style="text-align: center; padding-bottom: 40px;">';
        txt += '<button type="button" onclick="$.facebox.close(); return false;">chiudi</button>';
        txt += '</p>';
        $('div#facebox div.content').html(txt);
        $('#box_avvisoemail_email').val('');
        $('#avvisoemail_box_list').load(contextPath + '/_include/avvisoemail_box_list.jsp?' + urlTimestamp());
      }
      $('#avvisoemail_loading').hide();
      $('#avvisoemail_button').show();
     }
    });
}

/* Funzione per aggiungere un tag all'offerta */
function addTagOfferta(offertaId)
{
  return addTag(offertaId, 'offerta');
}

/* Funzione per rimuovere un tag all'offerta */
function removeTagOfferta(tagId, offertaId)
{
  return removeTag(tagId, offertaId, 'offerta');
}

/* Funzione per aggiungere un tag al curriculum */
function addTagCurriculum(curriculumId)
{
  return addTag(curriculumId, 'curriculum');
}

/* Funzione per rimuovere un tag al curriculum */
function removeTagCurriculum(tagId, curriculumId)
{
  return removeTag(tagId, curriculumId, 'curriculum');
}

/* Funzione per aggiungere un tag */
function addTag(entityId, tipoEntity)
{
  if ( tipoEntity != 'curriculum' && tipoEntity != 'offerta' )
    return;

  $('#tag-error').addClass('hidden');
  $('#tag-error #tag-error-1 span').html('');
  $('#tag-error #tag-error-2 span').html('');
  $('#tag-field-error').addClass('hidden');
  $('#tag-field-error span').html('');

  var tag = $('#fld_tag' + tipoEntity + '_tag').val();
  entityId = parseInt(entityId);

  if ( tag == null || tag == "" )
  {
    $('#tag-error #tag-error-1 span').html('Impossibile salvare il tag');
    $('#tag-error #tag-error-2 span').html('un campo obbligatorio non compilato');
    $('#tag-field-error span').html('obbligatorio');
    $('#tag-error').removeClass('hidden');
    $('#tag-field-error').removeClass('hidden');
    return;
  }

  if ( isNaN(entityId) || entityId <= 0 )
  {
    if ( tipoEntity == 'offerta' )
      window.location.href = contextPath + '/controller?action=azienda_controlpanel';
    if ( tipoEntity == 'curriculum' )
      window.location.href = contextPath + '/controller?action=candidato_controlpanel';
    return;
  }

  //ripulitura minima del tag
  tag = trim(tag);
  tag = tag.replace(/  /g, ' ');
  tag = tag.replace(/  /g, ' ');

  var myUrl   = contextPath + '/controller?action=tag' + tipoEntity + '_insert';
  var myPars  = 'tag' + tipoEntity + '_' + tipoEntity + '_id=' + encodeURIComponent(entityId);
  myPars     += '&tag' + tipoEntity + '_tag=' + encodeURIComponent(tag);
  myPars     += '&' + urlTimestamp();

  var r = $.ajax({
            url: myUrl,
            data: myPars,
            async: false
          }).responseText;

  arrResponse = r.split("|");

  if ( arrResponse[0] == 'notLogged' )
  {
    if ( tipoEntity == 'offerta' )
      window.location.href = contextPath + '/controller?action=azienda_controlpanel';
    if ( tipoEntity == 'curriculum' )
      window.location.href = contextPath + '/controller?action=candidato_controlpanel';
    return;
  }

  if ( arrResponse[0] == 'ok' )
  {
    var templateHtml = '';
    templateHtml    += '<div class="tag' + capitalize(tipoEntity) + ' hidden" id="tagcontainer_@TAGID@">';
    templateHtml    += '<span class="tag' + capitalize(tipoEntity) + '" id="tag_@TAGID@"></span>&nbsp;';
    templateHtml    += '<span class="delTag' + capitalize(tipoEntity) + '" id="del_@TAGID@"><a href="#" onclick="removeTag' + capitalize(tipoEntity) + '(@TAGID@, ' + entityId + '); return false;"><img src="' + contextPath + '/img/delete-ico.gif" alt="elimina" /></a></span>';
    templateHtml    += '</div>';
    templateHtml    += '';

    var tagId = arrResponse[1];
    var tag = arrResponse[2];
    var myNewHTML = templateHtml;
    myNewHTML = myNewHTML.replace(/@TAGID@/g, tagId);
    $('#tag' + tipoEntity + '-list').append(myNewHTML);
    $('#tag' + tipoEntity + '-list #tag_'+tagId).html(tag);
    $('#tag' + tipoEntity + '-list #tagcontainer_'+tagId).removeClass('hidden');
    $('#fld_tag' + tipoEntity + '_tag').val('');
  }
  else
  {
    if ( arrResponse[0] == 'failed' )
    {
      $('#tag-error #tag-error-1 span').html('Impossibile effettuare il salvataggio');
      $('#tag-error #tag-error-2 span').html(arrResponse[1]);
      $('#tag-field-error span').html('controllare');
      $('#tag-error').removeClass('hidden');
      $('#tag-field-error').removeClass('hidden');
    }
    if ( arrResponse[0] == 'error' )
    {
      window.location.href = contextPath + '/error.jsp';
      return;
    }
  }

  return;
}

/* Funzione per rimuovere un tag */
function removeTag(tagId, entityId, tipoEntity)
{
  if ( tipoEntity != 'curriculum' && tipoEntity != 'offerta' )
    return;

  $('#tag-error').addClass('hidden');
  $('#tag-error #tag-error-1 span').html('');
  $('#tag-error #tag-error-2 span').html('');
  $('#tag-field-error').addClass('hidden');
  $('#tag-field-error span').html('');

  entityId = parseInt(entityId);

  if ( isNaN(tagId) || tagId == null )
  {
    $('#tag-error #tag-error-1 span').html('Impossibile eliminare il tag');
    $('#tag-error #tag-error-2 span').html('Il sito &egrave; temporaneamente sovraccarico, si prega di riprovare pił tardi');
    $('#tag-error').removeClass('hidden');
    return;
  }

  if ( isNaN(entityId) || entityId <= 0 )
  {
    if ( tipoEntity == 'offerta' )
      window.location.href = contextPath + '/controller?action=azienda_controlpanel';
    if ( tipoEntity == 'curriculum' )
      window.location.href = contextPath + '/controller?action=candidato_controlpanel';
    return;
  }

  var myUrl   = contextPath + '/controller?action=tag' + tipoEntity + '_delete';
  var myPars  = 'tag' + tipoEntity + '_' + tipoEntity + '_id=' + encodeURIComponent(entityId);
  myPars     += '&tag' + tipoEntity + '_id=' + encodeURIComponent(tagId);
  myPars     += '&' + urlTimestamp();

  var r = $.ajax({
            url: myUrl,
            data: myPars,
            async: false
          }).responseText;

  arrResponse = r.split("|");

  if ( arrResponse[0] == 'notLogged' )
  {
    if ( tipoEntity == 'offerta' )
      window.location.href = contextPath + '/controller?action=azienda_controlpanel';
    if ( tipoEntity == 'curriculum' )
      window.location.href = contextPath + '/controller?action=candidato_controlpanel';
    return;
  }

  if ( arrResponse[0] == 'ok' )
  {
    var tagId = arrResponse[1];
    $('#tag' + tipoEntity + '-list #tagcontainer_'+tagId).hide( function() {$('#tag' + tipoEntity + '-list #tagcontainer_'+tagId).remove()} );
  }
  else
  {
    if ( arrResponse[0] == 'failed' )
    {
      $('#tag-error #tag-error-1 span').html('Impossibile eliminare il tag');
      $('#tag-error #tag-error-2 span').html(arrResponse[1]);
      $('#tag-error').removeClass('hidden');
    }
    if ( arrResponse[0] == 'error' )
    {
      window.location.href = contextPath + '/error.jsp';
      return;
    }

  }

  return;
}

//Reagisce al response ajax dalle azioni richieste per la visibilita'
function checkResponseVisibilita ( responseText, azione, from )
{
  var arrResponse = responseText.split('|');

  if ( arrResponse[0] == 'notLogged' )
  {
    window.location.href = contextPath + '/controller?action=azienda_controlpanel';
    return;
  }

  if ( arrResponse[0] == 'error'  )
  {
    window.location.href = contextPath + '/error.jsp';
    return;
  }

  if ( arrResponse[0] == 'failed' )
  {
    if ( from == 'acquistovis_confermato' )
    {
      var offertaId = arrResponse[1]; //id offerta restituito dall'azione per sicurezza
      $('#visibilita_' + offertaId).attr('checked','checked');
      var myErrorBox = errorBox;
      loadInFacebox ( myErrorBox.replace('@text@', arrResponse[2]) );
    }

    if ( from == 'offerta_list' )
    {
      var offertaId = arrResponse[1]; //id offerta restituito dall'azione per sicurezza
      var info  = arrResponse[2];
      info    += '<div class="clearboth" style="margin: 5px;"></div>';
      if ( azione == 'insert' )
        info    += '<button type="button" class="right-button" id="close-facebox" onclick="$(document).trigger(\'close.facebox\'); $(\'#visibilita_' + offertaId + '\').removeAttr(\'checked\');">Chiudi</button> ';
      if ( azione == 'stop' )
        info    += '<button type="button" class="right-button" id="close-facebox" onclick="$(document).trigger(\'close.facebox\'); $(\'#visibilita_' + offertaId + '\').attr(\'checked\',\'checked\');">Chiudi</button> ';
      info    += '<div class="clearboth"></div>';

      $('#visibilita_' + offertaId).attr('checked','checked');
      var myErrorBox = errorBox;
      loadInFacebox ( myErrorBox.replace('@text@', info) );
    }

    return;

  }

  if ( azione == 'insert' )
  {
    if ( arrResponse[0] == 'ok' )
    {
      if ( from == 'acquistovis_confermato' )
      {
        var offertaId = arrResponse[1]; //id offerta restituito dall'azione per sicurezza
        window.location.href = contextPath + '/controller?action=offerta_list&oid=' + offertaId ;
      }

      if ( from == 'offerta_list' )
      {
        $.facebox.close();
        var offertaId = arrResponse[1]; //id offerta restituito dall'azione per sicurezza
        var creditovis = arrResponse[2]; //crediti rimasti
        var offertavisibilitacount= arrResponse[3]; //numero totale offerte in visibilita

        $('#manage-' + offertaId).attr('src',contextPath + '/img/manage-fg.gif');
        $('#active-' + offertaId).attr('src',contextPath + '/img/active-ico-fg.gif');
        $('#top-' + offertaId + ' td.sx').addClass('sf-sx');
        $('#top-' + offertaId + ' td.dx').addClass('sf-dx');
        $('#top-' + offertaId + ' td.cn').addClass('sf-cn');
        $('#bottom-' + offertaId + ' td.sx').addClass('sf-sx');
        $('#bottom-' + offertaId + ' td.dx').addClass('sf-dx');
        $('#bottom-' + offertaId + ' td.cn').addClass('sf-cn');
        $('#middle-' + offertaId + ' td').css('background-color','#E4F3CA');
        $('#offertavisibilitacount').html(offertavisibilitacount);
        $('#creditovis').html(creditovis);
      }

      return;
    }
    if ( arrResponse[0] == 'noCrediti' )
    {
      if ( from == 'acquistovis_confermato' )
        window.location.href = contextPath + '/controller?action=offerta_list' ;

      if ( from == 'offerta_list' )
      {
        var offertaId = arrResponse[1]; //id offerta restituito dall'azione per sicurezza
        var info = '<div style="text-align: center;">Non hai crediti di visibilit&agrave; disponibili per tue offerte!<br />';
        info    += 'Puoi acquistare i crediti di visibilit&agrave; e portare le tue offerte in "Primo Piano" nella homepage di Lavoro.org e nelle prime ';
        info    += ' posizioni nelle ricerche, rendendole subito visibili a migliaia di candidati.<br />';
        info    += 'Acquista crediti e conferisci valore ai tuoi annunci.</div>';
        info    += '<div class="clearboth" style="margin: 5px;"></div>';
        info    += '<button class="left-button" onclick="$(document).trigger(\'close.facebox\'); $(\'#visibilita_' + offertaId + '\').removeAttr(\'checked\');">Chiudi</button> ';
        info    += '<button class="right-button" onclick="window.location.href=\'' + contextPath + '/controller?action=prodotto_vislist&amp;offerta_id=' + offertaId + '\';">Acquista</button>';
        info    += '<div class="clearboth"></div>';
        var myInfoBox = infoBox;
        loadInFacebox ( myInfoBox.replace('@text@', info) );
      }

      return;
    }
  }

  //Se provengo dalla conferma finale acquisto ciclo visibilita', fermo tutto perche' non e' previsto lo stop del consumo visibilita'.
  if ( from == 'acquistovis_confermato' )
    return;

  if ( azione == 'stop' && arrResponse[0] == 'ok' )
  {
    $.facebox.close();
    var offertaId = arrResponse[1]; //id offerta restituito dall'azione per sicurezza
    var creditovis = arrResponse[2]; //crediti rimasti
    var offertavisibilitacount= arrResponse[3]; //numero totale offerte in visibilita

    $('#manage-' + offertaId).attr('src',contextPath + '/img/manage.gif');
    $('#active-' + offertaId).attr('src',contextPath + '/img/active-ico.gif');
    $('#top-' + offertaId + ' td.sx').removeClass('sf-sx');
    $('#top-' + offertaId + ' td.dx').removeClass('sf-dx');
    $('#top-' + offertaId + ' td.cn').removeClass('sf-cn');
    $('#bottom-' + offertaId + ' td.sx').removeClass('sf-sx');
    $('#bottom-' + offertaId + ' td.dx').removeClass('sf-dx');
    $('#bottom-' + offertaId + ' td.cn').removeClass('sf-cn');
    $('#middle-' + offertaId + ' td').css('background','none');
    $('#offertavisibilitacount').html(offertavisibilitacount);
    $('#creditovis').html(creditovis);
    return;
  }

  return;
}

//Azione chiamata ogni volta che si vuole togliere/aggiungere visibilita' ad un'offerta
function consumovisibilita ( azione, offertaId, from )
{
  if ( from == 'offerta_list' )
    loadInFacebox ( '<div style="text-align: center; padding: 20px 0px;"><img src="' + contextPath + '/img/loading2.gif" alt="" /></div>' );

  if ( from == 'acquistovis_confermato' )
    $('body').css ( 'cursor', 'wait' );

  if ( ( azione != 'insert' && azione != 'stop' ) || isNaN(offertaId) || ( from != 'offerta_list' && from != 'acquistovis_confermato' ) )
    return;

  var myUrl  = contextPath + '/controller';
  var myPars = 'action=consumovisibilita_' + azione;
  myPars    += '&consumovisibilita_offerta_id=' + encodeURIComponent(offertaId);
  myPars    += '&' + urlTimestamp();

  var response = $.ajax({
       url: myUrl,
       data: myPars,
       async: false
  }).responseText;

  checkResponseVisibilita( response, azione, from );
}

//funzione generica per il maiuscolo
function capitalize(stringa)
{
  return stringa.replace( /(^|\s)([a-z])/g , function(m,p1,p2){ return p1+p2.toUpperCase(); } );
};