mp.report.advanced = {};
mp.report.advanced.click_handlers = function() {
    
    mp.report.advanced.hide_flag = null;
    $("#advanced").blur(function(event) {
        mp.report.advanced.hide_flag = setTimeout(function() {
           $("#advanced").hide();
        }, 250);
        event.stopPropagation();
    });

    $("#adv_button").mousedown(function() {
        clearTimeout(mp.report.advanced.hide_flag);
		if ($("#advanced").is(':visible')) {
			$("#advanced").blur();
			$("#advanced").hide();
		} else {
			$("#advanced").show();
			setTimeout(function() {
				$("#advanced").focus();
			}, 100);

		}
			
    });

    $('.custom-element.event_name').live('click', function() {
        var check = $(this).siblings(':checkbox');
        if (check.is(':checked')) {
            check.attr('checked', false);
        } else {
            check.attr('checked', true);
        }
    });

    $('.custom-element.tofocus').live('click', function() {
        $("#advanced").focus();
    });
    
    $('.custom-element').live('mousedown', function() {
        // Prevent loss of focus when clicking checkboxes, buttons
        setTimeout(function() {
            clearTimeout(mp.report.advanced.hide_flag);
        }, 40);
    });

    $("#check_all_button").click(function() {
        $(".custom-box").each(function() {
            this.checked = true;
        });
    });

    $("#show_custom_button").click(function() {
        var selected = [];
        $("#advanced .custom-box:checked").each(function() {
            selected.push($(this).val());
        });
        // Here we need to handle the selected events, and the type they are.
        // If properties, save as value array
        // If events, update the global event param
        var maps = {
            "#events": mp.report.globals.wrappers.event.adv_map,
            "#events/properties": mp.report.globals.wrappers.property.values,
            "#events/geo": mp.report.globals.wrappers.maps.values
        };
        
        var map = function(arr, obj) {
            var result = [];
            for (var i in arr) {
                if (arr.hasOwnProperty(i)) {
                    result.push(obj[arr[i]]);
                }
            }
            return result;
        };
        
        if (selected.length > 0) {
            var request = mp.report.globals.nav.getURLRequest();
            if (request.path == "#events") {
                mp.report.globals.nav.updateURL(request.path, { event: map(selected, maps[request.path])});
            } else if (request.path == "#events/properties") {
                mp.report.globals.nav.updateURL(request.path, { values: map(selected, maps[request.path])});
            } else if (request.path == "#events/geo") {
                mp.report.globals.nav.updateURL(request.path, { values: map(selected, maps[request.path])});
            }
            $("#advanced").blur();
        }
    });

    $("#clear_custom_button").click(function() {
        $(".custom-box:checked").each(function() {
            this.checked = false;
        }) ;
    });
};
mp.report.advanced.fill_advanced = function(data) {
    // Fill advanced using a dictionary like 
    // { 'event1': 'My event name', 'event2': 'other event name' }
    function average_length(strings, buffer) {
        //buffer is a dec. from 0-1 (or bigger, i guess) for the amount of padding to add
        var total = 0, longest = 0, num = 0;
        for (var s in strings) {
            if (s) {
                num++;
                total += strings[s].length;
                if (strings[s].length > longest) {
                    longest = strings[s].length;
                }
            }
        }
        if (num === 0) { num = 1; }
        // Weight the longest string into the result
        return parseInt((longest + 2 * (total / num)) / 3 * (1 + buffer), 10); 
    }
    // Fill in advanced property menu
    var html = '', char_width_px = 8.5;
    var length = average_length(data, 0.15);
    var width = length * char_width_px;

    // XXX: Issue if we change the width of advanced.
    // Handle various widths for cells
    var min = 165; // Divides into thirds
    var mid = 247; // Divides into halves
    var max = 500; // Full width
    var buffer = 1.3;
    if (width < min) {
        width = min;
    } else if (width > min && width < mid * buffer) {
        width = mid;
    } else if (width > mid * buffer) {
        width = max;
    }
    length = width / char_width_px;
    
    var sorted_events = [];
    for (var d in data) {
        if (data.hasOwnProperty(d)) {
            var clean = mp.utility.sanitize(data[d]);
            sorted_events.push([clean, d]);
        }
    }
    
    // Sort in alphabetical order
    sorted_events.sort(function(a, b) { 
			var A = a[0].toLowerCase(),
				B = b[0].toLowerCase(); 
			if (A < B) { 
				return -1;
			} else if (A > B) {
				return 1;
			} else {
				return 0;
			}		
		});
    for (var e in sorted_events) {
        if (sorted_events.hasOwnProperty(e)) {
            var ev_clean = sorted_events[e];
            html += "<div class='checkbox-cell' style='width: " + width + 
                    "px;'><input type='checkbox' class='custom-box custom-element tofocus' value='" + 
                    ev_clean[1] + "' /><span class='custom-element event_name' title='" + ev_clean[0] + "' >" + mp.utility.shorten_string(ev_clean[0], length) + "</span></div>";
        }
    }
    $('#advanced #checkboxes').html(html);
};


