/* (Requires jQuery, base.js, search.js) *

/* ColorQuery performs live colour searches via the color.search
 * Espion API method. Each search is handled as a request to a 
 * remote EspionServer instance, which executes the query against
 * a preindexed set of images.
 */
function ColorQuery(colors, weights) {
    this.colors = colors;       // colors in hex format (rrggbb, without leading #)
    this.weights = weights;
    this.page = 0;              // Current page number (int, starting from 0)
    this.total_pages = 50;      // Initial guess at the number of pages (int)
    this.has_more = true;       // Are there remaining pages? (bool)
    QueryHistory.add(this);     // add to global history
}

ColorQuery.prototype = new Query;
ColorQuery.MAX_SEARCH_COLORS = 5;

ColorQuery.search = function(params) {
    var cq = new ColorQuery();
    cq.set(params);
    cq.load();
}

ColorQuery.prototype.set = function(params) {
    if(!defined(params)) return;
    if(defined(params['quantity'])) this.quantity = params['quantity'];
    if(defined(params['colors'])) this.colors = params['colors'];
    else this.colors = [];
    if(defined(params['weights'])) this.weights = params['weights'];
    else this.weights = [];
    set_hash(this.to_hash());
}

ColorQuery.prototype.load = function() {
    var self = this;
    var data = {method: 'flickr_color_search', limit: this.quantity + 10, offset: this.page * this.quantity};
    this.weights = this.normalize_weights();
    for(var i in this.colors)
        data['colors[' + i + ']'] = this.colors[i];
    for(var i in this.weights)
        data['weights[' + i + ']'] = this.weights[i];
    getJSON(self, "/rest/", data);
}

ColorQuery.prototype.normalize_weights = function() {
    var new_weights = [];
    var s = 0;
    for(var i in this.weights)
        s += this.weights[i];
    for(var i in this.weights)
        new_weights[i] = this.weights[i] / s;
    return new_weights
}

ColorQuery.prototype.handle_response = function(response) {

    if(response['status'] != 'ok') {
        handle_error(response['error'].join(', '));
        stop_color_loading();
        return;
    } 

    // Did we get any results back?
    if(this.page > 0 && response['result'].length == 0) {
        // We hit a dead end. Revert to the previous page.
        this.page--;
        this.total_pages = this.page;
        this.load();
        return;
    }

    if(response['result'].length <= this.quantity)
        this.has_more = false;
    else
        this.has_more = true;

    this.draw(response);
}

ColorQuery.prototype.draw = function(response) {
    show_images(response['result']);
    show_pagination(response);
}

ColorQuery.prototype.to_hash = function() {
    return encode_hash({colors: this.colors, weights: this.weights});
}

