/*
 * Fonctions lancées au démarrage
 */

// Permet de garder un back
var backupData = new Array();
var backupS    = 5;


//Genere un mot de passe et attends un nombre de caractere et l'id de l'input
function generatePassword(nbcar,input){

        $.ajax({
            type: "POST",
            url: urlConfig+"/wm-public/scripts/space-generatePassword.ajax.php",
            data : "nbcar="+nbcar,
            success: function(data){

                $("#"+input).val(data);
            }
        });

}

//Ferme tous les widgets
function closeWidgets() {

    $("#widget h3 a").parent().next().slideUp("1100");
    $("#widget h3 a").parent().parent().addClass("close");
}

//Ferme unwidget selon l'id passé
function closeThisWidget(widget) {

    $("#"+widget).addClass("close");
}


//Change le captcha illisible
function changeSecureImage(relative) {
    $("#captcha").attr("src",relative+"/wm-public/tools/securimage/securimage_show.php?sid=" + Math.random());
    $(".captcha").attr("src",relative+"/wm-public/tools/securimage/securimage_show.php?sid=" + Math.random());
    return false;
}


//Nettoie...
function formSanitize(str) {
    str=str.replace(/\"/gi,"&quot;");
    str=str.replace(/\n/g, " ");
    return str;
}


//inclus un javascript - pas vraiment utilisé je pense
function includeJS(url)

{
    var script = document.createElement('script')

    script.type = 'text/javascript';

    script.src = url;

    $("head").append(script);
}

/*
 * récriture du in_array de PHP
 */
Array.prototype.in_array = function(p_val) {
    for(var i = 0, l = this.length; i < l; i++) {
        if(this[i] == p_val) {
            rowid = i;
            return true;
        }
    }
    return false;
}

$(document).ready( function () {
	
	// SEB 
	//	1 - Fiche client logo, on positionne le logo centré sur l'axe x & y 
	//  -----------------------------------------------------------------------------------------
	var zone_width = $("#fiche-logo").width();
	var zone_height = $("#fiche-logo").height();
	
	var logo_width = $("#fiche-logo img").width();
	var logo_height = $("#fiche-logo img").height();
	
	var logo_posX = (zone_width - logo_width)/2;
	var logo_posY = (zone_height - logo_height)/2;
	
	$("#fiche-logo img").css ({ "paddingLeft" : logo_posX, "paddingTop" : logo_posY});	
			
			
	//	2 - Résultats de recherche, on positionne les logos centrés sur l'axe x & y 
	//  -----------------------------------------------------------------------------------------
	// Int
	var search_width = $("#search-engine-results .list-results .visual").width();
	var search_height = $("#search-engine-results .list-results .visual").height();
	
	/* on parcours tous les éléments
	$('#search-engine-results .list-results .visual').each(
		function() {
			
			var search_logo_width = $(this).children("img").width();
			var search_logo_height = $(this).children("img").height();
			
			var search_logo_posX = (search_width - search_logo_width)/2;
			var search_logo_posY = (search_height - search_logo_height)/2;
			
			$(this).children("img").css ({ "paddingLeft" : search_logo_posX, "paddingTop" : search_logo_posY});
		}
	); */

    /* VIDE LES CHAMPS DES FORMULAIRES */

    $("#rencontrer-un-commercial input[type='text']").focus(function()  {if(this.value == this.defaultValue) {this.value = "";}});
    $("#rencontrer-un-commercial input[type='text']").blur(function()  {if(this.value == "") {this.value = this.defaultValue;}});
    $("#rencontrer-un-commercial textarea").focus(function()  {if(this.value == this.defaultValue) {this.value = "";}});
    $("#rencontrer-un-commercial textarea").blur(function()  {if(this.value == "") {this.value = this.defaultValue;}});

    $("#plus-de-documentation input[type='text']").focus(function()  {if(this.value == this.defaultValue) {this.value = "";}});
    $("#plus-de-documentation input[type='text']").blur(function()  {if(this.value == "") {this.value = this.defaultValue;}});
    $("#plus-de-documentation textarea").focus(function()  {if(this.value == this.defaultValue) {this.value = "";}});
    $("#plus-de-documentation textarea").blur(function()  {if(this.value == "") {this.value = this.defaultValue;}});

    $("#concours input[type='text']").focus(function()  {if(this.value == this.defaultValue) {this.value = "";}});
    $("#concours input[type='text']").blur(function()  {if(this.value == "") {this.value = this.defaultValue;}});

    $("#changePassword input[type='text']").focus(function()  {if(this.value == this.defaultValue) {this.value = "";}});
    $("#changePassword input[type='text']").blur(function()  {if(this.value == "") {this.value = this.defaultValue;}});

    $("#frm_keywords").focus(function()  {if(this.value == this.defaultValue) {this.value = "";}});
    $("#frm_keywords").blur(function()  {if(this.value == "") {this.value = this.defaultValue;}});

    $("#formID #frm_mail").focus(function()  {if(this.value == this.defaultValue) {this.value = "";}});
    $("#formID #frm_mail").blur(function()  {if(this.value == "") {this.value = this.defaultValue;}});

    $(".inputToEmpty").focus(function()  {if(this.value == this.defaultValue) {this.value = "";}});
    $(".inputToEmpty").blur(function()  {if(this.value == "") {this.value = this.defaultValue;}});

    /*
     * Liste des membres effet de survol
     *
     **/
    
    $(".logos-result .denomination").hover(function(){$(this).css({"opacity":"1"})},function(){$(this).css({"opacity":"0"})})


    /**
     * pas de listing ajout de fiches, petit datepicker n'es ce pas
     **/

    if($("#frm_date_go").length) {

        $("#frm_date_go").datepicker({
                changeMonth: true,
                maxDate : 0,
                regional: 'fr'
        });

        $("#frm_date_end").datepicker({
                changeMonth: true,
                maxDate : 0,
                regional: 'fr'
        });
        
        //Fonciton qui réaffcihe les fiches selon un time stamp

        $("#frm_date_go").change(function(){

            //reload news
            $.ajax({
                type: "POST",
                url: urlConfig+"/wm-public/scripts/space-getAddFromTimeStamp.ajax.php",
                data: "timestampstart="+$("#frm_date_go").val()+"&timestampend="+$("#frm_date_end").val(),
                success: function(data){

                    if(data!="") {
                        $("#list-add").html(data);
                    }
                }
            });

        })

        $("#frm_date_end").change(function(){

            //reload news
            $.ajax({
                type: "POST",
                url: urlConfig+"/wm-public/scripts/space-getAddFromTimeStamp.ajax.php",
                data: "timestampstart="+$("#frm_date_go").val()+"&timestampend="+$("#frm_date_end").val(),
                success: function(data){

                    if(data!="") {
                        $("#list-add").html(data);
                    }
                }
            });

        })
    }
    
    /* ******************************** */

    /* INITIALISATION DES ALBUMS PHOTOS */

    $("#fiche-banner li a").lightBox({
        overlayBgColor: "#000",
        containerResizeSpeed: 350,
        txtImage: "",
        txtOf: "/"
    });

    $("#events li a").lightBox({
        overlayBgColor: "#000",
        containerResizeSpeed: 350,
        txtImage: "",
        txtOf: "/"
    });

    $("#events-mif li a").lightBox({
        overlayBgColor: "#000",
        containerResizeSpeed: 350,
        txtImage: "",
        txtOf: "/"
    });

    $(".wm-gallery a").lightBox({
        overlayBgColor: "#000",
        containerResizeSpeed: 350,
        txtImage: "",
        txtOf: "/"
    });

    $(".wm-gallery a").lightBox({
        overlayBgColor: "#000",
        containerResizeSpeed: 350,
        txtImage: "",
        txtOf: "/"
    });

    $("#presse .journal a").lightBox({
        overlayBgColor: "#000",
        containerResizeSpeed: 350,
        txtImage: "",
        txtOf: "/"
    });

    $(".wm-gallery a:nth-child(5n)").addClass("lastColumn");

    /* ************************************************** */

    /**
     *
     * TEST MAP FULL
     *
    */

    /*Affiche les images des communes sur la home quand ils sont chargés*/
    $(".slideshow .item").fadeIn();
    //Animations sur la home
    $('.slideshow').cycle({
        fx: 'custom',
        cssBefore: {top:  0,left: 0,width: 0,height: 0,zIndex: 1},
        animIn:  {width: 210,height: 120},
        cssAfter: {zIndex: 0},delay: -1000
    });


    /* GESTION DES NEWS */

    //Masque les textes body des news
    $(".txt-body").hide();
    $(".btnMore a").html($(".btnMore a").attr("show"));
    
    //on regarde si il faut afficher une news en particulier ou la premiere (si on en a pas précisé)
    if ($(".showthatone").length) {
        $(".showthatone .txt-body").show();
        $(".showthatone .btnMore a").html($(".btnMore a").attr("hide"));
    }
    else {
        //$(".txt-body:first").show();
        //$(".btnMore:first a").html($(".btnMore a").attr("hide"));
    }


    $(".btnMore a").click(
        function () {
            if ($(this).html() == $(this).attr("show")) {
                $(".txt-body").slideUp();
                $(".btnMore a").html($(".btnMore a").attr("show"));
                $(this).parent().prev(".txt-body").slideDown();
                $(this).html($(this).attr("hide"));
            }
            else {
                $(this).parent().prev(".txt-body").slideUp();
                $(this).html($(this).attr("show"));
            }
        }
    );

    $("#newsPrev").click(function(){

        //reload news
        $.ajax({
            type: "POST",
            url: urlConfig+"/wm-public/scripts/newsMotion.ajax.php",
            data: "act=1",
            success: function(data){
                if(data!="") {
                    $(".list-news").html(data);
                }
            }
        });
    })

    $("#newsNext").click(function(){

        //reload news
        $.ajax({
            type: "POST",
            url: urlConfig+"/wm-public/scripts/newsMotion.ajax.php",
            data: "act=2",
            success: function(data){

                if(data!="") {
                    $(".list-news").html(data);
                }
            }
        });
    })

    /* ********************************************************************** */

    /* GESTION DES EVENTS EN FAMENNE */

    $(".liensEvents").change(function() {

        window.location.href = $(this).val();
    })

    /***********************************/

    /* GESTION DES CONCOURS */
        
    $("#concours .list-results a").click(function () {

        $(".noborder").removeClass("noborder");

        $("#meteo").addClass("close");
        $("#imageconcours"+$(this).attr("rel")+" .img").remove();


        if($("#legendeImg"+$(this).attr("rel")).attr("rel") != '') {

            $("#legendImg"+$(this).attr("rel")).html($("#legendImg"+$(this).attr("rel")).attr("rel"));
        }

        $(".list-results").fadeOut("fast");
        $(".list-results-winners").fadeOut("fast");
        $("#winners-title").fadeOut("fast");
        //$(".pagination").removeClass("displayNone");
        $("#"+$(this).attr("rel")).next().fadeIn("100");
        $("#"+$(this).attr("rel")).fadeIn("100");
        $("#imageconcours"+$(this).attr("rel")+" .img2").fadeIn("fast");


        $("html:not(:animated),body:not(:animated)").animate({scrollTop: 0+"px"}, 1100);

        $(".pagination").fadeIn();
    });

    /* ******************************** */

    /* GESTION DES WIDGETS */

    $("#widget h3 a").click(function(){

        if($(this).parent().parent().hasClass("close")) {

            $(this).parent().next().slideDown("1100");
            $(this).parent().parent ().removeClass("close");
        }
        else {

            $(this).parent().next().slideUp("1100");
            $(this).parent().parent().addClass("close");
        }
    })

    /* GESTION DES LIRE LA SUITE SUR LA PAGE DEVENIR MEMBRE*/

    $("#devenir-membre .btnMore").click(function(){


        if($(this).html()=="Fermer") {

            $(this).addClass('btnMore');
            $(this).removeClass('btnMin');
            $(this).parent().prev().slideUp("1500");
            $(this).html("Lire la suite");
        } else {

               $(".btnMin").html("Lire la suite");
               $(".btnMin").addClass('btnMore');
               $(".btnMin").removeClass('btnMin');
               $(this).removeClass('btnMore');
               $(this).addClass('btnMin');
               $('.elementHide').slideUp("1500");
               
               $(this).html("Fermer");
               $(this).parent().prev().slideDown("1500");
        }
    })


    //cette partie du code gère les "lire la suite" multiple au sein d'une page
    $("a.wm-readmore-multiple").html($("a.wm-readmore-multiple").attr("show"));

    $("a.wm-readmore-multiple").click(
        function () {
            $(this).hide();
            $('.wm-readmore-multiple-hidden:hidden:first').slideDown();
        }
    );

    //INFOS UTILES - BUS TEC - COMBO BOX
    $(".Scommunes").change(function()  {

        id=$(this).attr("rel");
        val=$(this).val();

        $("div[rel=PDF"+id+"]").slideUp("1000");

        $("#description"+id+" .SLignes").addClass("displayNone");
        $("#description"+id+" .SLignes").fadeOut("fast");

        $("select[commune="+val+"]").removeClass("displayNone");
        $("select[commune="+val+"]").fadeIn("fast");
        
        Ville = $("#V"+id).val();

        ligne=$("select[commune="+val+"]").val();

         $("div[rel=PDF"+id+"]").html("<a class='floatRight' href='#' target='_blank'>"+$("#Scommunes"+id+"").val()+" - "+Ville+"<br /></a>");

    })

    $(".SLignes").change(function()  {

        id=$(this).attr("rel");
        val=$(this).val();

        Ville = $("#V"+id).val();

        $("div[rel=PDF"+id+"]").slideDown("1000");

        $("div[rel=PDF"+id+"]").html("<a class='floatRight' href='"+urlConfig+"/wm-media/tec/pdfs/"+val+".pdf' target='_blank'>"+$("#Scommunes"+id+"").val()+" - "+Ville+"<br />"+val+"</a>");
    })


	

});


/* DEVENIR MEMBRE LOGOS QUI TOURNENT */

boucl1 = '';
boucl2 = '';

function startLogos(){

    getLogos();
    boucl1 = setTimeout('setLogos()',8000);
}

function setLogos(){

    clearTimeout(boucl1);
}


function getLogos() {

//reload news
$.ajax({
    url: urlConfig+"/wm-public/scripts/devenimembre-getLogos.ajax.php",
        type: "POST",
    dataType: "json",
    success: function(data){
        
        var content = "";
        var i       = 0;
        var myTimeout = 0; 
        var myIncrement = 1000;
        for (i=0; i<13; i++) {
            $("#imgS"+i).append('<a class="newImages" style="display:none;width:80px;height:60px" href="'+data[i].url+'/"><img src="'+data[i].src+'" alt="Logo de '+data[i].name+' sur made in famenne" width="80" height="60"/><span class="arrow"></span></a>');
            
            changeLogo(i, myTimeout);
            myTimeout = myTimeout+myIncrement;
    
        }
        
            
            
    }
});


}

function changeLogo(id, timeOut) {

            setTimeout(function() {
                  $("#imgS"+id+" a:first").remove();
                  $("#imgS"+id+" a:last").fadeIn("1500");
                  if(id==12) {getLogos();}
                  
            },timeOut);

}


