var timeout_resize;
var resize_content_inited = false;
var map;

var Qtab = {
    id: 'quicktab-container',
    prefix: 'quicktab-',
    $ctn: null,
    duration: 500,

    init: function() {
        // Nothing to do here
        this.$ctn = $('#'+this.id);
    },

    show: function(id) {
        $id = $('#'+ this.prefix + id);

        // Clic sur l'element affiche actuel : on le cache
        if (this.$ctn.find('#'+ this.prefix + id + ':visible').length) {
            this.$ctn.find('.qtab:visible').slideUp(this.duration);
            $('#tabs .on').removeClass('on');
            $('#content').css({'padding-top' : '5px'});
        } else {
            // Element actuellement affiche
            this.$ctn.find('.qtab:visible').not('#'+ this.prefix + id).slideUp(this.duration);
            $('#tabs .on').removeClass('on');
            $('#content').css({'padding-top' : '5px'});
            // Affichage de l'element demande
            if ($id.length) {
                $id.slideDown(this.duration);
                $('#tab-'+id).addClass('on');
                $('#content').css({'padding-top' : '0'});
            }
        }
    }
};

$(document).ready(function() {

    $(".navigation ul.subMenu").hide();
    $(".navigation li.toggleSubMenu > a").click( function () {
        if ($(this).next("ul.subMenu:visible").length != 0) {
            $(this).next("ul.subMenu").slideUp("normal");
            $(this).parent().removeClass('on');
        }
        else {
            $(".navigation ul.subMenu").slideUp("normal");
            $(".navigation li.on").removeClass('on');
            $(this).next("ul.subMenu").slideDown("normal");
            $(this).parent().addClass('on');
        }
        if ($(this).next()) {
            return false;
        } else {
            return true;
        }
    });

    $('#img-site-marchand').click(function() {
        if ($('#content-marchand').is(":hidden")) {
            $('#site-marchand').animate({'width' : '259px'}, 500);
            $('#tab-marchand').animate({'width' : '209px'}, 500);
            $('#content-marchand').css({display : "block"});
            $('#outils_marchand').css({display : "block"});
            $('#checkall_marchand').css({display : "block"});
        } else {
            $('#site-marchand').animate({'width' : '50px'}, 500);
            $('#tab-marchand').animate({
                width : '0'
            }, 500, function() {
                $('#content-marchand').css({display : "none"});
                $('#outils_marchand').css({display : "none"});
                $('#checkall_marchand').css({display : "none"});
            });
        }
    });
    /*$('#date #date-picker').jdPicker();

    $('#picker').jdPicker();
    $('#picker1').jdPicker();*/


    $('#img-site-marchand').click();
    $('#img-site-marchand').click();

    /* ***** partie formulaire recherche s ur home page ******** */
    $('.encart_closed').click(function() {
        $(this).css({'display' : 'none'});
        $(this).parent().find('.encart_opened').css({'display' : 'block'});
    });
    $('.close_link').click(function() {
        $(this).parent().css({'display' : 'none'});
        $(this).parent().parent().find('.encart_closed').css({'display' : 'block'});
        return false;
    });

    /* Sous menu espace commune */
    $('ul.menu_prive,ul#onglets_commercant').superfish();

    resize_content_init();

    //height minimum contenu

//    var divHeight = $('#sansmea_contenu').height();
//    //alert(divHeight);
//
//    if(divHeight < 320) {
//        $('#sansmea_contenu').css({'height':320});
//    }else {
//        $('#sansmea_contenu').css({'height':divHeight});
//    }

});

$(window).resize(function(){
    if (!resize_content_inited) resize_content_init();
    else resize_content();
});

function resize_content_init() {
    if (resize_content_inited) {
        resize_content();
        return;
    }
    var test_hauteur = $('#main').height();
    if (!test_hauteur) {
        timeout_resize = setTimeout(resize_content_init(), 100);
    } else {

        if($('#actualite_wrapper').length) {
            $('#colbot_wrapper').append('<div id="bottom_colonne_actu"></div>');
            var content_height = $('#content_center').outerHeight();
            var actu_height = $('#actualite_wrapper').outerHeight();
            $('#actualite_wrapper').outerHeight(content_height);
            /*$('#actualite_fond').height(content_height);*/
        }

        resize_content_inited = true;
        clearTimeout(timeout_resize);
        resize_content();
    }
}

function resize_content() {
    var w = $( window );
    var H = w.height();
    var W = w.width();

    $('#pre_footer').width(W);
}

$(function(){
    Qtab.init();
    $('#recherche').click(function() {
        Qtab.show($(this).attr('id').replace('tab-', ''));
    });
});

$(function(){
    $("ul#scroll-text").liScroll({travelocity: 0.05});
});

$(function() {
    $('a#connectez_vous').fancybox({
        'zoomSpeedIn': 300,
        'zoomSpeedOut': 300,
        'overlayShow': true,
        'enableEscapeButton': true,
        'hideOnContentClick': false,
        'showNavArrows': false,
        'cyclic': false,
        'padding': 30,
        'type_fond' : 'connexion'
    });
});

$(function() {
    $('a#launchPopupMarche,a.ficheMarche,a#focus').fancybox({
        'zoomSpeedIn': 300,
        'zoomSpeedOut': 300,
        'overlayShow': true,
        'enableEscapeButton': true,
        'hideOnContentClick': false,
        'showNavArrows': false,
        'cyclic': false,
        'padding': 10,
        'frameWidth' : 926,
        'frameHeight' : 600
    });
});

$(function() {
    $('a#marche').fancybox({
        'zoomSpeedIn': 300,
        'zoomSpeedOut': 300,
        'overlayShow': true,
        'enableEscapeButton': true,
        'hideOnContentClick': false,
        'showNavArrows': false,
        'cyclic': false,
        'padding': 30,
        'frameWidth' : 500,
        'frameHeight' : 500,
        'type_fond' : 'blanc'
    });
});
$(function() {
    $('a#voir').fancybox();
});
$(function() {
    $('a.fancybox').fancybox({
        'zoomSpeedIn': 300,
        'zoomSpeedOut': 300,
        'overlayShow': true,
        'enableEscapeButton': true,
        'hideOnContentClick': false,
        'showNavArrows': false,
        'cyclic': false,
        'padding': 30,
        'frameWidth' : 600,
        'frameHeight' : 400,
        'type_fond' : 'blanc'
    });

    $('a#apercu').fancybox({
        'autoDimensions' : true,
        'hideOnContentClick': false,
        'showNavArrows': false,
        'scrolling'   : 'no' ,
        'padding'       : 30,
        'frameWidth' : 600,
        'frameHeight' : 600,
        'type_fond' : 'blanc'
    });
});

function UserValidationCommune(theForm) {
    var expCP=new RegExp("^[0-9]{5}$","gi");

    if (theForm.web.value) {
        if (theForm.web.value.substr(0,7) != 'http://') {
            alert('Le champ \'Site internet\' est incorrect, il doit contenir http:// !');
            theForm.web.focus();
        }
    }

    if (!TesteChaine(theForm.nom_admin,'Nom et Prénom', 100, true)) return false;
    if (!TesteChaine(theForm.fonction_admin,'Fonction', 100, true)) return false;

    if (!TesteChaine(theForm.tel_admin,'Tel', 10, true)) return false;
      var expTel=new RegExp("^0[0-9][0-9]{8}$","gi");
      if (theForm.tel_admin.value && theForm.tel_admin.value.length != 10 || !expTel.test(theForm.tel_admin.value)) {
        alert("Le numéro de téléphone administrateur entré n\'a pas un format correct.");
          return false;
      }


    if (theForm.reglement.value) {
        taille_chaine = (theForm.reglement.value.length - 4);
        if (theForm.reglement.value.substr(taille_chaine,4) != '.pdf') {
            alert('Veuillez choisir un fichier au format pdf pour le règlement des marchés');
        }
    }
    if (!(TesteEMail(theForm.mail_admin, 100, true))) return false;
    if (theForm.mail_commercant.value) {
        if (!(TesteEMail(theForm.mail_commercant, 100, true))) return false;
    }
//    var expTel=new RegExp("^0[0-9][0-9]{8}$","gi");
//    if (theForm.tel1_commercant.value && theForm.tel1_commercant.value.length != 10 || !expTel.test(theForm.tel1_commercant.value)) {
//        alert("Le numéro de téléphone entré n\'a pas un format correct2.");
//        return false;
//    }
//    var expTel=new RegExp("^0[0-9][0-9]{8}$","gi");
//    if (theForm.tel2_commercant.value && theForm.tel2_commercant.value.length != 10 || !expTel.test(theForm.tel2_commercant.value)) {
//        alert("Le numéro de téléphone entré n\'a pas un format correct3.");
//        return false;
//    }
    if (theForm.code_admin.value && (theForm.code_admin.value.length != 5 || !expCP.test(theForm.code_admin.value))) {
        alert("Le code postal entré n\'a pas un format correct.");
        return false;
    }
    return true;
}

function UserValidationMarche(theForm) {
    /*if (!theForm.nom.value) {
        alert('Veuillez entrer un nom de marché');
        return false;
    }*/
    if (!theForm.adresse.value) {
        alert('Veuillez entrer une adresse');
        return false;
    }

    /*if (!theForm.rec_placier.value) {
        alert('Veuillez entrer un placier');
        return false;
    }
    if (!theForm.nom_placier.value) {
        alert('Veuillez entrer le nom du placier');
        return false;
    }
    if (!theForm.prenom_placier.value) {
        alert('Veuillez entrer le prénom du placier');
        return false;
    }*/

//    if (!theForm.elements["equipement[]"].value) {
//        alert('Veuillez cocher au moins un équipement');
//        return false;
//    }
//
//    if (!theForm.elements["accessibilite[]"].value) {
//        alert('Veuillez cocher au moins un moyen d\'accès');
//        return false;
//    }

   // if (!TesteListeMultiple(theForm.elements["equipement[]"], "Equipement", true)) return false;
   // if (!TesteListeMultiple(theForm.elements["accessibilite[]"], "accessibilite", true)) return false;

    if (theForm.reglement_contact.value) {
        taille_chaine = (theForm.reglement_contact.value.length - 4);
        if (theForm.reglement_contact.value.substr(taille_chaine, 4) != '.pdf') {
            alert('Veuillez choisir un fichier au format pdf pour le règlement du marché');
            return false;
        }
    }

    if (theForm.image.value) {
        taille_chaine = (theForm.image.value.length - 4);
        if ((theForm.image.value.substr(taille_chaine, 4) != '.jpg') && (theForm.image.value.substr(taille_chaine, 4) != '.gif') && (theForm.image.value.substr(taille_chaine, 4) != '.png') && (theForm.image.value.substr((taille_chaine - 1), 5) != '.jpeg')) {
            alert('Veuillez choisir un fichier au format jpg/gif/png pour le règlement du marché');
            return false;
        }
    }
    if (theForm.tel1_contact.value) {
        if (!TesteChaine(theForm.tel1_contact,'Téléphone 1', 10, true)) return false;
    }
    if (theForm.tel2_contact.value) {
        if (!TesteChaine(theForm.tel2_contact,'Téléphone 2', 10, true)) return false;
    }
    if (theForm.email_contact.value) {
        if (!TesteChaine(theForm.email_contact, 'Email', 100, true)) return false;
    }
    if (theForm.web_contact.value) {
        if (theForm.web_contact.value.substr(0,7) != 'http://') {
            alert('Le champ \'Web\' est incorrect, il doit contenir http:// !');
            theForm.web.focus();
        }
    }
    // @todo gestion de la date ici pour date_creation
    return true;

}

function UserValidationAnnonce(theForm) {

    //Nom_de_l_objet = new Date(année, mois, jour);
    if (theForm.date_depot.value && theForm.date_fin) {
        var date_depot = new Date(theForm.date_depot.value.substr(6, 4), theForm.date_depot.value.substr(3, 2), theForm.date_depot.value.substr(0, 2));
        var date_fin = new Date(theForm.date_fin.value.substr(6, 4), theForm.date_fin.value.substr(3, 2), theForm.date_fin.value.substr(0, 2));
        if (date_depot > date_fin) {
            alert('La période n\'est pas valide car la date de fin est plus ancienne que la date de début de période');
            return false;
        }
    } else if (!theForm.date_depot.value && theForm.date_fin) {
        alert('Veuillez entrer une date de début de période');
        return false;
    }

    if (!TesteListeMultiple(theForm.elements["metiers[]"], "Métiers", true)) return false;
    if (!TesteListeMultiple(theForm.elements["produits[]"], "Produits", true)) return false;
    if (!TesteListeMultiple(theForm.elements["marches"], "Marches", true)) return false;
    if (!TesteListeMultiple(theForm.elements["tenu_marches"], "Tenu de marches", true)) return false;

    if (!TesteNombre(theForm.tel_contact, 'Tèl', true)) return false;
    if (!TesteChaine(theForm.nom_contact, 'Nom et prénom',100, true)) return false;

    if (!TesteChaine(theForm.email_contact_annonce, 'Email', 50, true)) return false;
    if (!(TesteEMail(theForm.email_contact_annonce, 100, true))) return false;

    return true;
}

function UserValidationTenumarche(theForm) {
    var expDate=/^(\d{1,2}\/){2}\d{4}$/;

    if (!TesteChaine(theForm.jour,'jour', 100, true)) return false;
    if (!TesteChaine(theForm.groupe,'groupe', 100, true)) return false;
    if (!TesteChaine(theForm.periodicite,'periodicite', 100, true)) return false;
    //if (!TesteListeMultiple(theform.elements["attribution[]"], "attribution des places", true)) return false;
    if (!TesteNombre(theForm.heure_debut, 'heure de debut', true)) return false;
    if (!TesteNombre(theForm.minute_debut, 'minute de debut', true)) return false;
    if (!TesteNombre(theForm.heure_fin, 'heure de fin', true)) return false;
    if (!TesteNombre(theForm.minute_fin, 'minute de fin', true)) return false;
    if (!TesteNombre(theForm.heure_debut_rappel, 'heure de début de rappel', true)) return false;
    if (!TesteNombre(theForm.heure_fin_rappel, 'minute de fin de rappel', true)) return false;

    if (theForm.date_debut.value && !theForm.date_fin.value && !expDate.test(theForm.date_fin.value)) {
        alert('Veuillez entrer une date de fin de publication');
        return false;
    } else if (theForm.date_fin.value && !theForm.date_debut.value && !expDate.test(theForm.date_debut.value)) {
        alert('Veuillez entrer une date de début de publication');
        return false;
    } else if (theForm.date_debut.value && theForm.date_fin.value && !expDate.test(theForm.date_debut.value) && !expDate.test(theForm.date_fin.value)) {
        if (expDate.test(theForm.date_debut.value) && expDate.test(theForm.date_fin.value)) {
            var date_debut = new Date(theForm.date_debut.value.substr(6, 4), theForm.date_debut.value.substr(3, 2), theForm.date_debut.value.substr(0, 2));
            var date_fin = new Date(theForm.date_fin.value.substr(6, 4), theForm.date_fin.value.substr(3, 2), theForm.date_fin.value.substr(0, 2));
            if (date_debut > date_fin) {
                alert('La période n\'est pas valide car la date de fin est plus ancienne que la date de début de période');
                return false;
            }
        } else {
            alert('Le format des date est dd/mm/yyyy');
            return false;
        }
    }
    return true;
}

function UserValidationCreationAlerteCommercant(theForm) {
    if (!jQuery('#terr_id').val() && !jQuery('#intervalle').val() && !jQuery('#produit').val()) {
        alert('Veuillez choisir au moins un paramètre.');
        return false;
    }
    return true;
}

function UserValidationrecherche(theForm) {
    if (!TesteChaine(theForm.sect_nom,'Zone', 100, true)) return false;
    if (!TesteChaine(theForm.comm_nom,'Commune', 100, true)) return false;
    if (!TesteListeMultiple(theform.elements["metiers[]"], "Métiers", true)) return false;
    if (!TesteListeMultiple(theform.elements["produits[]"], "Produits", true)) return false;
    return false;;
}

function isInteger(s){
    return (s%(parseInt(s)/Number(s)))===0;
}

// laisser en fin de fichier !!! Sinon des scripts ne fonctionnent pas
$(document).ready(function() {

//    $("input#tous_secteur").click(function(){
//        if ($("input#tous_secteur:checked")) {
//            console.debug('checked');
//            $(':checkbox').attr('checked', 'checked');
//        }else {
//            console.debug('unchecked');
//            $(':checkbox').attr('checked', '');
//        }
//    });

//    jQuery('#tous').attr('checked',true);
//    alert(jQuery('#tous').attr('checked'));
//    jQuery('#check_liste input').each(function() {
//        //alert(jQuery('#tous').attr('checked'));
//        jQuery(this).attr('checked', jQuery('#tous').attr('checked'));
//    });

// COMMUNE RECHERCHE CHECK

    $('#tous_communes').click(function() {
        console.debug('todo');
        var cases = $("#check_liste_communes").find(':checkbox'); //on recherche les checkbox
        if(this.checked){ // si 'cocheTout' est coché
            cases.attr('checked', true); // on coche les cases
        }else{ // si on décoche 'cocheTout'
            cases.attr('checked', false);// on decoche les cases
        }

    });
    jQuery('#date_debut,#date_fin,#date_crea, #date #date-picker, #picker, #picker1').datepicker({
        "dateFormat": 'dd/mm/yy',
        "monthNames":['Janvier','Fevrier','Mars','Avril','Mai','Juin','Juillet','Août','Septembre','Octobre','Novembre','Décembre'],
        "dayNames": ['Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi'],
        "dayNamesMin": ['Di','Lu','Ma','Me','Je','Ve','Sa'],
        "dayNamesShort":["Dim","Lun","Mar","Mer","jeu","Ven","Sam"],
        "monthNamesShort":["Jan","Fev","Mar","Avr","Mai","Jui","Jul","Aou","Sep","Oct","Nov","Déc"],
        "inline": true
    });
});


$(function(){
    $("ul#defilement-annonce").liScroll();
});
