function set_sort(default_sort) {
    query_string = new Querystring();
    if (query_string.get('s')) {
        $("select[name='s']").val(query_string.get('s'));
    } else {
        $("select[name='s']").val(default_sort);
    }
}

function sort(sort) {
    query_string = new Querystring();
    sort_url = '?s=' + sort.value;
    if (query_string.get('q')) {
        sort_url = sort_url + '&q=' + query_string.get('q');
    }
    window.location = sort_url;
}

// XXX: This should be merged with sort() which should handle any existing
//      GET args.
function sort_results(sort) {
    query_string = new Querystring();
    sort_url = '?s=' + sort.value;
    if (query_string.get('price_range')) {
        sort_url = sort_url + '&price_range=' + query_string.get('price_range');
    }
    window.location = sort_url;
}

function pfv() {
    query_string = new Querystring();
    sort_url = '?s=' + $('#s').val();
    if (query_string.get('q')) {
        sort_url = sort_url + '&q=' + query_string.get('q');
    }
    sort_url = sort_url + '&pfv';
    window.open(sort_url, "_BLANK");
}

function update_chars_remaining(dom_object, limit) {
    text = $('#'+ dom_object).val();
    var remaining_obj = $("#"+ dom_object +"_chars_remaining");
    remaining = limit - text.length;
    remaining_obj.html(remaining +" characters remaining");
    if (remaining <= 0) {
        $('#'+ dom_object).val(text.substr(0, limit-1));
    }
    return true;
}

function character_limit(dom_object, limit) {
    // This method will inject a character limition on {dom_object} of length
    // {limit}. {dom_object} must just be a string containing the id of the 
    // object, we do the lookup here.
    var obj = $('#'+ dom_object);
    if (obj) {
        // Add notification text
        obj.parent().html(obj.parent().html() +"<br /><span id='"+ dom_object +"_chars_remaining'>"+ limit +" characters remaining</span>");
        update_chars_remaining(dom_object, limit);

        // Setup event handler
        $('#'+ dom_object).keyup(function() {
            update_chars_remaining(dom_object, limit);
        });
    }
}

function trim(str){
    return jQuery.trim(str);
}

function remove_double_quotes(str) {
    return (str.replace(/"/g, "'"));
}

function truncate_words(str, numwords){
    var words = trim(str).split(" ");
    var truncated_text = words[0];
    
    for (i = 1; i <= numwords; i++) {
        if (words[i] != undefined) {
            truncated_text += " " + words[i];
        }
    }
    
    return truncated_text + "...";
}

String.prototype.startsWith = function(str) {
    return (this.match("^"+str)==str)
}

String.prototype.endsWith = function(str) {
    return (this.match(str+"$")==str)
}

