/*
 *
 *  JAVASCRIPTS LIES A L'AFFICHAGE ET EDITION D'UNE FICHE
 *
 */
var lastID = 0;

//objet qui contient une adresse de fiche
function SpaceAdress(name, adress, cp, city, tel, fax, mail, url, area, areaName, openingHours, specials,latitude,longitude) {

    this.name           = name;
    this.adress         = adress;
    this.cp             = cp;
    this.city           = city;
    this.tel            = tel;
    this.fax            = fax;
    this.mail           = mail;
    this.url            = url;
    this.area           = area;
    this.areaName       = areaName;
    this.openingHours   = openingHours;
    this.specials       = specials;
    this.latitude       = latitude;
    this.longitude      = longitude;


    this.__get = function (paramName) {
        if ( typeof(this[paramName]) != "undefined" )
            return(this[paramName])
        return (false);
    }

    this.__set = function (paramName, paramValue) {
        this[paramName] = paramValue;
    }
}




function addAdress (name, adress, cp, city, tel, fax, mail, url, area, areaName, openingHours, specials) {

    $("#space-edition-add-adress").remove();

    var sa = new SpaceAdress(name, adress, cp, city, tel, fax, mail, url, area, areaName, openingHours.replace(/\n/g, "<br/>"), specials);

    tAdresses.push(sa);

    displayAdresses(true);
}


function removeAdress (index) {

    var tempArray = new Array();
    for (i=0; i<tAdresses.length; i++) {
        if (i != index) {
            tempArray.push(tAdresses[i]);
        }
    }
    tAdresses = tempArray;

    $(".space-adress-mystifier:visible").fadeOut(500, function () {displayAdresses(true);});
}

function reloadAdress () {
    $(document).ready(function() {
        $("#space-edition-add-adress").click( function () {

            makeAdressModal(formSanitize(this.name), -1);
        });
    });

}


function displayAdresses(editMode) {

    $(".editAdress").remove();

    var i                   =0;
    var output              ="";
    var moreThanOneAdress   = false;
    //suppression des adresses de l'affichage
    $(".space-adress-mystifier").remove();
    $(".frm_filter").parent("div").remove();
    $("#space-edition-no-adresses").show();

    //si il y a plusieurs adresses, on affiche la combo de sélection
    if (tAdresses.length > 1) {
        moreThanOneAdress = true;
        output = '  <div>\n\
                        <form class="frm_filter">\n\
                            <ul>\n\
                                <li>\n\
                                    <label>Sélectionnez</label>\n\
                                    <select name="function" id="space-adress-selector">';
        
        for (i=0; i<tAdresses.length; i++) {
            var tmp="";

            if(i==lastID) {
                tmp = 'selected="selected"';
            }

            output += '                 <option value="'+i+'" '+tmp+'>'+tAdresses[i].__get("city")+'</option>';
        }
        output += '                 </select>\n\
                                </li>\n\
                            </ul>\n\
                        </form>\n\
                    </div>';

        $("#space-adresses-container").append(output);
    }
    var passage=false;
    for (i=0; i<tAdresses.length; i++) {
        //alert(tAdresses[i].__get("openingHours"));
        output = '';

         output += '  <div id="space-adress-'+i+'" rel="'+i+'" class="space-adress-mystifier" '+( (i>0) ? 'style="display:none;"' : '' )+'>';
        
        if (editMode) {

            output += '<div class="floatLeft"><ul class="menu fiche-adresse-menu"><li><a class="space-edition-edit-adress" rel="'+i+'" href="javascript:void(0);">Editer cette adresse</a></li></ul></div>';
        }

        output += '  <h3>Coordonnées</h3>\n\
                        <div>\n\
                            <p class="marginBottom10px">\n\
                                <strong>'+tAdresses[i].__get("name")+'</strong><br/>\n\
                                <span class="adress">'+tAdresses[i].__get("adress")+'</span><br/>\n\
                                <span class="cp">'+tAdresses[i].__get("cp")+'</span> <span class="city">'+tAdresses[i].__get("city")+'</span>\n\
                            </p>\n\
                            <p class="marginBottom10px">\n\
                                '+( (tAdresses[i].__get("tel").length>5) ? 'T. '+tAdresses[i].__get("tel")+'<br/>' : '' )+'\n\
                                '+( (tAdresses[i].__get("fax").length>5) ? 'F. '+tAdresses[i].__get("fax") : '' )+'\n\
                            </p>\n\
                            <p>';
        
                            if(tAdresses[i].__get("mail")!="") {
                                output += '<a class="formMail" href="mailto:'+tAdresses[i].__get("mail")+'?subject=Demande de contact sur madeinfamenne" target="_blank">Email</a><br/>';
                            }
                            
                            if(tAdresses[i].__get("url")!="") {

                                if(tAdresses[i].__get("url").substring(0, 7) != "http://") {

                                    output += '<a href="http://'+tAdresses[i].__get("url")+'" target="_blank">Website</a>';
                                }

                                else {

                                    output += '<a href="'+tAdresses[i].__get("url")+'" target="_blank">Website</a>';
                                }
                                
                            }

           output += '      </p>\n\
                        </div>\n\
                        \n\
                        <h3>Horaire</h3>\n\
                        <div>\n\
                            <p>'+tAdresses[i].__get("openingHours").replace(/\n/gi, "<br/>")+'</p>\n\
                        </div>\n\
                        \n\
                        <h3>Accès</h3>\n\
                        <div class="acces">\n\
                            <div id="map'+i+'" class="google-map"></div>\n\
                        </div>';
        if (editMode) {
            passage=true;
            output += ' <div class="floatLeft"><ul class="menu fiche-adresse-menu"><li><a class="space-edition-delete-adress" rel="'+i+'" href="javascript:void(0);">Supprimer cette adresse</a></li><li><a id="space-edition-add-adress" href="javascript:void(0);">Ajouter une adresse</a></li></ul></div>';
            
        }
        output += ' </div>';
        $("#space-adresses-container").append(output);
        reloadAdress ();
        /*
        includeJS("http://maps.google.com/maps/api/js?sensor=true");
        includeJS("http://maps.google.com/maps?file=api&v=2&key=ABQIAAAAD9cWFacfbChr6AjUg2h8mhRH5Ag-HcVl75qhJqki4fmF0NXdrRT3ZJIfMhEkkiOn3OAXZbfGAzetLA");


        $(document).ready(function () {
            var s = document.createElement("script");
            s.type = "text/javascript";
            s.src = "http://somedomain.com/somescri...;
            $("head").append(s);
        });*/
        
        if(tAdresses[i].__get("latitude"))initGoogleMap(tAdresses[i].__get("latitude"),tAdresses[i].__get("longitude"),"map"+i);

        if(i==0 && tAdresses[i].__get("latitude"))getFullScreenMap("map"+i,tAdresses[i].__get("latitude"),tAdresses[i].__get("longitude"),tAdresses[i].__get("adress")+" "+tAdresses[i].__get("cp")+" "+tAdresses[i].__get("city"));

        $("#space-edition-no-adresses").hide();

    }

    if (!passage && editMode) {
            output = ' <div class="floatLeft"><ul class="menu fiche-adresse-menu"><li><a id="space-edition-add-adress" href="javascript:void(0);">Ajouter une adresse</a></li></ul></div>';
            $("#space-adresses-container").html(output);

            reloadAdress ();
    }





    /*
     * Activation de la combo de sélection si on a plus d'une adresse
     */
    if ( moreThanOneAdress ) {
        //on affiche la première
        $("#space-adress-0").fadeIn(200);
            $("#space-adress-selector").change( function () {
                $("div.space-adress-mystifier:visible").fadeOut(200);
                var value = $(this).val();
                $("#space-adress-"+value).fadeIn(200);
                getCenterMap($("#space-adress-"+value+" .adress").html(),$("#space-adress-"+value+" .cp").html(),$("#space-adress-"+value+" .city").html(),"map"+value);
            });
    }


    /*
     * activation des boutons d'édition et suppression d'adresses
     */
    $("a.space-edition-edit-adress").click( function () {
        var index = $(this).attr("rel");
        var pName = tAdresses[index].__get("name");
        var tSpecials = tAdresses[index].__get("specials").split(',');
        var i = 0;

        makeAdressModal(pName, index);

        $("#modal_adress").val( tAdresses[index].__get("adress") );
        $("#modal_pc").val( tAdresses[index].__get("cp") );
        $("#modal_city").val( tAdresses[index].__get("city") );
        $("[rel="+parseInt(tAdresses[index].__get("area"))+"]").attr("selected","selected");
        $("#modal_tel").val( tAdresses[index].__get("tel") );
        $("#modal_fax").val( tAdresses[index].__get("fax") );
        $("#modal_mail").val( tAdresses[index].__get("mail") );
        $("#modal_url").val( tAdresses[index].__get("url") );
        $("#modal_opening_hours").val( tAdresses[index].__get("openingHours").replace(/<br \/>/gi, "\n") );
        for (i=0; i<tSpecials.length; i++) {
            $("input:checkbox[value="+tSpecials[i]+"]").attr('checked', true);
        }

    });

    $("a.space-edition-delete-adress").click( function () {
       removeAdress($(this).attr("rel"));
    });

    setLastId(0);
}

/*
 *
 *  Instancie l'id en cours
 *
 */

function setLastId(pId) {

    lastID = pId;
}

/*
 * création de la modale d'ajout/edition d'adresse
 * pId = id de l'adresse a éditer ou -1 si nouvelle
 */
function makeAdressModal(pName, pId) {

    $( "#space-edition-dialog-adress input:not(:checkbox)" )
        .val("")
        .attr('checked', false);
    $( "#space-edition-dialog-adress textarea" ).val("");
    $( "#space-edition-dialog-adress" )
        .dialog("destroy")
        .dialog({
            autoOpen: true,
            height: 'auto',
            width: 500,
            modal: true,
            resizable: false,
            buttons: {
                "Annuler" : function() {$( this ).dialog( "close" );},
                "Confirmer" : function() {

                    var IdL = 0;

                    var specials = new Array();
                    $.each($("input[rel='modal_specials']:checked"), function() {
                        specials.push($(this).val());
                    });
                    if (pId < 0) { //ajout
                        addAdress(
                            pName,
                            $("#modal_adress").val(),
                            $("#modal_pc").val(),
                            $("#modal_city").val().toUpperCase(),
                            $("#modal_tel").val(),
                            $("#modal_fax").val(),
                            $("#modal_mail").val(),
                            $("#modal_url").val(),
                            $("#modal_area").val().substr(0,11),
                            $("#modal_area").val().substr(11),
                            $("#modal_opening_hours").val(),
                            specials.join(",")
                        );
                            
                            idShow = tAdresses.length-1;
                            setLastId(pId);
                    }
                    else { // edition
                        tAdresses[pId].__set("adress", $("#modal_adress").val());
                        tAdresses[pId].__set("cp", $("#modal_pc").val());
                        tAdresses[pId].__set("city", $("#modal_city").val().toUpperCase());
                        tAdresses[pId].__set("tel", $("#modal_tel").val());
                        tAdresses[pId].__set("fax", $("#modal_fax").val());
                        tAdresses[pId].__set("mail", $("#modal_mail").val());
                        tAdresses[pId].__set("url", $("#modal_url").val());
                        tAdresses[pId].__set("area", $("#modal_area").val().substr(0,11));
                        tAdresses[pId].__set("areaName", $("#modal_area").val().substr(11));
                        tAdresses[pId].__set("openingHours", $("#modal_opening_hours").val());
                        tAdresses[pId].__set("specials", specials.join(","));

                        idShow = pId;
                        setLastId(pId);

                        displayAdresses(true);
                    }

                    $(".space-adress-mystifier").fadeOut(200);
                    $("#space-adress-"+idShow).fadeIn(200);
                    $(".space-adress-mystifier").attr("selected","");
                    $("#space-adress-"+idShow).attr("selected","selected");
                    $( this ).dialog( "close" );
                }
            }
    });

}

/*
 * Maps google en gros plan
 */
function getFullScreenMap(e,latitude,longitude,adress) {

    wWidth = (document.body.clientWidth-250);
    $("#"+e).append('<ul id="custom_content'+e+'" class="menu"><li class="agrandire opacity"><a href="#?custom=true&width=600&height=500" rel="prettyPhoto[custom]">Agrandir</a></li><li class="itineraire opacity"><a href="#?custom=true&width='+wWidth+'&height=450" rel="prettyPhoto[custom]">Itinéraire</a></li></ul>');

    $(document).ready(function(){

        $("#custom_content"+e+" a[rel^='prettyPhoto']:first").prettyPhoto({
                custom_markup: '<div id="map_canvas" style="width:600px; height:500px"></div>',
                 keyboard_shortcuts: false, /* Set to false if you open forms inside prettyPhoto */
                changepicturecallback: function(){FullMap(latitude,longitude);}
        });

        $("#custom_content"+e+" a[rel^='prettyPhoto']:last").prettyPhoto({
                custom_markup: '<div id="map_canvas" style="width:'+(wWidth/2)+'px; height:400px"></div>',
                 keyboard_shortcuts: false, /* Set to false if you open forms inside prettyPhoto */
                changepicturecallback: function(){FullItineraire(latitude,longitude,adress);}
        });
    });
}

/*
 * Maps google en gros plan
 */
function FullMap(latitude,longitude) {
    $("#map_canvas").html(initGoogleMapWithOptions(latitude,longitude,"map_canvas"));
}

/*
 * Maps google - Itineraire
 */
function FullItineraire(latitude,longitude,adress) {

    $("#map_canvas").before('<div id="formItin"><div id="errorAdress"></div><br /><div class="txtBold">Votre adresse : <input name="adrDep" id="adrDep" style="width:300px;z-index:9999" value="" /> <a style="text-decoration:none" href="javascript:void(0)" onclick="rechercher(\'adrDep\',true,\''+adress+'\')">Calcul de l\'itinéraire</a><br /><input name="adrArr" id="adrArr" value="'+adress+'" class="displayNone"></div><div id="planEcrit" class="displayNone"><br /><a href="javascript:void(0)" onclick="">Afficher l\'itinéraire</a></div></div><br /><br />');
    $("#map_canvas").css({

        'margin-right' : '15px',
        'float' : 'left'
    });
    $("#map_canvas").after('<div id="panel" style="height:400px;overflow:auto;padding:5px;"><div class="txtBold">Votre itinéraire : </div></div>');
    $("#map_canvas").html(initItineraire(latitude,longitude,"map_canvas",adress));
}

/*
 * Rechargement de la map google pour que l'endroit puisse être centré.
 */
function getCenterMap(adress,cp,city,div) {

    //reload map
    $.ajax({
        type: "POST",
        url: urlConfig+"/wm-public/scripts/center-map.ajax.php",
        data: "adress="+adress+"&cp="+cp+"&city="+city+"&div="+div,
        success: function(data){

        latlgt = data.split(',');

        lat=latlgt[0];
        lgt=latlgt[1];

        infosCity = adress+" "+cp+" "+city;
        initGoogleMap(lat, lgt, div);
        getFullScreenMap(div,lat,lgt,infosCity)

        }
    });

}


/*
 *
 * Création du formulaire pour l'ajout d'une news
 *
 */
function createAddNewsForm () {

    $(".list-news").fadeOut("15000");


    var limitTitle   = 100;
    var limitHeading = 90;
    var content      = "";
    
    content = ' <h3>Création d\'une nouvelle news/promo</h3>\n\
                <form class="form_add_news">\n\
                    <ul>\n\
                        <li><br/></li>\n\
                        <li>\n\
                            <label>Choisissez News ou Promo :</label>\n\
                            <input type="radio" name="modal_type" value="news" style="width:10px; margin-right:5px; float:none;" />News&nbsp;&nbsp;&nbsp;&nbsp;\n\
                            <input type="radio" name="modal_type" value="promo" style="width:10px; margin-right:5px; float:none;" />Promo\n\
                        </li>\n\
                        <li><br/></li>\n\
                        <li>\n\
                            <label>Entrez le titre :</label>\n\
                            <input type="text" id="modal_title" value="" maxlength="'+limitTitle+'" />\n\
                        </li>\n\
                        <li>\n\
                            <label>Entrez une brève description :</label>\n\
                            <textarea id="modal_heading"></textarea>\n\
                            <span><span id="numcharzheading">0</span>/'+limitHeading+' car.</span>\n\
                            <span><em>Cette description ne sera pas affichée avec la news/promo que vous écrivez. Son contenu pourra être affiché dans l\'espace des brèves de <strong>madeinfamenne</strong></em></span>\n\
                        </li>\n\
                    </ul>\n\
                </form>\n\
                <label>Rédigez le contenu :</label>\n\
                <textarea style="width:500px;" id="modal_content"></textarea>\n\
                <form class="form_add_news">\n\
                    <ul>\n\
                        <li>\n\
                            <label>Date de publication :</label>\n\
                            <input type="text" id="modal_date" value="" />\n\
                            <span><em>L\'information sera publiée trois mois à partir de la date que vous renseignez.</em></span>\n\
                        </li>\n\
                        <li>\n\
                            <br/>\n\
                            <input type="checkbox" style="width:15px; margin-right:10px; float:none;" id="modal_private" value="1" />\n\
                            Cochez cette case pour restreindre l\'affichage de cette news aux membres de <strong>madeinfamenne</strong>. Seuls eux pourront voir cette information.\n\
                        </li>\n\
                    </ul>\n\
                </form>\n\
                <div class="btnSubmit">\n\
                    <ul id="validationNews" class="menu fiche-user-menu floatRight">\n\
                        <li><a id="space-edition-submit-add-adress" href="javascript:void(0);">Confirmer</a></li>\n\
                        <li><a id="space-edition-cancel-add-adress" href="javascript:void(0);">Annuler</a></li>\n\
                    </ul>\n\
                </div>';

    $("#space-edition-add-adress-wrapper")
        .html(content)
        .fadeIn();

    /* limitation du champ heading */
    $("#modal_heading").keyup(function() {
        var content = $(this).val();
        if (content.length > limitHeading) {
            content = content.substring(0, limitHeading);
            $(this).val(content);
        }
        $("#numcharzheading").html(content.length);
    });

    /* xinha */
    xinha_init = xinha_init ? xinha_init : function() {
        xinha_plugins = xinha_plugins ? xinha_plugins : [ 'SuperClean','wmMIFExtendedFileManager' ];
        if(!Xinha.loadPlugins(xinha_plugins, xinha_init)) return;
        xinha_config = xinha_config ? xinha_config() : new Xinha.Config();
        xinha_config.pageStyleSheets = [ xinha_url_css ];
        xinha_config.toolbar =  [
            ["undo","redo"],
            ["separator","formatblock"],
            ["separator","justifyleft","justifyright"],
            ["separator","bold","italic","underline"],
            ["separator","subscript","superscript"],
            ["separator","insertorderedlist","insertunorderedlist"],
            ["separator","createlink","insertimage"],
            (Xinha.is_gecko ? [] : ["cut","copy","paste","overwrite"])
        ];
        xinha_editors = xinha_editors ? xinha_editors : ['modal_content'];
        xinha_editors = Xinha.makeEditors(xinha_editors, xinha_config, xinha_plugins);
        Xinha.baseHref = xinha_basehref;
        Xinha.killWordOnPaste = true;
        Xinha.startEditors(xinha_editors);
    }
    xinha_init();

    /* calendrier de sélection de date */
    $('#modal_date').datepicker({
        minDate: 0,
        maxDate: "+1Y",
        changeMonth: true,
        numberOfMonths: 1,
        dateFormat: "dd/mm/yy",
        regional: "fr"
    });

    /* cacher le bouton de création de news */
    $("#space-edition-create-news").hide();

    /* bouton d'annulation */
    $("#space-edition-cancel-add-adress").click( function () {
        $("#space-edition-add-adress-wrapper")
            .fadeOut(   500,
                        function () {
                            $("#space-edition-create-news").show();
                             xinha_init = false;
                             xinha_config = false;
                             xinha_editors = false;
                        }
            );
    } );

    /* bouton de validation */
    $("#space-edition-submit-add-adress").click ( function () {

        var newsType    = $("input[name='modal_type']:checked");
        var newsTitle   = $("#modal_title").val();
        var newsHeading = $("#modal_heading").val();
        var newsContent = document.getElementById("XinhaIFrame_modal_content").contentWindow.document.body.innerHTML;
        var newsDate    = $("#modal_date").val();
        var newsPrivate = $("#modal_private:checked").length;
        var errorz      = "";
        var dateRegex   = /^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$/;

        if ( newsType.length == 0 ) {errorz += "Veuillez sélectionner news ou promo.<br/>"}
        if ( newsTitle.length < 3 ) {errorz += "Veuillez entrer un titre.<br/>"}
        if ( newsHeading.length < 3 ) {errorz += "Veuillez entrer une description.<br/>"}
        if ( newsContent.length < 3 ) {errorz += "Veuillez entrer un contenu.<br/>"}
        if ( ! dateRegex.test(newsDate) ) {errorz += "Veuillez entrer une date valide.<br/>"}

        if ( errorz.length ) {
            errorz = "<h3>Veuillez effectuer les corrections suivantes</h3><p>"+errorz+"</p>";
            var modal = $( "#space-edition-news-modal-error" );
            modal.children("div").html(errorz);
            modal
                .dialog("destroy")
                .dialog({
                    autoOpen: true,
                    height: 'auto',
                    width: 500,
                    modal: true,
                    resizable: false,
                    buttons: {
                        "Ok" : function() {$( this ).dialog( "close" );}
                    }
                });
        }
        else {

            //ajout des champs au formulaire pour submit
            $("#formThatSubmitANewNews")
                .append('<input type="hidden" name="frm_news_type" value="'+formSanitize(newsType.val())+'" />')
                .append('<input type="hidden" name="frm_news_title" value="'+formSanitize(newsTitle)+'" />')
                .append('<input type="hidden" name="frm_news_heading" value="'+formSanitize(newsHeading)+'" />')
                .append('<input type="hidden" name="frm_news_content" value="'+formSanitize(newsContent)+'" />')
                .append('<input type="hidden" name="frm_news_date" value="'+formSanitize(newsDate)+'" />')
                .append('<input type="hidden" name="frm_news_private" value="'+(newsPrivate)+'" />')
                .submit();

        }

        //$("#formThatSubmitANewNews")
    });
    
}



/*
 * Parfois, certaines actions se passent alors que le user Menu est déjà affiché.
 * Et donc le montant des crédits et autres infos ne sont pas actualisé.
 * Cette fonciton le fait.
 */
function refreshUserBar(userId, relative) {

    //refresh des crédits
    $.ajax({
        type: "POST",
        url: relative+"/wm-public/scripts/user-get-credits.ajax.php",
        data: "userId="+userId,
        success: function(data){
            $("#user-menu-credits-amount")
                .fadeOut()
                .html(data)
                .fadeIn();
        }
    });
    
}




function activateNewsLinksForEdition(relative) {

    //edition d'une news
    $("a.space-edition-news-edit").click(function() {

        $(".toEdited").fadeOut();
        $("#news-block-"+newsId).fadeIn("150");

        var newsId          = $(this).attr("rel");
        var newsLI          = $("#news-block-"+newsId);
        var formLI          = "undefined";
        var limitTitle      = 100;
        var limitHeading    = 90;
        var content         = "";
        var news            = "";

        $(".space-edition-news-edition-li").remove();

        content = ' <li class="space-edition-news-edition-li">\n\
                        <h3>Modification d\'une news/promo</h3>\n\
                        <form class="form_add_news">\n\
                            <ul>\n\
                                <li><br/></li>\n\
                                <li>\n\
                                    <label>Entrez le titre :</label>\n\
                                    <input type="text" id="news_edit_title" value="" maxlength="'+limitTitle+'" />\n\
                                </li>\n\
                                <li>\n\
                                    <label>Entrez une brève description :</label>\n\
                                    <textarea id="news_edit_heading"></textarea>\n\
                                    <span><span id="numcharzheading">0</span>/'+limitHeading+' car.</span>\n\
                                    <span><em>Cette description ne sera pas affichée avec la news/promo que vous écrivez. Son contenu pourra être affiché dans l\'espace des brèves de <strong>madeinfamenne</strong></em></span>\n\
                                </li>\n\
                            </ul>\n\
                        </form></li></ul>\n\
                        <div class="space-edition-news-edition-li">\n\
                            <label>Rédigez le contenu :</label>\n\
                            <textarea style="width:500px;" id="news_edit_content"></textarea>\n\
                        </div>\n\
                        \n\
                        <ul class="list-news">\n\
                        <li class="space-edition-news-edition-li">\n\
                        <form class="form_add_news">\n\
                            <ul>\n\
                                <li>\n\
                                    <br/>\n\
                                    <input type="checkbox" style="width:15px; margin-right:10px; float:none;" id="news_edit_private" value="1" />\n\
                                    Cochez cette case pour restreindre l\'affichage de cette news aux membres de <strong>madeinfamenne</strong>. Seuls eux pourront voir cette information.\n\
                                </li>\n\
                            </ul>\n\
                        </form>\n\
                        <div class="btnSubmit">\n\
                            <ul id="validationNews" class="fiche-user-menu floatRight">\n\
                                <li><a id="space-edition-submit-edit-adress" class="floatRight" href="javascript:void(0);">Confirmer</a></li>\n\
                                <li><a id="space-edition-cancel-edit-adress" class="floatRight" href="javascript:void(0);">Annuler</a></li>\n\
                            </ul>\n\
                        </div>\n\
                    </li>';

        //on cache la news ...
        newsLI.hide();
        //on insere le form juste devant
        formLI = newsLI.before(content);

        //on charge la news
        $.ajax({
            async: false,
            type: "POST",
            dataType: "json",
            url: relative+"/wm-public/scripts/news-edition-getNewsInJSON.ajax.php",
            data: "newsId="+newsId,
            success: function(data){
                $("#news_edit_title").val(data.title);
                $("#news_edit_heading").val(data.heading);
                $("#news_edit_content").val(data.content);
            }
        });

        //on démarre xinha
        /* limitation du champ heading */
        $("#numcharzheading").html($("#news_edit_heading").val().length);
        $("#news_edit_heading").keyup(function() {
            var content = $(this).val();
            if (content.length > limitHeading) {
                content = content.substring(0, limitHeading);
                $(this).val(content);
            }
            $("#numcharzheading").html(content.length);
        });

        /* xinha */
        xinha_init = xinha_init ? xinha_init : function() {
            xinha_plugins = xinha_plugins ? xinha_plugins : [ 'SuperClean','wmMIFExtendedFileManager' ];
            if(!Xinha.loadPlugins(xinha_plugins, xinha_init)) return;
            xinha_config = xinha_config ? xinha_config() : new Xinha.Config();
            xinha_config.pageStyleSheets = [ xinha_url_css ];
            xinha_config.toolbar =  [
                ["undo","redo"],
                ["separator","formatblock"],
                ["separator","justifyleft","justifyright"],
                ["separator","bold","italic","underline"],
                ["separator","subscript","superscript"],
                ["separator","insertorderedlist","insertunorderedlist"],
                ["separator","createlink","insertimage"],
                (Xinha.is_gecko ? [] : ["cut","copy","paste","overwrite"])
            ];
            xinha_editors = xinha_editors ? xinha_editors : ['news_edit_content'];
            xinha_editors = Xinha.makeEditors(xinha_editors, xinha_config, xinha_plugins);
            Xinha.baseHref = xinha_basehref;
            Xinha.killWordOnPaste = true;
            Xinha.startEditors(xinha_editors);
        }
        xinha_init();

        /* cacher le bouton de création de news */
        $("#space-edition-create-news").hide();

        /* bouton d'annulation */
        $("#space-edition-cancel-edit-adress").click( function () {

            $(".toEdited").fadeIn();
            $(".space-edition-news-edition-li")
                .fadeOut(   500,
                            function () {
                                $("#space-edition-create-news").show();
                                xinha_init = false;
                                xinha_config = false;
                                xinha_editors = false;
                                newsLI.fadeIn();
                            }
                );
        } );

        /* bouton de validation */
        $("#space-edition-submit-edit-adress").click ( function () {

            var newsTitle   = $("#news_edit_title").val();
            var newsHeading = $("#news_edit_heading").val();
            var newsContent = document.getElementById("XinhaIFrame_news_edit_content").contentWindow.document.body.innerHTML;
            var newsPrivate = $("#news_edit_private:checked").length;
            var errorz      = "";

            if ( newsTitle.length < 3 ) {errorz += "Veuillez entrer un titre.<br/>"}
            if ( newsHeading.length < 3 ) {errorz += "Veuillez entrer une description.<br/>"}
            if ( newsContent.length < 3 ) {errorz += "Veuillez entrer un contenu.<br/>"}
        
            if ( errorz.length ) {
                errorz = "<h3>Veuillez effectuer les corrections suivantes</h3><p>"+errorz+"</p>";
                var modal = $( "#space-edition-news-modal-error" );
                modal.children("div").html(errorz);
                modal
                    .dialog("destroy")
                    .dialog({
                        autoOpen: true,
                        height: 'auto',
                        width: 500,
                        modal: true,
                        resizable: false,
                        buttons: {
                            "Ok" : function() {$( this ).dialog( "close" );}
                        }
                    });
            }
            else {
                //ajout des champs au formulaire pour submit
                $("#formThatSubmitAEditNews")
                    .append('<input type="hidden" name="frm_editnews_id" value="'+newsId+'" />')
                    .append('<input type="hidden" name="frm_news_title" value="'+formSanitize(newsTitle)+'" />')
                    .append('<input type="hidden" name="frm_news_heading" value="'+formSanitize(newsHeading)+'" />')
                    .append('<input type="hidden" name="frm_news_content" value="'+formSanitize(newsContent)+'" />')
                    .append('<input type="hidden" name="frm_news_private" value="'+(newsPrivate)+'" />')
                    .submit();
            }
        
        });


        $("#space-edition-news-edit-cancel").click(function () {
            formLI
                .slideUp()
                .remove();
            newsLI.slideDown();
        });

    });

    //suppression d'une news
    $("a.space-edition-news-delete").click(function(){
        var newsId = $(this).attr("rel");
        $( "#space-edition-news-modal-confirm-delete-news" ).dialog("destroy");
        $( "#space-edition-news-modal-confirm-delete-news" ).dialog({
            autoOpen: true,
            height: 'auto',
            width: 500,
            modal: true,
            resizable: false,
            buttons: {
                "Annuler" : function() {$( this ).dialog( "close" );},
                "Confirmer la suppression" : function() { 
                    $("#frm_deletenews_id").val(newsId);
                    $("#formThatSubmitADeleteNews").submit();
                }
            }
        });
    });
    
    $(".space-news-link").hover(
        function () {
            $(this).find("span.space-edition-news-link").show();
        },
        function () {
            $(this).find("span.space-edition-news-link").hide();
        }
    );

}






function activateJobLinksForEdition(relative) {

    //edition d'une news
    $("a.space-edition-job-edit").click(function() {

        var jobId           = $(this).attr("rel");
        var jobLI           = $("#job-block-"+jobId);
        var formLI          = "undefined";
        var limitTitle      = 100;
        var limitHeading    = 150;
        var content         = "";
        var job             = "";

        $(".toEdited").fadeOut();
        $("#job-block-"+jobId).fadeIn();

        $(".space-edition-job-edition-li").remove();

        content = ' <li class="space-edition-job-edition-li">\n\
                        <h3>Modification d\'une offre d\'emploi</h3>\n\
                        <form class="form_add_news">\n\
                            <ul>\n\
                                <li><br/></li>\n\
                                <li>\n\
                                    <label>Entrez le titre :</label>\n\
                                    <input type="text" id="job_edit_title" value="" maxlength="'+limitTitle+'" />\n\
                                </li>\n\
                                <li>\n\
                                    <label>Entrez une brève description :</label>\n\
                                    <textarea id="job_edit_heading"></textarea>\n\
                                    <span><span id="numcharzheading">0</span>/'+limitHeading+' car.</span>\n\
                                    <span><em>Cette description ne sera pas affichée avec le job que vous écrivez. Son contenu pourra être affiché dans l\'espace des brèves de <strong>madeinfamenne</strong></em></span>\n\
                                </li>\n\
                            </ul>\n\
                        </form>\n\
                        <label>Rédigez le contenu :</label>\n\
                        <textarea style="width:500px;" id="job_edit_content"></textarea>\n\
                        <!--<form class="form_add_news">\n\
                            <ul>\n\
                                <li>\n\
                                    <br/>\n\
                                    <input type="checkbox" style="width:15px; margin-right:10px; float:none;" id="job_edit_private" value="1" />\n\
                                    Cochez cette case pour restreindre l\'affichage de cette news aux membres de <strong>madeinfamenne</strong>. Seuls eux pourront voir cette information.\n\
                                </li>\n\
                            </ul>\n\
                        </form>-->\n\
                    <div class="btnSubmit">\n\
                        <ul id="validationNews" class="fiche-user-menu floatRight">\n\
                            <li><a id="space-edition-submit-edit-adress" href="javascript:void(0);">Confirmer</a></li>\n\
                            <li><a id="space-edition-cancel-edit-adress" href="javascript:void(0);">Annuler</a></li>\n\
                        </ul>\n\
                    </div></li></ul>';

        //on cache la news ...
        jobLI.hide();
        //on insere le form juste devant
        formLI = jobLI.before(content);

        //on charge la news
        $.ajax({
            async: false,
            type: "POST",
            dataType: "json",
            url: relative+"/wm-public/scripts/news-edition-getNewsInJSON.ajax.php",
            data: "newsId="+jobId,
            success: function(data){
                $("#job_edit_title").val(data.title);
                $("#job_edit_heading").val(data.heading);
                $("#job_edit_content").val(data.content);
            }
        });

        //on démarre xinha
        /* limitation du champ heading */
        $("#numcharzheading").html($("#job_edit_heading").val().length);
        $("#job_edit_heading").keyup(function() {
            var content = $(this).val();
            if (content.length > limitHeading) {
                content = content.substring(0, limitHeading);
                $(this).val(content);
            }
            $("#numcharzheading").html(content.length);
        });

        /* xinha */
        xinha_init = xinha_init ? xinha_init : function() {
            xinha_plugins = xinha_plugins ? xinha_plugins : [ 'SuperClean','wmMIFExtendedFileManager' ];
            if(!Xinha.loadPlugins(xinha_plugins, xinha_init)) return;
            xinha_config = xinha_config ? xinha_config() : new Xinha.Config();
            xinha_config.pageStyleSheets = [ xinha_url_css ];
            xinha_config.toolbar =  [
                ["undo","redo"],
                ["separator","formatblock"],
                ["separator","justifyleft","justifyright"],
                ["separator","bold","italic","underline"],
                ["separator","subscript","superscript"],
                ["separator","insertorderedlist","insertunorderedlist"],
                ["separator","createlink","insertimage"],
                (Xinha.is_gecko ? [] : ["cut","copy","paste","overwrite"])
            ];
            xinha_editors = xinha_editors ? xinha_editors : ['job_edit_content'];
            xinha_editors = Xinha.makeEditors(xinha_editors, xinha_config, xinha_plugins);
            Xinha.baseHref = xinha_basehref;
            Xinha.killWordOnPaste = true;
            Xinha.startEditors(xinha_editors);
        }
        xinha_init();

        /* cacher le bouton de création de news */
        $("#space-edition-create-job").hide();

        /* bouton d'annulation */
        $("#space-edition-cancel-edit-adress").click( function () {
            $(".toEdited").fadeIn();
            $(".space-edition-job-edition-li")
                .fadeOut(   500,
                            function () {
                                $("#space-edition-create-job").show();
                                xinha_init = false;
                                xinha_config = false;
                                xinha_editors = false;
                                jobLI.fadeIn();
                            }
                );
        } );

        /* bouton de validation */
        $("#space-edition-submit-edit-adress").click ( function () {

            var jobTitle   = $("#job_edit_title").val();
            var jobHeading = $("#job_edit_heading").val();
            var jobContent = document.getElementById("XinhaIFrame_job_edit_content").contentWindow.document.body.innerHTML;
            var jobPrivate = $("#job_edit_private:checked").length;
            var errorz      = "";

            if ( jobTitle.length < 3 ) {errorz += "Veuillez entrer un titre.<br/>"}
            if ( jobHeading.length < 3 ) {errorz += "Veuillez entrer une description.<br/>"}
            if ( jobContent.length < 3 ) {errorz += "Veuillez entrer un contenu.<br/>"}

            if ( errorz.length ) {
                errorz = "<h3>Veuillez effectuer les corrections suivantes</h3><p>"+errorz+"</p>";
                var modal = $( "#space-edition-job-modal-error" );
                modal.children("div").html(errorz);
                modal
                    .dialog("destroy")
                    .dialog({
                        autoOpen: true,
                        height: 'auto',
                        width: 500,
                        modal: true,
                        resizable: false,
                        buttons: {
                            "Ok" : function() {$( this ).dialog( "close" );}
                        }
                    });
            }
            else {
                //ajout des champs au formulaire pour submit
                $("#formThatSubmitAEditJob")
                    .append('<input type="hidden" name="frm_editjob_id" value="'+jobId+'" />')
                    .append('<input type="hidden" name="frm_job_title" value="'+formSanitize(jobTitle)+'" />')
                    .append('<input type="hidden" name="frm_job_heading" value="'+formSanitize(jobHeading)+'" />')
                    .append('<input type="hidden" name="frm_job_content" value="'+formSanitize(jobContent)+'" />')
                    .append('<input type="hidden" name="frm_job_private" value="'+(jobPrivate)+'" />')
                    .submit();
            }

        });


        $("#space-edition-job-edit-cancel").click(function () {
            formLI
                .slideUp()
                .remove();
            jobLI.slideDown();
            //alert(jobLI.html());
        });

    });

    //suppression d'une news
    $("a.space-edition-job-delete").click(function(){
        var jobId = $(this).attr("rel");
        $( "#space-edition-job-modal-confirm-delete-job" ).dialog("destroy");
        $( "#space-edition-job-modal-confirm-delete-job" ).dialog({
            autoOpen: true,
            height: 'auto',
            width: 500,
            modal: true,
            resizable: false,
            buttons: {
                "Annuler" : function() {$( this ).dialog( "close" );},
                "Confirmer la suppression" : function() {
                    $("#frm_deletejob_id").val(jobId);
                    $("#formThatSubmitADeleteJob").submit();
                }
            }
        });
    });

    $(".space-job-link").hover(
        function () {
            $(this).find("span.space-edition-news-link").show();
        },
        function () {
            $(this).find("span.space-edition-news-link").hide();
        }
    );

}




/*
 *
 * Création du formulaire pour l'ajout d'une offre d'emploi
 *
 */
function createAddJobForm () {

    var limitTitle   = 100;
    var limitHeading = 90;
    var content      = "";

    $(".list-news").fadeOut("15000");

    content = ' <h3>Création d\'une offre d\'emploi</h3>\n\
                <form class="form_add_news">\n\
                    <ul>\n\
                        <li><br/></li>\n\
                        <li>\n\
                            <label>Type d\'annonce :</label>\n\
                            <input type="radio" name="modal_type" value="employee" style="width:10px; margin-right:5px; float:none;" />Employé&nbsp;&nbsp;&nbsp;&nbsp;\n\
                            <input type="radio" name="modal_type" value="worker" style="width:10px; margin-right:5px; float:none;" />Ouvrier&nbsp;&nbsp;&nbsp;&nbsp;\n\
                            <input type="radio" name="modal_type" value="student" style="width:10px; margin-right:5px; float:none;" />Etudiant\n\
                        </li>\n\
                        <li><br/></li>\n\
                        <li>\n\
                            <label>Entrez le titre :</label>\n\
                            <input type="text" id="modal_title" value="" maxlength="'+limitTitle+'" />\n\
                        </li>\n\
                        <li>\n\
                            <label>Entrez une brève description :</label>\n\
                            <textarea id="modal_heading"></textarea>\n\
                            <span><span id="numcharzheading">0</span>/'+limitHeading+' car.</span>\n\
                            <span><em>Cette description ne sera pas affichée avec le job que vous écrivez. Son contenu pourra être affiché dans l\'espace des brèves de <strong>madeinfamenne</strong></em></span>\n\
                        </li>\n\
                    </ul>\n\
                </form>\n\
                <label>Rédigez le contenu :</label>\n\
                <textarea style="width:500px;" id="modal_content"></textarea>\n\
                <form class="form_add_news">\n\
                    <ul>\n\
                        <li>\n\
                            <label>Date de publication :</label>\n\
                            <input type="text" id="modal_date" value="" />\n\
                            <span><em>L\'information sera publiée trois mois à partir de la date que vous renseignez.</em></span>\n\
                        </li>\n\
                        <!--<li>\n\
                            <br/>\n\
                            <input type="checkbox" style="width:15px; margin-right:10px; float:none;" id="modal_private" value="1" />\n\
                            Cochez cette case pour restreindre l\'affichage de ce job aux membres de <strong>madeinfamenne</strong>. Seuls eux pourront voir cette information.\n\
                        </li>-->\n\
                    </ul>\n\
                </form>\n\
                <div class="btnSubmit">\n\
                    <ul id="validationNews" class="menu fiche-user-menu floatRight">\n\
                        <li><a id="space-edition-submit-add-adress" class="floatRight" href="javascript:void(0);">Confirmer</a></li>\n\
                        <li><a id="space-edition-cancel-add-adress" class="floatRight" href="javascript:void(0);">Annuler</a></li>\n\
                    </ul>\n\
                </div>';



    $("#space-edition-add-adress-wrapper")
        .html(content)
        .fadeIn();

    /* limitation du champ heading */
    $("#modal_heading").keyup(function() {
        var content = $(this).val();
        if (content.length > limitHeading) {
            content = content.substring(0, limitHeading);
            $(this).val(content);
        }
        $("#numcharzheading").html(content.length);
    });

    /* xinha */
    xinha_init = xinha_init ? xinha_init : function() {
        xinha_plugins = xinha_plugins ? xinha_plugins : [ 'SuperClean','wmMIFExtendedFileManager' ];
        if(!Xinha.loadPlugins(xinha_plugins, xinha_init)) return;
        xinha_config = xinha_config ? xinha_config() : new Xinha.Config();
        xinha_config.pageStyleSheets = [ xinha_url_css ];
        xinha_config.toolbar =  [
            ["undo","redo"],
            ["separator","formatblock"],
            ["separator","justifyleft","justifyright"],
            ["separator","bold","italic","underline"],
            ["separator","subscript","superscript"],
            ["separator","insertorderedlist","insertunorderedlist"],
            ["separator","createlink","insertimage"],
            (Xinha.is_gecko ? [] : ["cut","copy","paste","overwrite"])
        ];
        xinha_editors = xinha_editors ? xinha_editors : ['modal_content'];
        xinha_editors = Xinha.makeEditors(xinha_editors, xinha_config, xinha_plugins);
        Xinha.baseHref = xinha_basehref;
        Xinha.killWordOnPaste = true;
        Xinha.startEditors(xinha_editors);
    }
    xinha_init();

    /* calendrier de sélection de date */
    $('#modal_date').datepicker({
        minDate: 0,
        maxDate: "+1Y",
        changeMonth: true,
        numberOfMonths: 1,
        dateFormat: "dd/mm/yy",
        regional: "fr"
    });

    /* cacher le bouton de création de news */
    $("#space-edition-create-job").hide();

    /* bouton d'annulation */
    $("#space-edition-cancel-add-adress").click( function () {
        $("#space-edition-add-adress-wrapper")
            .fadeOut(   500,
                        function () {
                            $("#space-edition-create-job").show();
                             xinha_init = false;
                             xinha_config = false;
                             xinha_editors = false;
                        }
            );
    } );

    /* bouton de validation */
    $("#space-edition-submit-add-adress").click ( function () {

        var jobType    = $("input[name='modal_type']:checked");
        var jobTitle   = $("#modal_title").val();
        var jobHeading = $("#modal_heading").val();
        var jobContent = document.getElementById("XinhaIFrame_modal_content").contentWindow.document.body.innerHTML;
        var jobDate    = $("#modal_date").val();
        var jobPrivate = $("#modal_private:checked").length;
        var errorz      = "";
        var dateRegex   = /^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$/;

        if ( jobType.length == 0 ) {errorz += "Veuillez sélectionner un type.<br/>"}
        if ( jobTitle.length < 3 ) {errorz += "Veuillez entrer un titre.<br/>"}
        if ( jobHeading.length < 3 ) {errorz += "Veuillez entrer une description.<br/>"}
        if ( jobContent.length < 3 ) {errorz += "Veuillez entrer un contenu.<br/>"}
        if ( ! dateRegex.test(jobDate) ) {errorz += "Veuillez entrer une date valide.<br/>"}

        if ( errorz.length ) {
            errorz = "<h3>Veuillez effectuer les corrections suivantes</h3><p>"+errorz+"</p>";
            var modal = $( "#space-edition-job-modal-error" );
            modal.children("div").html(errorz);
            modal
                .dialog("destroy")
                .dialog({
                    autoOpen: true,
                    height: 'auto',
                    width: 500,
                    modal: true,
                    resizable: false,
                    buttons: {
                        "Ok" : function() {$( this ).dialog( "close" );}
                    }
                });
        }
        else {

            //ajout des champs au formulaire pour submit
            $("#formThatSubmitANewJob")
                .append('<input type="hidden" name="frm_job_type" value="'+formSanitize(jobType.val())+'" />')
                .append('<input type="hidden" name="frm_job_title" value="'+formSanitize(jobTitle)+'" />')
                .append('<input type="hidden" name="frm_job_heading" value="'+formSanitize(jobHeading)+'" />')
                .append('<input type="hidden" name="frm_job_content" value="'+formSanitize(jobContent)+'" />')
                .append('<input type="hidden" name="frm_job_date" value="'+formSanitize(jobDate)+'" />')
                .append('<input type="hidden" name="frm_job_private" value="'+(jobPrivate)+'" />')
                .submit();

        }

        //$("#formThatSubmitANewNews")
    });

}

function startShuffle(space){

    setTimeout('getShuffle('+space+')',5500);
}


function getShuffle(space) {

$('#friendLinksContent').animate({opacity:50},1500);


//reload news
$.ajax({
    url: urlConfig+"/wm-public/scripts/recommendations-getShuffle.ajax.php",
    type: "POST",
    data:"space="+space,
    success: function(data){
        $("#friendLinksContent").html(data);

    }
});

$('#friendLinksContent').animate({opacity:100},1500);

setTimeout('getShuffle('+space+')',5500);


}

