/*
 * This script supplies autocomplete functionality on the search boxes
 * of the website.
 * When a user starts to enter imput an autocomplete box is generated
 * to give the user a hand in selecting what they want.
 */

$(document).ready(function() {

    /*
     * We attach our script to all elements with the ID of spadasearch.
     * This means that we are listening for a change event on any element
     * with this ID. (Should only be search boxes!)
     */
    var searchId = '#spadasearch'; // Set the ID of the search box (inclide a #)
    var minSearchLen = 2; // The mininum number of characters to start searching on (better results).
    var host = "http://www.spadaclothing.co.uk/";

    // Set the position of the autocomplete menu to the search box
    var searchIdPos = $(searchId).offset();
    $('#autoCompleteMenu').css({'top' : (searchIdPos.top + 40), 'left' : (searchIdPos.left - 75)});
    $(searchId).keyup(function() {
        if($(searchId).val().length >= minSearchLen) { // Only start searching on min search length
            // Submit the value to the server to get the results.
            
            $.ajax({
                type: "POST",
                url: host + "autocomplete.php", // Gets the URL from the hyperlink
                data: "searchContent=" + $(searchId).val(), // gets the data we need
                dataType: "json",
                success: function(data) {
                    html = ""; // This holds the HTML for the drop down.
                    for(var i = 0; i < data.length; i++) { // Cycle through the returned data
                        // Build the hyper link from the data.
                        html += '<li><a href="'+host+'productdetail.php?subcat='+data[i].productSubCatId+'&cat='+data[i].productCatId+'&product='+data[i].productId+'">' + data[i].productName + '</a> | ';
                        html += '<a href="'+host+'products.php?subcat='+data[i].productSubCatId+'&cat='+data[i].productCatId+'">' + data[i].productSubCatTitle + '</a></li>'; // Put in the category sub title.
                    }

                    if(data != "") { // No results
                        $('#autoCompleteItemCont').html(html);
                        $('#autoCompleteMenu').slideDown("medium");
                    }
                    
                },
                error: function(data) { // If an error happens with the request send an alert.
                    alert("Status: " + data.statusText + " Response: " + data.responseText);
                }
            })
        } else {
            $('#autoCompleteMenu').slideUp("medium");
        }
    })
});

