$(document).ready(function () {
    $("#searchbutton").click(function () {
        trackSearch($(".searchQuery").val());
        //onSearchButtonClick($(".searchQuery").val());
        return false;
    });

    $(".searchQuery").keydown(function (event) {
        if (event.keyCode == 13) {
            trackSearch($(".searchQuery").val());
            //onSearchButtonClick($(".searchQuery").val());
            return false;
        }
        return true;
    });
});

function onSearchButtonClick(searchQueryValue) {
    search(TrimString(searchQueryValue).replace('&', '').replace('/', ' ').replace('?', ''));
}


// Use this approach to avoid usage of a cache
function replaceQueryParameter(url, name, value) {
    var decodedURI = decodeURIComponent(url);
    var slashIndex = decodedURI.lastIndexOf('/')
    var baseUrl = decodedURI.substring(0, slashIndex + 1);

    var arr = decodedURI.substr(slashIndex + 1).split('-');
    for (var i = 0, n = arr.length; i < n; i++) {
        if (arr[i] == name) {
            arr[i + 1] = encodeURIComponent(value);
        } else {
            arr[i + 1] = encodeURIComponent(arr[i + 1]);
        }
        i++;
    }
    url = baseUrl + arr.join("_");
    return url;
}

function searchRoomIdeas(query)
{
    if (query != "") {
        //TODO: refactor as searchProducts()
        document.location.href = "/roomideas/keyword_" + encodeUrl(query);
    }
}

function searchProducts(searchQueryValue) {
    if (searchQueryValue != "") {
        document.location.href = getSearchProductsUrl(0, searchQueryValue);
        return;
    }
}

function search(query) {
    if (document.location.href.indexOf('/roomidea') > 0)
        searchRoomIdeas(query);
    else
        searchProducts(query);
}


