
var searchShortcutIsOpen = false;
var isSearchShortcutMoving = false;
var passwordText = '';
var passage=true;
var indexPath = '';
var isOpened = true;
var isOpeningMenu = false;
var isOpeningNotifications = false;
var clickedOnNotifications = false;
var isTweazTabOpenning = false;
var authNotifPreviewRedirect = true;
var clickedInQuickSearch = false;

$(function() {
        if($('.postToWallTitleDivLeft').length>1)
            {
                $('.fastPostButton').remove();
            }
            else
                {
                    $('.fastPostButton').show();
                }
    
        if($('.rightTopBecomeShareHolder:visible').length>0 && $('.becomeShareHolderForFree:visible').length>0)
            $('.becomeShareHolderForFree').hide();
    
        if($('.notificationIcon').length>0)
            {
                updateNotificationNumbers(); 
                $(this).everyTime(30000, function() {
                       updateNotificationNumbers();
                });
            }
        

        $('html').click(function(){
            //$('.fastSearchPreview:visible').hide();
           // $('.fastSearchPreviewResult').html('');
            $("ul.topnav li.withSubNav .subnav").each(function(){
                
                if(!isOpeningMenu)
                {
                        $(this).slideUp('slow',function(){
                            isOpeningMenu = false;
                        });
                        $(this).parents('.withSubNav').removeClass("subhover");
                }

            });
            if(!clickedOnNotifications)   
                {
                    $('#notificationsPreview').hide();
                    $('#mailsPreview').hide();
                }
                else
                    clickedOnNotifications = false;
                
            /*  if(!clickedInQuickSearch && ($('.fastSearchInput').val() == "" || $('.fastSearchInput').val() == $('.fastSearchInput').attr('rel')) )
                {
                    $('.searchShortcutsContainer').show();  
                }
                else if(clickedInQuickSearch)
                    {
                        clickedInQuickSearch = false;
                    }
            */
        });
     

	$("ul.topnav li.withSubNav").click(function() { //Lorsque l'on clique sur le bouton (flèche)...
                
                if($(this).parent().find("ul.subnav").css('display')=='none')
                    //Les événements suivants sont appliqués à la sous-navigation (menu déroulant).
                    {
                        isOpeningMenu = true;
                        $(this).parent().find("ul.subnav").slideDown('fast',function(){
                            isOpeningMenu = false;
                        }).show(); //Ouverture du menu déroulant lorsque l'on clique sur le bouton
                    }
                else{
                    $(this).parent().find("ul.subnav").slideUp('fast').hide(function(){
                            isOpeningMenu = false;
                        }); //Ouverture du menu déroulant lorsque l'on clique sur le bouton
                }
                    

		$(this).parent().hover(function() {
		}, function(){
			//$(this).parent().find("ul.subnav").slideUp('slow'); //Lorsque l'on survol à l'extérieur du menu déroulé, le menu déroulant remontra
		});

		//Les événements suivant s'appliquent lors du survol du bouton de la flèche.
		}).hover(function() {
			$(this).addClass("subhover"); //Lorsque l'on survol, ajout de la classe "subhover"
		}, function(){	//On Hover Out
			//$(this).removeClass("subhover"); //Lorsque l'on survol à l'extérieur, enlève la classe "subhover"
	});



      $('.fastSearchInput').click(function(){
          clickedInQuickSearch = true;
        $('.searchShortcutsContainer').hide();  
      });
    



      activateRadioBox();

      

        

        activateAutoEmpty();
        //Active les champs seulement numériques
        activateNumericOnlyField();
        //active les tooltips
        activeToolTip();
        //active les textarea élastiques
        if($('#elastic').length>0)
            activateElastic();


  });

function openCloseSearchShortcuts()
{
    var top;
    
    if(!isSearchShortcutMoving)
    {
        isSearchShortcutMoving = true;
        if(!searchShortcutIsOpen)
            top = "0px";
        else
            top = "-121px";
        $('#searchShortcutsMove').animate({
                top: top
              }, 
              600,
              'easeInOutCirc',
              function(){
                  isSearchShortcutMoving = false;
                  if(searchShortcutIsOpen)
                    {
                        $('.searchShortcutsButton a img').attr('src','/images/searchMoreArrows.png');
                        searchShortcutIsOpen = false;
                    }
                else
                    {
                        $('.searchShortcutsButton a img').attr('src','/images/closeSearchMoreArrows.png');
                        searchShortcutIsOpen = true;
                    }
              }
          );    
    }
    
    
}

 function postPublicationPopup(loadFull){
    
        $.fn.colorbox({inline:true, href:"#postPublicationPopup"},function(){
            $('#postToWallLinkElementsDiv .postType.selected a').click();
        });
}

  function hideNotificationsPreview()
  {
      $('#notificationsPreview').hide();
  }
   
   
  function hideNotificationMailsPreview(){
       $('#mailsPreview').hide();
  }
   


  function getPhone(studioToken){


    var href = indexPath + "/communAjaxActions";

     $.ajax(
    {
        type: 'get',
        url: href,
        cache: false,
        data: 'part=getStudioPhone&studioToken='+studioToken,
        success: function(data)
        {
           $.fn.colorbox({width:"400px",inline:true,href:"#studioPhone"});
        }
    });
}

function looksLikeUrl(string){
    if(string.indexOf('http://')!=-1) return true;
    if(string.indexOf('https://')!=-1) return true;
    if(string.indexOf('www.')!=-1) return true;
    return false;
}


function colorateTabs(){
    $('.tableToColorate tr:even').addClass('even');
    $('.tableToColorate tr:odd').addClass('odd');
    $('.tableToColorate').addClass('coloredTable');
}

function colorateTab(table){
    $(table +' tr:even').addClass('even');
    $(table +' tr:odd').addClass('odd');
    $(table).addClass('coloredTable');
}


   /**
   * @name EstSirenValide
   *
   * @param 	Le code SIREN dont on veut vérifier la validité.
   *
   * @return 	Un booléen qui vaut 'true' si le code SIREN passé en
   *                           paramètre est valide, false sinon.
   */
  function EstSirenValide(siren) {
    var estValide;
    if ( (siren.length != 9) || (isNaN(siren)) )
      estValide = false;
    else {
      // Donc le SIREN est un numérique à 9 chiffres
      var somme = 0;
      var tmp;
      for (var cpt = 0; cpt<siren.length; cpt++) {
        if ((cpt % 2) == 1) { // Les positions paires : 2ème, 4ème, 6ème et 8ème chiffre
          tmp = siren.charAt(cpt) * 2; // On le multiplie par 2
          if (tmp > 9)
            tmp -= 9;	// Si le résultat est supérieur à 9, on lui soustrait 9
        }
        else
          tmp = siren.charAt(cpt);
        somme += parseInt(tmp);
      }
      if ((somme % 10) == 0)
        estValide = true;	// Si la somme est un multiple de 10 alors le SIREN est valide
      else
        estValide = false;
    }
    return estValide;
  }

/**
   * @name EstSiretValide
   *
   * @param 	Le code SIRET dont on veut vérifier la validité.
   *
   * @return 	Un booléen qui vaut 'true' si le code SIRET passé en
   *                           paramètre est valide, false sinon.
   */
  function EstSiretValide(siret) {
    var estValide;
    if ( (siret.length != 14) || (isNaN(siret)) )
      estValide = false;
    else {
       // Donc le SIRET est un numérique à 14 chiffres
       // Les 9 premiers chiffres sont ceux du SIREN (ou RCS), les 4 suivants
       // correspondent au numéro d'établissement
       // et enfin le dernier chiffre est une clef de LUHN.
      var somme = 0;
      var tmp;
      for (var cpt = 0; cpt<siret.length; cpt++) {
        if ((cpt % 2) == 0) { // Les positions impaires : 1er, 3è, 5è, etc...
          tmp = siret.charAt(cpt) * 2; // On le multiplie par 2
          if (tmp > 9)
            tmp -= 9;	// Si le résultat est supérieur à 9, on lui soustrait 9
        }
       else
         tmp = siret.charAt(cpt);
         somme += parseInt(tmp);
      }
      if ((somme % 10) == 0)
        estValide = true; // Si la somme est un multiple de 10 alors le SIRET est valide
      else
        estValide = false;
    }
    return estValide;
  }


function activateAutoWithSelect()
{
    if (/MSIE (\d+\.\d+);/.test(navigator.userAgent))
    {
    /* IE obscures the option text for fixed-width selects if the text
     * is longer than the select. To work around this we make the width
     * auto whenever the drop down is visible.
     */
            /* Use mousedown rather than focus because the focus event gets
             * interrupted and the dropdown does not appear
             */
            /* Handle blur if the user does not change the value */
            $("select").each(function(){
                 $(this).blur(function(){
                    $(this).css("width", $(this).attr("origWidth"));
                });
                /* Handle change of the user does change the value */
                  $(this).change(function(){

                    $(this).css("width", $(this).attr("origWidth"));

                 });


                $(this).mousedown(function(){

                    if($(this).css("width") != "auto") {
                        var width = $(this).width();
                        $(this).attr("origWidth", $(this).css("width"));
                         $(this).css("width","auto");
                         //$(this).css("width", "auto").css("position", "absolute");
                        /* if the width is now less than before then undo */
                        if($(this).width() < width) {
                            $(this).css("width", $(this).attr("origWidth"));
                        }
                    }
                });
            });





    }
}

function delStudioFav(studioToken)
{
    var href = indexPath + "/communAjaxActions";

     $.ajax(
    {
        type: 'get',
        url: href,
        cache: false,
        data: 'part=delStudioFav&studioToken='+studioToken,
        success: function(data)
        {
            $('#'+studioToken).fadeOut();
        }
    });
}
function delProFav(proToken)
{
    var href = indexPath + "/communAjaxActions";

     $.ajax(
    {
        type: 'get',
        url: href,
        cache: false,
        data: 'part=delProFav&proToken='+proToken,
        success: function(data)
        {
            $('.'+proToken).fadeOut();
        }
    });
}

function addToFavorite(token,isStudio)
{
    var href = window.location.protocol + "//" + window.location.host + indexPath + "/communAjaxActions";

     $.ajax(
    {
        type: 'get',
        url: href,
        cache: false,
        data: 'part=addToFavorite&token='+token+'&isStudio='+isStudio,
        success: function(data)
        {
            $('.favButton').fadeOut(500,function(){
                $('.isFav').fadeIn();
            });
        }
    });
}
function resizePopup(idForFocus){
    $.fn.colorbox.resize();
    if(idForFocus)
        $(idForFocus).focus();
}

function sendMessagePopup(isFromMailPage,tokenProfile, nameProfile,adToken){
    var tokenLimit = 15;
    if(!adToken)
    {
        adToken = 0;
    }
    if(tokenProfile)
        tokenLimit = 1;
    if(isFromMailPage || $('.mailDetailPanel').length>0)
     {
       closeMailDetail();
     }
    
    var href = indexPath + "/communAjaxActions";
     $.ajax(
    {
        type: 'get',
        url: href,
        cache: false,
        data: 'part=sendMessagePopup&tokenProfile='+tokenProfile+'&isFromMailPage='+isFromMailPage+"&adToken="+adToken+"&tokenLimit="+tokenLimit,
        success: function(data)
        {
            if(data !='0')
            {
                $('#popup').html(data);
                $.fn.colorbox({width:"440px",inline:true, href:"#popup",overlayClose: false},function(){
                    $.fn.colorbox.resize();
                    activateAutoEmpty();

                    $('#postMessageContent').bind('paste',function(){setTimeout(function(){checkMessageForLinks(false,true);},100)});

                    //Initialisation de la liste dynamique de destinataires getProfilesForMailing
                    if(!tokenProfile){
                        $("#messageTargets").tokenInput(href+"?part=getFollowersForMailing", {
                            theme: "Tweaz",
                            preventDuplicates: true,
                            animateDropdown: false,
                            searchDelay: 0,
                            tokenLimit:tokenLimit,
                            onAdd: function (item) {
                                //attention de faire le resize ca fait sortir de l'input, à corriger si possible
                                $.fn.colorbox.resize();
                                $('#messageTargets').focus();
                            }

                        });
                    }else{

                        $("#messageTargets").tokenInput(href+"?part=getFollowersForMailing", {
                            theme: "Tweaz",
                            preventDuplicates: true,
                            animateDropdown: false,
                            tokenLimit:tokenLimit,
                            searchDelay: 0,
                            prePopulate: [
                                {id: tokenProfile, name: nameProfile}
                            ],
                            onAdd: function (item) {
                                //attention de faire le resize ca fait sortir de l'input, à corriger si possible
                                $.fn.colorbox.resize();
                                $('#messageTargets').focus();
                            }
                        });
                    }
                });
            }
            else
            {
                showNeedConnexionPopup();
            }
            
        }
    });
}

function sendNotMessagePopup(tokenProfile, nameProfile){
    $.fn.colorbox({inline:true, href:"#sendNotMessagePopup"});
}

function sendMessage(isFromMailPage,adToken)
{
    var href = indexPath + "/communAjaxActions";
    var object = $('#messageObject').val();
    var targets = $('#messageTargets').val();
    var message = "";
    if(!adToken)
        adToken = '0';
    if($('#postMessageContent').val() != $('#postMessageContent').attr('"rel'))
        message = $('#postMessageContent').val();
    
    if(targets.length>0)
    {
            
        //Apparition du ajax loader
        $('#sendNewMessageButtons,#sendMessagePublicationContainer #targetsEmptyError').hide();
        $('#sendNewMessageButtonsContainer .ajaxLoaderSmall').show();

        if($('#postMessageAttachmentContainer #postToWallAttachmentContainer:visible').length!=0){
            //Si la partie upload de fichier est ouverte
            var type = $('#sendMessagePublicationContainer #postToWallAttachmentContainer #uploadifyDiv').attr('rel');
            var fileContent = escape($('#sendMessagePublicationContainer #fileName').val());
            if($('#sendMessagePublicationContainer #linkedVideoUrl:visible').length>0){
                //on vérifie que le lien est correct
                if(($('#sendMessagePublicationContainer #linkedVideoUrlOk').length>0)&&($('#sendMessagePublicationContainer #linkedVideoUrlOk').html()!='')){
                    $.ajax(
                    {
                        type: 'get',
                        url: href,
                        cache: false,
                        data: {
                            "part":"sendMessage",
                            "hasAttachment":true,
                            "targets":targets,
                            "object":object,
                            "adToken":adToken,
                            "message":message,
                            "uploadType":$('#sendMessagePublicationContainer #linkedVideoType').html(),
                            "fileContent":$('#sendMessagePublicationContainer #linkedVideoType').html(),
                            "image":$('#sendMessagePublicationContainer #linkedVideoImage').html(),
                            "name":$('#sendMessagePublicationContainer #linkedVideoName').html(),
                            "description":$('#sendMessagePublicationContainer #linkedVideoDescription').html(),
                            "url":$('#sendMessagePublicationContainer #linkedVideoUrlOk').html()
                        },
                        success: function(data)
                        {
                            closePopup();
                            if(isFromMailPage)
                               {
                                   loadMails(1,0,1);
                               }
                        }
                    }); 

                }else{
                    $('#sendMessagePublicationContainer #wrongVideoError').effect('pulsate',{times:4});
                    //Disparition du ajax loader
                    $('#sendNewMessageButtonsContainer .ajaxLoaderSmall').hide();
                    $('#sendNewMessageButtons').show();
                }
            }else if($('#sendMessagePublicationContainer #linkedAudioUrl:visible').length>0){
                //on vérifie que le lien est correct
                if(($('#sendMessagePublicationContainer #linkedAudioUrlOk').length>0)&&($('#sendMessagePublicationContainer #linkedAudioUrlOk').html()!='')){
                    $.ajax(
                    {
                        type: 'get',
                        url: href,
                        cache: false,
                        data: {
                            "part":"sendMessage",
                            "hasAttachment":true,
                            "targets":targets,
                            "object":object,
                            "adToken":adToken,
                            "message":message,
                            "uploadType":$('#sendMessagePublicationContainer #linkedAudioType').html(),
                            "fileContent":$('#sendMessagePublicationContainer #linkedAudioType').html(),
                            "image":$('#sendMessagePublicationContainer #linkedAudioImage').html(),
                            "name":$('#sendMessagePublicationContainer #linkedAudioName').html(),
                            "description":$('#sendMessagePublicationContainer #linkedAudioDescription').html(),
                            "url":$('#sendMessagePublicationContainer #linkedAudioUrlOk').html()
                        },
                        success: function(data)
                        {
                            closePopup();
                            if(isFromMailPage)
                            {
                               loadMails(1,0,1);
                            }
                        }
                    });

                }else{
                    $('#sendMessagePublicationContainer #wrongAudioError').effect('pulsate',{times:4});
                    //Disparition du ajax loader
                    $('#sendNewMessageButtonsContainer .ajaxLoaderSmall').hide();
                    $('#sendNewMessageButtons').show();
                }
            }else if($('#sendMessagePublicationContainer #linkedLinkUrl:visible').length>0){
               if($('#sendMessagePublicationContainer #linkedLinkUrlOk').length>0 && $('#sendMessagePublicationContainer #linkedLinkUrlOk').html()!=''){
                        $.ajax(
                        {
                            type: 'get',
                            url: href,
                            cache: false,
                            data: {
                                "part":"sendMessage",
                                "hasAttachment":true,
                                "targets":targets,
                                "object":object,
                            "adToken":adToken,
                                "message":message,
                                "uploadType":'link',
                                "fileContent":'',
                                "image":$('#sendMessagePublicationContainer #linkedLinkImage').html(),
                                "name":$('#sendMessagePublicationContainer #linkedLinkName').html(),
                                "description":$('#sendMessagePublicationContainer #linkedLinkDescription').html(),
                                "url":$('#sendMessagePublicationContainer #linkedLinkUrlOk').html()
                            },
                            success: function(data)
                            {
                                closePopup();
                                if(isFromMailPage)
                                {
                                   loadMails(1,0,1);
                                }
                            }
                        });
                }else{
                    $('#sendMessagePublicationContainer #wrongUrlError').effect('pulsate',{times:4});
                    //Disparition du ajax loader
                    $('#sendNewMessageButtonsContainer .ajaxLoaderSmall').hide();
                    $('#sendNewMessageButtons').show();
                }
            }else if($('#sendMessagePublicationContainer #postToWallDiv #fileName:visible').length>0){
                if($('#sendMessagePublicationContainer #postToWallDiv #fileName:visible').val()!=''){
                    $.ajax(
                    {
                        type: 'get',
                        url: href,
                        cache: false,
                        data: {
                            "part":"sendMessage",
                            "hasAttachment":true,
                            "targets":targets,
                            "object":object,
                            "adToken":adToken,
                            "message":message,
                            "uploadType":type,
                            "fileContent":fileContent,
                            "sleeveTempName":sleeveTempName
                        },
                        success: function(data)
                        {
                            closePopup();
                            if(isFromMailPage)
                            {
                               loadMails(1,0,1);
                            }
                        }
                    });
                }else{
                    $('#sendMessagePublicationContainer #fileEmptyError').effect('pulsate',{times:4});
                    //Disparition du ajax loader
                    $('#sendNewMessageButtonsContainer .ajaxLoaderSmall').hide();
                    $('#sendNewMessageButtons').fadeIn('slow');
                }
            }else{
                $('#sendMessagePublicationContainer #fileEmptyError').effect('pulsate',{times:4});
                //Disparition du ajax loader
                $('#sendNewMessageButtonsContainer .ajaxLoaderSmall').hide();
                $('#sendNewMessageButtons').show();
            }
        }else{
            //Si il n'y a aucun fichier d'envoyé avec le message
            if($('#sendMessagePublicationContainer #postMessageContent').val()=="" || $('#sendMessagePublicationContainer #postMessageContent').val() == $('#sendMessagePublicationContainer #postMessageContent').attr('rel')){
                $('#sendMessagePublicationContainer #titleEmptyError').effect('pulsate',{times:4});
                //Disparition du ajax loader
                $('#sendNewMessageButtonsContainer .ajaxLoaderSmall').hide();
                $('#sendNewMessageButtons').show();
            }else{
                 $.ajax(
                {
                    type: 'post',
                    url: href,
                    cache: false,
                    data: {
                        "part":"sendMessage",
                        "hasAttachment":false,
                        "targets":targets,
                        "object":object,
                        "adToken":adToken,
                        "message":message
                    },
                    success: function(data)
                    {
                        closePopup();
                        if(isFromMailPage)
                        {
                           loadMails(1,0,1);
                        }
                    }
                });
            }
        } 
    }
    else{
        $('#sendMessagePublicationContainer #targetsEmptyError').effect('pulsate',{times:4});
        resizePopup();
    }
}

function detectFlash()
{
	if( navigator.mimeTypes.length > 0 )
	{
		return navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin != null;
	}
	else if( window.ActiveXObject )
	{
		try
		{
			new ActiveXObject( "ShockwaveFlash.ShockwaveFlash" );
			return true;
		}
		catch( oError )
		{
			return false;
		}
	}
	else
	{
		return false;
	}

}


function getProfilePhone()
{
    var href = indexPath + "/communAjaxActions";
    $.ajax(
    {
        type: 'get',
        url: href,
        cache: false,
        data: "part=getProfilePhone",
        success: function(data)
        {
            $('#phoneProfile').html(data);
            $.fn.colorbox({width:"400px", inline:true, href:"#phoneProfile"});
        }
    });
}

function showFavorites(){
    var href = window.location.protocol + "//" + window.location.host + indexPath + "/communAjaxActions";
     $.ajax(
    {
        type: 'get',
        url: href,
        cache: false,
        data: 'part=showFavorites',
        success: function(data)
        {
            $('#favoritesPopup').html(data);
            $.fn.colorbox({width:"790px",inline:true,href:"#favoritesPopup"});
        }
    });
}


function disconnect(){
    var href = window.location.protocol + "//" + window.location.host + indexPath + "/communAjaxActions";
     $.ajax(
    {
        type: 'get',
        url: href,
        cache: false,
        data: 'part=disconnect',
        success: function(data)
        {
                window.location.reload();
        }
    });

}

function checkLogin(type){
    var href = window.location.protocol + "//" + window.location.host + indexPath + "/check_login.html";

    var login = "";
    var password = "";

    if(type=='top'){
        login = trim($('#connexionBarForm').find('#login').val());
        password = trim($('#connexionBarForm').find('#password').val());
        remember = $('#connexionBarForm').find('#rememberMeCheckbox').hasClass('checked');
    }else{
        login = trim($('#connexionNeededForm').find('#login').val());
        password = trim($('#connexionNeededForm').find('#password').val());
        remember = $('#connexionNeededForm').find('#rememberMeCheckbox').hasClass('checked');
    }
     $.ajax(
    {
        type: 'post',
        url: href,
        cache: false,
        data: 'login='+login+'&password='+password+'&remember='+remember,
        success: function(data)
        {
            window.location.reload();
        }
    });
}

function addToCart(token,withLogo)
{
    if(withLogo!=0)
        withLogo = true;
    var href = window.location.protocol + "//" + window.location.host + indexPath + "/communAjaxActions";

     $.ajax(
    {
        type: 'get',
        url: href,
        cache: false,
        data: 'part=addToCart&token='+token,
        success: function(data)
        {
            if(withLogo)
            {
                $('.addToCart').fadeOut(500,function(){
                    $('.delFromCart').fadeIn();
                });
            }


            $.fn.colorbox({width:"400px",inline:true,href:"#basketPopup"});

        }
    });
}


function delFromCart(token)
{
    var href = window.location.protocol + "//" + window.location.host + indexPath + "/communAjaxActions";

     $.ajax(
    {
        type: 'get',
        url: href,
        cache: false,
        data: 'part=delFromCart&token='+token,
        success: function(data)
        {
            $('.delFromCart').fadeOut(500,function(){
                $('.addToCart').fadeIn();
            });
        }
    });
}
function deleteFromFavorite(token,isStudio)
{
    var href = window.location.protocol + "//" + window.location.host + indexPath + "/communAjaxActions";

     $.ajax(
    {
        type: 'get',
        url: href,
        cache: false,
        data: 'part=deleteFromFavorite&token='+token+'&isStudio='+isStudio,
        success: function(data)
        {
             $('.isFav').fadeOut(500,function(){
                $('.favButton').fadeIn();
            });
        }
    });
}

function changeSearchFields(type){

    var href = window.location.protocol + "//" + window.location.host + indexPath + "/communAjaxActions";
    $('#searchFields').fadeOut(500);

         $.ajax(
        {
            type: 'get',
            url: href,
            cache: false,
            data: 'part=changeSearchFields&type='+type,
            success: function(data)
            {
                $('#searchFields').html(data);
                activateJobChange();
                $('#searchFields').fadeIn(500);
                updateSearchResults(type);
                activateRadioBox();
                activateTownsAutoComplete();
                activateAutoEmpty();
                activateAutoWithSelect();
            }
        });
}


function passwordRecoveryPopup(){
    $.fn.colorbox({width:"550px",inline:true,href:"#passwordRecoveryPopup"});
}
function recoverPassword(){
    var mail = $('#mailInput').val();
    var href = window.location.protocol + "//" + window.location.host + indexPath + "/communAjaxActions";

    $.ajax(
    {
        type: 'get',
        url: href,
        cache: false,
        data: 'part=recoverPassword&mail='+mail,
        success: function(data)
        {
            $('#passwordRecoveryPopup .popupContent').css('height',$('#passwordRecoveryPopup .popupContent').height());
            $('#passwordRecoveryPopup .popupContent').html('<div id="passwordSentConfirmation">Votre nouveau mot de passe a été envoyé à l\'adresse <b>'+mail+'</b></div>')
        }
    });
}

function signUpStudio(){
    $.fn.colorbox({width:"550px",height:"780px",inline:true,href:"#signUpFormDiv",overlayClose:false});
    activateTownsAutoComplete();
 }

function isZipCodeValid(zipCode)
{
     var reZip = new RegExp(/(^\d{5}$)|(^\d{5}-\d{4}$)/);
     if (!reZip.test(zipCode))
         return false;
     else return true;
}

function isFieldEmpty(value){
    var newValue = value.replace(/(^\s*)|(\s*$)/g,"");
    if(newValue.length!=0) return false;
    else return true;
}

function trim(value){
    var newValue = value.replace(/(^\s*)|(\s*$)/g,"");
    return newValue;
}
function mytrim(value){
    var newValue = value.replace(/(^\s*)|(\s*$)/g,"");
    return newValue;
}

function isMailValid(mail)
{
    var expr = new RegExp('^[0-9a-z._-]+@{1}[0-9a-z.-]{2,}[.]{1}[a-z]{2,5}$','i');
   // var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
    return expr.test(mail);
}


function isPhoneValid(fld) {
    /*var result = true;
    var stripped = fld.replace(/[\(\)\.\-\ ]/g, '');

   if (fld.value == "") {
        result = false;
    } else if (isNaN(parseInt(stripped))) {
        result = false;
    } else if (!(stripped.length == 10)) {
        result = false;
    }
    return result;*/
    
    // Definition du motif a matcher
	var regex = new RegExp(/^(01|02|03|04|05|06|08)[0-9]{8}/gi);
	
	// Definition de la variable booleene match
	var match = false;
	
	// Test sur le motif
	if(regex.test(fld) && fld.length==10)
	{
		match = true;
	}
	  else
	{
		match = false;
	}
	
	// On renvoie match
	return match;
}


function getDateValue(id)
{
    return $(':date[name='+id+']').data('dateinput').getValue('dd/mm/yyyy');
}
function activateDateInput()
{
    // the french localization
    $.tools.dateinput.localize("fr",  {
       months:        'janvier,f&eacute;vrier,mars,avril,mai,juin,juillet,ao&ucirc;t,' +
                            'septembre,octobre,novembre,d&eacute;cembre',
       shortMonths:   'jan,f&eacute;v,mar,avr,mai,jun,jul,ao&ucirc;,sep,oct,nov,d&eacute;c',
       days:          'dimanche,lundi,mardi,mercredi,jeudi,vendredi,samedi',
       shortDays:     'dim,lun,mar,mer,jeu,ven,sam'
    });


   $(":date").dateinput({
	lang: 'fr',
	format: 'dd/mm/yyyy',
	offset: [5, 0],
        firstDay: 1,
        selectors: true
    });

    $(":input.date").change(function(event, date) {

        var value  = $(this).data('dateinput').getValue();

    	switch($(this).attr('name'))
        {
            case 'dateBR':
                   $(this).parents('tr').find(':date[name=dateER]').data('dateinput').setMin(value,false);
                   $(this).parents('tr').find(':date[name=dateER]').data('dateinput').setValue(value);
                 break;
            case 'dateER':
                    $(this).parents('tr').find(':date[name=dateBP]').data('dateinput').setMin(value,false);
                   $(this).parents('tr').find(':date[name=dateBP]').data('dateinput').setValue(value);
                 break;
            case 'dateBP':
                    $(this).parents('tr').find(':date[name=dateEP]').data('dateinput').setMin(value,false);
                  $(this).parents('tr').find(':date[name=dateEP]').data('dateinput').setValue(value);
                 break;
        }

    });

}

function activateDateInputWithDiv(div)
{
     // the french localization
    $.tools.dateinput.localize("fr",  {
       months:        'janvier,f&eacute;vrier,mars,avril,mai,juin,juillet,ao&ucirc;t,' +
                            'septembre,octobre,novembre,d&eacute;cembre',
       shortMonths:   'jan,f&eacute;v,mar,avr,mai,jun,jul,ao&ucirc;,sep,oct,nov,d&eacute;c',
       days:          'dimanche,lundi,mardi,mercredi,jeudi,vendredi,samedi',
       shortDays:     'dim,lun,mar,mer,jeu,ven,sam'
    });


   div.find(":date").dateinput({
	lang: 'fr',
	format: 'dd/mm/yyyy',
	offset: [5, 0],
        firstDay: 1,
        selectors: true
    });

     div.find(":input.date").change(function(event, date) {

        var value  = $(this).data('dateinput').getValue();

    	switch($(this).attr('name'))
        {
            case 'dateBR':
                   // $(this).parents('.personalFormuleLine').find(':date[name=dateER]').data('dateinput').setMin(value,true);
                   $(this).parents('tr').find(':date[name=dateER]').data('dateinput').setMin(value,true);

            case 'dateER':
                    $(this).parents('tr').find(':date[name=dateBP]').data('dateinput').setMin(value,true);

            case 'dateBP':
                    $(this).parents('tr').find(':date[name=dateEP]').data('dateinput').setMin(value,true);
                break;
        }
    });
}


function activateGallery(){
        var r = (jQuery.browser.msie)? "?r=" + Math.random(10000) : "";
        Galleria.loadTheme('/js/galleria/themes/classic/galleria.classic.js' + r);
        $('.images').galleria({
            image_crop:false,
            clicknext:true,
            transition:'fade',
            transition_speed:700,
            extend: function() {
                this.bind(Galleria.IMAGE, function(e) {
                    $(e.imageTarget).click(this.proxy(function() {
                       //Galleria.get(0).next();
                       //this.openLightbox();
                    }));
                });
                this.bind(Galleria.FULLSCREEN_ENTER, function() {
                    Galleria.get(0).options.image_crop = false;
                    Galleria.get(0).options.background_color = '#000000';
                    Galleria.get(0).rescale();
                });
                this.bind(Galleria.FULLSCREEN_EXIT, function() {
                    Galleria.get(0).options.image_crop = false;
                    Galleria.get(0).rescale();
                });
            },
            data_config: function(img) {
                return {
                    author: $(img).attr('rel') // sets author to "John Doe"
                };
            }
        });
}

function connectError(){
    $.fn.colorbox({width:"400px",height:"140px", inline:true, href:"#popupConnectError"});
}

function popupAbuseReport(culture,isFromCollab){

    var href = window.location.protocol + "//" + window.location.host + indexPath + "/communAjaxActions";

    if(!isFromCollab)
        isFromCollab = false;


    $.ajax(
    {
        type: 'get',
        url: href,
        cache: false,
        data: 'part=popupAbuseReport&isFromCollab='+isFromCollab,
        success: function(data)
        {
            $('#popup').html(data);

            $.fn.colorbox({width:"630px",height:"510px", inline:true, href:"#popup"});

            insertWysiwyg(culture,'abuseReportMessage');
        }
    });
}

function confirmAbuseReport(isFromCollab){

    var href = window.location.protocol + "//" + window.location.host + indexPath + "/communAjaxActions";

    var message  = CKEDITOR.instances['abuseReportMessage.ckeditor'].getData();
    if(!isFromCollab)
        isFromCollab = false;

    $.ajax(
    {
        type: 'get',
        url: href,
        cache: false,
        data: 'part=confirmAbuseReport&isFromCollab='+isFromCollab+'&message='+escape(message),
        success: function(data)
        {
            closePopup();
        }
    });
}

function insertWysiwyg(culture,div)
{
   $('#'+div).html('<textarea name="'+div+'.ckeditor">'+$('#'+div).html()+'</textarea>');
   if (CKEDITOR.instances[div+'.ckeditor']) {
        CKEDITOR.remove(CKEDITOR.instances[div+'.ckeditor']);
    }
    CKEDITOR.config.forcePasteAsPlainText = true;
    CKEDITOR.replace(div+'.ckeditor',
    {
        language: culture,
        toolbar :
            [
                ['Undo','Redo','-','Find','Replace','-','Scayt','Maximize'],
                '/',
                ['Bold','Italic','Underline','Strike'],
                ['Font','FontSize','TextColor','BGColor'],
                ['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],
            ]
    });

}

//active le scrolllbar pour une div dont la class est className
function activateJScrollPane(className)
{
     return $('.'+className).jScrollPane({showArrows:true, scrollbarWidth: 15, arrowSize: 16,autoReinitialise: true});
}
function activateJScrollPaneByElement(element)
 {
     return element.jScrollPane({showArrows:true, scrollbarWidth: 15, arrowSize: 16,autoReinitialise: true});
 }
//ferme la popup
function closePopup()
{
        parent.$.fn.colorbox.close();
}

function activateClicOnHour(idLine){
    $('#'+idLine+' .clickableNiche a').each(function(){
       $(this).click(function(){


            if($(this).parent('td').hasClass('selected'))
                {
                   $(this).parent('td').removeClass('selected');
                   if($(this).parent('td').hasClass('availability'))
                   {
                        $(this).parent('td').next().removeClass('selected');
                   }
                   else
                   {
                        $(this).parent('td').prev().removeClass('selected');
                   }
                }
                else
                {
                    $(this).parent('td').addClass('selected');
                   if($(this).parent('td').hasClass('availability'))
                   {
                        $(this).parent('td').next().addClass('selected');
                   }
                   else
                   {
                        $(this).parent('td').prev().addClass('selected');
                   }
                }
            if($('#nbHoursSelected') != undefined)
           {
               $('#nbHoursSelected').html($('.availability.selected').length);
           }
       });


    });
}

function activateAllClicOnHour(){
    $('.clickableNiche').each(function(){
       $(this).click(function(){
            var niche  = $(this).attr('rel');
            var nicheCell = $(this).parents('tr').find('td[rel='+niche+']');

            if(nicheCell.hasClass('selected'))
                {
                    nicheCell.removeClass('selected')
                }
                else
                    nicheCell.addClass('selected')

           if($('#nbHoursSelected') != undefined)
               {
                   $('#nbHoursSelected').html($('.availability.selected').length);
               }
       });
    });
}

//fonction qui permet de gérer le clic sur les checkbox personnalisées
function activateRadioBox()
{
    $('.checkBox:not([isActivated=1])').click(function(){
            if($(this).hasClass('unchecked'))
            {
                $(this).removeClass('unchecked');
                $(this).addClass('checked');
            }
            else
            {
                $(this).removeClass('checked');
                $(this).addClass('unchecked');
            }
        });

    $('.checkBox:not([isActivated=1])').attr('isActivated',1);
}

function activateRadioButton(rel)
{

    $('.radioButton[rel='+rel+']').click(function(){

        if(!$(this).hasClass('checked'))

            {
                $('.radioButton[rel='+rel+']').each(function(){
                        $(this).removeClass('checked');
                         $(this).addClass('unchecked');
                });
                $(this).removeClass('unchecked');
                $(this).addClass('checked');
            }


    });
}

//fonction qui permet de gérer le clic sur les checkbox personnalisées
function activateSwitch()
{
    $('.switch').each(function(){
        $(this).click(function(){

            if($(this).hasClass('switchOff'))
            {
                $(this).removeClass('switchOff');
                $(this).addClass('switchOn');
            }
            else
            {
                $(this).removeClass('switchOn');
                $(this).addClass('switchOff');
            }
        });
    });

}

//fonction qui permet d'activer les textarea élastiques, grandissant en fonction du contenu
 function activateElastic(textAreaHeight,launchOnHeightChange,launchOnHeightChangeParam){
     
	jQuery.fn.extend({
		elastic: function() {

			//	We will create a div clone of the textarea
			//	by copying these attributes from the textarea to the div.
			var mimics = [
				'paddingTop',
				'paddingRight',
				'paddingBottom',
				'paddingLeft',
				'fontSize',
				'lineHeight',
				'fontFamily',
				'width',
				'fontWeight'];

			return this.each( function() {

				// Elastic only works on textareas
				if ( this.type != 'textarea' ) {
					return false;
				}

				var $textarea	=	jQuery(this),
					$twin		=	jQuery('<div />').css({'position': 'absolute','display':'none','word-wrap':'break-word'}),
					lineHeight	=	parseInt($textarea.css('line-height'),10) || parseInt($textarea.css('font-size'),'10'),
					minheight	=	parseInt($textarea.css('height'),10) || lineHeight*3,
					maxheight	=	parseInt($textarea.css('max-height'),10) || Number.MAX_VALUE,
					goalheight	=	0,
					i 			=	0;

				// Opera returns max-height of -1 if not set
				if (maxheight < 0) {maxheight = Number.MAX_VALUE;}

				// Append the twin to the DOM
				// We are going to meassure the height of this, not the textarea.
				$twin.appendTo($textarea.parent());

				// Copy the essential styles (mimics) from the textarea to the twin
				var i = mimics.length;
				while(i--){
					$twin.css(mimics[i].toString(),$textarea.css(mimics[i].toString()));
				}


				// Sets a given height and overflow state on the textarea
				function setHeightAndOverflow(height, overflow){
					curratedHeight = Math.floor(parseInt(height,10));
					if($textarea.height() != curratedHeight){
						$textarea.css({'height': curratedHeight + 'px','overflow':overflow});
                                                if(launchOnHeightChange)
                                                    {
                                                        if(launchOnHeightChangeParam)
                                                            launchOnHeightChange(launchOnHeightChangeParam);
                                                        else
                                                            launchOnHeightChange();
                                                    }
                                                        
					}
				}


				// This function will update the height of the textarea if necessary
				function update() {

					// Get curated content from the textarea.
					var textareaContent = $textarea.val().replace(/&/g,'&amp;').replace(/  /g, '&nbsp;').replace(/<|>/g, '&gt;').replace(/\n/g, '<br />');

					// Compare curated content with curated twin.
					var twinContent = $twin.html().replace(/<br>/ig,'<br />');

					if(textareaContent+'&nbsp;' != twinContent){

						// Add an extra white space so new rows are added when you are at the end of a row.
						$twin.html(textareaContent+'&nbsp;');

						// Change textarea height if twin plus the height of one line differs more than 3 pixel from textarea height
						if(Math.abs($twin.height() + lineHeight - $textarea.height()) > 3){

							var goalheight = $twin.height()+lineHeight;
							if(goalheight >= maxheight) {
								setHeightAndOverflow(maxheight,'auto');
							} else if(goalheight <= minheight) {
								setHeightAndOverflow(minheight,'hidden');
							} else {
								setHeightAndOverflow(goalheight,'hidden');
							}
                                                    

						}

					}

				}

				// Hide scrollbars
				$textarea.css({'overflow':'hidden'});

				// Update textarea size on keyup, change, cut and paste
				$textarea.bind('keyup change cut paste', function(){
					update();
				});

				// Compact textarea on blur
				// Lets animate this....
				/*$textarea.bind('blur',function(){
					if($twin.height() < maxheight){
						if($twin.height() > minheight) {
							$textarea.height($twin.height());
						} else {
							$textarea.height(minheight);
						}
					}
				});*/

				// And this line is to catch the browser paste event
				$textarea.live('input paste',function(e){setTimeout( update, 250);});

				// Run update once when elastic is initialized
				update();

			});

        }
    });
    $('.elastic:not([activated=1])').elastic();
    if(textAreaHeight)
        $('.elastic:not([activated=1])').css('height',textAreaHeight+'px');
    else
        $('.elastic:not([activated=1])').css('height','20px');
    $('.elastic:not([activated=1])').attr('activated',1);
 }

//fonction qui permet d'activer les tooltips, à utiliser lorsqu'on met à jour du contenu en ajax'
 function activeToolTip()
 {
     //supprime les tooltip dèja affiché pour éviter les bugs
     $('.tipsy').each(function(){
         $(this).remove();
     })

     //active le plugin pour les tooltips
     $('.tooltipOn').tipsy({gravity:'a',html:true});
 }


 function activateAutoEmpty()
 {
       //gestion des textes par défaut dans formulaire de connexion
        $("input[class*='autoEmpty']").each(function(){
            $(this).css('color','#939393');
            $(this).focus(
                function(){
                    $(this).css('color','#000');
                    var text = $(this).attr('rel');
                    if($(this).val() == text) {
                        $(this).val("");
                    }

                }
            );

            $(this).blur(
                function(){
                    var text = $(this).attr('rel');
                    if($(this).val() == '') {
                        $(this).css('color','#c5c5c5');
                        $(this).val(text);
                     }
                }
            );
        });

        //gestion des textes par d�faut dans formulaire de connexion
        $("input[class*='autoEmptyOnce']").each(function(){
            $(this).css('color','#939393');
            $(this).focus(
                function(){
                    $(this).css('color','#000');
                    var text = $(this).attr('rel');
                    if($(this).val() == text) {
                        $(this).val("");
                    }
                    $(this).attr('rel',"");

                }
            );


        });

        //gestion des textes par défaut dans formulaire de connexion
        $("textarea[class*='autoEmpty']").each(function(){
            $(this).css('color','#c5c5c5');
            $(this).focus(
                function(){
                    if($(this).attr('isBold')=='1')
                        $(this).css('font-weight','normal');
                    $(this).css('color','#000');
                    var text = $(this).attr('rel');
                    if($(this).val() == text) {
                        $(this).val("");
                    }

                }
            );

            $(this).blur(
                function(){
                    
                    var text = $(this).attr('rel');
                    if($(this).val() == '') {
                        $(this).css('color','#c5c5c5');
                        if($(this).attr('isBold')=='1')
                        $(this).css('font-weight','bold');
                        $(this).val(text);
                     }
                }
            );
        });

         $("input[class*='autoEmpty2']").each(function(){
            $(this).css('color','#939393');
            $(this).focus(
                function(){
                    $(this).css('color','#000');
                    
                    this.type = 'password';
                    var text = $(this).attr('rel');
                    if($(this).val() == text) {
                        $(this).val("");
                    }
                }
            );

            $(this).blur(
                function(){
                    var text = $(this).attr('rel');
                    if($(this).val() == '') {
                        $(this).css('color','#c5c5c5');
                        $(this).val(text);
                     }
                }
            );
        });
 }



 //fonction permettant d'automatiquement supprimer les caractères dans un champ numérique
 function activateNumericOnlyField()
 {
    $('.numericOnly').each(function(){
        //Suppression automatique des caractères non numériques
        $(this).keyup(function(e){

            var chaine = $(this).val();
            var expr =  new RegExp("[^0-9]", "g");
            chaine=chaine.replace(expr,"");

            var i;
            i=parseInt(chaine);

           /* if(passage){
                //si touche +
                if(e.keyCode==107){
                        i++;
                        passage=false;
                }
                //si touche -
                else if(e.keyCode==109)
                {
                        if(i>0){
                            i--;
                        }
                        passage=false;
                }

                $(this).val(i);
                return false;
            }
            else{
                passage=true;

                $(this).val(i);
                return false;
            }*/

            if(!isNaN(i)){
                $(this).val(i);
            }else $(this).val('');

        });
     });
 }


function activateExpander(classDiv,slicePoint,widow,expandSpeed)
 {

      $('div.'+classDiv).expander({
        slicePoint:      slicePoint,  // default is 100
        widow: widow,
        expandSpeed: expandSpeed,
        expandText:         '<img src="/images/studio/readMore.png" style="float:right">', // default is 'read more...'
        userCollapseText:  '<img src="/images/studio/readLess.png" style="float:right">',  // default is '[collapse expanded text]'
        expandEffect: 'fadeIn'
      });
 }


 function activateTweazWrappers(closeOpenned){



      $('.TweazWrapper:not([wrapActivated=1])').click(function(){

         if(closeOpenned)
         {

            $(this).siblings().each(function(){
                if(!$(this).hasClass('TweazWrapper'))
                    $(this).slideUp();

             });
         }
        if(($(this).next().css('display')=='none'))
        {
            $(this).next().slideDown(200);
            $(this).find('.showMore').addClass('showLess');
            $(this).find('.showMore').removeClass('showMore');
        }
        else
        {
            $(this).next().slideUp(200);
            $(this).find('.showLess').addClass('showMore');
            $(this).find('.showLess').removeClass('showLess');
        }
   });
    $('.TweazWrapper:not([wrapActivated=1])').attr('wrapActivated','1');
 }

 function activatePagination(idTable,culture,nbLines)
 {
     if(!nbLines) nbLines=10;
     $('#'+idTable).dataTable( {
         "sPaginationType": "full_numbers",
         "oLanguage":
             {
             "sUrl": "/js/i18n/data-table/"+culture+".txt"
              },
         "aaSorting": [],
         "bLengthChange": false,
         "bInfo": false,
         "bAutoWidth": false,
         "bFilter": false,
         "iDisplayLength":nbLines
     } );
 }

///* Create an array with the values of all the select options in a column */
//$.fn.dataTableExt.afnSortData['nbDateEmpty'] = function  ( oSettings, iColumn )
//{
//	var aData = [];
//	$( 'td:eq(0) select', oSettings.oApi._fnGetTrNodes(oSettings) ).each( function () {
//		aData.push( $(this).val() );
//	} );
//	return aData;
//}
//$.fn.dataTableExt.afnSortData['nbHavingEquipment'] = function  ( oSettings, iColumn )
//{
//	var aData = [];
//	$( 'td:eq(3) select', oSettings.oApi._fnGetTrNodes(oSettings) ).each( function () {
//		aData.push( $(this).val() );
//	} );
//	return aData;
//}


  function activateSearchPagination(idTable,culture,nbLines)
 {
$.fn.dataTableExt.oSort['currency-asc'] = function(a,b) {
	/* Remove any commas (assumes that if present all strings will have a fixed number of d.p) */
	var x = a == "-" ? 0 : a.replace( /,/g, "" );
	var y = b == "-" ? 0 : b.replace( /,/g, "" );

	/* Remove the currency sign */
	x = x.substring(0,x.length-2);
	y = y.substring(0,y.length-2);

	/* Parse and return */
	x = parseFloat( x );
	y = parseFloat( y );
	return x - y;
};

$.fn.dataTableExt.oSort['currency-desc'] = function(a,b) {
	/* Remove any commas (assumes that if present all strings will have a fixed number of d.p) */
	var x = a == "-" ? 0 : a.replace( /,/g, "" );
	var y = b == "-" ? 0 : b.replace( /,/g, "" );

	/* Remove the currency sign */
	x = x.substring(0,x.length-2);
	y = y.substring(0,y.length-2);

	/* Parse and return */
	x = parseFloat( x );
	y = parseFloat( y );
	return y - x;
};
 if(!nbLines) nbLines=10;

     $('#'+idTable).dataTable( {
         "sPaginationType": "full_numbers",
         "aoColumnDefs": [
                            {"bVisible": false,"aTargets": ['hideTh']},
                            {"asSorting": [ "desc" ],"aTargets": [ "lastConnexion" ]},
                            {"sSortDataType": "nbHavingEquipment","asSorting": [ "asc" ][ "desc" ],"aTargets": [ "sortByNbHavingMateriel" ]},
                            {"sSortDataType": "nbDateEmpty","asSorting": [ "asc" ][ "desc" ],"aTargets": [ "sortByNbDateEmpty" ]},
                            {"sType": [ "currency" ],"aTargets": [ "sortByCurrency" ]}
                         ],

         "oLanguage":
             {
             "sUrl": "/js/i18n/data-table/"+culture+".txt"
              },
         "bLengthChange": false,
         "bInfo": false,
         "bAutoWidth": false,
         "bFilter": false,
         "iDisplayLength":nbLines
     } );


 }

  function activateSearchPaginationPro(idTable,culture,nbLines)
 {

 if(!nbLines) nbLines=10;

     $('#'+idTable).dataTable( {
         "sPaginationType": "full_numbers",
         "aoColumnDefs": [
                            {"bVisible": false,"aTargets": ['hideTh']},
                            {"sSortDataType": "nbHavingEquipmentPro","asSorting": [ "asc" ][ "desc" ],"aTargets": [ "sortByNbHavingMateriel" ]},
                            {"asSorting": [ "currency-asc" ][ "currency-desc" ],"aTargets": [ "sortByCurrency" ]}
                         ],

         "oLanguage":
             {
             "sUrl": "/js/i18n/data-table/"+culture+".txt"
              },
         "bLengthChange": false,
         "bInfo": false,
         "bAutoWidth": false,
         "bFilter": false,
         "iDisplayLength":nbLines
     } );


 }

 function ActivatePaginationWithThemeFR(idTable)
{
    $('#'+idTable).dataTable( {
         "bJQueryUI": true,
         "sPaginationType": "full_numbers",
         "oLanguage":
             {
             "sUrl": "/js/i18n/data-table/frTheme.txt"
              },
         "bLengthChange": false,
         "bInfo": false,
         "bAutoWidth": false
     } );
}

function quickSearch(doReturn){
    var href = window.location.protocol + "//" + window.location.host + indexPath + "/communAjaxActions";
    var search = $('#quickSearch input').val();
    if(search == $('#quickSearch input').attr('rel'))
        search = "";
    $.ajax(
    {
        type: 'get',
        url: href,
        cache: false,
        data: 'part=quickSearch&search='+search,
        success: function(data)
        {
            window.location.href=data;
        }
    });
   if(doReturn)
       return false;
}
function launchSearch(doReturn,isOnTuto)
{
    var href = indexPath + "/communAjaxActions";
    var searchEl = $('.fastSearchInput');
    if(isOnTuto)
        searchEl = $('.tweazFonctionnementBottom3 .fastSearchInput');
    
    var search = searchEl.val();
    if(search == searchEl.attr('rel'))
        search = "";
    $.ajax(
    {
        type: 'get',
        url: href,
        cache: false,
        data: 'part=launchSearch&search='+search,
        success: function(data)
        {
            window.location.href=data;
        }
    });
   if(doReturn)
       return false;
}

function activateStudioTypesChange()
{
    $('#studioTypes').change(function(){
        updateSearchStandardForms();

    });
}

function onFormChange(){
     if($('#standardForms').val() == 4)
    	{
        	if($('.searchByNbDaysText').css('display') != 'none')
    		{
        		$('#nbHoursByDayLine').fadeOut('200',function(){
        			$('#searchByNbTracks').fadeIn('200');
        		});
        		$('.searchByNbDaysText').fadeOut('200',function(){
        			$('.searchByNbTracksText').fadeIn('200');
        		});
    		}
    	}
        else
    	{
        	if($('#searchByNbTracks').css('display') != 'none')
    		{
        		$('#searchByNbTracks').fadeOut('200',function(){
        			$('#nbHoursByDayLine').fadeIn('200');
        		});
        		$('.searchByNbTracksText').fadeOut('200',function(){
        			$('.searchByNbDaysText').fadeIn('200');
        		});
    		}
    	}
}

function activateFormsChange(){
    $('#standardForms').change(function(){
        onFormChange();
    });
}

function updateSearchStandardForms()
{
    var idStudioType = $('#studioTypes').val();
    var href = indexPath + "/communAjaxActions";
    $.ajax(
    {
        type: 'post',
        url: href,
        cache: false,
        data: "part=updateSearchStandardForms&idStudioType="+idStudioType,
        success: function(data)
        {
            $('#standardFormsContainer').html(data);
            onFormChange();
            activateFormsChange();
        }
    });
}



function switchDispoMode(){
    if($('#fromUntilMode').hasClass('checked'))
    {
           $('#whileHour').attr('disabled',true);
           $('#fromHour').attr('disabled',false);
           $('#untilHour').attr('disabled',false);

    }
    else
    {
        $('#whileHour').attr('disabled',false);
        $('#fromHour').attr('disabled',true);
        $('#untilHour').attr('disabled',true);
    }
}


function submitIngeSonSearch()
{
    if($('#hub').css('display') != 'none')
	{
		$('#hub').fadeOut('500',function(){
			$('#searchResultContainer').slideDown('500');
		})
	}
    var href = indexPath + "/communAjaxActions";
    var idRegion = $('#regionsSelect').val();
    var idDepartment = $('#departmentsSelect').val();
    var town = $('#town').val();
    if(town == $('#town').attr('rel'))
        town = "";
    var specialitiesSelect = $('#specialitiesSelect').val();
    var withDispo = 1;

    if($('#checkBoxDispo').hasClass('switchOff'))
        withDispo = 0;
    var dateDispo = $(':date[name=dateDispo]').data('dateinput').getValue('dd/mm/yyyy');
    var nbDaysDispo = $('#nbDaysDispo').val();
    var fromHour = 0;
    var untilHour = 0;
    var whileHour = 0;
    if($('#fromUntilMode').hasClass('checked'))
    {
        fromHour = $('#fromHour').val();
        untilHour = $('#untilHour').val();
        whileHour = 0;
    }
    else
    {
        fromHour = 0;
        untilHour = 0;
        whileHour = $('#whileHour').val();
    }

    var expInge  = $('#expInge').val();
    var consolesExp  = $('#consolesExp').val();
    var recordersExp  = $('#recordersExp').val();
    var softwaresExp  = $('#softwaresExp').val();
    var languagesExp  = $('#languagesExp').val();

    var consoles = $('#consoles').val();
    var recorders = $('#recorders').val();
    var softwares = $('#softwares').val();
    var language = $('#language').val();

    var brands = "";
    var references = "";

    $('#selectedBrands li.padded').each(function(){
       if(brands.length>0)
           brands += "|";
       brands += $(this).attr('rel');
    });

    $('#selectedReferences li.padded').each(function(){
       if(references.length>0)
           references += "|";
       references += $(this).attr('rel');
    });

    $('#searchResult').fadeOut(function(){
        $('#searchResult').html('<div class="ajax-loader"><img src="/images/studio/ajax-loader-bar.gif" alt="" /></div>');
        $('#searchResult .ajax-loader').show();
        $('#searchResult').show();
        $.ajax(
        {
            type: 'get',
            url: href,
            cache: false,
            data: {
                    "part":"submitIngeSonSearch",
                    "idRegion":idRegion,
                    "idDepartment":idDepartment,
                    "town":town,
                    "specialitiesSelect":specialitiesSelect,
                    "dateDispo":dateDispo,
                    "nbDaysDispo":nbDaysDispo,
                    "fromHour":fromHour,
                    "untilHour":untilHour,
                    "whileHour":whileHour,
                    "expInge":expInge,
                    "consolesExp":consolesExp,
                    "recordersExp":recordersExp,
                    "softwaresExp":softwaresExp,
                    "languagesExp":languagesExp,
                    "consoles":consoles,
                    "recorders":recorders,
                    "softwares":softwares,
                    "language":language,
                    "brands":brands,
                    "withDispo":withDispo,
                    "references":references
            },
            success: function(data)
            {
                $('#searchResult').hide();
                $('#searchResult').html(data);
                $('#searchResult').fadeIn();
                //active le plugin pour les tooltips
                activateSearchPagination('searchResults','fr');
                activeToolTip();
            }
        });
    });
}

function submitTechSearch()
{
    if($('#hub').css('display') != 'none')
	{
		$('#hub').fadeOut('500',function(){
			$('#searchResultContainer').slideDown('500');
		})
	}
    var href = indexPath + "/communAjaxActions";
    var idRegion = $('#regionsSelect').val();
    var idDepartment = $('#departmentsSelect').val();
    var town = $('#town').val();
    if(town == $('#town').attr('rel'))
        town = "";
    var specialitiesSelect = $('#specialitiesSelect').val();
    var withDispo = 1;

    if($('#checkBoxDispo').hasClass('switchOff'))
        withDispo = 0;
    var dateDispo = $(':date[name=dateDispo]').data('dateinput').getValue('dd/mm/yyyy');
    var nbDaysDispo = $('#nbDaysDispo').val();
    var fromHour = 0;
    var untilHour = 0;
    var whileHour = 0;
    if($('#fromUntilMode').hasClass('checked'))
    {
        fromHour = $('#fromHour').val();
        untilHour = $('#untilHour').val();
        whileHour = 0;
    }
    else
    {
        fromHour = 0;
        untilHour = 0;
        whileHour = $('#whileHour').val();
    }

    var expJob  = $('#expJob').val();
    var language = $('#language').val();

    var brands = "";
    var references = "";

    $('#selectedBrands li.padded').each(function(){
       if(brands.length>0)
           brands += "|";
       brands += $(this).attr('rel');
    });

    $('#selectedReferences li.padded').each(function(){
       if(references.length>0)
           references += "|";
       references += $(this).attr('rel');
    });

    $('#searchResult').fadeOut(function(){
        $('#searchResult').html('<div class="ajax-loader"><img src="/images/studio/ajax-loader-bar.gif" alt="" /></div>');
        $('#searchResult .ajax-loader').show();
        $('#searchResult').show();
        $.ajax(
        {
            type: 'get',
            url: href,
            cache: false,
            data: {
                    "part":"submitTechSearch",
                    "idRegion":idRegion,
                    "idDepartment":idDepartment,
                    "town":town,
                    "specialitiesSelect":specialitiesSelect,
                    "dateDispo":dateDispo,
                    "nbDaysDispo":nbDaysDispo,
                    "fromHour":fromHour,
                    "untilHour":untilHour,
                    "whileHour":whileHour,
                    "expJob":expJob,
                    "language":language,
                    "brands":brands,
                    "withDispo":withDispo,
                    "references":references
            },
            success: function(data)
            {
                $('#searchResult').hide();
                $('#searchResult').html(data);
                $('#searchResult').fadeIn();
                //active le plugin pour les tooltips
                activateSearchPagination('searchResults','fr');
                activeToolTip();
            }
        });
    });
}

function submitMusicianSearch()
{
    if($('#hub').css('display') != 'none')
	{
		$('#hub').fadeOut('500',function(){
			$('#searchResultContainer').slideDown('500');
		})
	}
    var href = indexPath + "/communAjaxActions";
    var idRegion = $('#regionsSelect').val();
    var idDepartment = $('#departmentsSelect').val();
    var town = $('#town').val();
    if(town == $('#town').attr('rel'))
        town = "";
    var specialitiesSelect = $('#specialitiesSelect').val();
    var idJob = $('#jobsSelect').val();
    var withDispo = 1;

    if($('#checkBoxDispo').hasClass('switchOff'))
        withDispo = 0;
    var dateDispo = $(':date[name=dateDispo]').data('dateinput').getValue('dd/mm/yyyy');
    var nbDaysDispo = $('#nbDaysDispo').val();
    var fromHour = 0;
    var untilHour = 0;
    var whileHour = 0;
    if($('#fromUntilMode').hasClass('checked'))
    {
        fromHour = $('#fromHour').val();
        untilHour = $('#untilHour').val();
        whileHour = 0;
    }
    else
    {
        fromHour = 0;
        untilHour = 0;
        whileHour = $('#whileHour').val();
    }

    var expJob  = $('#expJob').val();
    var language = $('#language').val();

    var directory = 0;
    if($('#musicDirectoriesDiv li.selected').length>0){
        directory = $('#musicDirectoriesDiv li.selected').attr('rel');
    }

    var brands = "";
    var references = "";

    $('#selectedBrands li.padded').each(function(){
       if(brands.length>0)
           brands += "|";
       brands += $(this).attr('rel');
    });

    $('#selectedReferences li.padded').each(function(){
       if(references.length>0)
           references += "|";
       references += $(this).attr('rel');
    });

    $('#searchResult').fadeOut(function(){
        $('#searchResult').html('<div class="ajax-loader"><img src="/images/studio/ajax-loader-bar.gif" alt="" /></div>');
        $('#searchResult .ajax-loader').show();
        $('#searchResult').show();
        $.ajax(
        {
            type: 'get',
            url: href,
            cache: false,
            data: {
                    "part":"submitMusicianSearch",
                    "idRegion":idRegion,
                    "idDepartment":idDepartment,
                    "town":town,
                    "idJob":idJob,
                    "specialitiesSelect":specialitiesSelect,
                    "dateDispo":dateDispo,
                    "nbDaysDispo":nbDaysDispo,
                    "fromHour":fromHour,
                    "untilHour":untilHour,
                    "whileHour":whileHour,
                    "expJob":expJob,
                    "language":language,
                    "brands":brands,
                    "references":references,
                    "withDispo":withDispo,
                    "directory":directory
            },
            success: function(data)
            {
                $('#searchResult').hide();
                $('#searchResult').html(data);
                $('#searchResult').fadeIn();
                //active le plugin pour les tooltips
                activateSearchPagination('searchResults','fr');
                activeToolTip();
            }
        });
    });
}
function submitArtistSearch()
{
    if($('#hub').css('display') != 'none')
	{
		$('#hub').fadeOut('500',function(){
			$('#searchResultContainer').slideDown('500');
		})
	}
    var href = indexPath + "/communAjaxActions";
    var idRegion = $('#regionsSelect').val();
    var idDepartment = $('#departmentsSelect').val();
    var town = $('#town').val();
    if(town == $('#town').attr('rel'))
        town = "";
    var specialitiesSelect = $('#specialitiesSelect').val();
    var idJob = $('#jobsSelect').val();
    var withDispo = 1;

    if($('#checkBoxDispo').hasClass('switchOff'))
        withDispo = 0;
    var dateDispo = $(':date[name=dateDispo]').data('dateinput').getValue('dd/mm/yyyy');
    var nbDaysDispo = $('#nbDaysDispo').val();
    var fromHour = 0;
    var untilHour = 0;
    var whileHour = 0;
    if($('#fromUntilMode').hasClass('checked'))
    {
        fromHour = $('#fromHour').val();
        untilHour = $('#untilHour').val();
        whileHour = 0;
    }
    else
    {
        fromHour = 0;
        untilHour = 0;
        whileHour = $('#whileHour').val();
    }

    var expJob  = $('#expJob').val();
    var language = $('#language').val();

    var directory = 0;
    if($('#musicDirectoriesDiv li.selected').length>0){
        directory = $('#musicDirectoriesDiv li.selected').attr('rel');
    }

    var brands = "";
    var references = "";

    $('#selectedBrands li.padded').each(function(){
       if(brands.length>0)
           brands += "|";
       brands += $(this).attr('rel');
    });

    $('#selectedReferences li.padded').each(function(){
       if(references.length>0)
           references += "|";
       references += $(this).attr('rel');
    });

    $('#searchResult').fadeOut(function(){
        $('#searchResult').html('<div class="ajax-loader"><img src="/images/studio/ajax-loader-bar.gif" alt="" /></div>');
        $('#searchResult .ajax-loader').show();
        $('#searchResult').show();
        $.ajax(
        {
            type: 'get',
            url: href,
            cache: false,
            data: {
                    "part":"submitArtistSearch",
                    "idRegion":idRegion,
                    "idDepartment":idDepartment,
                    "town":town,
                    "idJob":idJob,
                    "specialitiesSelect":specialitiesSelect,
                    "dateDispo":dateDispo,
                    "nbDaysDispo":nbDaysDispo,
                    "fromHour":fromHour,
                    "untilHour":untilHour,
                    "whileHour":whileHour,
                    "expJob":expJob,
                    "language":language,
                    "brands":brands,
                    "references":references,
                    "withDispo":withDispo,
                    "directory":directory
            },
            success: function(data)
            {
                $('#searchResult').hide();
                $('#searchResult').html(data);
                $('#searchResult').fadeIn();
                //active le plugin pour les tooltips
                activateSearchPagination('searchResults','fr');
                activeToolTip();
            }
        });
    });
}



function submitStudioSearch()
{
	if($('#hub').css('display') != 'none')
	{
		$('#hub').fadeOut('500',function(){
			$('#searchResultContainer').slideDown('500');
		})
	}
    var href = indexPath + "/communAjaxActions";
    var idRegion = $('#regionsSelect').val();
    var idDepartment = $('#departmentsSelect').val();
    var style = $('#stylesSelect').val();
    var dateDispo = $(':date[name=dateDispo]').data('dateinput').getValue('yyyy-mm-dd');

    var nbDaysDispo;
    var idStudioType = $('#studioTypes').val();
    var idStandardForm = $('#standardForms').val();

    if(idStandardForm == 4)
	{
    	nbDaysDispo = $('#nbTracks').val();
	}
    else
	{
    	nbDaysDispo = $('#nbDaysDispo').val();
	}
    var withDispo = 1;

    if($('#checkBoxDispo').hasClass('switchOff'))
        withDispo = 0;
    var residenceOffering = 0;
    if($('#residenceOffering').hasClass('checked'))
        residenceOffering = 1;

    var liveRecord = 0;
    if($('#liveRecord').hasClass('checked'))
        liveRecord = 1;

    var capacity = $('#capacity').val();
    var surface = $('#surface').val();
    var brands = "";
    var references = "";

    $('#selectedBrands li.padded').each(function(){
       if(brands.length>0)
           brands += "|";
       brands += $(this).attr('rel');
    });

    $('#selectedReferences li.padded').each(function(){
       if(references.length>0)
           references += "|";
       references += $(this).attr('rel');
    });



    $('#searchResult').fadeOut(function(){
    $('#searchResult').html('<div class="ajax-loader"><img src="/images/studio/ajax-loader-bar.gif" alt="" /></div>');
    $('#searchResult .ajax-loader').show();
    $('#searchResult').show();
    $.ajax(
    {
        type: 'get',
        url: href,
        cache: false,
        data: "part=submitStudioSearch"
              +"&idRegion="+idRegion
              +"&idDepartment="+idDepartment
              +"&style="+style
              +"&dateDispo="+dateDispo
              +"&nbDaysDispo="+nbDaysDispo
              +"&residenceOffering="+residenceOffering
              +"&liveRecord="+liveRecord
              +"&capacity="+capacity
              +"&surface="+surface
              +"&idStudioType="+idStudioType
              +"&idStandardForm="+idStandardForm
              +"&brands="+brands
              +"&withDispo="+withDispo
              +"&references="+references
          ,
        success: function(data)
        {
           $('#searchResult').hide();
           $('#searchResult').html(data);
           $('#searchResult').fadeIn();
           //active le plugin pour les tooltips
           activateSearchPagination('searchResults','fr');
           activeToolTip();
        }
    });

    });
}


function communSubmitSearch()
{

    var idRegion = $('#regionsSelect').val();
    var idDepartment = $('#departmentsSelect').val();
    var idSpeciality = $('#specialitiesSelect').val();
    var doesRecord = 0;
    var doesMastering = 0;
    var doesRepeating = 0;
    var town = $('#searchBarFields #town').val();
    if(town == $('#searchBarFields #town').attr('rel'))
        town = "";
    var searchTab = $('.searchTypeButton.selected').attr('rel');

    if($('#doesRecord').hasClass('checked'))
        doesRecord = 1;
    if($('#doesRepeating').hasClass('checked'))
        doesRepeating = 1;
    if($('#doesMastering').hasClass('checked'))
        doesMastering = 1;

    var idJob = $('#jobsSelect').val();

    var href = window.location.protocol + "//" + window.location.host + indexPath + "/communAjaxActions";
    $.ajax(
    {
        type: 'get',
        url: href,
        cache: false,
        data: "part=communSubmitSearch&searchTab="+searchTab+"&idRegion="+idRegion+"&idDepartment="+idDepartment+"&idJob="+idJob+"&idSpeciality="+idSpeciality+"&doesRecord="+doesRecord+"&doesRepeating="+doesRepeating+"&doesMastering="+doesMastering+"&town="+town,
        success: function(data)
        {
            window.location.href = data;
        }
    });


}

function activateJobChange(callbackFunction)
{
    $('#jobsSelect').change(function(){
        updateJobSpecialities2('jobsSelect','specialities',callbackFunction);
    });
}

function activateJobChange1()
{
    $('#jobsSelect').change(function(){
        updateJobSpecialities();
    });
}

function updateJobs(idProfileType,idcontainer,callbackFunction)
{
    //gestion du changement automatique du select des departements quand on modifie une région
        var href = indexPath+"/communAjaxActions";

        $.ajax(
        {
            type: 'get',
            url: href,
            cache: false,
            data: 'part=updateJobs&idProfileType='+idProfileType,
            success: function(data)
            {
                $('#'+idcontainer).html(data);
                activateJobChange(callbackFunction);
            }
        });
}

function updateJobSpecialities() {


        //gestion du changement automatique du select des departements quand on modifie une région
        var href = indexPath+"/communAjaxActions";

        var idJob = $('#jobsSelect').val();
        $.ajax(
        {
            type: 'get',
            url: href,
            cache: false,
            data: 'part=updateJobSpecialities&idJob='+idJob,
            success: function(data)
            {
                $('#specialities').html(data);
            }
        });

 }

function activateSpecialityChange(idSpecialitySelect,callbackFunction)
{
    $('#'+idSpecialitySelect).change(function(){
        if(callbackFunction)
            callbackFunction();
    });
}

function updateJobSpecialities2(idJobSelect,idSpecialitySelect,callbackFunction) {
        //gestion du changement automatique du select des departements quand on modifie une région
        var href = window.location.protocol + "//" + window.location.host + indexPath+"/communAjaxActions";
        var idSpecialitySelected = $('#'+idSpecialitySelect+'Select').val();
        var idJob = $('#'+idJobSelect).val();
        $.ajax(
        {
            type: 'get',
            url: href,
            cache: false,
            data: 'part=updateJobSpecialities&idJob='+idJob+'&idSpecialitySelect='+idSpecialitySelect+"&idSpecialitySelected="+idSpecialitySelected,
            success: function(data)
            {
                //$('#'+idSpecialitySelect).hide();
                $('#'+idSpecialitySelect).html(data);
                //$('#'+idSpecialitySelect).fadeIn();
                if(callbackFunction)
                    {
                        callbackFunction();
                    }
                    activateSpecialityChange(idSpecialitySelect,callbackFunction);
            }
        });
}


function updateUniverseJobs(idUniverseSelect,idJobSelect,callbackFunction) {
        //gestion du changement automatique du select des departements quand on modifie une région
        var href = window.location.protocol + "//" + window.location.host + indexPath+"/communAjaxActions";
        var idJobSelected = $('#'+idJobSelect+'Select').val();
        var idUniverse = $('#'+idUniverseSelect).val();
        
        $.ajax(
        {
            type: 'get',
            url: href,
            cache: false,
            data: 'part=updateUniverseJobs&idUniverse='+idUniverse+'&idJobSelect='+idJobSelect+"&idJobSelected="+idJobSelected,
            success: function(data)
            {
                //$('#'+idJobSelect).hide();
                $('#'+idJobSelect).html(data);
                //$('#'+idJobSelect).fadeIn();
                if(callbackFunction)
                    {
                        callbackFunction();
                    }
                    //activateJobChange(idJobSelect,callbackFunction);
            }
        });
}


function launchMusicPlayer(idDiv,tokenFile,tokenProfile)
{
   //gestion du changement automatique du select des departements quand on modifie une région
        var href = window.location.protocol + "//" + window.location.host + indexPath+"/communAjaxActions";
        $.ajax(
        {
            type: 'get',
            url: href,
            cache: false,
            data: 'part=launchMusicPlayer&tokenFile='+tokenFile+'&tokenProfile='+tokenProfile,
            success: function(data)
            {
                $('#'+idDiv).html(data);
            }
        });
}

function popupVideoFile(token,tokenProfile)
{


    var href = window.location.protocol + "//" + window.location.host + indexPath+"/communAjaxActions";
    $.ajax(
    {
        type: 'post',
        url: href,
        cache: false,
        data: "part=popupVideoFile&token="+token+"&tokenProfile="+tokenProfile,
        success: function(data)
        {
           $('#popupVideoFile').html(data);
           $.fn.colorbox({width:'510',height:'440', inline:true, href:"#popupVideoFile"});
        }
    });
}

function popupTextFile(token)
{
    var href = window.location.protocol + "//" + window.location.host + indexPath+"/communAjaxActions";
    $.ajax(
    {
        type: 'post',
        url: href,
        cache: false,
        data: "part=popupTextFile&token="+token,
        success: function(data)
        {
           $('#popupTextFile').html(data);
           $.fn.colorbox({width:"630px", inline:true, href:"#popupTextFile"},function(){
                      activateJScrollPane('textDiv');
            });

        }
    });
}

function in_array(p_val,array) {
    for(var i = 0, l = array.length; i < l; i++) {
        if(array[i] == p_val) {
            rowid = i;
            return true;
        }
    }
    return false;
}



function fadeOutTweaz(element,time,callback){
    if($.browser.msie){
        if(element){
                if(callback){
                    $(element).css('display','none');
                    callback();
                }else{
                    $(element).css('display','none');
                }
        }
    }else{
        if(element){
            if(time){
                if(callback){
                    $(element).fadeOut(time,function(){callback()});
                }else{
                    $(element).fadeOut(time);
                }
            }else{
                if(callback){
                    $(element).fadeOut(function(){callback()});
                }else{
                    $(element).fadeOut();
                }
            }
        }
    }
}
function fadeInTweaz(element,time,callback){
    if($.browser.msie){
        if(element){
                if(callback){
                    $(element).show(function(){callback()});
                }else{
                    $(element).show();
                }
        }
    }else{
        if(element){
            if(time){
                if(callback){
                    $(element).fadeIn(time,function(){callback()});
                }else{
                    $(element).fadeIn(time);
                }
            }else{
                if(callback){
                    $(element).fadeIn(function(){callback()});
                }else{
                    $(element).fadeIn();
                }
            }
        }
    }
}

function activatDeliveryPlaceChange()
{
    $('#deliveryPlace').change(function(){
        if($(this).val() == 1)
            $('#myTown').fadeIn();
        else
            $('#myTown').fadeOut();
    });
}
function activateLickSmallBasket()
{
    $('#waitingsFieldset .smallBasket.needClickEvent').click(function(){
        if($('.waitingLine').length>1)
        {
            $(this).parents('.waitingLine').slideUp(500,function(){
                $(this).remove();
                $(this).removeClass('needClickEvent');
                activateJScrollPane('waitings');
            })
        }

    });
}

function addNewWaiting()
{
    var href = indexPath+"/communAjaxActions";

    $.ajax(
    {
        type: 'post',
        url: href,
        cache: false,
        data: 'part=addNewWaiting',
        success: function(data)
        {
            $('.waitings').prepend(data);
            activateLickSmallBasket();
            activateJScrollPane('waitings');
        }
    });

}
function askForQuote(providerToken,isStudio){
    var href = indexPath+"/communAjaxActions";
    $.ajax(
    {
        type: 'post',
        url: href,
        cache: false,
        data: "part=askForQuote&providerToken="+providerToken+"&isStudio="+isStudio,
        success: function(data)
        {
            $('#popup').html(data);

            $.fn.colorbox({width:'800px',inline:true,href:"#popup",overlayClose:false},function(){
                 $('#quoteObject').click(function(){
                    $(this).removeClass('fc-r1');
                });
                activatDeliveryPlaceChange();
                activateNumericOnlyField();
                activateLickSmallBasket();
                activateAutoEmpty();
                activeToolTip();
                activateRadioBox();
                activateAutoWithSelect();
                $('.whiteSpace').hide();
            });

        }
    });
}

function sendPersonalQuote(providerToken,isStudio)
{
    var isOk = true;

    var data = "part=sendQuote&providerToken="+providerToken+"&isStudio="+isStudio;

    var object = $('#quoteObject').val();
    data += "&object="+object;
    if(trim(object).length == 0)
        {
            isOk = false;
            $('#quoteObject').css('background-color','red');
            $('#quoteObject').css('color','white');
        }
    else
        {
            if($('#quoteObject').css('background-color') == 'red')
               {
                   $('#quoteObject').css('color','#636363');
                   $('#quoteObject').css('background-color','inherit');
               }
        }

    var forRecord = 0;
    if($('#forRecord').hasClass('checked'))
        forRecord = 1;
    data += "&forRecord="+forRecord;

    var forMix = 0;
    if($('#forMix').hasClass('checked'))
        forMix = 1;
    data += "&forMix="+forMix;

    var forMastering = 0;
    if($('#forMastering').hasClass('checked'))
        forMastering = 1;
    data += "&forMastering="+forMastering;

    var nbTitlesToRecord =$('#nbTitlesToRecord').val();
    data += "&nbTitlesToRecord="+nbTitlesToRecord;
    var nbTitlesToMix = $('#nbTitlesToMix').val();
    data += "&nbTitlesToMix="+nbTitlesToMix;
    var nbTitlesToMastering = $('#nbTitlesToMastering').val();
    data += "&nbTitlesToMastering="+nbTitlesToMastering;
    var nbPeople = $('#nbPeople').val();
    data += "&nbPeople="+nbPeople;

    var lockOut = 0;
    if($('#lockOut').hasClass('checked'))
        lockOut = 1;
    data += "&lockOut="+lockOut;
    var withSoundEngineer = 0;
    if($('#withSoundIngineer').hasClass('checked'))
        withSoundEngineer = 1;
    data += "&withSoundEngineer="+withSoundEngineer;

    var deliveryPlace = $('#deliveryPlace').val();
    data += "&deliveryPlace="+deliveryPlace;

    var customerDeliveryPlace = $('#town').val();
    data += "&customerDeliveryPlace="+customerDeliveryPlace;

    var duration = $('#duration').val();
    data += "&duration="+duration;
    if(trim(duration).length == 0)
        {
            isOk = false;
            $('#duration').css('background-color','red');
            $('#duration').css('color','white');
        }
    else
        {
            if($('#duration').css('background-color') == 'red')
               {
                   $('#duration').css('color','#636363');
                   $('#duration').css('background-color','inherit');
               }
        }


    var phone = $('#phone').val();
    data += "&phone="+phone;
    if(!isPhoneValid(phone))
        {
            isOk = false;
            $('#phone').css('background-color','red');
            $('#phone').css('color','white');
        }
    else
        {
            if($('#phone').css('background-color') == 'red')
               {
                   $('#phone').css('color','#636363');
                   $('#phone').css('background-color','inherit');
               }
        }

    var date = $('#date').val();
    data += "&date="+date;
    if(trim(date).length == 0)
        {
            isOk = false;
            $('#date').css('background-color','red');
            $('#date').css('color','white');
        }
    else
        {
            if($('#date').css('background-color') == 'red')
               {
                   $('#date').css('color','#636363');
                   $('#date').css('background-color','inherit');
               }
        }
    var budget = $('#budget').val();
    data += "&budget="+budget;
    if(trim(budget).length == 0)
        {
            isOk = false;
            $('#budget').css('background-color','red');
            $('#budget').css('color','white');
        }
    else
        {
            if($('#budget').css('background-color') == 'red')
              {
                  $('#budget').css('background-color','inherit');
                  $('#budget').css('color','#636363');
              }
        }

   var nbNotEmptyWaiting = 0;
    $('.waitingLine').each(function(){
        if(trim($(this).find('input').val()).length>0)
        {
                nbNotEmptyWaiting++;
                data += "&waiting"+nbNotEmptyWaiting+"="+escape($(this).find('input').val());
        }
    });
    if(nbNotEmptyWaiting == 0)
      {
          isOk = false;
          $('.waitingLine:first input').css('background-color','red');
          $('.waitingLine:first input').css('color','white');
        }
    else
        {
            if($('.waitingLine:first input').css('background-color') == 'red')
                {
                    $('.waitingLine:first input').css('background-color','inherit');
                    $('.waitingLine:first input').css('color','#636363');
                }
        }

    if(isOk)
    {
        var href = indexPath+"/communAjaxActions";

        $.ajax(
        {
            type: 'post',
            url: href,
            cache: false,
            data: data,
            success: function(dataBack)
            {
                if(dataBack == '0')
                {
                    //l'utilisateur n'est pas connecté, on va lui proposer soit de se connecter soit de s'inscrire'
                     $.ajax(
                    {
                        type: 'post',
                        url: href,
                        cache: false,
                        data: "part=logOrSubscribe",
                        success: function(dataBack2)
                        {
                            $('#logOrSubscribe').html(dataBack2);
                            activateAutoEmpty();
                            $.fn.colorbox({width:'710px',inline:true,href:"#logOrSubscribe",overlayClose:false});
                        }
                    });
                }
                else
                {
                    $.fn.colorbox({width:'620px',inline:true,href:"#quoteSended"},function(){
                        activateRadioBox();
                    });
                }
            }
        });
    }

}


function roomPopup(idRoom){
    var href = indexPath+"/communAjaxActions";
    $.ajax(
    {
        type: 'get',
        url: href,
        cache: false,
        data: "part=popupRoom&idRoom="+idRoom,
        success: function(data)
        {
            $('#popup').html(data);
            $("a[rel='photoRoomStudio']").colorbox();
            $.fn.colorbox({width:"500px",inline:true,href:"#popup",overlayClose:true},function(){
                activateJScrollPane('descriptionContent');
                activeToolTip();
            });

        }
    });
}

function myScrollTo(ancre,speed,focus)
{
    if(!focus)
        focus = false;
    if(!speed)
        speed = 2000;
    jQuery('html,body').animate({scrollTop:jQuery(ancre).offset().top},speed,'swing',function(){

       if(focus){
          jQuery(ancre).attr('tabindex','-1');
          jQuery(ancre).focus();
          jQuery(ancre).removeAttr('tabindex');
      }
    });
}

function activateAutocomplete(idInputName,height,width,partInAction)
{
    if($('#'+idInputName).parent().find('#'+idInputName+"Hidden").length == 0)
        //ajoute un input du meme nom+hidden en caché
        $('#'+idInputName).parent().append('<input type="hidden" id="'+idInputName+'Hidden">');

    var href = indexPath+"/communAjaxActions?part="+partInAction;

    $('#'+idInputName).autocomplete({
    serviceUrl:href,
    minChars:0,
    maxHeight:height,
    width:width,
    zIndex: 9999,
    deferRequestBy: 0, //miliseconds
    noCache: false, //default is false, set to true to disable caching
    // callback function:
    onSelect: function(value, data){$('#'+idInputName+'Hidden').val(value + '|' + data);}
    
  });


}

function activateCaracterLeft(idInput, idNumberSpan)
{
    $(idInput).keyup(function(){
        var limit = $(this).attr('MAXLENGTH');
        var actualSize = $(this).val().length;
        var nbLeftCaracter = parseInt(limit,10) - parseInt(actualSize,10);
        $(idNumberSpan).html(nbLeftCaracter);
    });

}
function activateCaracterLeftByElement(elInput, elNumberSpan)
{   
    elInput.keyup(function(){
        var limit = $(this).attr('MAXLENGTH');
        var actualSize = $(this).val().length;
        var nbLeftCaracter = parseInt(limit,10) - parseInt(actualSize,10);
        elNumberSpan.html(nbLeftCaracter);
    });

}

function askReferencePopup(token,type){
    var href = indexPath+"/communAjaxActions";
    $.ajax(
    {
        type: 'post',
        url: href,
        cache: false,
        data: "part=askReferencePopup&token="+token+"&type="+type,
        success: function(data)
        {
            if(data != '0')
            {
                $('#popup').html(data);
                $.fn.colorbox({width:"480px", inline:true, href:"#popup"});
            }
            else
            {
                showNeedConnexionPopup();
            }
        }
    });
}

function askReference(token){
    var href = indexPath+"/communAjaxActions";
    $.ajax(
    {
        type: 'post',
        url: href,
        cache: false,
        data: "part=askReference&token="+token+'&text='+$('#askReferenceTextArea').val(),
        success: function(data)
        {
            $('#askReferenceLink').remove();
            closePopup();
        }
    });
}

function askStudioReference(token){
    var href = indexPath+"/communAjaxActions";
    $.ajax(
    {
        type: 'post',
        url: href,
        cache: false,
        data: "part=askStudioReference&token="+token+'&text='+$('#askReferenceTextArea').val(),
        success: function(data)
        {
            $('#askReferenceLink').remove();
            closePopup();
        }
    });
}

function askAffiliationPopup(token,type){
    var href = indexPath+"/communAjaxActions";
    $.ajax(
    {
        type: 'post',
        url: href,
        cache: false,
        data: "part=askAffiliationPopup&token="+token+"&type="+type,
        success: function(data)
        {
            $('#popup').html(data);
            $.fn.colorbox({width:"480px",height:"250px", inline:true, href:"#popup"});
        }
    });
}

function askAffiliation(token){
    var href = indexPath+"/communAjaxActions";
    $.ajax(
    {
        type: 'post',
        url: href,
        cache: false,
        data: "part=askAffiliation&token="+token+'&text='+$('#askAffiliationTextArea').val(),
        success: function(data)
        {
            $('#askForAffiliate').remove();
            closePopup();
        }
    });
}


function askStudioAffiliation(token){
    var href = indexPath+"/communAjaxActions";
    $.ajax(
    {
        type: 'post',
        url: href,
        cache: false,
        data: "part=askStudioAffiliation&token="+token+'&text='+$('#askAffiliationTextArea').val(),
        success: function(data)
        {
            $('#askForAffiliate').remove();
            closePopup();
        }
    });
}

function confirmIKnow(el,profileToken,askState,doLoadOneMore)
{
    var container;
    if($(el).parents('.notificationPreviewActions').length>0)
         container = $(el).parents('.notificationPreviewActions');
    else
         container = $(el).parents('.notificationActions');
    var href = indexPath+"/communAjaxActions";
    $.ajax(
    {
        type: 'get',
        url: href,
        cache: false,
        data:{
            "part":"confirmIKnow",
            "profileToken":profileToken,
            "askState":askState
        },
        success: function(data)
        {
           container.remove();
           if(doLoadOneMore)
           {
              var forbiddenIdProfile = "";
              $('.friendsSuggestions .friendSuggestionLine').each(function(){
                  if(forbiddenIdProfile!="")
                      forbiddenIdProfile +=',';
                 forbiddenIdProfile += $(this).attr('rel');
              });
              var href = indexPath + "/communWallAjaxActions";
               $.ajax(
               {
                    type: 'get',
                    url: href,
                    cache: false,
                    data:{
                        "part":"getOneMoreSuggestion",
                        "forbiddenIdProfile":forbiddenIdProfile
                    },
                    success: function(data)
                    {
                       $('.friendsSuggestionsContent').append(data);
                    }
               });
           }
        }
    });
}

function askFollow(token){
    $('.askFollow[id="'+token+'"]').each(function(){
        $(this).css('display','none');
    });
    var href = indexPath+"/communAjaxActions";
    $.ajax(
    {
        type: 'post',
        url: href,
        cache: false,
        data: {
            "part":"askFollow",
            "token":token
        },
        success: function(data)
        {
            if(data != '0')
                {
                    
                    if($('.needToFollow:visible').length>0 && $('#notificationsPreview:visible').length==0)
                        window.location.reload();
                }
                else
                     {
                         showNeedConnexionPopup();
                         $('.askFollow[id="'+token+'"]').each(function(){
                                $(this).css('display','block');
                            });
                     }
            
        }
    });
}


function unfollow(token,needToReload){
    var href = indexPath+"/communAjaxActions";
    $.ajax(
    {
        type: 'post',
        url: href,
        cache: false,
        data: {
            "part":"unfollow",
            "token":token
        },
        success: function(data)
        {
            if(needToReload)
                window.location.reload();
        }
    });
}

function activateTweazSlideBehind()
{
    $('.TweazSlideBehind').each(function(){
       // $(this).css('width',$(this).find('.TweazSlidePhoto').width());
        //$(this).css('height',$(this).find('.TweazSlidePhoto').height());
        $(this).css('overflow','hidden');


        $(this).find('.TweazSlideContent').css('width',$(this).width());
        $(this).find('.TweazSlideContent').css('height',$(this).height());

        $(this).find('.TweazSlidePhoto').css('position','relative');
        $(this).find('.TweazSlidePhoto').css('top','-'+$(this).height()+'px');


        $(this).hover(function(){
            if($(this).attr('isMoving') != '1')
            {
                $(this).attr('isMoving','1');
               $(this).find('.TweazSlidePhoto').animate({
                opacity: 0.25
              }, 200);    
            }

        },function(){
               $(this).find('.TweazSlidePhoto').animate({
                opacity: 1
              }, 200
              ,function(){
                   $(this).parents('.TweazSlideBehind').attr('isMoving','0');
               });
               
        }
        );






    });
}

function popupPremiumNeeded(){
    var href = indexPath+"/communAjaxActions";
    $.ajax(
    {
        type: 'get',
        url: href,
        cache: false,
        data: {
            "part":"popupPremiumNeeded"
        },
        success: function(data)
        {
            $('#popup').html(data);

            $.fn.colorbox({
                width:"630px",
                inline:true,
                href:"#popup",
                overlayClose:true
            });

        }
    });
}
function popupComingSoon(){
    var href = indexPath+"/communAjaxActions";
    $.ajax(
    {
        type: 'get',
        url: href,
        cache: false,
        data: {
            "part":"popupComingSoon"
        },
        success: function(data)
        {
            $('#popup').html(data);

            $.fn.colorbox({
                width:"430px",
                inline:true,
                href:"#popup",
                overlayClose:true
            });

        }
    });
}
function loggedNeeded(){
    var href = indexPath+"/communAjaxActions";
    $.ajax(
    {
        type: 'get',
        url: href,
        cache: false,
        data: {
            "part":"popupLoggedNeeded"
        },
        success: function(data)
        {
            $('#popup').html(data);

            $.fn.colorbox({
                width:"330px",
                inline:true,
                href:"#popup",
                overlayClose:true
            });

        }
    });
}
function activatedNeeded(){
    var href = indexPath+"/communAjaxActions";
    $.ajax(
    {
        type: 'get',
        url: href,
        cache: false,
        data: {
            "part":"popupActivatedNeeded"
        },
        success: function(data)
        {
            $('#popup').html(data);

            $.fn.colorbox({
                width:"330px",
                inline:true,
                href:"#popup",
                overlayClose:true
            });

        }
    });
}

function submitCallBack(){
    var phone = $('#callBackPhone').val();
    if(!isPhoneValid(phone))
        $('#callBackPhone').css('color','red');
    else
        {
            $('#callBackPhone').css('color','black');
            var href = indexPath+"/communAjaxActions";
            $.ajax(
            {
                type: 'get',
                url: href,
                cache: false,
                data: {
                    "part":"submitCallBack",
                    "phone":phone
                },
                success: function(data)
                {
                    $('#callBackPhone').val($('#callBackPhone').attr('rel'));
                    $.fn.colorbox({
                        width:"430px",
                        inline:true,
                        href:"#callBackOk",
                        overlayClose:true
                    });
                }
            });
        }

}

function activateCuteTime(selector,culture)
{
    $.fn.cuteTime.settings.refresh = 600000;
    //////////// FRENCH ///////////////////
        var french = {
                time_ranges: [
                        {bound: Number.NEGATIVE_INFINITY,
                                        cuteness: '1s',			unit_size: 0},
                        {bound: 0,
                                        cuteness: '1s',			unit_size: 0},
                        {bound: 1000,
                                        cuteness: '%CT% s',                     unit_size: 1000},
                        {bound: 60 * 1000,
                                        cuteness: '1m',		unit_size: 0},
                        {bound: 60 * 1000 * 2,
                                        cuteness: '%CT% m',	unit_size: 60 * 1000},
                        {bound: 60 * 1000 * 60,
                                        cuteness: '1h',		unit_size: 0},
                        {bound: 60 * 1000 * 60 * 2,
                                        cuteness: '%CT% h',		unit_size: 60 * 1000 * 60},
                        {bound: 60 * 1000 * 60 * 24,
                                        cuteness: 'hier',			unit_size: 0},
                        {bound: 60 * 1000 * 60 * 24 * 2,
                                        cuteness: '%CT%j',		unit_size: 60 * 1000 * 60 * 24},
                        {bound: 60 * 1000 * 60 * 24 * 30,
                                        cuteness: '1 mois',		unit_size: 0},
                        {bound: 60 * 1000 * 60 * 24 * 30 * 2,
                                        cuteness: '%CT% mois',		unit_size: 60 * 1000 * 60 * 24 * 30},
                        {bound: 60 * 1000 * 60 * 24 * 30 * 12,
                                        cuteness: '1 an',		unit_size: 0},
                        {bound: 60 * 1000 * 60 * 24 * 30 * 12 * 2,
                                        cuteness: '%CT% ans',		unit_size: 60 * 1000 * 60 * 24 * 30 * 12},
                        {bound: Number.POSITIVE_INFINITY,
                                        cuteness: 'il y a tr&egrave;s longtemps',	unit_size: 0}
                ]
        };

        switch(culture)
        {
            case 'fr':
            default:
               $(selector).cuteTime(french).fadeIn(400);
                break;
        }


}

function activateTextCuteTime(selector,culture)
{
    $.fn.cuteTime.settings.refresh = 600000;
    //////////// FRENCH ///////////////////
        var french = {
                time_ranges: [
			{bound: Number.NEGATIVE_INFINITY,
					cuteness: 'maintenant',							unit_size: 0},
			{bound: 0,
					cuteness: 'maintenant',							unit_size: 0},
			{bound: 20 * 1000,
					cuteness: 'il y a quelques secondes',			unit_size: 0},
			{bound: 60 * 1000,
					cuteness: 'il y a une minute',					unit_size: 0},
			{bound: 60 * 1000 * 2,
					cuteness: 'il y a %CT% minutes',				unit_size: 60 * 1000},
			{bound: 60 * 1000 * 60,
					cuteness: 'il y a une heure',					unit_size: 0},
			{bound: 60 * 1000 * 60 * 2,
					cuteness: 'il y a %CT% heures',					unit_size: 60 * 1000 * 60},
			{bound: 60 * 1000 * 60 * 24,
					cuteness: 'hier',								unit_size: 0},
			{bound: 60 * 1000 * 60 * 24 * 2,
					cuteness: 'il y a %CT% jours',					unit_size: 60 * 1000 * 60 * 24},
			{bound: 60 * 1000 * 60 * 24 * 30,
					cuteness: 'le mois dernier',					unit_size: 0},
			{bound: 60 * 1000 * 60 * 24 * 30 * 2,
					cuteness: 'il y a %CT% mois',					unit_size: 60 * 1000 * 60 * 24 * 30},
			{bound: 60 * 1000 * 60 * 24 * 30 * 12,
					cuteness: 'l\'année dernière',	unit_size: 0},
			{bound: 60 * 1000 * 60 * 24 * 30 * 12 * 2,
					cuteness: 'il y a %CT% ans',					unit_size: 60 * 1000 * 60 * 24 * 30 * 12},
			{bound: Number.POSITIVE_INFINITY,
					cuteness: 'il y a très longtemps',		unit_size: 0}
		]
        };

        switch(culture)
        {
            case 'fr':
            default:
               $(selector).cuteTime(french).fadeIn(400);
                break;
        }


}

function accountPopup(){
    if($('#myAccountPopup').css('display')=='none')
        $('#myAccountPopup').show();
    else
        $('#myAccountPopup').hide();
}


function loadNotificationsPreview(){
    $('#nbUnreadNotifications').hide();
    if($('#notificationsPreview').css('display')=='none')
    {
        isOpeningNotifications = true;
        $('#notificationsPreview #notificationsPreviewLines').html('<center><br/><img src="/images/ajax-loader-fb.gif"></center>');
        $('#notificationsPreview').show();
        
        
        var href = indexPath+"/communAjaxActions";
        $.ajax(
        {
            type: 'get',
            url: href,
            cache: false,
            data:{
                "part":"loadNotificationsPreview"
            },
            success: function(data)
            {
                $('#notificationsPreview #notificationsPreviewLines').html(data);
                activeToolTip();
                activateTextCuteTime('.notificationCreatedAt','fr');
                $('#notificationsPreview').click(function(){
                    clickedOnNotifications = true;
                });
            }
        });
    }
    
}


function acceptChoice(token)
{
    clickedOnNotifications = true;
    $('.waitingAskLine#'+token).find('.choiceButtons').slideUp(function(){
        $('.waitingAskLine#'+token).find('.confirmAcceptChoice').slideDown();
    });
}
function refuseChoice(token)
{
    clickedOnNotifications = true;
    $('.waitingAskLine#'+token).find('.choiceButtons').slideUp(function(){
        $('.waitingAskLine#'+token).find('.confirmRefuseChoice').slideDown();
    });
}

function cancelChoice(token)
{
    clickedOnNotifications = true;
    $('.waitingAskLine#'+token).find('.confirmChoice:visible').slideUp(function(){
        $('.waitingAskLine#'+token).find('.choiceButtons').slideDown();
    });
}

function updateContactAskWaiting()
{
    $('#contactAskWaiting').css('height',$('#contactAskWaiting').height());
    $('#contactAskWaiting .moduleContent').fadeOut(function(){
        $('#contactAskWaiting .moduleContent').html('<img class="ajax-loader" src="/images/studio/ajax-loader.gif">');
        $('#contactAskWaiting .moduleContent .ajax-loader').show();
        $('#contactAskWaiting .moduleContent').show();
        var href = indexPath+"/communAjaxActions";
        $.ajax(
        {
            type: 'get',
            url: href,
            cache: false,
            data: {
                "part":"updateContactAskWaiting"
            },
            success: function(data)
            {
                $('#contactAskWaiting .moduleContent').fadeOut(function(){
                    $('#contactAskWaiting .moduleContent').html(data);
                    $('#contactAskWaiting .moduleContent').fadeIn();
                });
                
            }
        });
    });
    
}


function confirmAcceptAffiliation(token)
{
    clickedOnNotifications = true;
    var href = indexPath+"/communAjaxActions";
    $.ajax(
    {
        type: 'get',
        url: href,
        cache: false,
        data: {
            "part":"confirmAcceptAffiliation",
            "token":token
        },
        success: function(data)
        {
            $('.waitingAskLine#'+token).fadeOut();
        }
    });
}
function confirmRefuseAffiliation(token)
{
    var href = indexPath+"/communAjaxActions";
    $.ajax(
    {
        type: 'get',
        url: href,
        cache: false,
        data: {
            "part":"confirmRefuseAffiliation",
            "token":token
        },
        success: function(data)
        {
           $('.waitingAskLine#'+token).fadeOut();
        }
    });
}

function loadMailsPreview(){
    if($('#mailsPreview').css('display')=='none')
    {
        isOpeningNotifications = true;
        $('#mailsPreview #mailsPreviewLines').html('<center><br/><img src="/images/ajax-loader-fb.gif"></center>');
        $('#mailsPreview').show();
        
        
        var href = indexPath+"/communAjaxActions";
        $.ajax(
        {
            type: 'get',
            url: href,
            cache: false,
            data:{
                "part":"loadMailsPreview"
            },
            success: function(data)
            {
                $('#mailsPreview #mailsPreviewLines').html(data);
                activeToolTip();
                activateTextCuteTime('.notificationMailsCreatedAt','fr');
                $('#mailsPreview').click(function(){
                    clickedOnNotifications = true;
                });
                $('#nbUnreadMails').hide();
            }
        });
    }
    
}

function updateNotificationNumbers(){
    var href = indexPath+"/communAjaxActions";
    $.ajax(
    {
        type: 'get',
        url: href,
        cache: false,
        data:{
            "part":"updateNotificationNumbers"
        },
        success: function(data)
        {
           if(data == '-1')
           {
               window.location.reload();
           }
           else
           {
               var obj = eval(data);
               var nbNotifs = parseInt(obj[0], 10);
               var nbMailsNotifs = parseInt(obj[1], 10);
               var nbNetworkNotifs = obj[2];
               
               if(nbNotifs>0)
               {
                   $('#nbUnreadNotifications .number').html(nbNotifs);
                   $('#nbUnreadNotifications').show();
               }
               else
                   $('#nbUnreadNotifications').hide();

               if(nbMailsNotifs>0)
               {
                   $('#nbUnreadMails .number').html(nbMailsNotifs);
                   $('#nbUnreadMails').show();
               }
               else           
                   $('#nbUnreadMails').hide();
               
               if(nbNetworkNotifs>0)
               {
                   $('#nbUnreadNetwork .number').html(nbNetworkNotifs);
                   $('#nbUnreadNetwork').show();
               }
               else           
                   $('#nbUnreadNetwork').hide();
           }
           
        }
    });
}

function str_replace (search, replace, subject, count) {
    // Replaces all occurrences of search in haystack with replace  
    // 
    // version: 1103.1210
    // 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];
}
function cleanUploadedFileName(string)
{
    string =  string.replace(/[^a-zA-Z0-9\-.]/,'');
    return string;
}
 
function showCgcPopup(){
    var href = indexPath+"/communAjaxActions";
    $.ajax(
    {
        type: 'get',
        url: href,
        cache: false,
        data:{
            "part":"ContestCgpPopup"
        },
        success: function(data)
        {
            $('#popup').html(data);
           $.fn.colorbox({inline:true,href:'#popup',overlayClose:true,width:'400px',onComplete:function(){
                   activateJScrollPaneByElement($('.contestRules'));
           }});
        }
    });
    
}
                

function validateJobs(isPopup){
    var href = indexPath+"/communAjaxActions";

    $('#validateJobsOk').hide();
    $('#validateJobsNOk').hide();
    $('#validateJobsNOk2').hide();



    /*if($('#firstJobSelect').val()==0){
        $('#validateJobsNOk').effect("pulsate", {times:4}, 500);

    }else{*/
        var jobsAndSpecialities = '';
        jobsAndSpecialities+=$('#firstJobSelect').val()+':'+$('#firstJobFirstSpecialitySelect').val()+'-'+$('#firstJobSecondSpecialitySelect').val()+'-'+$('#firstJobThirdSpecialitySelect').val()+'-'+$('#firstJobFourthSpecialitySelect').val()+'|';
        jobsAndSpecialities+=$('#secondJobSelect').val()+':'+$('#secondJobFirstSpecialitySelect').val()+'-'+$('#secondJobSecondSpecialitySelect').val()+'-'+$('#secondJobThirdSpecialitySelect').val()+'-'+$('#secondJobFourthSpecialitySelect').val()+'|';
        jobsAndSpecialities+=$('#thirdJobSelect').val()+':'+$('#thirdJobFirstSpecialitySelect').val()+'-'+$('#thirdJobSecondSpecialitySelect').val()+'-'+$('#thirdJobThirdSpecialitySelect').val()+'-'+$('#thirdJobFourthSpecialitySelect').val();
        var experiences = $('#firstJobExperience').val()+'|'+$('#secondJobExperience').val()+'|'+$('#thirdJobExperience').val();
        $.ajax(
        {
            type: 'get',
            url: href,
            cache: false,
            data: "part=insertJobsAndSpecialities&jobsAndSpecialities="+jobsAndSpecialities+"&experiences="+experiences+"&isPopup="+isPopup,
            success: function(data)
            {
                if(data=="0"){
                    $('#validateJobNOk').effect("pulsate", {times:4}, 500);
                }
                else{
                    
                    if(isPopup == 1)
                    {
                        $('.profileJobs').html(data);
                        closePopup();
                    }
                    else
                    {
                        $('#validateJobsOk').effect("pulsate", {times:4}, 500);
                    }
                }
                
            }
        });
   // }

}

function activateEditJobs()
{
    activateAutoWithSelect();
    activateNumericOnlyField();
    
    $('#firstUniverseSelect').change(function(){
        $('#firstJobSelect').attr('disabled','disabled');
        updateUniverseJobs('firstUniverseSelect','firstJob',function(){
            $('#firstJobSelect').attr('disabled','');
            $('#firstJobSelect').change(function(){
                updateJobSpecialities2('firstJobSelect','firstJobFirstSpeciality');
                updateJobSpecialities2('firstJobSelect','firstJobSecondSpeciality');
            });
        });
    });
    $('#secondUniverseSelect').change(function(){
        $('#secondJobSelect').attr('disabled','disabled');
        updateUniverseJobs('secondUniverseSelect','secondJob',function(){
            $('#secondJobSelect').attr('disabled','');
            $('#secondJobSelect').change(function(){
                updateJobSpecialities2('secondJobSelect','secondJobFirstSpeciality');
                updateJobSpecialities2('secondJobSelect','secondJobSecondSpeciality');
            });
        });
    });
    $('#thirdUniverseSelect').change(function(){
        $('#thirdJobSelect').attr('disabled','disabled');
        updateUniverseJobs('thirdUniverseSelect','thirdJob',function(){
            $('#thirdJobSelect').attr('disabled','');
            $('#thirdJobSelect').change(function(){
                updateJobSpecialities2('thirdJobSelect','thirdJobFirstSpeciality');
                updateJobSpecialities2('thirdJobSelect','thirdJobSecondSpeciality');
            });
        });
    });
    $('.spin-button').SpinButton({"min":0,"max":100,"step":1});
    $('#firstJobSelect').change(function(){
        updateJobSpecialities2('firstJobSelect','firstJobFirstSpeciality');
        updateJobSpecialities2('firstJobSelect','firstJobSecondSpeciality');
    });

    $('#secondJobSelect').change(function(){
        updateJobSpecialities2('secondJobSelect','secondJobFirstSpeciality');
        updateJobSpecialities2('secondJobSelect','secondJobSecondSpeciality');
    });

    $('#thirdJobSelect').change(function(){
        updateJobSpecialities2('thirdJobSelect','thirdJobFirstSpeciality');
        updateJobSpecialities2('thirdJobSelect','thirdJobSecondSpeciality');
    });
}

function activateTweazTabs()
{
   
    
    var href = indexPath+"/communAjaxActions";
    $('.TweazTabMenu:not([activated=1])').each(function(){
       $(this).attr('activated',1);
       var menu = $(this);
       
       //charge le premeier onglet
       menu.find('li:first').addClass('selected');
       var firstTabRel = menu.find('li:first').attr('rel');
       $('.TweazTabsContent #'+firstTabRel).show();
       $('.TweazTabsContent #'+firstTabRel).addClass('openedTab');
       
       menu.find('li a').click(function(){
           if(!isTweazTabOpenning)
           {
               
               $('.universRightPart').css('min-height',$('.universRightPart').height());
               var openedTabRel = $(this).parent().attr('rel');
               if($('.TweazTabMenu li.selected').attr('rel') != openedTabRel || $('.TweazTabsContent #'+openedTabRel).html()=='' || ($('.TweazTabsContent .publicationsGoHere').length>0 && $('.TweazTabsContent .publicationsGoHere').html()!=''))
               {
                   isTweazTabOpenning = true;
                   closeDetailPublication();
                   menu.find('li').removeClass('selected');
                   $(this).parent().addClass('selected');
                   
                   openedTabRel = $(this).parent().attr('rel');

                   //affiche l'onglet
                   $('.TweazTabsContent #'+openedTabRel).parents('.TweazTabsContent').find('li.openedTab').fadeOut(function(){
                       
                       $(this).removeClass('openedTab');
                       if($('.TweazTabsContent #'+openedTabRel+' .publicationsGoHere').length > 0 && trim($('.TweazTabsContent #'+openedTabRel+' .publicationsGoHere').html()) != '')
                       {
                           $('.TweazTabsContent #'+openedTabRel).fadeIn(function(){
                               $(this).addClass('openedTab');
                               isTweazTabOpenning = false;
                           });
                       }
                       else if($('.TweazTabsContent #'+openedTabRel+' .publicationsGoHere').length == 0 && $('.TweazTabsContent #'+openedTabRel).html()!=''){
                           $('.TweazTabsContent #'+openedTabRel).fadeIn(function(){
                               $(this).addClass('openedTab');
                               isTweazTabOpenning = false;
                           });
                       }else{
                           switch(openedTabRel){
                               case 'parcours':
                               case 'prices':
                               case 'equipments':
                               case 'studioParcours':
                               case 'studioPrices':
                               case 'studioEquipments':
                               case 'shareHolderSkills':
                               case 'shareHolderInfos':
                               case 'shareHolderCni':
                               case 'shareHolderMinor':

                                   $('.TweazTabsContent #'+openedTabRel).html('<br/><center><img class="loaderMoreCollumn" src="/images/studio/ajax-loader-bar.gif"></center>');
                                   $('.TweazTabsContent #'+openedTabRel).show();
                                   closeDetailPublication(); 
                                    $.ajax(
                                    {
                                        type: 'get',
                                        url: href,
                                        cache: false,
                                        data:{
                                            "part":"loadTweazTabContent",
                                            "tab":openedTabRel
                                        },
                                        success: function(data)
                                        {
                                           $('.TweazTabsContent #'+openedTabRel).html(data);

                                           $('.TweazTabsContent #'+openedTabRel).fadeIn(function(){
                                               $(this).addClass('openedTab');
                                               isTweazTabOpenning = false;
                                           });
                                           switch(openedTabRel)
                                           {
                                               case 'prices':
                                               case 'studioPrices':
                                                   activateTweazWrappers(true);
                                                   activatesCollumnsTableColors();
                                               break;
                                               case 'shareHolderSkills':
                                                   activateRadioBox();
                                               break;
                                               case 'shareHolderInfos':
                                               break;
                                               case 'shareHolderCni':
                                                   loadShareHolderCniUpload();
                                               break;
                                               case 'shareHolderMinor':
                                               break;
                                               case 'equipments':
                                               case 'studioEquipments':
                                                   colorateTabs();
                                                   activeToolTip();
                                               break;
                                               case 'parcours':
                                                    //active les bouton d'édition et de suppression des projets'
                                                    activateActionsButtonForProject();
                                                    activateActionsButtonForOccupedJob();
                                                    activateActionsButtonForStudies();
                                                    activateActionsButtonForDiploma();
                                                    activateActionsButtonForStudioRef();
                                                    activateActionsButtonForArtistRef();
                                                    activateActionsButtonForProRef();
                                                    activeToolTip();
                                                    refreshDirectories();

                                                    $('#directoryName').keyup(function(){
                                                        $(document).stopTime();
                                                        $(document).everyTime("0.4s", function() {
                                                            refreshDirectories();
                                                        });
                                                    });
                                                   colorateTabs();
                                               case 'studioParcours':
                                                   activateTweazSlideBehind();
                                                  // colorateTabs();
                                               break;
                                           }

                                        }
                                    });
                               break;
                               default:
                                   $('.TweazTabsContent #'+openedTabRel).fadeIn(function(){
                                       $(this).addClass('openedTab');
                                       isTweazTabOpenning = false;
                                   });

                                   //si l'onglet contient une collonne de publicatione et que celle ci est vide je charge le contenu
                                   if($('.TweazTabsContent #'+openedTabRel).find('.publicationsContainer').length>0)
                                   {
                                       if($('.TweazTabsContent #'+openedTabRel).find('.publicationsContainer .publicationContainer').length==0)
                                       {
                                           loadMoreCollumn($('.TweazTabsContent #'+openedTabRel).find('.publicationsContainer').attr('type'));
                                       }
                                   }
                               break;
                       }

                       }

                   });
               }



           }
              
       });
       
       
    });
    $('.TweazTabMenu li:first a').click();
}


function updateHeightPage()
{
   
    var firstCollumn = $('.universLeftPart').height();
    var secondCollumn = $('.universRightPart').height();
    if(secondCollumn < firstCollumn)
        {
            $('.universRightPart').css('min-height',firstCollumn+100);
            $('.universLeftPart').css('min-height',firstCollumn+100);
        }
    else 
        {
            $('.universLeftPart').css('min-height',secondCollumn+100);
            $('.universRightPart').css('min-height',secondCollumn+100);       
        }
}



function activateActionsButtonForProject(){
    $('.deleteProjectLine:not([activated=1])').each(function(){
        $(this).attr('activated',1);
        $(this).click(function(){
            var token = $(this).parents('.projectLine').attr('id');
            var href = indexPath+'/communProfileAjaxActions'; 
            $.ajax(
            {
                type: 'get',
                url: href,
                cache: false,
                data: {
                    "part":"popupDeleteProjectLine",
                    "token":token
                },
                success: function(data)
                {
                    $('#popup').html(data);
                    $.fn.colorbox({width:"430px", inline:true, href:"#popup"});
                }
            });

        });


    });

    $('.editProjectLine:not([activated=1])').each(function(){
        $(this).attr('activated',1);
        $(this).click(function(){

            var token = $(this).parents('.projectLine').attr('id');
            var href = indexPath+'/communProfileAjaxActions'; 
            $.ajax(
            {
                type: 'get',
                url: href,
                cache: false,
                data: {
                    "part":"editProjectLine",
                    "token":token
                },
                success: function(data)
                {
                    if($('#projects .formAddNewProject').length>0)
                    {
                        $('#projects .formAddNewProject').slideUp(function(){
                                $(this).remove();
                                $('#projects').prepend(data);

                                $('#projects .formAddNewProject').slideDown();
                        });
                    }
                    else
                        {
                            $('#projects').prepend(data);
                            $('#projects .formAddNewProject').slideDown();
                        }
                    activateAutoEmpty();
                    activateAutocomplete('projectName',200,153,'getAllProjectNames');
                    activateCaracterLeft('#projects .formAddNewProject #description','#projects .formAddNewProject #caracterLeft');
                }
            });

        });


    });
}


function activateActionsButtonForOccupedJob(){
    $('.deleteOccupedJobLine:not([activated=1])').each(function(){
        $(this).attr('activated',1);
        $(this).click(function(){
            var token = $(this).parents('.occupedJobLine').attr('id');
            var href = indexPath+'/communProfileAjaxActions';
            $.ajax(
            {
                type: 'get',
                url: href,
                cache: false,
                data: {
                    "part":"popupDeleteOccupedJobLine",
                    "token":token
                },
                success: function(data)
                {
                    $('#popup').html(data);
                    $.fn.colorbox({width:"430px", inline:true, href:"#popup"});
                }
            });

        });


    });

    $('.editOccupedJobLine:not([activated=1])').each(function(){
        $(this).attr('activated',1);
        $(this).click(function(){

            var token = $(this).parents('.occupedJobLine').attr('id');
            var href = indexPath+'/communProfileAjaxActions';
            $.ajax(
            {
                type: 'get',
                url: href,
                cache: false,
                data: {
                    "part":"editOccupedJobLine",
                    "token":token
                },
                success: function(data)
                {
                    if($('#occupedJobs .formAddNewOccupedJob').length>0)
                    {
                        $('#occupedJobs .formAddNewOccupedJob').slideUp(function(){
                                $(this).remove();
                                $('#occupedJobs').prepend(data);

                                $('#occupedJobs .formAddNewOccupedJob').slideDown();
                        });
                    }
                    else
                        {
                            $('#occupedJobs').prepend(data);
                            $('#occupedJobs .formAddNewOccupedJob').slideDown();
                        }

                        activateAutoEmpty();
                        activateAutocomplete('occupedJobName',200,153,'getAllOccupedJobNames');
                        activateAutocomplete('occupedJobPlace',200,153,'getAllReferencePlaces');
                        activateCaracterLeft('#occupedJobs .formAddNewOccupedJob #description','#occupedJobs .formAddNewOccupedJob #caracterLeft');
                }
            });

        });


    });
}




function activateActionsButtonForDiploma(){
    $('.deleteDiplomaLine:not([activated=1])').each(function(){
        $(this).attr('activated',1);
        $(this).click(function(){
            var token = $(this).parents('.diplomaLine').attr('id');
            var href = indexPath+'/communProfileAjaxActions';
            $.ajax(
            {
                type: 'get',
                url: href,
                cache: false,
                data: {
                    "part":"popupDeleteDiplomaLine",
                    "token":token
                },
                success: function(data)
                {
                    $('#popup').html(data);
                    $.fn.colorbox({width:"430px", inline:true, href:"#popup"});
                }
            });

        });


    });

    $('.editDiplomaLine:not([activated=1])').each(function(){
        $(this).attr('activated',1);
        $(this).click(function(){

            var token = $(this).parents('.diplomaLine').attr('id');
            var href = indexPath+'/communProfileAjaxActions';
            $.ajax(
            {
                type: 'get',
                url: href,
                cache: false,
                data: {
                    "part":"editDiplomaLine",
                    "token":token
                },
                success: function(data)
                {
                    if($('#diplomas .formAddNewDiploma').length>0)
                    {
                        $('#diplomas .formAddNewDiploma').slideUp(function(){
                                $(this).remove();
                                $('#diplomas').prepend(data);
                                $('#diplomas .formAddNewDiploma').slideDown();
                        });
                    }
                    else
                        {
                            $('#diplomas').prepend(data);
                            $('#diplomas .formAddNewDiploma').slideDown();
                        }
                    activateAutoEmpty();
                    activateAutocomplete('diplomaName',200,325,'getAllDiplomaNames');
                }
            });

        });


    });
}

function activateActionsButtonForStudies(){
    $('.deleteStudieLine:not([activated=1])').each(function(){
        $(this).attr('activated',1);
        $(this).click(function(){
            var token = $(this).parents('.studieLine').attr('id');
            var href = indexPath+'/communProfileAjaxActions';
            $.ajax(
            {
                type: 'get',
                url: href,
                cache: false,
                data: {
                    "part":"popupDeleteStudieLine",
                    "token":token
                },
                success: function(data)
                {
                    $('#popup').html(data);
                    $.fn.colorbox({width:"430px", inline:true, href:"#popup"});
                }
            });

        });


    });

    $('.editStudieLine:not([activated=1])').each(function(){
        $(this).attr('activated',1);
        $(this).click(function(){

            var token = $(this).parents('.studieLine').attr('id');
            var href = indexPath+'/communProfileAjaxActions';
            $.ajax(
            {
                type: 'get',
                url: href,
                cache: false,
                data: {
                    "part":"editStudieLine",
                    "token":token
                },
                success: function(data)
                {
                    if($('#studies .formAddNewStudie').length>0)
                    {
                        $('#studies .formAddNewStudie').slideUp(function(){
                                $(this).remove();
                                $('#studies').prepend(data);

                                $('#studies .formAddNewStudie').slideDown();
                        });
                    }
                    else
                        {
                            $('#studies').prepend(data);
                            $('#studies .formAddNewStudie').slideDown();
                        }
                    activateAutoEmpty();
                    activateAutocomplete('studieName',200,321,'getAllSchoolNames');
                    activateAutocomplete('studiePlace',200,321,'getAllTownNames2');
                }
            });

        });


    });
}
function activateActionsButtonForStudioRef()
{
    $('.deleteStudioRefLine:not([activated=1])').each(function(){
        $(this).attr('activated',1);
        $(this).click(function(){
            var token = $(this).parents('.studioRefLine').attr('id');
            var href = indexPath+'/communProfileAjaxActions';
            $.ajax(
            {
                type: 'get',
                url: href,
                cache: false,
                data: {
                    "part":"popupDeleteStudioRefLine",
                    "token":token
                },
                success: function(data)
                {
                    $('#popup').html(data);
                    $.fn.colorbox({width:"430px", inline:true, href:"#popup"});
                }
            });

        });


    });

   /* $('.editStudioRefLine:not([activated=1])').each(function(){
        $(this).attr('activated',1);
        $(this).click(function(){

            var token = $(this).parents('.studioRefLine').attr('id');
            var href = window.location.pathname;
            $.ajax(
            {
                type: 'get',
                url: href,
                cache: false,
                data: {
                    "part":"editStudioRefLine",
                    "token":token
                },
                success: function(data)
                {
                    if($('#studioRefs .formAddNewStudioRef').length>0)
                    {
                        $('#studioRefs .formAddNewStudioRef').slideUp(function(){
                                $(this).remove();
                                $('#studioRefs').prepend(data);

                                $('#studioRefs .formAddNewStudioRef').slideDown();
                        });
                    }
                    else
                        {
                            $('#studioRefs').prepend(data);
                            $('#studioRefs .formAddNewStudioRef').slideDown();
                        }
                    activateAutoEmpty();
                    activateAutocomplete('studioName',200,140,'getAllStudioNames2');
                }
            });

        });


    });*/
}
function activateActionsButtonForArtistRef()
{
    $('.deleteArtistRefLine:not([activated=1])').each(function(){
        $(this).attr('activated',1);
        $(this).click(function(){
            var token = $(this).parents('.artistRefLine').attr('id');
            var href = indexPath+'/communProfileAjaxActions';
            $.ajax(
            {
                type: 'get',
                url: href,
                cache: false,
                data: {
                    "part":"popupDeleteArtistRefLine",
                    "token":token
                },
                success: function(data)
                {
                    $('#popup').html(data);
                    $.fn.colorbox({width:"430px", inline:true, href:"#popup"});
                }
            });

        });


    });

   /* $('.editArtistRefLine:not([activated=1])').each(function(){
        $(this).attr('activated',1);
        $(this).click(function(){

            var token = $(this).parents('.artistRefLine').attr('id');
            var href = window.location.pathname;
            $.ajax(
            {
                type: 'get',
                url: href,
                cache: false,
                data: {
                    "part":"editArtistRefLine",
                    "token":token
                },
                success: function(data)
                {
                    if($('#artistRefs .formAddNewArtistRef').length>0)
                    {
                        $('#artistRefs .formAddNewArtistRef').slideUp(function(){
                                $(this).remove();
                                $('#artistRefs').prepend(data);

                                $('#artistRefs .formAddNewArtistRef').slideDown();
                        });
                    }
                    else
                        {
                            $('#artistRefs').prepend(data);
                            $('#artistRefs .formAddNewArtistRef').slideDown();
                        }
                    activateAutoEmpty();
                    activateAutocomplete('artistName',200,140,'getAllArtistOnlyNames');
                }
            });

        });


    });*/
}
function activateActionsButtonForProRef()
{
    $('.deleteProRefLine:not([activated=1])').each(function(){
        $(this).attr('activated',1);
        $(this).click(function(){
            var token = $(this).parents('.proRefLine').attr('id');
            var href = indexPath+'/communProfileAjaxActions';
            $.ajax(
            {
                type: 'get',
                url: href,
                cache: false,
                data: {
                    "part":"popupDeleteProRefLine",
                    "token":token
                },
                success: function(data)
                {
                    $('#popup').html(data);
                    $.fn.colorbox({width:"430px", inline:true, href:"#popup"});
                }
            });

        });


    });

  /*  $('.editProRefLine:not([activated=1])').each(function(){
        $(this).attr('activated',1);
        $(this).click(function(){

            var token = $(this).parents('.proRefLine').attr('id');
            var href = window.location.pathname;
            $.ajax(
            {
                type: 'get',
                url: href,
                cache: false,
                data: {
                    "part":"editProRefLine",
                    "token":token
                },
                success: function(data)
                {
                    if($('#proRefs .formAddNewProRef').length>0)
                    {
                        $('#proRefs .formAddNewProRef').slideUp(function(){
                                $(this).remove();
                                $('#proRefs').prepend(data);

                                $('#proRefs .formAddNewProRef').slideDown();
                        });
                    }
                    else
                        {
                            $('#proRefs').prepend(data);
                            $('#proRefs .formAddNewProRef').slideDown();
                        }
                    activateAutoEmpty();
                    activateAutocomplete('proName',200,86,'getAllProOnlyNames');
                }
            });

        });


    });*/
}


function refreshDirectories()
{
    $(document).stopTime();
    var name = $('#directoryName').val();
    if(name == $('#directoryName').attr('rel')) name='';
    var href = indexPath+'/communProfileAjaxActions';
    $.ajax(
    {
        type: 'post',
        url: href,
        cache: false,
        data: "part=changeDirectories&name="+name,
        success: function(data)
        {
            $('#musicDirectoriesDiv').html(data);
            activateJScrollPane('scrollableDirectories');
            $('#musicDirectoriesDiv ul li').click(function(){addMusicDirectoryToList($(this).attr('rel'))});
        }
    });
}

function loadStudioFormInPanel(token,isStandardForm,el)
{
    $('.formTable.inProfileRightTabs').removeClass('rightTabLineSelected');
    
    $(el).find('.formTable.inProfileRightTabs').addClass('rightTabLineSelected');
    
    $('#publicationDetailPanelContent').fadeOut(200,function(){
            $('#publicationDetailPanelContent').html('<br/><center><img class="ajax-loader loaderMoreCollumn" src="/images/studio/ajax-loader-bar.gif"></center>');
            $('#publicationDetailPanelContent .ajax-loader').show();
            $('#publicationDetailPanelContent').fadeIn();

           var href = indexPath+'/communProfileAjaxActions';
            $.ajax(
            {
                type: 'get',
                url: href,
                cache: false,
                data:{
                    "part":"loadStudioFormInPanel",
                    "token":token,
                    "isStandardForm":isStandardForm
                },
                success: function(data)
                {
                   fillLeftPanelFromData(data);
                }
            }); 
    });
    
}


function isIE7()
{
    if (/MSIE (\d+\.\d+);/.test(navigator.userAgent))
        { //test for MSIE x.x;
         var ieversion=new Number(RegExp.$1) // capture x.x portion and store as a number
         if (ieversion==7){
            return true;
         }
         else
             return false;
        }
        else
            return false;
}
function isIE8()
{
    if (/MSIE (\d+\.\d+);/.test(navigator.userAgent))
        { //test for MSIE x.x;
         var ieversion=new Number(RegExp.$1) // capture x.x portion and store as a number
         if (ieversion==8){
            return true;
         }
         else
             return false;
        }
        else
            return false;
}
function isFF()
{
    if (/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent))
        { //test for MSIE x.x;
             return true;
        }
        else
            return false;
}


function isIEX()
{
    if (/MSIE (\d+\.\d+);/.test(navigator.userAgent))
        { //test for MSIE x.x;
            return true;
        }
        else
            return false;
}


function activateSpinButton()
{
    $('.spin-button:not([activated=1])').SpinButton({"min":0,"step":1});
    $('.spin-button').attr('activated',1);
}

function filePopup(fileToken)
{
    $.fn.colorbox({
        href: indexPath + "/communWallAjaxActions",
        data: {
            "part":"filePopup",
            "fileToken":fileToken
        },
        onComplete:function(){
            if(isFF())
                window.setTimeout(resizeFilePopup, 100);
        }
    });
    
    /*
    var href = indexPath + "/communWallAjaxActions";
    $.ajax(
    {
        type: 'get',
        url: href,
        cache: false,
        data:{
            "part":"filePopup",
            "fileToken":fileToken
        },
        success: function(data)
        {
            $('#popup').html(data);
            $('#popup').colorbox();
            doIShowDetailPublication = false;
            if(isIEX())
                {
                    var arrowsWidth;
                    
                   if(isIE8())
                       {
                           arrowsWidth = 105;
                       }
                       else
                       {
                            arrowsWidth = 100;
                       }
                       $.fn.colorbox({
                           width:"0 px",
                            inline:true, 
                            href:"#popup",onComplete:function() {
                                var widthPopup  = arrowsWidth+$('#popup .fileContainer').width();
                                $.fn.colorbox({
                                   width:widthPopup+" px",
                                    inline:true,
                                    href:"#popup",onComplete:function() {
                                        var photoHeight = $('#popup .fileContainer').height();
                                        $('.leftArrowContainer').height(photoHeight);
                                        $('.rightArrowContainer').height(photoHeight);
                                    }
                                });
                            }
                        });
                }
                else if(isFF() && data.indexOf("<object",0)>-1){
                        $.fn.colorbox({
                            inline:true,
                            href:"#popup",onComplete:function() {
                                window.setTimeout(resizeFilePopup, 10);
                            }
                        });
                    }
                else{
                    
                        $.fn.colorbox({
                            inline:true, 
                            href:$"#popup",
                            onComplete:function() {
                                var photoHeight = $('#popup .fileContainer').height();
                                $('.leftArrowContainer').height(photoHeight);
                                $('.rightArrowContainer').height(photoHeight);
                            }
                        });
                    }
           
        }
    });*/
}

function resizeFilePopup()
{
    var photoHeight = $('.popupContent:visible .fileContainer').height();
    if(photoHeight>0)
    {
        $('.popupContent').css("height",photoHeight+50);
       // $('.leftArrowContainer').height(photoHeight);
       // $('.rightArrowContainer').height(photoHeight);
        $.colorbox.resize(
        {
            Height:(photoHeight+50)
        }
        );
    }
    else
    {
        window.setTimeout(resizeFilePopup, 100);
    }
    
}
function showNeedConnexionPopup(hideMessage)
{
    if(!hideMessage)
        hideMessage = 0;
    var href = indexPath + "/communAjaxActions";
    $.ajax(
    {
        type: 'get',
        url: href,
        cache: false,
        data:{
            "part":"showNeedConnexionPopup",
            "hideMessage":hideMessage
        },
        success: function(data)
        {
           $('#popup').html(data);
           activateAutoEmpty();
           activateRadioBox();
           $.fn.colorbox({
                width:"600px", 
                inline:true, 
                href:"#popup"
            });
        }
    });
}
function is_int(value){ 
    value = value.replace(' ', '');
   return !isNaN(parseInt(value * 1));
}


function lookForFacebookContacts() {
    saveFacebookId(lookForFacebookContactsCallBack);    
}
function lookForFacebookContactsCallBack() {
    var profileUrl = $('#profileUrl').html();
    var message = $('#facebookDirectMessage').html();
    var contents = '<fb:request-form action="'+$('#facebookReturnUrl').html()+'"  method="POST" invite="true" type="Tweaz" content="'+message+' <fb:req-choice url=\''+profileUrl+'\' label=\'Aller sur Tweaz\' /> "><fb:multi-friend-selector showborder="false" cols="4" rows="3" exclude_ids="" actiontext="Choisissez les amis à inviter."></fb:multi-friend-selector> </fb:request-form>';
    FB.ui({
        method: 'fbml.dialog',
        fbml: (contents),
        size: {width:630,height:600}, width:630, height:600
    });
    
    $(".FB_UI_Dialog").css('width', 630); 
}

function publishToWall(){
    saveFacebookId(publishToWallCallBack);
}
function publishToWallCallBack(){
    FB.ui(
   {
     method: 'feed',
     name: $('#facebookWallTitle').html(),
     link: $('#profileUrl').html(),
     picture: $('#tweazPicture').html(),
     caption: $('#facebookWallObject').html(),
     description: $('#facebookWallMessage').html(),
     message: $('#facebookWallMessage').html()
   },
   function(response) {
   }
 );
}
function publishLinkToWall(url){
    saveFacebookId(publishLinkToWallCallBack,url);
}
function publishLinkToWallCallBack(url){
   authNotifPreviewRedirect = false;
    FB.ui(
   {
     method: 'feed',
     link: url
   },
   function(response) {
   }
 );
}

function publishOnFacebook()
{
     saveFacebookId(publishOnFacebookCallBack);
}

function publishOnFacebookCallBack()
{ 
    $('#publishOnFacebook').html('');
    var href = indexPath + "/communAjaxActions";
    $.ajax(
    {
        type: 'get',
        url: href,
        cache: false,
        data:{
            "part":"publishOnFacebook"
        },
        success: function(data)
        {
        }
    });
}

function connectTweazToFacebook(){
   saveFacebookId(connectTweazToFacebookCallBack);
}
function connectTweazToFacebookCallBack()
{
    $('#visibilityFacebookConnectButton').hide();
    $('#visibilityFacebookConnectSucceed').show();
    var href = indexPath + "/communAjaxActions";
    $.ajax(
    {
        type: 'get',
        url: href,
        cache: false,
        data:{
            "part":"publishOnFacebook"
        },
        success: function(data)
        {
        }
    });
}
function saveFacebookId(callBack,param)
{ 
     FB.login(function(response) {
        if (response.authResponse) {
                FB.api('/me', function(user) {
                   if(user.id != undefined) {
                       var facebookId = user.id;
                       var access_token = response.authResponse.accessToken;
                       var href = indexPath + "/communAjaxActions";
                        $.ajax(
                        {
                            type: 'get',
                            url: href,
                            cache: false,
                            data:{
                                "part":"saveFacebookId",
                                "facebookId":facebookId,
                                "access_token":access_token
                            },
                            success: function(data)
                            { 
                                 if(callBack)
                                     {
                                         if(param)
                                            callBack(param);
                                        else
                                            callBack();
                                     }
                            }
                        });
                    }
                      
                 });

                // user is logged in and granted some permissions


         
        } else {
        // user is not logged in
        }
        }, {
            scope:'email,user_birthday,user_website,read_friendlists,publish_stream,offline_access'
        });
}

function hideVisibilityHelp(){
    $('#visiblityHelpPopup').fadeOut();
}

function showVisibilityHelp(isFirst)
{
    if($('#visiblityHelpPopup:visible').length>0)
        {
           hideVisibilityHelp();
        }
    else
        {
            if(isFirst)
            {
                $('#visiblityHelpPopup').hide().delay(3500).fadeIn(800);
                var href = indexPath + "/communAjaxActions";
                $.ajax(
                {
                    type: 'get',
                    url: href,
                    cache: false,
                    data:{
                        "part":"showVisibilityHelp"
                    },
                    success: function(data)
                    {

                    }
                });
            }
            else
            {
                $('#visiblityHelpPopup').fadeIn();
            }
        }
}



function switchFacebookAutoPublish() {
    var href = indexPath + "/communAjaxActions";
    $.ajax(
    {
        type: 'get',
        url: href,
        cache: false,
        data:{
            "part":"switchFacebookAutoPublish"
        },
        success: function(data)
        {
            var checkbox = $('.visibilityFacebookCheckbox .checkBox');
           if(data == '1')
           {
               checkbox.removeClass('unchecked');
               checkbox.addClass('checked');
           }
           else
           {
               checkbox.removeClass('checked');
               checkbox.addClass('unchecked');
           }
        }
    });
}

function getPhonePopup(profileToken,obj)
{
    if($('.moreInfosForAdFirstHelp:visible').length>0)
    {
        $('.moreInfosForAdFirstHelp').fadeOut(function(){
            $(this).remove();
            getPhonePopupCallBack(profileToken,obj);
        });
    }
    else
        getPhonePopupCallBack(profileToken,obj);
}

function getPhonePopupCallBack(profileToken,obj)
{
    
        var href = indexPath + "/communAjaxActions";
        $.ajax(
        {
            type: 'get',
            url: href,
            cache: false,
            data:{
                "part":"getPhonePopup",
                "profileToken":profileToken
            },
            success: function(data)
            {
                $('body').append(data);
                var linkTop = 0;
                var linkLeft = 0;
                var leftDelta=104;
                var topDelta=75;
                linkTop = $(obj).offset().top; 
                linkLeft = $(obj).offset().left;  
                
                $('.moreInfosForAdFirstHelp_4').css('top',linkTop-topDelta); 
                $('.moreInfosForAdFirstHelp_4').css('left',linkLeft-leftDelta); 
                $('.moreInfosForAdFirstHelp_4').fadeIn(); 
            }
        });
}

function showFirstHelpBubble(mode,obj){
    
    if($('.moreInfosForAdFirstHelp:visible').length>0)
        {
            $('.moreInfosForAdFirstHelp').fadeOut(function(){
                $(this).remove();
                showFirstHelpBubbleCallBack(mode,obj);
            });
        }
        else
            showFirstHelpBubbleCallBack(mode,obj);
}

function showFirstHelpBubbleCallBack(mode,obj)
{
    if(!mode)
        mode = $('.publicationContainer:first .moreInfosForAdLink').attr('isfirstsell');
    
    if(mode>0)
    {
        var href = indexPath + "/communAjaxActions";
        $.ajax(
        {
            type: 'get',
            url: href,
            cache: false,
            data:{
                "part":"isfirstsell",
                "mode":mode
            },
            success: function(data)
            {
                    
                $('body').append(data);
                activateAutoEmpty();
                var linkTop = 0;
                var linkLeft = 0;
                
                var leftDelta = 0;
                var topDelta = 0;
                
                switch(mode)
                {
                    case '1':
                            leftDelta=104;
                            topDelta=84;
                            if(!obj)
                            {
                                linkTop = $('.moreInfosForAdLink:first[isfirstsell='+mode+']:first').offset().top;
                                linkLeft = $('.moreInfosForAdLink:first[isfirstsell='+mode+']:first').offset().left; 
                            }
                            else
                            {
                                linkTop = $(obj).offset().top;
                                linkLeft = $(obj).offset().left; 
                            }
                            
                        break;
                    case '2':
                    case '4':
                            if(!obj)
                            {
                                linkTop = $('.publicationPhoneLink:first').offset().top;
                                linkLeft = $('.publicationPhoneLink:first').offset().left; 
                            }
                            else
                            {
                                linkTop = $(obj).offset().top;
                                linkLeft = $(obj).offset().left; 
                            }    
                            leftDelta=104;
                            topDelta=75;
                        break;
                    case '3':
                            leftDelta=104;
                            topDelta=146;
                            if(!obj)
                            {
                                linkTop = $('.moreInfosForAdLink:first[isfirstsell='+mode+']:first').offset().top;
                                linkLeft = $('.moreInfosForAdLink:first[isfirstsell='+mode+']:first').offset().left; 
                            }
                            else
                            {
                                linkTop = $(obj).offset().top;
                                linkLeft = $(obj).offset().left; 
                            }     
                        break;
                }
                
                $('.moreInfosForAdLink:first[isfirstsell='+mode+']').attr('isfirstsell',0);
                
                $('.moreInfosForAdFirstHelp_'+mode).css('top',linkTop-topDelta);
                $('.moreInfosForAdFirstHelp_'+mode).css('left',linkLeft-leftDelta);
                $('.moreInfosForAdFirstHelp_'+mode).fadeIn();
            }
        });
    }
}
function closeMoreInfosForAdFirstHelp(neverShow)
{
    $('.moreInfosForAdFirstHelp').fadeOut(function(){
        $(this).remove();
       if(neverShow)
           {
               var href = indexPath + "/communAjaxActions";
                $.ajax(
                {
                    type: 'get',
                    url: href,
                    cache: false,
                    data:{
                        "part":"neverShowMoreInfosForAdFirstHelp"
                    },
                    success: function(data)
                    {

                    }
                });
           }
    });
}

function legalInfosPopup()
{
    $.fn.colorbox({
        width:"450px", 
        inline:true, 
        href:"#legalInfosPopup"
    });
}
