
$(document).ready(function(){
  
   
    try {
        $('#moreActu').newsSwitcher();
    } catch (exception) {

    }

    try {
        $('#contactForm').validForm();
    } catch (exception) {

    }

    try {
       $('#moreActu').newsSwitcher();
    } catch (exception) {

    }

    try {
        $('.star-rating input').starRating();
    } catch (exception) {}

    try {
        $('#file').customFileInput();
    } catch (exception) {

    }

    $('#logo').click(function(){
        document.location.href = baseUrl;
    })

   $('#SendNewsletter').click(function(){

      var email = $('#newsEmail').val();
      var abonnement =  $('#abonnement').val();
      var url = baseUrl+"index.php/login/newsletter";
      var action
      if($('#abonnement').is(':checked')){
          action = 1;
      }else{
          action= 0;
      }

       var data = "email="+email+"&action="+action;
                $.ajax({
                     url: url,
                     type: "POST",
                     data: data,
                     dataType: "json",
                     success: function(result)
                            {
                               if(result){
                                  $('#newsLetterDirect form').fadeOut(400, function(){
                                      var markup;
                                      if(action == 1){
                                          markup = '<p class="success" style="width:200px; height=400px;">Inscription correctement enregistée !</p>';
                                      }else{
                                          markup = '<p class="success" style="width:200px; height=400px;">Désinscription correctement enregistée !</p>';
                                      }
                                      $('#newsLetterDirect').append(markup);
                                  })

                               }else{
                                   errorsDisplay("Erreur newsletter", "L'adresse Email est invalide ou le serveur n'a put enregistrer votre demande");
                               }

                            }
                              });

       return false;
   })


    startGalleries();
    persoPicture();
    galleryDoc();






/*
 * If the module is initialized, start the different sort of galleries
 */

function startGalleries() {


    // Try to launch the galleryView
   try {
            //Show all the pictures (correct the fix if no JS enable)
            $('.galleryViewSmall li').show();
            $('.galleryViewBig li').show();

            //Display the small Galleries
            $('.galleryViewSmall').galleryView({
                panel_width: 220,
                panel_height: 164,
                frame_width: 80,
                frame_height: 80
            });

            //Display the full screen galleries
            $('.galleryViewBig').galleryView({
                panel_width: 500,
                panel_height: 373,
                frame_width: 100,
                frame_height: 100,
                transition_speed: 1200,
                background_color: 'transparent',
                border: 'none',
                easing: 'easeOutBounce',
                pause_on_hover: true
            });
    }catch (exception) {

    }

    //Try to launch the nivoGallery
    try {
        $('.nivoGallerie').nivoSlider();
    } catch (exception) {

    }

}

function persoPicture(){
    

    $('.admin, .userConnect').click(function(){
            
            $("#ajaxLogin, #ajaxLogin input").keypress(function(e){
                if(e.which==13) logIn();
             });


           $("#ajaxLogin" ).dialog({
			resizable: false,
                        width: 600,
                        height:350,
			modal: true,
			buttons: {
				"Valider": function() {
                                        logIn();
				},
				"Fermer": function() {
					$( this ).dialog( "close" );
				}
			}
		});
         return false;
        });

         $('#username').change(function(){
               var username = document.getElementById('ajaxLoginForm').elements['username'].value;
               if( username== '')
                   return;

                var url = baseUrl+"index.php/login/searchPersoPicture";
                var data = "username="+username;
                $.ajax({
                     url: url,
                     type: "POST",
                     data: data,
                     dataType: "json",
                     error: function () {
                           // errorsDisplay("Serveur Erreur", "Un problème est survenue pendant la connexion avec le serveur");
                         },

                     success: function(result)
                            {
                                var reload = false;
                                var resp = eval(result);
                                var markup;
                                if(resp.id != 0){
                                    markup ='<img src="'+baseUrl+'ressources/docs/'+resp.server_name+resp.ext+'"</img>';
                                     $("#picturePlace").fadeOut("slow", function(){
                                        $("#picturePlace").empty().append(markup).fadeIn("slow");
                                        reload = true;
                                 })}
                                else{
                                    if(reload){
                                        markup ='<img src="'+baseUrl+'ressources/docs/NoPicture.gif"</img>';
                                        $("#picturePlace").fadeOut("slow", function(){
                                        $("#picturePlace").empty().append(markup).fadeIn("slow");
                                        reload = false;
                                        })
                                    }
                                }
                            }
                              });
            })
        }

function logIn(){
               var username = $('#username').val();
               var password = $('#password').val();
               if (username == '' || password =='' ){
                   errorsDisplay("Erreur de login", "Vous devez remplir tous les champs");
               }

                var url = baseUrl+"index.php/login/ajax_login";
                var data = "username="+username+"&password="+password;
                $.ajax({
                     url: url,
                     type: "POST",
                     data: data,
                     dataType: "json",
                     error: function () {
                          // errorsDisplay("Serveur Erreur", "Un problème est survenue pendant la connexion avec le serveur");
                         },
                     success: function(result)
                            {
                               if(result){
                                   if (jQuery.browser.msie) {
                                              var version = parseInt(jQuery.browser.version)
                                              if(version < 7){
                                                errorsDisplay("Navigateur trop ancien", "Connexion impossible : Votre navigateur est trop vétuste.");
                                              }else if(version < 8){
                                               errorsDisplay("Navigateur trop ancien", "Veuillez mettre votre navigateur à jour pour avoir toutes les fonctionalitées.","index.php/admin");

                                              }else{
                                                document.location.href = baseUrl+"index.php/admin";
                                              }
                                       }
                                       document.location.href = baseUrl+"index.php/admin";

                               }else{
                                   errorsDisplay("Erreur de login", "Mot de passe ou nom d'utilisateur invalide");
                               }

                            }
                              });

        }

function errorsDisplay(errorName, errorMsg, redirect){

                var markup = '<div id="dialog-message" title="'+errorName+'" style="display:none;">\
                               <p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 50px 0;"></span>'+errorMsg+'</p>\
                               </div>'

                $('body').append(markup);

                $("body").keypress(function(e){
                     if(e.which==13) $( "#dialog-message" ).dialog("close");
                 });

                 $( "#dialog-message" ).dialog({

                     modal: true,
                     buttons: [
                    {
                        text: "Ok",
                        click: function() {$(this).dialog("close");

                                $("#dialog-message").remove();
                                if(typeof(redirect) != 'undefined'){
                                    document.location.href = baseUrl+redirect;
                                }

                    }
                    }
                ]});


}

function galleryDoc(){
    //On crée les gallerie d'images pour les articles en ayant besoins'
    $('.galleriesPdf').each(function(){
        $(this).empty();
      if($(this).hasClass("hasGalleriePdf")){
          return;
      }

      $(this).addClass("hasGalleriePdf");


       var artId = $(this).closest('.article').attr('id');
       artId = artId.substr(4, artId.length);

       
       //On injecte le markup
       $(this).closest('.article').append('<div class="docGalleriesManager" id="dgm-'+artId+'"><h4 class="collapse" id="coldgm-'+artId+'"><span class="collapsible-heading collapsed"></span><a href="#">Documents Partagés :</a></h4><div class="collapse-container hide" style="display:none"><div id="docGalPlace-'+artId+'" class="docGalPlaces"></div></div></div>');

             $("#coldgm-"+artId).click(function(){
                 if($(this).next(".collapse-container").is(".hide")){
                        $(this).find("span").removeClass("collapsed");
                        $(this).next(".collapse-container").slideUp(function(){
                            $(this).show();
                            $(this).removeClass("hide");


                        })
                  }else{
                      $(this).find("span").addClass("collapsed");
                      $(this).next(".collapse-container").slideDown(function(){
                          $(this).hide();
                          $(this).addClass("hide");

                      })

                  }
                  return false;
                })



       // On lance le gallerie Manager
        $('#docGalPlace-'+artId).docGallerie({
                controllerUrl:baseUrl + 'index.php/admin-ajax/Galleriedoc/refresh/'+artId+"/null",
                deleteUrl: baseUrl+ 'Galleriedoc/delete/',
                sortUrl: baseUrl +'Galleriedoc/sort/',
                isProtectedUrl: baseUrl +'Galleriedoc/isProtect/'+artId,
                id :'#docGalPlace-'+artId,
                admin: false
                    });
    })
}


});

