
$(document).ready(function(){

//##########################################################################################
//##  Fonctions générales  #################################################################

    $("body").delegate("a[href='#']", 'click', function(e){e.preventDefault();});
    $("#promos_slider a[href='#']").click(function(e){e.preventDefault();}).css('cursor','default');

    $('.pt_thumb').live('mouseenter', function(){
        $(this).find('.pt_zoom').stop(true,true).fadeIn(500);
    });
    $('.pt_thumb').live('mouseleave', function(){
        $(this).find('.pt_zoom').stop(true,true).fadeOut(200);
    });

    $('#table_panier tr:odd td').css({backgroundColor: '#eeeeee'});

    $('#nav_ul .sous_menu li:has("ul") a').addClass('ul_unclickable');

    $('#cl_wrapper').flash({
        swf: '/flash/lclogos.swf',
        height: 112,
        width: 148
    });

    $('a[href^="http://"]').not('a[href*="'+window.location.host+'"]').attr('target', '_blank');
	$('a[href$=".pdf"]').attr('target', '_blank');

    // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    // ## COMMENTÉ PAR FRANCOIS; provoquait une erreur.
    //$("select, input:checkbox, input:radio, input:file").uniform();
    // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!


    //#####################################################################################
    //##  Confirmation  ###################################################################

    $('.table_checkout_hori tr:odd td, .table_checkout_hori tr:odd th').css({backgroundColor: '#eeeeee'}); 

    $('#table_panier_conf tbody tr:last td').css({borderBottom: '2px solid #ACACAC'});

    //#####################################################################################
    //##  Lightbox WT  ####################################################################

    $.wt_lightbox = function(type, target, lb_width, lb_height)
    {
        
        var b_black = $("#back_overlay");

        var b_loading = $("#b_loading");

        var w_height = $(window).height();
        var w_width = $(window).width();

        var d_height = $(document).height();
        var d_width = $(document).width();

        var pos_x = 0;
        var pos_y = 0;

        var box_width = 0;
        var box_height = 0;

        b_black.css({
            "width": d_width,
            "height": d_height
        });

        pos_x = w_width / 2;
        pos_y = (w_height / 2) + $(window).scrollTop();

        // Si on veux afficher une image ##############################################

        if(type == "image"){
            $('body').append('<div class="b_ctr_image b_ctr"></div>')

            var b_ctr_image = $(".b_ctr_image");

            b_ctr_image.html('<img id="curr_zoom_image" src="'+target+'" />');

            b_ctr_image.append('<a href="#" class="b_close" title="Fermer la fenêtre">Fermer la fenêtre</a>');

            $("#curr_zoom_image").one("load",function(){


                box_width = b_ctr_image.width();
                box_height = b_ctr_image.height() - 2;
                //console.log(box_height);

                // Setup du container de la photo
                b_ctr_image.css({
                    'opacity': '0',
                    "height": box_height,
                    "width": box_width,
                    "top": pos_y - (box_height/2),
                    "left": pos_x - (box_width/2),
                    'display': 'block'
                })

                // Setup de la toile de fond
                b_black.stop(true,true).fadeTo(400, 0.75, function(){
                    var l_pos_x =  w_width / 2;
                    var l_pos_y = (w_height / 2) + $(window).scrollTop();
                    var l_height = b_loading.outerHeight() / 2;
                    var l_width = b_loading.outerWidth() / 2;
                    b_loading.css({'left' : l_pos_x - l_width, 'right' : l_pos_y - l_height}).fadeIn(300);
                });

                b_ctr_image.animate({opacity: 1}, 500, function(){
                    b_loading.hide();
                });
            })
            .each(function(){
                if(this.complete) $(this).trigger("load"); 
            });

        // Si on veux afficher du content  ############################################

        }else if(type == "content"){

            $('body').append('<div class="b_ctr_content b_ctr"></div>');
            b_ctr_content = $('.b_ctr_content');
            if(target instanceof Object){
                var video_id = target.target_video;
                var video_div = target.target_div;
                $(video_div).find('iframe').attr('src','http://www.youtube.com/embed/'+video_id+'?rel=0&wmode=transparent');
                $(video_div).clone().appendTo(b_ctr_content);
                target_div = video_div;
            }else{
                target_div = target;
                $(target).clone().appendTo(b_ctr_content);
            }

            box_height = lb_height;
            box_width = lb_width;

            if(lb_width != '' && lb_height != ''){
                b_ctr_content.find(target_div).css({
                    "min-height": box_height,
                    "min-width": box_width,
                    'display': 'block'
                });
            }

            b_ctr_content.css({
                'opacity': '0',
                "min-height": box_height,
                "min-width": box_width,
                padding: '15px',
                backgroundColor: '#fff',
                'display': 'block'
            })

            b_ctr_content.css({
                "top": pos_y - (b_ctr_content.outerHeight()/2),
                "left": pos_x - (b_ctr_content.outerWidth()/2)
            })
            
            b_ctr_content.prepend('<a href="#" class="b_close" title="Fermer la fenêtre">Fermer la fenêtre</a>');
            b_black.stop(true,true).fadeTo(400, 0.75, function(){
                var l_pos_x =  w_width / 2;
                var l_pos_y = (w_height / 2) + $(window).scrollTop();
                var l_height = b_loading.outerHeight() / 2;
                var l_width = b_loading.outerWidth() / 2;
                b_loading.css({'left' : l_pos_x - l_width, 'right' : l_pos_y - l_height}).fadeIn(300);
            });
            
            b_ctr_content.animate({opacity: 1}, 500, function(){
                //console.log('hellwhoe');
                //$.uniform.update('select');
                b_loading.hide();
            });

            
        }
        // ############################################################################

        $(".b_close, .b_ctr img").live('click',function(){
            var popup_element;
            if (type == "image"){popup_element = b_ctr_image}else{popup_element = b_ctr_content}
            popup_element.stop(true,false).animate({opacity:0}, 300, function(){

                popup_element.find(".b_close").remove();
                
                if (type == "image"){  // Lorsque l'on ferme un popup image
                    popup_element.remove();
                }
                
                if(type == 'content'){  // Lorsque l'on ferme un popup content
                    $('.popup_errors_wrapper').hide().find(".errors_list").html("");
                    $('div.nj_form_lblfld label').css('color','#000');
                    popup_element.remove();
                }

                //$(this).css('left', '-9000px');
                b_black.fadeOut(200);
            });
        });
    }

    $('#pf_info_envami').click(function(){
        $.wt_lightbox('content', '#envoyer_ami_frm_wrapper', 435, 300);
    });
    $('#btn_demande_info').click(function(){
        $.wt_lightbox('content', '#demande_info_frm_wrapper', 400, 300); 
    });
    $("#pf_thumb .pf_thumb_image").live('click',function(){
        var target_img = $(this).attr('target_img');
        $.wt_lightbox('image', target_img);
    });

    $('.video_popup').click(function(){
        $.wt_lightbox('content', $(this).dataset(), 640, 390);
    });

    $("body").delegate('.close_popup','click', function(){
       $('.b_close').trigger('click');
    });

    //#####################################################################################
    //  Hover search btn  #################################################################

    $('#btn_search').hover(function(){
        $(this).parent().parent().css('background-position','0 -27px');
    }, function(){
        $(this).parent().parent().css('background-position','0 0');
    });
	$("#btn_search").click(function(){
        $("#search_frm").submit();
    });


    //#####################################################################################
    //  Text box click empty  #############################################################

    $(".text_input").focusin(function(){if($(this).val() == $(this).attr('title')){$(this).val('');}});
    $(".text_input").focusout(function(){if($(this).val() == ''){$(this).val($(this).attr('title'));}});


    //#####################################################################################
    //##  Vertical/Horizontal align  ######################################################

    // Centrer le menu principal
    menu_width = $("#nav_ul").outerWidth();
    diff_width = 960 - menu_width;
    margin_left = diff_width/2;
    $("#nav_ul").css('margin-left',margin_left+'px');

    // Redimension et centrer verticalement les tabs du Top Viewer
    function resize_valign(){
        var tv_height = $("#top_viewer").outerHeight();
        var tv_tab_h = (tv_height / 3)-2;
        $('#top_viewer ul li').css('height',tv_tab_h);

        $("#tv_tabs ul li div").each(function(){$(this).css('height',$(this).parent().outerHeight());});
        $('#tv_tabs ul li a').each(function(){
            elem_h = $(this).height();
            h_dif = tv_tab_h - elem_h;
            elem_topmargin = (h_dif / 2)+1;
            $(this).css("padding-top",elem_topmargin+"px");
        });
    }
    
    resize_valign();


    //#####################################################################################
    //##  Top Viewer Accueil  #############################################################

    function show_ajax_loader(){
        $overlay = $("#loading_overlay");
        $overlay.css({display: 'block', opacity: '0'})
        $overlay_height = $overlay.parent().outerHeight();
        $overlay_width = $overlay.parent().outerWidth();
        
        $overlay.css({
            height: $overlay_height,
            width: $overlay_width
        }).animate({opacity: '0.5'}, 300);

        $overlay_loader = $overlay.find('img');
        $overlay_loader_tp = ($overlay_loader.parent().height() / 2) - ($overlay_loader.outerHeight() / 2);
        $overlay_loader_lp = ($overlay_loader.parent().width() / 2) - ($overlay_loader.outerWidth() / 2);

        $overlay_loader.css({
            position: 'absolute',
            top: $overlay_loader_tp,
            left: $overlay_loader_lp
        })
    }

    //console.log("1");
    function hide_ajax_loader(){
        $overlay = $("#loading_overlay");
        $overlay.animate({opacity: '0'}, 300, function(){
            $(this).css({display: 'none'});
        });
    }

    // Setup des produits par default
	if($(this).find('#tv_right_content').size()>0){
		$.ajax({
			type: "GET",
			url: "/inc/tv_ajax.php",
			data: "type=nouveautes",
			context: $('#tv_right'), //context: $('#tv_viewport .tv_slide'),
			beforeSend : function(){
				show_ajax_loader();
			},
			success: function(msg){
				hide_ajax_loader();
				$(this).find('#tv_right_content').html(msg);
				
			}
		});
	}

    // Click sur les tabs pour changer les produit de catégorie et changement de page
    $('#top_viewer a[href*="tv_ajax.php"]').click(function(e){
        e.preventDefault();
        if($(this).hasClass("tv_tab")){
            $('#tv_tabs li[class*="active"]').removeClass('active');
            $(this).parent().parent().addClass('active');
        }

        var ajaxpage_params = $(this).attr('href').split('?');
        $.ajax({
            type: "GET",
            url: ajaxpage_params[0],
            data: ajaxpage_params[1],
            context: $('#tv_right'), //context: $('#tv_viewport .tv_slide'),
            beforeSend : function(){
                show_ajax_loader();
            },
            success: function(msg){
                hide_ajax_loader();
                $(this).find('#tv_right_content').html(msg);
            }
        });
    });

    /*##################################################################*/
	/*##  Gallery de publicites accueil  ###############################*/

    var $ss_container = $('#promos_slider');
    var $ss_nav = $('#promo_slider_nav');

    $ss_container.find('a[href="www"], a[href=""]').css('cursor','default').click(function(e){e.preventDefault();});

	var $counter_z = 20;
	var $counter = 0;
	var $pics = $ss_container.children("a.slide");
	var $nbr_pics = $pics.length;
	var $slideshow_timeout;

	$ss_container.data("cur_pic_nbr",'1');

	$ss_container.children("a.slide").each(function(){
		$counter_z--;
		$counter++;
		$(this).attr('id','image_'+$counter).css("z-index",$counter_z);
        if($nbr_pics > 1){
            $ss_nav.append('<li id="image_link_'+$counter+'" target_img="'+$counter+'">'+$counter+'</li>');
        }
	});

	$("#image_link_1").addClass("current_image_link");


	function switch_img(target_image, current_button){

		var $cur_pic_nbr = $ss_container.data("cur_pic_nbr");

		if(target_image != $cur_pic_nbr){
			var $target_pic = $("#image_"+target_image);
			var $cur_pic = $("#image_"+$cur_pic_nbr);

			if(!$cur_pic.is(":animated")){

				$target_pic.addClass("cur_image").css("z-index",$cur_pic.css("z-index")-1).show();

				$ss_nav.find('li.current_image_link').removeClass("current_image_link");
				current_button.addClass("current_image_link");

				$cur_pic.removeClass("cur_image").fadeOut(500, function(){
					$target_pic.css("z-index","20");
					$(this).css("z-index",$target_pic.css("z-index")-1)
					$ss_container.data("cur_pic_nbr",target_image).end().find("a[class!=cur_image]").hide();
				});
			}
		}
	}

    var $target_pic = '';

	function switch_img_auto(){
		var $cur_pic_nbr = $ss_container.data("cur_pic_nbr");

		var $cur_pic = $("#image_"+$cur_pic_nbr);

		if($cur_pic_nbr == $nbr_pics){
			$target_pic_nbr = 1;
			$target_pic = $("#image_"+$target_pic_nbr);
		}else{
			$target_pic_nbr = parseInt($cur_pic_nbr) + 1;
			$target_pic = $("#image_"+$target_pic_nbr);
		}

		$target_pic.addClass("cur_image").css("z-index",$cur_pic.css("z-index")-1).show();

		$ss_nav.find('li.current_image_link').removeClass("current_image_link");
		$("#image_link_"+$target_pic_nbr).addClass("current_image_link");

		$cur_pic.removeClass("cur_image").fadeOut(700, function(){
			$target_pic.css("z-index","20");
			$(this).css("z-index",$target_pic.css("z-index")-1)
			$ss_container.data("cur_pic_nbr",$target_pic_nbr).end().find("a[class!=cur_image]").hide();
			$slideshow_timeout = window.setTimeout(switch_img_auto, 7000);
		});
	}

    if($nbr_pics > 1){
        $slideshow_timeout = window.setTimeout(switch_img_auto, 7000);

        $ss_nav.find('li').click(function(){
            window.clearTimeout($slideshow_timeout);
            $slideshow_timeout = window.setTimeout(switch_img_auto, 30000);
            switch_img($(this).attr("target_img"), $(this));
        });
    }

    //#####################################################################################
    //##  Fonction fix d'animation de PNG sur IE7-8  ######################################

    (function ($) {
        if (!$) return;
        $.fn.extend({
            fixPNG: function(sizingMethod, forceBG) {
                if (!($.browser.msie)) return this;
                var emptyimg = "../img/blank.gif"; //Path to empty 1x1px GIF goes here
                sizingMethod = sizingMethod || "scale"; //sizingMethod, defaults to scale (matches image dimensions)
                this.each(function() {
                    var isImg = (forceBG) ? false : jQuery.nodeName(this, "img"),
                        imgname = (isImg) ? this.src : this.currentStyle.backgroundImage,
                        src = (isImg) ? imgname : imgname.substring(5,imgname.length-2);
                    this.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizingMethod='" + sizingMethod + "')";
                    if (isImg) this.src = emptyimg;
                    else this.style.backgroundImage = "url(" + emptyimg + ")";
                });
                return this;
            }
        });
    })(jQuery);

    $('.pt_zoom').fixPNG();



//##########################################################################################
//##  Fonctions - Produits  ################################################################


    //#####################################################################################
    //##  jQuery Tools - Overlay  #########################################################

    $("#back_overlay").css({opacity: 0.5});

    $.tools.overlay.addEffect("myEffect", function(position, done) {
          this.getOverlay().css(position).fadeIn(this.getConf().speed, done);
       },function(done) { // close function
          this.getOverlay().fadeOut(this.getConf().closeSpeed, done);
       }
    );

    $(".apercu_trigger").overlay({
        top: 'center',
        fixed: false,
        left: 'center',
		onBeforeLoad: function() {
            $("#back_overlay").show().animate({"opacity": 0.5}, 200);

			//console.log('onBeforeLoad');

            //show_ajax_loader();
		},
        onLoad: function(){
            //console.log('onLoad');
            var wrap = this.getOverlay().find(".contentWrap");

            //apercu_init(this.getTrigger().attr("href"), $(this));
            $.ajax({
                type: "GET",
                url: this.getTrigger().attr("href"),
                beforeSend : function(){
                    //console.log('AJAX START');
                    wrap.addClass('ajax_chargement');
                },
                success: function(msg){
                    //console.log('AJAX DONE');
                    wrap.removeClass('ajax_chargement');
                    wrap.html(msg);
                }
            });

            //wrap.load(this.getTrigger().attr("href"));
            //console.log(this.getTrigger().attr("href"));
            //hide_ajax_loader();
        },
        onClose: function(){
            //console.log('onClose');
            $("#back_overlay").animate({"opacity": 0.0}, 200, function(){
                $(this).hide();
            })
        }
	});


    //#####################################################################################
    //##  Galerie Fiche et apercu  ########################################################

    $('#pf_thumb_galerie ul li img').click(function(){
        $('.current_image_link').removeClass('current_image_link');
        $(this).parent().addClass('current_image_link');

        target_path = $(this).attr('target_path');
        target_big = $(this).attr('target_big');
        $("#pf_thumb .pf_thumb_image img").attr({'src': target_path});
        $("#pf_thumb .pf_thumb_image").attr({'target_img': target_big});
    });

    //#####################################################################################
    //###  Set du lien actif de section  ##################################################

    var current_url = document.location.href;
	if(current_url.indexOf("?") > 0){current_url = current_url.substr(0, current_url.indexOf("?"))}
	if(current_url.indexOf("postuler") > 0){current_url = current_url.substr(0, current_url.indexOf("postuler"))}
    var cur_url_split = current_url.split("/");

    function trim(arr2){
        var arr1=new Array();
        for(j=0;j<arr2.length;j++)
        if(arr2[j]!="")
        arr1[arr1.length]=arr2[j];
        arr2.length=arr1.length;
        for(j=0;j<arr1.length;j++)
        arr2[j]=arr1[j];
        return arr2;
    }

    new_array = trim(cur_url_split);

    var last_param = new_array.length - 1;
    var needle = new_array[last_param];

    $("#left_nav a, #panier_etapes a").each(function(){
        var cur_href = $(this).attr('href');
        var cur_href_split = cur_href.split("/");
        var new_href_array = trim(cur_href_split);
        var last_href_param = new_href_array.length - 1;
        var needle_href = new_href_array[last_href_param];

        if(needle_href === needle){
            $(this).addClass('active');
        }
        
    });
    
    $("#panier_etapes a[href='#']:not('.actif')").addClass('inactif');


    //#####################################################################################
    //##  Fonction d'accordeon pour le menu principale  ###################################

    var menu_container = "left_nav"; // ID du "div" qui contient le menu
    var sub_menu_type = "ul"; // Tag du conteneur de sous-menu
    var active_accordeon = "active_accordeon"; // La class donnee au "li" dont le sous-menu est ouvert
    var accordeon_menu = "accordeon_menu"; // La class donnee aux "li" qui contiennent un sous-menu
    var accordeon_trigger = "accordeon_trigger";
    var $menu_container = $('#'+menu_container); // Caching du "div" qui contient le menu

    $(".active").closest('ul').show().parent().addClass(active_accordeon);

    $menu_container.find("ul li ul").each(function(){$(this).parent().addClass(accordeon_menu).end().prev('a').addClass(accordeon_trigger);});

	$menu_container.find("."+accordeon_trigger).click(function(e){
		//e.preventDefault();
        $menu_container.find('.'+active_accordeon).removeClass(active_accordeon)
        if($(this).parent().hasClass(accordeon_menu)){$(this).parent().addClass(active_accordeon);}
		if($(this).next(sub_menu_type).is(":visible")){
            $(this).next(sub_menu_type).slideUp("medium", "easeOutQuad");
        }else{
			$menu_container.find("ul li "+sub_menu_type+":visible").slideUp("medium", "easeOutQuad");
			$(this).next(sub_menu_type).slideToggle("medium", "easeOutQuad");
		}
	});

    //** Sous fonction pour l'accordeon Surplus RD ****************************************

    $("."+accordeon_trigger).each(function(){$(this).append('<span></span>');});


    //#####################################################################################
    //##  Tooltip  ########################################################################

    function init_tooltip() {

        $('a.tooltip').hover(function(){

            $('body').append('<div id="tooltip_outer"><div id="tooltip_inner"><h5></h5><p></p></div></div>');

            $tt = $('#tooltip_outer');
            $tt_i = $('#tooltip_inner');

            tt_t = $(this).dataset('tt');
            tt_c = $(this).dataset('tc');

            $tt_i.data('title',$(this).attr('title'));

            $tt_i.find('h5').html(tt_t);
            $tt_i.find('p').html(tt_c);

            // Store title and emtpy it

            /*if($(this).attr('title')) {
                $tt_title = $(this).attr('title');
                $(this).attr('title', '');
            }*/

            if($tt_i.html != ''){$tt.stop(true, true).show();}
        },
        function() {
            $tt.stop(true, true).hide();
            $tt.remove();
        }).mousemove(function(ev) {

            // Event coordinates
            var $ev_x = ev.pageX;
            var $ev_y = ev.pageY;

            // Tooltip coordinates
            var $tt_x = $tt.outerWidth();
            var $tt_y = $tt.outerHeight();

            // Body coordinates
            var $bd_x = $('body').outerWidth();
            var $bd_y = $('body').outerHeight();

            // Move tool tip

            $tt.css({
                'top': $ev_y + $tt_y > $bd_y ? $ev_y - $tt_y : $ev_y - 10,
                'left': $ev_x + $tt_x > $bd_x ? $ev_x - $tt_x - 10 : $ev_x + 25
            });
        });
    }

    init_tooltip();


    //#####################################################################################
    //##  Boutons dans fiche  #############################################################

    $('#pf_info_print').click(function(){
        window.print();
    });


    // Permet au bouton ajouter au panier d'ajouter un élément au panier.
    $('#btn_ajout_panier').click(function(){
        var produitId = $(this).attr('rel');
        window.location.href="/panier?add=" + produitId;
        
        /*$.ajax({
           type: "POST",
           url: "/panier",
           data: "ajax=true&add=" + produitId,
           dataType: "json",
           success: function(data, textStatus, jqXHR){
                $("#qte_article").html(data.qte);

                $("#pluriel_article").html(data.qte<2 ? "" : "s");
                window.location.href = "/panier";
           },
           error: function(jqXHR, textStatus, errorThrown){
           }
        });*/

    });

    //#####################################################################################
    //##  Changement de tri list produits  ################################################
	$('#tri, #ordre').attr("disabled",false);
    $('#tri, #ordre').change(function(){
		$page = $('#page').val();
		$char = "?";
		console.log("page : "+$page)
		if($page.indexOf("?") != -1){$char = "&";}
        window.location = $page + $char+"tri="+$('#tri').val()+"&ordre="+$('#ordre').val()
    });
    
    //##  Widget AccordD  #################################################################

    $("#mois_accordd").change(function(e){
        var prix;
		prix = Math.round($("#prix_produit").val() * $("#taxe_produit").val() * $(this).val() * 100) / 100;
		prix = prix+"00";
		prix = prix.substring(0, prix.indexOf(".")+3);
        prix = prix.replace('.',',');
		//$("#prix_accordd").html('');
        document.getElementById('prix_accordd').innerHTML=prix;
	});



//##########################################################################################
//##  Fonctions formulaires / Validations / Processus de paiement  #########################


    // Formulaire de popup fiches

    $('.envoyer_ami_form .nj_form_lblfld label, .demande_info_form .nj_form_lblfld label').live('click', function(){
        if($(this).prev().is('input[type="checkbox"]')){
            
            if($(this).prev().is(':checked')){
                //console.log('Uncheck!');
                $(this).prev().attr('checked',''); 
            }else{
                //console.log('Check!');
                $(this).prev().attr('checked','checked');
            }
        }else{
            $(this).next().focus();
        }
    });


    /*####################################################################*/
    /*##  Validation  ####################################################*/
	$('#nj_form').keyup(function(event){
		switch(event.keyCode){
			case 13:
				validate("nj_form", '#errors_wrapper');
				break;
		}
	});
	
    $("#btn_soumettre").click(function(){
        validate("nj_form", '#errors_wrapper');
        //console.log('CLICKED!');
    });
	$("#btn_envoyer_ami").live('click', function(){
        validate("envoyer_ami_form", '.popup_errors_wrapper', true, $(this));
    })
	$("#btn_demande_info_submit").live('click', function(){
        //console.log('hello');
        validate("demande_info_form", '.popup_errors_wrapper', true, $(this));
    });
    $("#btn_next").click(function(){
        validate("checkout_form", '#errors_wrapper');
        return false;
    });

    $("#btn_prev, .panier_previous").click(function(){
        $("#checkout_form").attr("action", this.href);
        $("#checkout_form").submit();
    });

    // Fonctions de validation des champs

    function isInteger (s){
        var i;
        if (isEmpty(s))
        if (isInteger.arguments.length == 1) return 0;
        else return (isInteger.arguments[1] == true);

        for (i = 0; i < s.length; i++){
            var c = s.charAt(i);
            if (!isDigit(c)) return false;
        }

        return true;
    }

    function isEmpty(s){
        return ((s == null) || (s.length == 0))
    }

    function isDigit (c){
        return ((c >= "0") && (c <= "9"));
    }

    function isEmail(email) {
        var oRegExp = /^([a-zA-Z0-9])+([\.a-zA-Z0-9_-])*@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-]+)+$/;
        return oRegExp.test(email);
    }

    function is_postalcode(postalcode) {
        return ((/^[a-z]\d[a-z] ?\d[a-z]\d$/i).test(postalcode));
    }

    //############################################################################
    //###  Fonction qui cycle a travers les champs qui ont l'atribut  ############
    //###  "req" et les valide selon leurs "valtype" puis assigne le  ############
    //###  code d'erreur s'il y a lieu dans la liste "errors_list"    ############

    function validate(form_name, errors_wrapper, is_local_container, clicked_element){  // is_local_container est un boolean qui defini si c'ette validation doit se faire dans un container restreint et non dans toute la page

        //window.alert('test');

        //console.log('VALIDATING!');


        if(is_local_container == ""){is_local_container = false}
        if(clicked_element == undefined){clicked_element = ''} // Élement cliqué pour activer la fonction validate

        var passed = true;
        var errors = new Array();

        var $current_form;
        var $errors_wrapper;

        if(is_local_container){
            $errors_wrapper = clicked_element.closest('.b_ctr').find(errors_wrapper); // On trouve le div d'erreures le plus raprochée du bouton cliqué
            $current_form = clicked_element.siblings('form[name="'+form_name+'"]'); // On trouve la form ayant la classe provenant de 'form_name' la plus raprochée du bouton cliqué
        }else{
            $errors_wrapper = $(errors_wrapper);
            $current_form = $('form[name="'+form_name+'"]');
        }

        //console.log('Form name = '+$current_form.attr('name'));
        

        $errors_wrapper.find(".errors_list").html("");
        $errors_wrapper.fadeOut(100);

        //$current_form.find("label").css("color","#000");
        $('.error_field').removeClass('error_field');


        // Cycle through tous les champs du formulaire pour valider leurs contenu

        $current_form.find("input[req='true'], textarea[req='true'], select[req='true']").each(function(){
            //window.alert('test2');
            var $valtype = $(this).attr("valtype");
            var $label = $(this).prev();
            var $error_msg = $(this).attr('error_msg');

            if($valtype == "email"){
                if(!isEmail($(this).val())){
                    passed = false;
                    errors.push($error_msg);
                    //$label.css("color","#E30707");
                    $label.addClass('error_field');
                }
            }else if($valtype == "postalcode"){
                if(!is_postalcode($(this).val())){
                    passed = false;
                    errors.push($error_msg);
                    //$label.css("color","#E30707");
                    $label.addClass('error_field');
                }
            }
            else if($valtype == "notempty"){
                if(isEmpty($(this).val())){
                    passed = false;
                    errors.push($error_msg);
                    //$label.css("color","#E30707");
                    $label.addClass('error_field');
                }
            }
			else if($valtype == "checklst"){
                $label = $(this).closest(".nj_form_lblfld").find("label:eq(0)");

                // Si la case Telephone/Courriel est coche on verifie si le champ telephone/courriel est bel et bien remplie
                if(($(this).attr('value') == "Téléphone" || $(this).attr('value') == "Courriel") && $(this).is(':checked')){
                    //console.log('TEST');

                    if($(this).attr('value') == "Téléphone"){
                        // Validation du telephone selon le fait qu'il ai été coché comme moyen de contact
                        if($current_form.find("input[name='tel']").val() == ""){
                            $connected_input = $current_form.find("input[name='tel']");
                            passed = false;
                            errors.push($connected_input.attr('error_msg'));
                            //$connected_input.prev().css("color","#E30707");
                            $connected_input.prev().addClass('error_field');
                        }
                    }else{
                        // Validation du courriel selon le fait qu'il ai été coché comme moyen de contact
                       // if($current_form.find("input[name='email']").val() == ""){
                            $connected_input = $current_form.find("input[name='email']");
							if(!isEmail($connected_input.val())){
                                passed = false;
                                errors.push($connected_input.attr('error_msg'));
                                //$connected_input.prev().css("color","#E30707");
                                $connected_input.prev().addClass('error_field');
                            }
                        //}
                    }
                }

				if($current_form.find("input[name='"+$(this).attr("name")+"']:checked").length < 1){
                    passed = false;
                    var found = false;
                    for(i=0;i<= errors.length; i++){
                        if(errors[i] == $error_msg){
                            found = true;
                        }
                    }
                    if(!found){
                        errors.push($error_msg)
                    }
                    //
                    if($(this).attr('id')==="ship_type_2"){$('#lbl_ship_type_1').addClass('error_field');}
                    $label.addClass('error_field');
                }
            }
            else if($valtype == "selectsomething"){
                $label = $(this).closest(".nj_form_lblfld").find("label:eq(0)");
				if($(this).val() == 'null'){
                    passed = false;
                    errors.push($error_msg);
                    //$label.css("color","#E30707");
                    $label.addClass('error_field');
                }
                //console.log($(this).val());
            }
            else if($valtype == "selectentrepot"){
                $label = $(this).closest(".nj_form_lblfld").find("label:eq(0)");
                //console.log($label);
				if($(this).val() == 'null' && $("#ship_type_2").attr("checked")){
                    passed = false;
                    errors.push($error_msg);
                    //$label.css("color","#E30707");
                    $label.addClass('error_field');
                }
            }
			else if($valtype == "filetype"){
				var accept_type = $(this).attr("accepttype").split(",");
				if(isEmpty($(this).val())){
                    passed = false;
                    errors.push($error_msg);
                    //$label.css("color","#E30707");
                    $label.addClass('error_field');
                }else{
					var ext = $(this).val().substr($(this).val().lastIndexOf(".")+1)
					var found = false;
					for(var i=0; i<accept_type.length; i++) {
						if (accept_type[i] == ext) found = true;
					}
					if(!found){
						passed = false;
						errors.push($(this).attr('error_msg2'));
						//$label.css("color","#E30707");
                        $label.addClass('error_field');
					}
					
				}
            }else if($valtype == "datesep"){
				var dateformat = $(this).attr("dateformat").split("-"); // id_year - id_month - id_date
                
				var today = new Date();
				today.setDate(1);
				var exp_date = new Date();
                //console.log($("#"+dateformat[2]).val());
				if(dateformat[2] != "") {exp_date.setDate($("#"+dateformat[2]).val());}else{exp_date.setDate(1);}
				if(dateformat[1] != "") {exp_date.setMonth($("#"+dateformat[1]).val()-1);}else{exp_date.setMonth(0);}
				if(dateformat[0] != "") {exp_date.setFullYear($("#"+dateformat[0]).val());}
                
				if(exp_date < today){
					passed = false;
					errors.push($(this).attr('error_msg'));
					//$label.css("color","#E30707");
					$label.addClass('error_field');
				}
			}
			
			

            // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            // ## COMMENTÉ PAR FRANCOIS; provoquait une erreur.
            //$.uniform.update();
            // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        })

        //%%%  OPTIONAL  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        if($("#comment_ta").val() == ""){

            var $ta = $("#comment_ta");
            var $error_msg = $ta.attr('error_msg');

            passed = false;
            errors.push($error_msg);
            $ta.parent().find("label").css("color","#F34B1C");
        }
        //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

        //console.log(clicked_element.siblings('form').attr('name'));

        if(passed == true){
            if(clicked_element != ""){
                clicked_element.unbind('click');
            }
            
            if(is_local_container){
                $current_form.submit();
            }else{
                $current_form.submit();
            }
            
        }else{
            var i = 0;
            
            while(i<errors.length){
                $errors_wrapper.find(".errors_list").append("<li>"+errors[i]+"</li>");
                i++;
            }
            $errors_wrapper.fadeIn(400, function(){
                    $('html,body').animate({ scrollTop: $errors_wrapper.offset().top }, { duration: 'slow', easing: 'swing'});
                    //location.replace('#');
            });
            
            
            return false;
        }
    }
	
	
    //#########################################################################################
    //##  Processus de paiement  ##############################################################

    //Copie les informations de livraison dans les informations de billing et marque les champs billing.

    $("#commande_shipping_same_as_billing").click(function(){
        $("#adresse_pareil input[req]").attr("req", !$(this).is(':checked'));
        $(".commande_shipping").toggle(!$(this).is(':checked'));
        //$("#sondage_diffusion_content").toggle($(this).is(':checked'));
        $(".copySrc").trigger("change");
    });

    $(".copySrc").bind("change", function(){

        var destFieldId = this.id.replace("billing", "shipping");
        if($("#commande_shipping_same_as_billing").is(':checked'))
            $("#" + destFieldId).val($(this).val());
    });

    //Supprime les caractères non numérique du champs.

    $("#billing_card_number").keyup(function(event){
        var newValue = $("#billing_card_number").val().replace(/[^0-9]/g, '');
        $("#billing_card_number").val(newValue);
    });

    $("input[name=ship_type]").click(function(e){
        $("#choix_entrepot").toggle(  $(this).val()==2  );
    });
	
	$("input[name=contact]").click(function(e){
		if($(this).val() == "Téléphone"){
			if($(this).attr("checked")){
				$("#tel").attr("req","true");
			}else{
				$("#tel").attr("req","false");
			}
		}
    });
    
    //##  Update panier  ######################################################################

    $('#btn_actualiser, .btn_supprimer').click(function(){
        $('#cart').submit();
    });
	
	//#########################################################################################
    //##  S'abonner a la NL lors du sondage  ##################################################

    $("#sondage_add_nl").click(function(){
		$("#sondage_diffusion_content input[req]").attr("req", $(this).is(':checked'));
		$("#email").attr("req", $(this).is(':checked'));
		
		
        $("#sondage_diffusion_content").toggle($(this).is(':checked'));
    });

});




function checkout_validate(){
    if($(this).action!="checkout3")
        return true;

    if($("input[name=ship_type]:checked").val() == undefined){
        alert("Veuillez sélectionner un mode de livraison.");
        return false;
    }
    if($("input[name=ship_type]:checked").val() == 2 && $("#takeout_entrepot").val() == 0){
        alert("Veuillez sélectionner un entrepôt.");
        return false;
    }
    if($("#billing_card_prenom").val() == "" || $("#billing_card_nom").val() == ""){
        alert("Veuillez saisir le nom et le prénom apparaissant sur votre carte de crédit.");
        return false;
    }
    if($("#billing_card_number").val() == ""){
        alert("Veuillez saisir votre numéro de carte de crédit.");
        return false;
    }
    if($("#billing_card_ccv").val() == ""){
        alert("Veuillez saisir le numéro de sécurité de votre carte de crédit.");
        return false;
    }

}

function close_popup(){
    $('.b_close').trigger('click');
}

function send_ami(){
    
	$.ajax({
	   type: "POST",
	   url: "/inc/send_mail.php",
	   data: "flag=send_ami&votre_nom=" + $(".b_ctr #votre_nom").val()+ "&votre_email=" + $(".b_ctr #votre_email").val()+ "&ami_nom=" + $(".b_ctr #ami_nom").val()+ "&ami_email=" + $(".b_ctr #ami_email").val()+ "&comment_ami=" + $(".b_ctr #comment_ami").val()+ "&produit_info_ami=" + $(".b_ctr #produit_info_ami").val()+ "&url=" + window.location,
	   success: function(data){
			$(".b_ctr").html(data);
            $(".b_ctr").append('<a href="#" class="b_close" title="Fermer la fenêtre">Fermer la fenêtre</a>');
            window.setTimeout(close_popup, 3000);
	   },
	   error: function(jqXHR, textStatus, errorThrown){
	   }
	});
	
	return false;
}

function send_demande_info(){
	$contact = new Array();
	$(".b_ctr input[name=contact]:checked").each(function(){
		$contact.push($(this).val());										   
	});
	$.ajax({
	   type: "POST",
	   url: "/inc/send_mail.php",
	   data: "flag=demande_info&prenom=" + $(".b_ctr #prenom").val()+ "&nom=" + $(".b_ctr #nom").val()+ "&tel=" + $(".b_ctr #tel").val()+ "&email=" + $(".b_ctr #email").val()+ "&contact=" + $contact.join(",")+ "&entrepot=" + $(".b_ctr #entrepot").val()+ "&produit_info=" + $(".b_ctr #produit_info").val()+ "&comment_demande_info=" + $(".b_ctr #comment_demande_info").val(),
	   success: function(data){
			$(".b_ctr").html(data);
            $(".b_ctr").append('<a href="#" class="b_close" title="Fermer la fenêtre">Fermer la fenêtre</a>');
            window.setTimeout(close_popup, 3000);
	   },
	   error: function(jqXHR, textStatus, errorThrown){
	   }
	});
	
	return false;
}
