function wait_critere ( el ) {
	el = ( typeof el == 'undefined' ) ? '#middle' : el;

	if ( $('.loader').is(':visible') ) {
		$('.loader').hide('slow').remove();
	}
	else {
		$("body").append("<div class='loader'><div class='loader_in'></div></div>");
		$('.loader').show('slow');

		var zone_wait = $(el);
		var offset_zoneWait = zone_wait.offset();

		$(".loader").css({
			"zIndex": "100000",
			"position": "absolute",
			"width": zone_wait.width(),
			"height":zone_wait.height(),
			"top": offset_zoneWait.top,
			"left": offset_zoneWait.left
		});
	}
}

function str_replace (search, replace, subject, count) {
    var i = 0, j = 0, temp = '', repl = '', sl = 0, fl = 0,
            f = [].concat(search),
            r = [].concat(replace),
            s = subject,
            ra = r instanceof Array, sa = s instanceof Array;
    s = [].concat(s);
    if (count) {
        this.window[count] = 0;
    }

    for (i=0, sl=s.length; i < sl; i++) {
        if (s[i] === '') {
            continue;
        }
        for (j=0, fl=f.length; j < fl; j++) {
            temp = s[i]+'';
            repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
            s[i] = (temp).split(f[j]).join(repl);
            if (count && s[i] !== temp) {
                this.window[count] += (temp.length-s[i].length)/f[j].length;}
        }
    }
    return sa ? s : s[0];
}


function trim (str, charlist) {
    var whitespace, l = 0, i = 0;
    str += '';

    if (!charlist) {
        // default list
        whitespace = " \n\r\t\f\x0b\xa0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000";
    } else {
        // preg_quote custom list
        charlist += '';
        whitespace = charlist.replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '$1');
    }

    l = str.length;
    for (i = 0; i < l; i++) {
        if (whitespace.indexOf(str.charAt(i)) === -1) {
            str = str.substring(i);
            break;
        }
    }

    l = str.length;
    for (i = l - 1; i >= 0; i--) {
        if (whitespace.indexOf(str.charAt(i)) === -1) {
            str = str.substring(0, i + 1);
            break;
        }
    }

    return whitespace.indexOf(str.charAt(0)) === -1 ? str : '';
}

$(document).ready(function(){
	// BOF 10-TRI_SUR_LE_CATALOGUE
	$('#order_value').live('change', function() {
		$('.capl:eq(0)').click();
	});
	// EOF 10-TRI_SUR_LE_CATALOGUE

	$('.child_cat_masque').hide();
	$('.parent_cat').removeClass('open_boxe');

    $('#left .selected a').live( 'click', function() {
		return false;
	});

	$('.parent_cat').live( 'click', function() {
		var $this = $(this);
		
		$this.next(".child_cat").slideToggle('slow', function(){
			if ( $this.next(".child_cat").is(':visible') ) {
				$this.addClass('open_boxe');
			}
			else {
				console.log('fermer');
				$this.removeClass('open_boxe');
			}
		});
    });

	$('.capl a, a.capl, .cap2, .capl_delete').live( 'click', function() {
		wait_critere();

        var target_scroll = 'middle';
        var actual_search = $('#actual_search');

        var type = $(this).attr('type');
		var txt = $(this).text();
		var thisLI = $(this).parents('li');
        var rel = $(this).attr('rel');

        var appli;

        // BOF 10-TRI_SUR_LE_CATALOGUE
		var order_value = '&order_value='+$('#order_value').val();
        // EOF 10-TRI_SUR_LE_CATALOGUE

        if ( type == 'new_perpage' ) {
            var new_perpage = '&parpage='+rel;
            // BOF 62-PATCH_AJAX_PRODUCT_LISTING
            appli = '&appli='+$('#listOfAppli').val();
            // EOF 62-PATCH_AJAX_PRODUCT_LISTING
        }
        else {
        	var val_perpage = $('.bloc_filtre .selected:first').html();
            var new_perpage = '&parpage='+val_perpage;
        }

        if ( type == 'new_current_page' ) {
            var new_current_page = '&pageencour='+rel;
            // BOF 62-PATCH_AJAX_PRODUCT_LISTING
            appli = '&appli='+$('#listOfAppli').val();
            // EOF 62-PATCH_AJAX_PRODUCT_LISTING
        }
        else {
            new_current_page = '&pageencour=1';
        }

        if ( type == 'catproduct' ) {
            $('.catproduct_selected').each( function() {
                $(this).remove();
            });
            //target_scroll = 'boxe_conditionment';
        }
        else if ( type == 'echelle' ) {
            $('.echelle_selected').each( function() {
                $(this).remove();
            });
        }
        else if ( type == 'conditionnement' ) {
            $('.conditionnement_selected').each( function() {
                $(this).remove();
            });
            //target_scroll = 'boxe_nationalite';
        }
        else if ( type == 'nationalite' ) {
            //target_scroll = 'boxe_marques';
        }
        else if ( type == 'marque' ) {
            //target_scroll = 'boxe_echelle';
        }


        if ( type == 'delete' ) {
            thisLI.remove();
        }
        else if ( type != 'new_perpage' && type != 'new_current_page' ) {
        	actual_search.append( '<li class="delete '+type+'_selected"><a class="capl capl_delete" id="li_select_'+type+'_'+rel+'" type="delete" rel="'+type+'"><span>'+txt+'</span></a><input type="hidden" id="input_select_'+type+'_'+rel+'" name="'+type+'_selected[]" value="'+rel+'" /></li>' );
        }

		// BOF 62-PATCH_AJAX_PRODUCT_LISTING
		// BOF 10-TRI_SUR_LE_CATALOGUE
		var sendData = $('form#critere_search').serialize() + new_perpage + new_current_page + appli + order_value;
		// EOF 10-TRI_SUR_LE_CATALOGUE
		// EOF 62-PATCH_AJAX_PRODUCT_LISTING

		// requete ajax
		$.post (
			"ajax_update.php?action=new_critere_cat",
			sendData,
			function( data ) {
				// affiche le résultat de la requete au centre de la page
				tb_init('a.thickbox, area.thickbox, input.thickbox');



				$('.masque_select_ajax').each( function() {
                    $(this).hide();
                });

                $('#container-in').html( data );

                // permet d'afficher les boutons voir les détails  ( après html data )
				$('.view_details').hide();
                /*
				$(".image_produit").hover(function(){
                    masque_id = $(this).attr('rel');
                    $('#masque_'+masque_id).show();
                    	}, function() {
                    $('#masque_'+masque_id).hide();
                });
                */

                // BOF 85-STICKER_PRODUITS
				$(".product-survol").hover(
					function(){
						$(this).parent(".product").children('.product-sticker').show();
				    },
				    function(){
						$(this).parent(".product").children('.product-sticker').hide();
				    }
				);
				// EOF 85-STICKER_PRODUITS

                $.scrollTo( $('#'+target_scroll), 800 );

				wait_critere();
			}
		);

		var url = trim( sendData, '&' );
		url = str_replace( '%5B', '|c|', url );
		url = str_replace( '%5D', '|v|', url );

		self.location.hash = ''+url;

		return false;
	});

	if ( self.location.hash != '' ) {
		var url = trim( self.location.hash, '#' );

		url = str_replace( '|c|', '%5B', url );
		url = str_replace( '|v|', '%5D', url );

		wait_critere();

		var sendData = url;

		// requete ajax
		$.post (
			"ajax_update.php?action=new_critere_cat",
			sendData,
			function( data ) {
				// affiche le résultat de la requete au centre de la page
				tb_init('a.thickbox, area.thickbox, input.thickbox');

				$('.masque_select_ajax').each( function() {
                    $(this).hide();
                });

                $('#container-in').html( data );

                $('.child_cat_masque').hide();

                // permet d'afficher les boutons voir les détails  ( après html data )
				$('.view_details').hide();
                $(".image_produit").hover(function(){
                    masque_id = $(this).attr('rel');
                    $('#masque_'+masque_id).show();
                    	}, function() {
                    $('#masque_'+masque_id).hide();
                });

                // BOF 85-STICKER_PRODUITS
				$(".product-survol").hover(
					function(){
						$(this).parent(".product").children('.product-sticker').show();
				    },
				    function(){
						$(this).parent(".product").children('.product-sticker').hide();
				    }
				);
				// EOF 85-STICKER_PRODUITS

				wait_critere();
			}
		);
	}
});