jQuery.fn.linqia_countries_by_continent_widget = function(options) {
  var countries_by_continent = options.countries_by_continent;
  var countries_peer_select = options.countries_peer_select;
  var countries_select = options.countries_select;

  var continent_all = jQuery(this).find('#continent_all:first');
  var continents = jQuery(this).find('.continent');

  jQuery(this).click(function(e) {
    if ($(e.target).attr('id') == 'continent_all') {
      $.each(continents, function() { $(this).attr('checked', $(e.target).attr('checked')); });
    }
    else if ($(e.target).hasClass('continent')) {
      var continent_checked = jQuery.map(continents, function(el) { return $(el).attr('checked'); });
      continent_all.attr('checked', (jQuery.inArray(false, continent_checked) == -1));
    }

    // update available countries list
    var selected_continent_keys = $.map($('.continent:checked'), function(el) { return $(el).val(); })
    var selected_countries = [];
    $.each(selected_continent_keys, function() {
      $.merge(selected_countries, countries_by_continent[this]);
    });

    // sort by name and build HTML <option> tags
    selected_countries_options = $.map(selected_countries.sort(function(a,b) { return a[1] > b[1]; }), function(el) { return '<option value="'+el[0]+'">'+el[1]+'</option>'; });

    countries_peer_select.html(selected_countries_options.join(''));
    countries_select.html('');
  });

  return jQuery(this);
}
