$(document).ready(function() {

    $("#rechercheForm").attr("action", redirectIP + "/resultat-recherche.aspx");

    _initGsa();
	
    (function($) {
        $.fn.rePosition = function()
        {
            var position = $("#recherche").offset();

        $(this).css({
                top: position.top + $("#recherche").height() + 5,
                left: position.left
            });
        };
    })(jQuery)
	
    $("#recherche").blur(function() {
        if($(this).val() == "")
            $(this).val("Rechercher");
        $("#popine").slideUp();
    });

	
    $("#recherche").focus(function() {
        if($(this).val() == "Rechercher")
            $(this).val("");
        else
            $("#popine").slideDown();
    });
	
    $("#recherche").keyup(function(e) {
//        $("#popine").slideDown();
//        $("#popine").rePosition();
        switch(e.keyCode) {
            case 16: // Shift
            case 17: // Control
            case 37: // Gauche
            case 39: // Droit
            case 18: // Alt
            case 91: // Windows
            case 224: // Cmd
                break;
            case 38: // Haut
                $("#popine").each(function() {
                    var elem = $('#premier_mot , #second_mot , #troisieme_mot', this);
					
                    if(position > 1 ) {
                        position--;
						
                        var current = position - 1;
                        if(position < elem.length && position >= 0)
                            $(elem.get(position)).removeClass("active");
						
                        $(elem.get(current)).addClass("active");
						
                        if($(elem.get(current)).html().match(/^<a/)) {
                            $("#recherche").val(currentq);
                            enterlink=true;
                        }
                        else {
                            $("#recherche").val($(elem.get(current)).text());
                            enterlink=false;
                        }
                    }
                });
                break;
            case 40: // Bas
                $("#popine").each(function()	{
                    var elem = $('#premier_mot , #second_mot , #troisieme_mot', this);
			
                    if(position < elem.length)
                    {
                        var prec = position - 1;
						
                        if(prec >= 0 && prec < elem.length )
                            $(elem.get(prec)).removeClass("active");
						
                        $(elem.get(position)).addClass("active");
						
                        if($(elem.get(position)).html().match(/^<a/)) {
                            $("#recherche").val(currentq);
                            enterlink=true;
                        }
                        else {
                            $("#recherche").val($(elem.get(position)).text());
                            enterlink=false;
                        }
						
                        position++;
                    }
                });
                break;
            case 13:
                if(enterlink) {
                    $("#popine").each(function() {
                        var elem = $('#premier_mot , #second_mot , #troisieme_mot', this);
                        window.location = $(elem.get(position - 1)).find(".suggest-links").attr("href");
                    });
                } else {
                    $("#rechercheForm").submit();
                }
                $("#popine").slideUp();
                break;
            default:
                currentq = $("#recherche").val();
                autocomplete();
                break;
        }
    });
	
    $("#premier_mot , #second_mot , #troisieme_mot , .premier_article , .second_article , .troisieme_article").live('mouseover', function() {
        $(this).addClass("active");
    });
	
    $("#premier_mot , #second_mot , #troisieme_mot , .premier_article , .second_article , .troisieme_article").live('mouseout', function() {
        $(this).removeClass("active");
    });
	
    $("#premier_mot , #second_mot , #troisieme_mot").live('click',function() {
        if($(this).html().match(/^<a/)) {
            window.location = $(this).find(".suggest-links").attr("href");
        }
        else {
            $("#recherche").val($(this).text());          
            $("#rechercheForm").submit();
        }        
    });

    $("#rechercheForm").submit(function() {
        if(enterlink) return false;
    });
});

var position = 0;
var currentq = "";
var enterlink = false;
	
function _initGsa() {
//    $('<div></div>')
//    .appendTo(document.body)
//    .attr('id','popine')
//    .attr('class','resultats');
//		
//    $('<div></div>')
//    .appendTo('#popine')
//    .attr('class','inside')
//    .attr('id','inside');
//
//    $('<div></div>')
//    .appendTo('#inside')
//    .attr('class','gsa-results');
//		
//    $('<ul></ul>')
//    .appendTo('#inside')
//    .attr('class','gsa-results2');
    
    $('<div></div>')
    .appendTo('#moteurRecherche')
    .attr('id','popine');

    $('<div></div>')
    .appendTo('#popine')
    .attr('class','recherche_mot');
    
    $('<div><img width="307" height="11" alt="" src="/images/recherche_fleche_basse.gif" /></div>')
    .appendTo('#popine');
    
    $('<div></div>')
    .appendTo('#popine')
    .attr('class','recherche_article');
}

function autocomplete() {
    if($("#recherche").val() != "" && $("#recherche").val() != null) {
        getSuggest($("#recherche").val());
        getAutocomplete($("#recherche").val());
    }
    else
        $("#popine").hide();
}

function getAutocomplete(q) {
    Url = "/recherche/autocompletion/autocomplete.php";
    if(isCompario == 'true')
        Url = redirectIP + Url;
    
    $.post(Url, {
        q:q
    },
    function(data){
        handleResultAutocomplete(data);
    },"xml");
}

function getSuggest(q) {
    Url = "/recherche/autocompletion/suggest.php";
    if(isCompario == 'true')
        Url = redirectIP + Url;
    $.post(Url, {
        q:q
    },
    function(data){
        handleResultSuggest(data);
    },"json");
}


function handleResultSuggest(data)
{
    var exreg = new RegExp("($('#recherche').val())", "g");
//    $(".gsa-results").html("");
    $(".recherche_mot").html("");
    var nombres = new Array('premier', 'second', 'troisieme', 'quatrieme', 'cinquieme');
    if(data.results.length > 0)
    {
        //if result
        $("#popine").slideDown();
        var e = "";
		
        for(var i = 0; i < data.results.length; i++)
        {
//            e = e + '<div class="single-suggest-results">'+data.results[i].name+'</div>'
              e = e + '<div id="' + nombres[i] + '_mot"><span>'
                        + data.results[i].name.replace($("#recherche").val(), '<span class="rouge">' + $("#recherche").val() + '</span>')
                    + '</span></div>';
        }
        $(e).appendTo(".recherche_mot");
    }
}

function handleResultAutocomplete(xmlDoc)
{
    var result = xmlDoc.getElementsByTagName('R');
    var resultat = new Array();
			
    for (var i = 0; i < result.length; i++)
    {
        resultat[i] = new Array();
		
        resultat[i]['url'] = result[i].getElementsByTagName('U')[0].firstChild.data;
		
        var meta = result[i].getElementsByTagName('MT');
        for(var j = 0; j < meta.length; j++) {
            // !compario = image, compario = Photo
            if(meta[j].getAttribute('N') == "Photo")
                resultat[i]['image'] = meta[j].getAttribute('V');
            // !compario = title, compario = Référence unique
            if(meta[j].getAttribute('N') == "Référence unique")
                resultat[i]['titre'] = meta[j].getAttribute('V');
            // !compario = prix, compario = Prix de référence
            if(meta[j].getAttribute('N') == "Prix de référence")
                resultat[i]['prix'] = meta[j].getAttribute('V');
				
        }
       
    } 
	
    if(result.length > 0) {
        printResultAutocomplete(resultat);
        $("#popine").slideDown();
    }
		
    return resultat;
}

function printResultAutocomplete(result)
{
    var exreg = new RegExp("(" + $('#recherche').val() + ")", "g");
    var nombres = new Array('premier', 'second', 'troisieme', 'quatrieme', 'cinquieme');

    $(".recherche_article").html("");
	
    for(var i = 0; i < result.length; i++)
    {
        var div_article_i = document.createElement("div");
        div_article_i.className = nombres[i] + "_article";
		
        var a = document.createElement("a");
        a.className = "suggest-links";
        a.href = result[i]['url'];
        
        //image
        var image = document.createElement('div');
        image.className = "img";
        var img = document.createElement("img");
        var urlParts = result[i]['image'].split("/");
        img.src = scene7Url + urlParts[urlParts.length-1].split(".")[0] + "?$produit_xs$";
        image.appendChild(img);
        
        //desc
        var desc = document.createElement('div');
        desc.className = "desc";
        var titredesc = document.createElement('span');
        titredesc.innerHTML = result[i]['titre'].replace(exreg, '<span class="rouge">' + $("#recherche").val() + '</span>');
        desc.appendChild(titredesc);
        
        //prix
        var prix = document.createElement('div');
        prix.className = "prix";
        var prix_span = document.createElement('span');
	prix_span.innerHTML = result[i]['prix'] + " &euro;";
        prix.appendChild(prix_span);
        
        div_article_i.appendChild(a);
        a.appendChild(image);
        a.appendChild(desc);
        a.appendChild(prix);
		
        $(".recherche_article").append(div_article_i);
        if ( i < (result.length - 1) ){
            var separation = document.createElement("div");
            separation.className = "separation";
            $(".recherche_article").append(separation);
        }
    }
}

