var search_DefaultText;
var search_Autocomplete = false;
$(document).ready(function () {
    search_DefaultText = $(".search_magasin").val();

    $("body").outsourceIt();


    $(".search_magasin").focus (function(){
        if ($(this).val()==search_DefaultText) {
            $(this).val("");
        }
        
    });

   $(".search_magasin").blur (function(){
        if ($(this).val()=="") {
            $(this).val(search_DefaultText);
        }
    });

   $(".search_magasin").keyup(function(e){
        var parent = $(this).parent("div");
        if ($(this).val().length > 2) {

            
            $.getJSON(webUrl + lng + '/' + (lng == "fr" ? "magasins" : "stores") + '?q=' + $(this).val() + "&json=true", function(data) {

                if (data.length > 0) {
                    var html="";
                    html+="<ul>";
                    for (aa=0;aa<data.length;aa++) {
                        html += "<li><a class='magparmag' href='" + data[aa].permalink + "'>" + data[aa].name + "</a></li>";
                    }
                    html+="</ul>";
                    parent.find(".results_magasin").html(html);
                    parent.find(".results_magasin").css("display","block");
                    
                    initCloseAutocomplete();
                }

            });
        } else {

             parent.find(".results_magasin").css("display","none");
             parent.find(".results_magasin").html("");
        }

        // Enter ?
        if(e.which==13) $("#blocTrouverMagasin div .freeSearch").trigger("click");
   });

   $("#blocTrouverMagasin div .freeSearch").click(function(e) {
       location = webUrl + lng + '/' + (lng == "fr" ? "magasins" : "stores") + '?s=' + encodeURIComponent($(".search_magasin").val());
   });
   //

});

function initCloseAutocomplete(){
   if(!search_Autocomplete){
       search_Autocomplete = true;

       //$("#blocTrouverMagasin, #blocChercherMagasin").mouseleave(function(){
       $("body").unbind(".search").bind("click.search", function(){
            $(".results_magasin").css("display","none");
            $(".results_magasin").html("");
            search_Autocomplete = false;
       });

   }
}

