/**
 * jQuery resetDefaultValue plugin
 * @version 0.9.1
 * @author Leandro Vieira Pinho
 */
jQuery.fn.resetDefaultValue = function() {
	function _clearDefaultValue() {
		var _$ = $(this);
		if ( _$.val() == this.defaultValue ) {_$.val('');}
	};
	function _resetDefaultValue() {
		var _$ = $(this);
		if ( _$.val() == '' ) {_$.val(this.defaultValue);}
	};
	return this.click(_clearDefaultValue).focus(_clearDefaultValue).blur(_resetDefaultValue);
}

/*  reset the form    */
function resetJNiceForm(form){
    $('.jNiceFacebox .jNiceSelectWrapper ul .group0 li:first-child a').each(function(){$(this).click();});
}

/*personalisation*/
function refreshFacebox(data){
    $("#facebox .content").html(data);
}
function emptyFacebox(){
    wait = "<div align='center'><img src='/fileadmin/templates/images/img/facebox/loading.gif'/></div>";
    $("#facebox .content").html(wait);
}

function ajout_perso(){
    form = jQuery('#formPersonalisation');
    action = form.attr('action');
    data = form.serialize();
    emptyFacebox();
    jQuery.post(action, data, refreshFacebox);
    return false;
}
function supp_perso(){
    form = jQuery('#formPersonalisation');
    action = form.attr('action');
    data = form.serialize();
    emptyFacebox();
    jQuery.post(action, data+'&supp=1', refreshFacebox);
    return false;

}
function submitRefineForm(domId){
    var pmin = $('#'+domId).find("*[name=tx_mabvente_pi5[pmin]]").val();
    var pmax = $('#'+domId).find("*[name=tx_mabvente_pi5[pmax]]").val();
    if(pmin!="" && pmax!=""){
        if(parseInt(pmin)>parseInt(pmax))
            return true;
    }
    $('#'+domId).submit();
    return true;
}
/*refresh the html top right ontent with the new total bill after add a item to the cart*/
function miseAjourPanier(domid ,url, typenum_recap){
    $(document).bind('close.facebox', function(e){
        $.ajax({

            url: url+"&type="+typenum_recap,

            success: function(data, textStatus) {

                $('#'+domid).empty().append(data);

            }

        });
    });
    return false;
}
var criticalItem = [1,6,11,16,21];//25 items to be viewed 5 by 5
var cId = 0;
var carouselControler = new Array();
/*init carousel*/
function mycarousel_initCallback(carousel) {
        cId++;
        carousel.options.id = cId;
        jQuery('#carouselControleur'+cId+' .nav a').bind('click', function() {//bind click sur les perles correspondantes
                carousel.scroll(jQuery.jcarousel.intval(jQuery(this).text()));
                return false;
        });
        setControlerPosition(cId,0);//permiere perle highlightee
}
/*class active sur la perle numero arrayIndex*/
function setControlerPosition(idCarousel, arrayIndex){
    $(carouselControler[idCarousel-1]).each(function(i){
            if(i==arrayIndex)
                $(this).addClass("active");
            else
                $(this).removeClass("active");
    });
}
/*si un des produits "jalon" du carousel est visible, il faut mettre à jour la perle correspondante : highlightee*/
function mycarousel_itemVisibleInCallbackAfterAnimation(carousel, item, idx, state) {
    if(state=='init')
        return;
    var arrayIndex = jQuery.inArray(idx, criticalItem);
    if(arrayIndex!=-1){
        setControlerPosition(carousel.options.id,arrayIndex);
    }
}

function fixCss(){
    if($(".wrap-bloc div.bloc").length<4){
        /*aligner les bloc au centre, (probleme de width dynamique)*/
        var newWidth = 100;
        $(".wrap-bloc div.bloc").each(function(){
            newWidth += parseInt($(this).css("width"));
            newWidth += parseInt($(this).css("marginLeft"));
            newWidth += parseInt($(this).css("marginRight"));
        });
        
        $("div.wrap-bloc").css("width", newWidth + "px");
        $(".wrap-bloc").css("margin", "auto");
    }
    var name = navigator.userAgent.toLowerCase();
    if(name.indexOf("chrome")!=-1){
        //corrections chrome
        //$(".Accueil .addthis_toolbox a.addthis_button_facebook_like").css("margin-top", "-18px");
    }
    if(name.indexOf("firefox")!=-1){
        //corrections chrome
        $(".formactumab .rollover").css("padding", "0px 0 2px 14px");
    }
}


function suggestion(e) {
                if(e.keyCode==13)
                    return false;
		var input = $(this);
		var largeur = Math.max(input.width(),120);
		var page = "index.php?id=" + ajax_keyword_page_url + "&key=" + input.attr("value") + String.fromCharCode(e.which);
		var keywork = input.attr("value") + String.fromCharCode(e.which);

		if(keywork.length<2)
			return;

		$.get(page, function(data) {
			var elementsArray = new Array();
					$(data).find('li').each(function(){
							elementsArray.push(($(this).text()));
							});
					input.autocomplete(elementsArray, {width:largeur});
					});


}

/*change la cible du formulaire si un mot clé est present*/
function splitSearchSubmit(){
    var val = $('#tx_mabvente_pi5_keyword').val();
    var form = $('#prodnav_form');
    if(typeof(val)!='undefined' && val!=""){
        form.attr('action', '/');
        form.append('<input type="hidden" value="' + val + '" name="tx_mabrecherche_pi2[swords]"/>');
        form.append('<input type="hidden" value="' + pid_recherche_globale_resulats + '" name="id"/>');
        form.append('<input type="hidden" value="produits" name="section"/>');
    }
    form.submit();
}

function applySizePerCategory(){
    $(".jNiceFacebox .taille").addClass("disable");//desactive le fomulaire taille
    $(".jNiceFacebox .taille .group").css("display", "none");//cache toutes les tailles
    $(".jNiceFacebox .taille .group0").css("display", "");//affiche la taille par default
    $(".jNiceFacebox .categorie .jNiceSelectWrapper ul li a").bind('click', function(){
            $(".jNiceFacebox .taille .group").css("display", "none");//cache toutes les tailles
            if($(this).attr("value"))
                $(".jNiceFacebox .taille .group" + $(this).attr("value")).css("display", "");//affiche seulement les tailles dispo dans cette categorie
            $(".jNiceFacebox .taille .group0").css("display", "");//affiche la valeur par default
            $('.jNiceFacebox .taille .jNiceSelectWrapper ul .group0 li:first-child a').click();//active la valeur defaut pour la taille
            if( $(this).attr("index")!=0 ) // une categorie
                $(".jNiceFacebox .taille").removeClass("disable");
            else{//cache les tailles si aucune categorie selectionnee
                $(".jNiceFacebox .taille").addClass("disable");
            }
    });
    $(".jNiceFacebox .categorie a.selected").each(function(){//la valeur selectionnee par default au chargement
        if($(this).attr("value"))
            $(".jNiceFacebox .taille .group" + $(this).attr("value")).css("display", "");
        if( $(this).attr("index")!=0 )
                $(".jNiceFacebox .taille").removeClass("disable");
        else
                $(".jNiceFacebox .taille").addClass("disable");
    });
}

var originalAdvanceSearchHtml = '';
function applyJNiceToAdvanceSearch(){
    $('.jNiceFacebox .box label').each(function(){
        var label = $(this);
        label.addClass('disable');
        $(this).parent().find('option:selected').each(function(){//avant l'appel a jNice il y a encore les balises option native'
            if($(this).attr("value")!=0)
                label.removeClass('disable');
        });
    });
    originalAdvanceSearchHtml=$('.jNiceFacebox').html();//pour restaurer le html original si on ferme la box (jNice detruit la structure et ne marche pas sur les hiddens)
    $(document).bind('beforeReveal.facebox', function(e){
            $('#bloc-advanced-search').css('display','none');
    });
    $(document).bind('afterReveal.facebox', function(e){
            $('.jNiceFacebox').jNice();
            applySizePerCategory();
            $('.jNiceFacebox .jNiceSelectWrapper ul li a').bind('click', function(e){
                if($(this).attr("index")==0){
                   $(this).parents('.box').find('label').addClass('disable');
                }else{
                   $(this).parents('.box').find('label').removeClass('disable');//seul les elements filtres par l'utilisateur sont mis en evidence
                }
            });
    });
    $(document).bind('close.facebox', function(e){
            $('.jNiceFacebox .jNiceSelectWrapper ul li a').unbind('click');
            $('.jNiceFacebox').html(originalAdvanceSearchHtml);
    });
}



$(document).ready(function() {
	$('#manege_search, #manege_search2').resetDefaultValue(); // 277 boutiques
        $('#insc_email, #insc_email2').resetDefaultValue(); // newsletter
        $('#espacesmab_swords').resetDefaultValue(); // newsletter
        $.facebox.settings.opacity = 0.3;
        $.facebox.settings.loadingImage = "/fileadmin/templates/images/img/facebox/loading.gif";
        $.facebox.settings.closeImage = "/fileadmin/templates/images/img/facebox/closelabel.gif";
        $('a[rel=facebox]').facebox();//mon compte

        /*recencement des controleurs*/
        var coId = 0;
        jQuery('#tabs .nav').each(
            function(){
                carouselControler.push(new Array());
                $(this).find("a.resetCarousel").each(function(){
                    carouselControler[coId].push(this);
                });
                coId++;
            }
        );
        
        $('#carouselhome1, #carouselhome2, #carouselhome3').jcarousel({
            'buttonNextHTML':'<div class="next"><a title="Suivant"><span>Suivant</span></a></div>',
            'buttonPrevHTML':'<div class="prev"><a title="Précédent"><span>Précédent</span></a></div>',
            'initCallback': mycarousel_initCallback,
            'scroll': 5,
            itemVisibleInCallback: {
                onAfterAnimation:  mycarousel_itemVisibleInCallbackAfterAnimation
            }
        });

        fixCss();

        // Tabs
        /*fix librairie bugs with full url*/
        $('.search-advanced a').each(function(){
            var url = window.location.toString();
            $(this).attr('href', url.replace(/^(.*)#(.*)/g, "$1") + '#'+$(this).attr('href').replace(/^.*#/g, ""));//bug on /accueil/ for advance search if href=# directly
        });
        $('.search a[rel=facebox]').each(function(){
            var url = window.location.toString();
            $(this).attr('href', url.replace(/^(.*)#(.*)/g, "$1") + '#'+$(this).attr('href').replace(/^.*#/g, ""));//bug on /accueil/ for advance search if href=# directly
        });
        $('a[rel=facebox].kiala_button').each(function(){
            var url = window.location.toString();
            $(this).attr('href', url.replace(/^(.*)#(.*)/g, "$1") + '#'+$(this).attr('href').replace(/^.*#/g, ""));//bug on /accueil/ for advance search if href=# directly
        });
        $('#tabs ul.wrap-tabs li a').each(function(){
           $(this).attr('href', '#'+$(this).attr('href').replace(/^.*#/g, ""));
        });
        
        tab = $('#tabs').tabs();
        $('#tabs').css('visibility','visible');
        
        //autocomplete
        $("#tx_mabvente_pi5_keyword, #swords_1, #swords_0").attr("autocompete", "off");
        $("#tx_mabvente_pi5_keyword, #swords_1, #swords_0").keypress(suggestion);	//recherche section principale
	applyJNiceToAdvanceSearch();

});

