﻿/* "selects" a facet
This function sets window.location.search to a new query string based on the facet selected.
If replace is specified then it replaces any existing facet selection of the query string with the new one, rather than appending it.
Otherwise, the new facet selection is just appended
  
This function only returns if the selection causes no change to the selected facets (i.e. the query string actually changes)
*/
function SelectFacet(facetCollectionPrefix, facetName, facetValue, replace) {
    var q = window.location.search;

    if (replace) {
        var params;
        if (q && q.length > 1) {
            q = q.substring(1, q.length)
            params = q.split("&");
            var combinedFacetName = facetCollectionPrefix + facetName;
            for (var j = params.length - 1; j >= 0; j--) {
                if (params[j].indexOf(combinedFacetName) == 0) {
                    params.splice(j, 1);
                }
            }
            params[params.length] = [combinedFacetName, "=", facetValue].join("");
        }
        var newSearchString = "?" + params.join("&");
        if (newSearchString != window.location.search) {
            window.location.search = "?" + params.join("&");
        }
    } else {
        if (q) {
            q = [q, "&", facetCollectionPrefix, facetName, "=", facetValue].join("");
        }
        else {
            q = ["?", facetCollectionPrefix, facetName, "=", facetValue].join("");
        }
        window.location.search = q;
    }
}
