/*
 * GLOBAL JAVASCRIPT LAYOUT BEHAVIORS
 * (boxes, lightboxes, geolocation etc.)
 * PS : More generic functions can be found in plemiLibrary.js 
 * @todo : i18n ; adapt as a library and / or move / refactor functions into plemiLibrary.js
 */

/* ***************************
 * BASIC STRING & VAR HANDLING 
 *************************** */

var isInteger = function (string) {

	 /* Digits from start to end */
	 var reg_isinteger = /^\d+$/
	 if( reg_isinteger.test(string))
	 	return true;
	 else
	 	return false;
}

var trim  = function (string) {
  if (string != undefined) {
    return string.replace(/^\s+/g,'').replace(/\s+$/g,'');
  }
  else {
    return '';
  }
};

var empty = function ( mixed_var ) {
  var key;

  if (mixed_var === "" ||
      mixed_var === 0 ||
      mixed_var === "0" ||
      mixed_var === null ||
      mixed_var === false ||
      mixed_var === undefined
  ) {
    return true;
  }

  if (typeof mixed_var == 'object') {
    for (key in mixed_var) {
      return false;
    }

    return true;
  }

  return false;
}

// ADDSLASHES & STRIPSLASHES JS EQUIVALENT
add_slashes = function(str) {
  return str.replace(/("|'|\\)/g, "\\$1");
};
strip_slashes = function(str) {
  return str.replace(/\\("|'|\\)/g, "$1");
};

// Replaces all occurrences of search in haystack with replace
function str_replace(search, replace, subject, count) {
    
    //
    // version: 905.3122
    // discuss at: http://phpjs.org/functions/str_replace
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Gabriel Paderni
    // +   improved by: Philip Peterson
    // +   improved by: Simon Willison (http://simonwillison.net)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   bugfixed by: Anton Ongson
    // +      input by: Onno Marsman
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    tweaked by: Onno Marsman
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   input by: Oleg Eremeev
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Oleg Eremeev
    // %          note 1: The count parameter must be passed as a string in order
    // %          note 1:  to find a global variable in which the result will be given
    // *     example 1: str_replace(' ', '.', 'Kevin van Zonneveld');
    // *     returns 1: 'Kevin.van.Zonneveld'
    // *     example 2: str_replace(['{name}', 'l'], ['hello', 'm'], '{name}, lars');
    // *     returns 2: 'hemmo, mars'
    var i = 0, j = 0, temp = '', repl = '', sl = 0, fl = 0,
            f = [].concat(search),
            r = [].concat(replace),
            s = subject,
            ra = r instanceof Array, sa = s instanceof Array;
    s = [].concat(s);
    if (count) {
        this.window[count] = 0;
    }

    for (i=0, sl=s.length; i < sl; i++) {
        if (s[i] === '') {
            continue;
        }
        for (j=0, fl=f.length; j < fl; j++) {
            temp = s[i]+'';
            repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
            s[i] = (temp).split(f[j]).join(repl);
            if (count && s[i] !== temp) {
                this.window[count] += (temp.length-s[i].length)/f[j].length;}
        }
    }
    return sa ? s : s[0];
}

/**
 * @param fields Array : list of fields
 * @return Integer
 */
function countEmptyFields(fields) {
  var i = 0;
  if (fields.length == 1) {
    if (trim(jQuery(fields).val()) == '') {
      i++;
    }
  }
  else {
    fields.each(function(e) {
      if (trim(jQuery(fields[e]).val()) == '') {
        i++;
      }
    });
  }

  return i;
}


// Count the number of elements in a variable (usually an array)
function count( mixed_var, mode ) {
    
    //
    // version: 905.412
    // discuss at: http://phpjs.org/functions/count
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Waldo Malqui Silva
    // +      bugfixed by: Soren Hansen
    // *     example 1: count([[0,0],[0,-4]], 'COUNT_RECURSIVE');
    // *     returns 1: 6
    // *     example 2: count({'one' : [1,2,3,4,5]}, 'COUNT_RECURSIVE');
    // *     returns 2: 6
    var key, cnt = 0;

    if (mixed_var === null){
        return 0;
    } else if (mixed_var.constructor !== Array && mixed_var.constructor !== Object){
        return 1;
    }

    if( mode === 'COUNT_RECURSIVE' ) {
        mode = 1;
    }
    if( mode != 1 ) {
        mode = 0;
    }

    for (key in mixed_var){
        cnt++;
        if( mode==1 && mixed_var[key] && (mixed_var[key].constructor === Array || mixed_var[key].constructor === Object) ){
            cnt += count(mixed_var[key], 1);
        }
    }

    return cnt;
}


/* ***************
 * RATING RELATED
 *************** */

var openNotation = function() {
  $(this).next().show('fast');
  $(this).hide('fast');
  $(this).unbind('click', openNotation);
};


/* **********
 * FORM RESET
 *********** */

$.fn.clearForm = function() {
    return this.each(function() {
   var type = this.type, tag = this.tagName.toLowerCase();
   if (tag == 'form')
     return $(':input',this).clearForm();
   if (type == 'text' || type == 'password' || tag == 'textarea')
     this.value = '';
   else if (type == 'checkbox' || type == 'radio')
     this.checked = false;
   else if (tag == 'select')
     this.selectedIndex = -1;
    });
  };

/* *******************************
 * ONLOAD EVENT HANDLING FUNCTIONS
 ******************************* */

  // Loading scripts storing
  FuncOL = new Array();
  function StkFunc(Obj) {
      FuncOL[FuncOL.length] = Obj;
  };

  // Loading scripts launching
  window.onload = function() {
    var i = 0;
      for(i=0; i<FuncOL.length; i++)
          {FuncOL[i]();}
  };

/* **************
 * LOADING PAGES
 *************** */
  
  LoadEventParam = function(func, param) {
    var param = param || null;
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
      window.onload = func;
    } else {
      window.onload = function() {
        if (oldonload) {
          oldonload();
        }
        if (param) func(param);
        else func();
      };
    }
  }; 


/* *****************************
 * GEOLOCATION TOGGLE SEARCH MODE
 ******************************* */

  // Toggle search mode : simple or advanced
  var toggleGeolocSearchMode = function(){
    $('#geolocalisationSearchResults').empty();
    $('#advanced_search_block, #simple_search_block').toggle();
    var mode = $('#geolocalisationSearch #mode').val();
    if(mode == 'simple'){
      $('#geolocalisationSearch #mode').val('advanced');
      $('#citySearch', $('#geoloc_select_choice')).trigger('focus');
    }
    else if(mode == 'advanced') 
    {
      $('#geolocalisationSearch #mode').val('simple');
      $('#address', $('#geoloc_select_choice')).trigger('focus');
    }
    $(this).text($('#'+mode+'_search_block').attr('title'));
    return false;
  };
  

/* **************************************************************
 * ---------------------- DOCUMENT READY ---------------------- *
 ************************************************************** */

  // RG NOTE : PLEASE ONLY ONE DOCUMENT.READY BLOCK !
  
$(document).ready(function() {


    /* ************
     * LAYOUT LINKS
     **************/
    $('a[href=vide]').click(function(){
      return false;
    });


    /* *********************************
     * SHOWHIDE FUNCTIONS (deprecated ?)
     ********************************* */
    showhide = function() {
	    var namediv = arguments[0];
	    var tohide = arguments[1];
	    if (tohide) $('.'+tohide).hide('normal');
	    if ($('#'+namediv).css('display')=='none') {
        $('#'+namediv).show('normal');
	    } else {
        $('#'+namediv).hide('normal');
	    }
    };

    show = function(namediv) {
      var csscat = arguments[1] || '#';
      var effect = arguments[2] || 'normal';
      if (effect == 'none') {
        $(csscat+namediv).css('display','block');
      }
      else {
        //if ($(csscat+namediv).css('display')=='none') {
        $(csscat+namediv).show(effect);
        //}
      }
    };

    hide = function(namediv) {
      var csscat = arguments[1] || '#';
      var effect = arguments[2] || 'normal';
      if (effect == 'none') {
        $(csscat+namediv).css('display','none');
      }
      else {
        //if ($(csscat+namediv).css('display')!='none') {
        $(csscat+namediv).hide(effect);
        //}
      }
    };
    
    
    /* ******************
     *  GENERIC AJAX CALL
     ******************* */
    // do a simple phpside action
    // that do not require any layout
    doAction = function(action) {
      var calltype = arguments[1] || 'GET';
      var callsync = arguments[2] || false;
      var calldata = arguments[3] || null;
      var calldatatype = arguments[4] || 'json';
      $.ajax({
         type: calltype,
         async: callsync,
         data: calldata,
         datatype: calldatatype,
         url: action,
         error: function(err){
          alert('oups ! looks like there is a problem !');
          r = err;
         },
         success: function(ret){
	      r = ret   
         }
       });
      return r;
    };


    /* *****************
     * GENERIC LIGHTBOX
     ***************** */
    
    /*
     * Open a lightbox (with optional cancel button)
     * @param element: class or id of the element to display
     * @param h: height (disabled)
     * @param w: width
     * @param t: title
     * @param cancel: display a cancel button ? (boolean)
     * @param buttons: buttons to display at the bottom (json) ex: {Annuler:function(){$('#ID_OF_THE_BOX').dialog('close');}}
     **/
    openLBox = function(element, h, w, t, cancel, buttons) {
      var options = {};

      options.dialogClass = 'buttonsLightBox';
//      options.height = h;
      options.modal = true;
      options.position = ['50%', $('#header_content').height()];
      options.resizable = true;
      options.title = t;
      options.width = w;

      if (buttons != undefined) {
        options.buttons = buttons;
      }
      else {
        options.buttons = {};
      }
      if (cancel) {
        options.buttons.Annuler = function() {
          $(this).dialog('close');
        };
      }

      var d = plemiLibrary.dialog(element, null, options);
      $('.ui-dialog').css({'position':'fixed', 'top':$('#header_content').height()});
      
      return d;
    };


    /* **********************
     * GOOGLESURVEY LIGHTBOX 
    *********************** */
    /*
     *  @todo : i18n
     */
    $('#GoogleSurveyButton').click(function() {
      openLBox('#GoogleSurvey', '450px', '580px', 'Votre avis sur cette page !');
    });
    $('#GoogleSurveyButtonNotAuth').click(function() {
      openLBox('#GoogleSurvey', '200px', '460px', 'Votre avis sur cette page !');
    });
    $('#GoogleSurveyLink').click(function() {
      openLBox('#GoogleSurvey', '450px', '580px', 'Votre avis sur cette page !');
    });
    $('#GoogleSurveyLinkNotAuth').click(function() {
      openLBox('#GoogleSurvey', '200px', '460px', 'Votre avis sur cette page !');
    });

    
    /* ************************
     * BUGTRACKING LIGHTBOX 
     ************************ */
    /*
     * @todo : i18n
     * Reprise des declaration css pour ce form
     * temporaire, car je ne sais pas si simple form s'applique ailleur ou non
     * mycolonnegauche.css, ligne 256
     */
    $('#FormBugTrackingButton').click(function() {
      openLBox('#FormBugTracking', '400px', '585px', 'Rapport de Bug !');
    });
    $('#FormBugTrackingLink').click(function() {
      openLBox('#FormBugTracking', '400px', '585px', 'Rapport de Bug !');
    });
    $('#FormBugTrackingLinkNotAuth').click(function() {
      openLBox('#FormBugTracking', '200px', '460px', 'Rapport de Bug !');
    });
    $('#FormBugTrackingLink2').click(function() {
      openLBox('#FormBugTracking', '400px', '585px', 'Rapport de Bug !');
    });
    $('#FormBugTrackingLink3').click(function() {
      openLBox('#FormBugTracking', '400px', '585px', 'Rapport de Bug !');
    });
    closeBugTracking = function() {
      $('#FormBugTracking').dialog('close');
    };

    $('#EnvoyerBugTracking').click(function() {
      var donneesbug = $('#FormBugTracking form').serialize();
      $.ajax({
        type: 'POST',
        url: '/fr/main/sendBugTracking',
        data: donneesbug,
        success: function(retour){
          $('#FormBugTracking').empty();
          $('<p></p>')
            .html(retour)
            .hide()
            .appendTo('#FormBugTracking')
            .show('normal');
          setTimeout(closeBugTracking,15000);
        }
      });
    });


    /* **************************
     * NOT READY FEATURE LIGHTBOX
     ************************** */
    // @todo : i18n
    $('.pasencorefait').click(function() {
      openLBox('#BoitePasEncoreLa', 160, 400, 'En développement', false, {
        'En parler sur le forum': function() {
          $('#BoitePasEncoreLa').dialog('close');
          window.location='/fr/forum';
        },
        'Fermer cette boîte': function() {
          $('#BoitePasEncoreLa').dialog('close');
        }
      });
      return false;
    });


    /* ****************************************************
     * OPEN & CLOSE RIGHTCOL BOXES BEHAVIORS (with cookies)
    ****************************************************** */

    //1 - On teste la presence du cookie, et si absent, on le crée (valable 7 jours)
    if(!$.cookie('cookie_plemi_javascript')){
      $.cookie('cookie_plemi_javascript', 'present', {expires: 7, domain: 'plemi.com', secure: false});
    }

    // 2 - Au clic, on remplit le cookie et on inverse le contenu
    $('#col3_content .bloc_header_showhidebloc a').click(function(){
      var id = $(this).parents(".bloc").attr('id');
      if($(this).hasClass("currentIsShown")){
        $(this).parents(".bloc").find('.bloc_content').slideUp('fast');
        $(this).addClass('currentIsHidden').removeClass('currentIsShown');
        $.cookie(id, 'closed', {expires: 7});
      }
      else {
        $(this).parents(".bloc").find('.bloc_content').slideDown('fast');
        $(this).addClass('currentIsShown').removeClass('currentIsHidden');
        $.cookie(id, 'open', {expires: 7});
      }
      return false;
    });

    // 3 - Maintenant à chaque chargement de page, on teste les cookies, pour tous les id de boite
    $('#col3_content .bloc_header_showhidebloc a').each(function() {
      var id = $(this).parents(".bloc").attr('id');
      var status = $.cookie(id);
      if (status == 'closed') {
        $(this).parents(".bloc").find('.bloc_content').hide();
        $(this).addClass('currentIsHidden').removeClass('currentIsShown');
      }
    });


    /* **************************************
     * MORE DETAILS RIGHT COL BOXES BEHAVIORS
    *************************************** */
    
    //D'abord, on teste les boites droite, pour voir si elles ont une comportement "plus",
    //et si oui, on ajoute le lien plus, et on creer la boite d'ouverture
    $('#col3_content .auto').each(function() {
      if($(this).find('div.contenu_cache').length) {
        var id = $(this).attr('id')+'_plus';
        $(this).find('div.content').append('<span class="openplus">En savoir plus </span>');
        var contentTemp = '<div id="'+id+'" class="boite_droite_plus"><div class="wait"><img src="/css/screen/images/ajax-loader2.gif" alt="Plemi" /></div><p>Boite en savoir plus de la boite '+id+'<p></div>';
        $('#col1_content').prepend(contentTemp);
        }
      });

    $('#col3_content .module .content span.openplus').click(function() {
      var id = '#'+$(this).parent().parent().attr('id')+'_plus'; //on choppe l'id de la boite complete
      var hauteur_col1 = $('#col1').height(); // On prend la hauteur de la colonne gauche
      var hauteur_col3 = $('#col3').height(); // On prend la hauteur de la colonne droite
      if (hauteur_col1 << hauteur_col3) {
        var newHauteur = hauteur_col3;
        $('#col1').css({'height': newHauteur});
        }
      var $panneau = $(id); //On choppe le panneau gauche correspondant à la boite droite
      if ($('#col1 div.header')) { //On fait apparaitre la boite sous le titre de la page, si il y'en a un !!!
        var hauteur_titre = $('#col1 div.header').height();
        newHauteur = newHauteur - hauteur_titre;
        var top = hauteur_titre + 'px';
        $panneau.css({'top': top});
        }
      var hauteur_boite = $(this).parent().height(); // On prend la hauteur de la boite gauche
      $panneau.css({'height': newHauteur}).animate({'left':'0'}, 'slow'); //On lui met la hauteur de la colonne gauche, et on le fait apparaitre
      $(this).parent().find('.contenu_cache').css({'height': hauteur_boite}).animate({'left':'0'}, 'slow'); //idem dans la boite droite


      $('#col3_content .module .header a.btnshowhide').animate({'opacity' : '0'},'slow'); //On fait disparaitre les bouton +- des boite droites
      $('#col3_content .module .content span.openplus').animate({'opacity' : '0'},'slow'); // On cache les en savoir plus des boites droites
      $(this).parent().css({'border-color':'#0089E7'}); //On met les bord content de gris bleu

      //On applique le comportement de fermeture de la boite droite
      $(this).parent().find('.contenu_cache').bind('click', function() {
       var id = '#'+$(this).parent().parent().attr('id')+'_plus';
       var $panneau = $(id);
       $panneau.animate({'left':'671px'}, 'slow');
       $(this).animate({'left':'301px'}, 'slow');
       $('#col3_content .module .header a.btnshowhide').animate({'opacity' : '1'},'slow');
       $('#col3_content .module .content span.openplus').animate({'opacity' : '1'},'slow');
       $(this).parent().css({'border-color':'grey'});
       });

     });

    /* *********************
     * AUTHENTICATION MODULE
    ********************** */
    $('#topnav a.gbox').click(function(){
      $('#topnav').find('.menu').slideUp('normal').end().find('.connexion').slideDown('normal');
      return false;
    });


    /* ***********************
     * CENTRAL TAB VIEW SYSTEM
    ************************ */

    hauteurOnglets = function(){
      var nbBoite = $('ul#onglets li').size();
      //var hauteurOnglet = $('ul#onglets li:nth(1)').css('height');
      //var hauteurOnglet = $('ul#onglets').height();
      var hauteurOnglet = nbBoite * 28;
      //var hauteur_fiche = $('#contenufiche_content').height();
      var hauteurFiche = $('div#contenufiche_content').height();
      //$('#contenufiche_content').css({'height': hauteur_fiche});
      //$('#contenufiche_content').css({'border': '1px solid red'});
      //alert('hauteur onglet : '+hauteurOnglet+'/ hauteur fiche : '+hauteurFiche+' / il y a '+nbBoite+' boites');
      if (hauteurOnglet >= hauteurFiche) {
        //alert('onglets plus haut !');
        var newHauteur = hauteurOnglet * 1.5;
        $('#contenufiche_content').css({'height': newHauteur});
      }
    };

    hauteurOnglets();

    /* **************************************
     * CLOSING HEADER PROFILE IF NOT SUMMARY
    ************************************** */
     $('ul#onglet li.first').toggle(function() {
      $(this).addClass('on').removeClass('off');
      $(this).parent().parent().find('.profilDetails').slideUp('normal');
      }, function () {
      $(this).addClass('off').removeClass('on');
      $(this).parent().parent().find('.profilDetails').slideDown('normal');
     });

     fermeCartouche = function(){
      //$('ul#onglets li.first').css({'border':'1px solid red'});
      //alert($('ul#onglets li.first').attr('class'));
      if ($('ul#onglets li.first').attr('class') != 'first current') {
        $('#cartouche_profil_membre .profilDetails').hide();
        $('#cartouche_profil_membre .titre .switch').trigger('click');
      }
    };

    fermeCartouche();

	
    /* ***********************************
     * GEOLOCATION SEARCH OR EDIT ACTIONS
    ************************************ */
      /*
       * @description New code to use for geolocalisation tab
       */
      jQuery('#geoloc_select a').click(function() {
        plemiLibrary.openLoader();
        jQuery.ajax({
          url: jQuery(this).attr('href'),
          success: function(data) {
            plemiLibrary.closeLoader();
            plemiLibrary.dialog('#geoloc_select_choice', data, {
              title: plemiLibrary.val('geoloc_select_title'),
              modal: true
            });
          }
        });
        return false;
      });
      jQuery('#geoLocalisationBox a.switchMode').live('click', function() {
        jQuery('#geoLocalisationBox div.form_block').toggle();
      });
      jQuery('#geoLocalisationBox form.searchGeoloc').live('submit', function() {

        var elmnts = jQuery('div.required_row input', jQuery(this)), nb = elmnts.length;
        if (countEmptyFields(elmnts) == nb) {
          alert(plemiLibrary.val('field_cannot_be_empty'));
          return false;
        }

        jQuery(this)
          .ajaxSubmit({
            beforeSubmit: function(){
              plemiLibrary.openLoader();
            },
            success: function(data){
              plemiLibrary.closeLoader();
              jQuery('#geoLocalisationBox #geoLocalisationBoxResult').html(data).show();
 		        }
 		      });
          return false;
      });
    	
      /*$('a.locbox').click(function() {
        // Set custom parameters
        var header_height = $('#header_content').height();
        var type_session = $(this).attr('rel');
        var type_lightbox = $(this).attr('title');
        var mode = $('#geolocalisationSearch #mode').val();
        if(mode == 'simple'){
          $('#address',$('#geoloc_select_choice')).trigger('focus');
        }
        else if(mode == 'advanced') {
          $('#citySearch',$('#geoloc_select_choice')).trigger('focus');
        }
        // Set lightbox settings
        $('#geoloc_select_choice').dialog({
          autoOpen: false,
          autoResize: true,
          close: function(event, ui) {
            $('#reset_search').trigger('click');
          },
          dialogClass : 'geoLightbox',
//           height: 470,
          modal: true,
          open : function(event, ui){
            $('#type_session').val(type_session);
          },
          position: ['50%',header_height],
          resizable: true,
          title: type_lightbox,
          width: 550
        }).dialog('open');
        $('.geoLightbox.ui-dialog').css({'position':'fixed', 'top':header_height});
        loadGeolocLbox();
        return false;
      });*/

      // Restore suggestions on reset
      $('#reset_search').click(function(){
        $('#geolocalisationSearchResults').empty().fadeOut();
        $('#shortListVilles').fadeIn();
        $('#autoSuggestCity').empty();
      });


      // Set autocomplete on city field in geo search
      var autocomplete_mousedown;
      $('#geolocalisationSearch #citySearch').keyup(function(){
        if($(this).attr('rev') != $(this).val()){
          $(this).attr('rev', $(this).val());
          autoSuggestCityName($(this).val(), '#autoSuggestCity');
        }
      }).blur(function(){
        if(!autocomplete_mousedown){
          window.setTimeout(
            function(){
              $('#autoSuggestCity').hide();
            },
            500
          );
        }
      }).focus(function(){
        if($('#autoSuggestCity').is(':parent')){
          $('#autoSuggestCity').show();
        }
      });
      $('#autoSuggestCity').mousedown(function() {
        autocomplete_mousedown = true;
      }).mouseup(function() {
        autocomplete_mousedown = false;
        $('#geolocalisationSearch #citySearch').trigger('focus');
      }).blur(function(){
        $('#geolocalisationSearch #citySearch').trigger('blur');
      });
      
  	
  	/* *****************************
  	 * CONNEXIONS ACTIONS AND EVENTS
  	 ***************************** */
  	
    // Standard connector
    $('a.plDemandConnector').live('click', function() {
      var node = $(this);
      $.ajax({
        dataType: 'html',
        type: 'GET',
        url: $(this).attr('href'),
        beforeSend: function(){
          $('img', node).attr('rel', $('img', node).attr('src'));
          $('img', node).attr('src', '/css/images/icons/indicator_bg_white.gif')
        },
        success: function(data){
          plemiLibrary.dialog("#mylbox_demand", data, {title: 'Plemi'});
          $('img', node).attr('src', $('img', node).attr('rel'));
        }
      });
      return false;
    });

    $('a.plConnector').live('click', function() {
      var node = $(this);
      $.ajax({
        dataType: 'json',
        type: 'GET',
        url: $(this).attr('href'),
        beforeSend: function(){
          $('img', node).attr('rel', $('img', node).attr('src'));
          $('img', node).attr('src', '/css/images/icons/indicator_bg_white.gif')
        },
        success: function(data){
          if(data.method == 'custom')
          {
            plemiLibrary.dialog(null, data.html, {title: 'Plemi', close: 'destroy'});
            plemiLibrary._activeDialogNodeCaller = node;
            $('img', node).attr('src', $('img', node).attr('rel'));
          }
          else if (plemiLibrary._activeDialogNodeCaller != '')
          {
            $('#'+plemiLibrary.val('dialog_name')+plemiLibrary._activeDialogId).dialog('close');
            var update = $(plemiLibrary._activeDialogNodeCaller).replaceWith(data.html);
            if (update) {
              plemiLibrary.notify(
                plemiLibrary.val('manageConnexionTitle'),
                plemiLibrary.val('manageConnexionSuccessMsg'),
                '/css/images/icons/notification_done.png'
              );
              plemiLibrary._activeDialogNodeCaller = '';
            }

          }
          else
          {
            var update = $(node).replaceWith(data.html);
            if (update) {
              plemiLibrary.notify(
                plemiLibrary.val('manageConnexionTitle'),
                plemiLibrary.val('manageConnexionSuccessMsg'),
                '/css/images/icons/notification_done.png'
              );
            }
          }
        },
        error: function(){
          $('img', node).attr('src', $('img', node).attr('rel'));
          plemiLibrary.notify(
            plemiLibrary.val('manageConnexionTitle'),
            plemiLibrary.val('manageConnexionErrorMsg'),
            '/css/images/icons/notification_error.png'
          );
        }
      });
      return false;
    });

    // Cancel asked friendship
    $('a.cancelfriendship').click(function() {
      var slug = $(this).attr('id');
      if(slug){
        $.ajax({
         type: 'GET',
         url: '/fr/user/cancelaskfriend/'+slug,
         success: function(retour){
           if (retour=='ok') {
             location.reload()
           }
         }
        });
      }
      return false;
    });
    
    // Validate friendship
    $('a.validatefriendship').click(function() {
      var slug = $(this).attr('id');
      if(slug){
        $.ajax({
         type: 'GET',
         url: '/fr/user/acceptaskfriend/'+slug,
         success: function(retour){
           if (retour=='ok') {
             location.reload()
           }
         }
        });
      }
      return false;
    });
    
    // Refuse friendship
    $('a.refusefriendship').click(function() {
      var slug = $(this).attr('id');
      if(slug){
        $.ajax({
         type: 'GET',
         url: '/fr/user/removeaskfriend/'+slug,
         success: function(retour){
           if (retour=='ok') {
             location.reload()
           }
         }
        });
      }
      return false;
    });
    
    // Remove friendship
    $('a.removefriendship').click(function() {
      var slug = $(this).attr('id');
      if(slug){
        $.ajax({
         type: 'GET',
         url: '/fr/user/removefriendship/'+slug,
         success: function(retour){
           if (retour=='ok') {
             location.reload()
           }
         }
        });
      }
      return false;
    });
    
  /* FINDERS */
  /** TAGS **/
  jQuery('#widget-tags').find('input[type=checkbox]')
    .hide()
    .click(function(){
      var parent = jQuery(this).parent('.widget-element');
      parent.toggleClass('widget-element-active');
      if (jQuery('#widget-tags .widget-element-active').length == 0) {
        jQuery('#widget-tags .tag-alltags')
          .addClass('widget-element-active')
          .find('input[type=checkbox]').attr('checked', 'checked');
      }
      else if (parent.hasClass('tag-alltags')) {
        jQuery('#widget-tags .widget-element-active:not(.tag-alltags)')
          .removeClass('widget-element-active')
          .find('input[type=checkbox]').removeAttr('checked');
      }
      else {
        jQuery('#widget-tags .tag-alltags')
          .removeClass('widget-element-active')
          .find('input[type=checkbox]').removeAttr('checked');
      }
    });

  /** SUBMIT **/
  $("#livefinder form, #bandfinder form, #stagefinder form")
    .bind("submit", function(){
      plemiLibrary.openLoader(plemiLibrary.val('search_loader_text'));
    });

  /** Widget plCheckboxSelector **/
  jQuery(".plCheckboxSelector .plCheckboxSelectorAll")
    .live('click', function(){
      jQuery('.plCheckboxSelector input[type=checkbox]').attr('checked','checked');
    });
  jQuery(".plCheckboxSelector .plCheckboxSelectorNone")
    .live('click', function(){
      jQuery('.plCheckboxSelector input[type=checkbox]').removeAttr('checked');
    });
    
}); // ------------- CLOSING DOCUMENT READY ! -----------------------
