/*
*	Sorter
*	Provides AJAX-based sorting and pagination functionality
*	
*	Requires Trapeze jQuery distribution
*	
*	Taylan Pince (tpince at trapeze dot com) - February 26, 2009
*/

$.namespace("trapeze.Sorter");

trapeze.Sorter = $.Class.extend({
    
    selector : "",
    sort_key : "sort-by",
    order_key : "order",
    page_key : "page",
    unique_type : null,
    
    update_pagination_event : function(evt) {
        this.update_sorter($(evt.target).attr("href"), true);
        
        return false;
    },
    
    update_sorter_event : function(evt) {
        this.update_sorter($(evt.target).attr("href"));
        
        return false;
    },
    
    update_sorter : function(url, paginate) {
        var params = trapeze.parse_query(url);
        
        if (this.unique_type) {
            params["type"] = this.unique_type;
        } else if ("type" in params) {
            params["type"] = "";
        }

        $(this.selector).addClass("stand-by").load(
            trapeze.build_url(url, params),
            {},
            this.parse_content.bind(this)
        );

        if (!(this.order_key in params)) {
            params[this.order_key] = "";
        }
        
        if (this.page_key in params && paginate != true) {
            params[this.page_key] = "";
        }

        trapeze.update_query(params);
    },
    
    parse_content : function() {
        $(this.selector).removeClass("stand-by");
        
        trapeze.init_markers(this.selector);
    },
    
    init : function(selector, options) {
        this.selector = selector;
        
        if (options) {
            if (options.unique_type) {
                this.sort_key = options.unique_type + "-" + this.sort_key;
                this.order_key = options.unique_type + "-" + this.order_key;
                this.page_key = options.unique_type + "-" + this.page_key;
                
                this.unique_type = options.unique_type;
            }
        }
        
        $(this.selector).find("ul.sorting").find("a").live("click", this.update_sorter_event.bind(this));
        $(this.selector).find("p.pagination").find("a").live("click", this.update_pagination_event.bind(this));
        
        var url = window.location.toString();
        var params = trapeze.parse_query(url);

        if (this.sort_key in params || this.page_key in params) {
            if (url.indexOf("?") > -1) {
                window.location.href = url.replace("?", "#");
            } else {
                this.update_sorter(url.replace("#", "?"), (this.page_key in params));
            }
        }
    }
    
});
