/*
 * AJAX Sorting functions
 *
 * Copyright (c) 2008 Loopo Ltd
 */

// Replaces the specified GET parameter in the specified URL with the specified
// value.  Also removes any fragment identifier in the URL.
function replaceParam(url, param, value) {
    url = url.replace(/#.*$/, '');
    var re = new RegExp("([\\?&])"+param+"=([^&#]*)");
    if (url.match(re)) {
        url = url.replace(re, '$1' + param + '=' + value);
    } else if (url.indexOf('?') != -1) {
        url += '&' + param + '=' + value;
    } else {
        url += '?' + param + '=' + value;
    }
    return url;
}

// Reloads the target element of the current page, with a new sort value in the
// GET request.
function changeSort(target, el) {
    var sort_val = $(el).val();
    var new_url = window.location.href;
    new_url = replaceParam(new_url, 'sort', sort_val);
    new_url = replaceParam(new_url, 'page', '1');    
    // $(target).load(new_url + '&xhr=1');
    // window.location.hash = 'sort=' + sort_val;
    window.location.href = new_url;
    return false;
}

$(function() {
    $('div.paginator a').click(function() {
        var hash = window.location.hash;
        var re = new RegExp("sort=([^&#]*)");
        var match = re.exec(hash);
        if (match != null && match.length > 0) {
            window.location.href = replaceParam($(this).attr('href'), 'sort', match[1]);
            return false;
        }
        return true;
    });
});
