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

var color_slider;
var IMAGES_PER_PAGE = 50;

// Draw loading image in Color tab (in place of color wheel)
function start_color_loading() {
    $("#colors_message").html("<img src=\"/images/ajax-loader.gif\" /> <strong>Loading</strong>");
}

// Stop loading search by displaying search colors
function stop_color_loading() {
    $("#colors_message").html("<strong>Your search colours</strong>");
    color_slider.swap_message();
}

// Add a colour to the list of colours in the query
function add_color(color) {
    color_slider.add(color);
}

// Show image tile
function show_images(images) {
    var num_images = 0;
    var images_block = $("#result_images");
    images_block.empty();
    if(images.length) {
        dimensions = tile(images, 790, 380);
        var resulthtml = "";
        var num_images = 0;
        $.each(images, function(key, value) {
            var image_html = '<a href="' + value.photosite + '"><img src="http://img.tineye.com/flickr-images/?filepath=labs-flickr/' + value.filepath;
            image_html += '&size=' + Math.round(value.width) + '" width="' + Math.round(value.width) + '" height="' + Math.round(value.height);
            image_html += '" style="position: absolute; width: ' + Math.round(value.width) + 'px; height: ' + Math.round(value.height)
            image_html += 'px; left:' + Math.round(value.x) + 'px; top:' + Math.round(value.y) + 'px;" /></a>\n'
            images_block.append($(image_html));
            num_images++;
        });
    }

    // fill remaining area with spacers
    for (; num_images < 50; num_images++) {
        var new_filler = $("<img class=\"filler\" src=\"/images/result-filler.png\">");
        images_block.append(new_filler);
    }

    $("#colors_message").html("<strong>Your search colours</strong>");
    color_slider.swap_message();
}

// Perform operations based on the information provided in the address bar
function process_hash() {
    params = decode_hash(window.location.hash);

    var colors = new Array();
    var weights = new Array();

    // If there were specified paramaters, then we need to make sure that
    // it is valid
    if (defined(params['colors'])) {

        // Split and keep number of colours within specified number
        colors = params['colors'].split(',');
        colors = colors.slice(0, ColorQuery.MAX_SEARCH_COLORS);

        var error_values = [];

        // Check if the colours hex provided are correct
        for(var i = colors.length - 1; i >= 0; i--) {
            if(!check_hex_color(colors[i]) && colors[i] != 'wildcard') {
                error_values.push(colors[i]);
                colors.splice(i, 1);
            }
        }

        // Split weightss if they exist
        if(defined(params['weights'])) {
            weights = params['weights'].split(',');
        }

        // Check if the weightss provided are correct
        for(var i = 0; i < weights.length; i++) {
            if(!check_percentage(weights[i])) {
                error_values.push(weights[i]);
                weights[i] = 20;
            }
        }

        // Check number of weightss
        if(weights.length > colors.length) {
            weights = weights.slice(0, colors.length);
        } else if(weights.length < colors.length) {
            for(var i = weights.length; i < colors.length; i++) {
                weights.push(20);
            }
        }

        // Display errors if there were any
        if(error_values.length)
            handle_error(generate_error_msg(error_values));

    }

    color_slider = new ColorSlider(ColorQuery.MAX_SEARCH_COLORS, colors, weights);

    show_images(new Array(), [790, 390]);           // fake empty results
    if(colors.length)
        submit_query();
}

// Format an error message depending on the number of erroneous values
function generate_error_msg(error_values) {

    if(error_values.length == 0)
        return "";
    else if(error_values.length == 1)
        return "The value " + error_values[0] + " is not valid.";
    else {
        var error_msg = "The values ";
        for(var i = 0; i < error_values.length - 1; i++)
            error_msg += error_values[i] + ", ";
        error_msg += " and " + error_values[error_values.length - 1] + " are not valid.";
        return error_msg;
    }
}

// Submit color query and update address bar
function submit_query() {
    params = decode_hash(window.location.hash);
    params['colors'] = color_slider.get_colors();
    params['weights'] = color_slider.get_weights();
    if (defined(params['colors'])) {
        params['quantity'] = IMAGES_PER_PAGE;
        ColorQuery.search(params);
        start_color_loading();
    }
}

/* (Requires jQuery) *

/* ColorSlider sits on top of the (heavily modified) jQuery slider and adds 
 * extra functionality on the slider like the color refining and removing colors.
 */

function ColorSlider(max_num_colors, color, weights) {
    this.num_colors = max_num_colors;
    this.color_div = [];
    this.color = color;
    this.weights = weights;
    this.pickers = [];
    this.init(color, weights);
    this.draw();
}

// Draws the elements required by the slider
ColorSlider.prototype.draw = function() {
    this.augment_ranges();
    this.draw_pickers();
}

// Draw the divs for the colours
ColorSlider.prototype.augment_ranges = function() {

    var slider_div = $('<div id="slider" class="ui-slider"></div>');

    // Set up colour div
    for(var i = 0; i < this.num_colors; i++) {
        var item = $('<div class="ui-slider-handle"></div>');
        slider_div.append(item);
    }

    $("#slider_colors").html(slider_div);

    $("#slider").slider({axis:"vertical", range:true, max:100, color: this.color, weights: this.weights});
    var slider = $("#slider");


    // Mouse over function - show remove and refine icons
    function show_functions(index) {
        if($("#slider").slider("getColor")[index] != 'wildcard')
	    $("#slider_refine_" + index).show();
        $("#slider_remove_" + index).show();
    }

    // Mouse out function - hide remove and refine icons
    function hide_functions(index) {
        $("#slider_refine_" + index).hide();
        $("#slider_remove_" + index).hide();
    }

    for(var i = 0; i < this.num_colors + 1; i++) {
    
        // Add the remove and refine icons to the ranges
        $(".ui-slider-range:eq(" + i + ")").remove("slider_remove_" + i);
        $(".ui-slider-range:eq(" + i + ")").remove("slider_refine_" + i);
        this.color_div[i] = $(".ui-slider-range:eq(" + i + ")");
        this.color_div[i].prepend(
                     "<img id=\"slider_remove_" + i + "\" src=\"/images/delete.png\" class=\"remove_icon\" title=\"Remove this colour\" width=\"50\" height=\"20\" />" +
                     "<img id=\"slider_refine_" + i + "\" src=\"/images/refine.png\" class=\"refine_icon\" title=\"Refine this color\" width=\"50\" height=\"20\" >"
        );

        // Bind events to elements
        this.color_div[i].bind("mouseover", {index: i}, function(event) { show_functions(event.data.index); });
        this.color_div[i].bind("mouseout", {index: i}, function(event) { hide_functions(event.data.index); });

        // Bind event to remove icon
        $("#slider_remove_" + i).bind("click", {index: i, slider: this}, function(event) { var d = event.data; d.slider.remove(d.index); });

        // Bind event to refine icon
        $("#slider_refine_" + i).bind("click", {index: i, slider: this}, function(event) { var d = event.data; d.slider.show_picker(event, event.data.index); d.slider.refine_color(d.index);});

        // Hide them
        hide_functions(i);

    }

    // Remove all events and rebind click event to wildcard div
    $("#wildcard").unbind("click");
    $("#wildcard").bind("click", {slider: this}, function(event) { event.data.slider.add('wildcard'); } );
    this.swap_message();
}

// Renders the YUI colour pickers
ColorSlider.prototype.draw_pickers = function() {

    var target = $("#slider_pickers");
    target.html("");

    // HTML required for the pickers, so we can modify their appearance
    for(var i = 0; i <= this.num_colors; i++) {
        var p = '<div id="picker_dialog_' + i + '" class="picker_dialog">' +
                '<div id="picker_' + i + '"></div><div align="center"><input type="text" id="color_' + i + '" name="color" value="#123456" /></div></div>';
        target.append(p);
    }

    // Submit function
    var handleSubmit = function(e) {
        //submit the Dialog
        $("#slider").slider("changeColor", this.index, $('#color_' + this.index).val().substring(1));
        this.hide();
        submit_query();
    }

    // Cancel function
    var handleCancel = function() {
        this.cancel();
    }

    for(var i = 0; i <= this.num_colors; i++) {

        // Instantiate the colour picker dialog
        this.pickers[i] = new YAHOO.widget.Dialog("picker_dialog_" + i,
                                            { fixedcenter : false, visible : false, draggable: false,
                                              constraintoviewport : true, zindex: 1000, width: "200px", height: "245px", modal: true,
                                              buttons : [ { text:"Submit", handler:handleSubmit, isDefault:true },
                                                          { text:"Cancel", handler:handleCancel} ]
        });
        // Add some extra information to the dialogs, so we can access them
        YAHOO.lang.augmentObject(this.pickers[i], { index: i, slider: this });

        // Once the Dialog renders, we want to create our Color Picker instance.
        this.pickers[i].renderEvent.subscribe(function() {
            if (!this.picker) { //make sure that we haven't already created our Color Picker
                this.picker = $('#picker_' + i).farbtastic('#color_' + i);
            }
        });

        this.pickers[i].render();
    }
}

// Initialize the slider with colours and normalized percentages
ColorSlider.prototype.init = function(colors, percent) {
    this.percent = normalize_percentages(percent);
}

// Normalizes percentages (we don't want the values to
// add up to over 100%.
function normalize_percentages(values) {
    var sum = 0;
    var n_values = [];
    for(var i in values)
        sum += parseInt(values[i]);
    if(sum > 100) {
        for(var i = 0; i < values.length; i++)
            n_values[i] = Math.round((values[i] / sum) * 100);
    }
    else n_values = values;
    return n_values;
}

// Add colour to slider
ColorSlider.prototype.add = function(color) {
    $("#slider").slider("addColor", color);
    this.swap_message();
    submit_query();
}

// Remove colour from slider
ColorSlider.prototype.remove = function(index) {
    $("#slider").slider("removeColor", index);
    this.swap_message();
    if (this.get_colors().length)
        submit_query();
    else {
        // Removing the last colour, setting off the hash and clear pagination
        window.location.hash = '#';
        process_hash();
        $('#pages').empty();
    }

}

ColorSlider.prototype.get_colors = function() {
    return $("#slider").slider("getColor");
}

ColorSlider.prototype.get_weights = function() {
    return $("#slider").slider("getRatio");
}

// Toggle info message depending on whether there are colors to show
ColorSlider.prototype.swap_message = function() {
    var message = $("#colors_message");
    if (!this.get_colors().length) {
        message.html("<img src=\"/images/selectsomecolours.png\" width=\"160\" height=\"169\" />");
        $("#slider_colors").hide();
    } else {
        message.html("<strong>Your search colours</strong>");
        $("#slider_colors").show();
    }
}

// Show colour picker where user clicked
ColorSlider.prototype.show_picker = function(e, index) {
    var coords = get_coords(e, 'absolute');
    this.pickers[index].moveTo(coords[0], coords[1]);
    this.pickers[index].show();
}

function RGBToHex(value) {
    var re = /\d+/g;
    var matches = value.match(re);
    var r = parseInt(matches[0]);
    var g = parseInt(matches[1]);
    var b = parseInt(matches[2]);
    return "#" + r.toString(16) + g.toString(16) + b.toString(16);
}

// Refine color
ColorSlider.prototype.refine_color = function(index) {
    var color = $(".ui-slider-range:eq(" + index + ")").css('background-color');
    // For browsers that get non hex values for the background colour
    if(color.substring(0, 3) == 'rgb')
        color = RGBToHex(color)
    $.farbtastic('#picker_' + index).setColor(color);
}

