var cc = function() {

var tests = {
  'aa':  { name: 'Dominio thepiratebay.org',
	   url:  'http://thepiratebay.org/ifpi/kopimi_link.png' },
  'ab':  { name: 'Dominio labaia.org',
	   url:  'http://labaia.org/ifpi/kopimi_link.png' },
  'ba':  { name: 'IP 83.140.33.40',
	   url:  'http://83.140.33.40/ifpi/kopimi_link.png' },
  'bb':  { name: 'Dominio www.partypoker.com',
	   url:  'http://www.partypoker.com/images/black_line.gif' },
  'ca':  { name: 'Dominio colombo-bt.org',
	   url:  'http://colombo-bt.org/Themes/endar-105/images/row.gif' },
  'cb':  { name: 'IP 87.236.194.90',
	   url:  'http://87.236.194.90/Themes/endar-105/images/row.gif' }
//  'bb':  { name: 'IP 10.0.176.200 (test)',
//	   url:  'http://10.0.176.200/ifpi/kopimi_link.png' }
};

var client_id;

// public methods
var pub = {};

pub.loaded = function(caller) {
  var element = $(caller);
  var name = element.attr('id').replace(/^cc_..._/, '');
  if (!tests[name]) return;
  tests[name].loaded = true;
}

// create an img tag and load the target URL in it
function load_test_img(name, url) {
  // this code is supposed to be equivalent, but does not work with Opera
  //$('#cc-zone').append('<img id="cc_img_' + name + '" src="' + url
  //    + '" onload="cc.loaded(this);">');
  var img = document.createElement('img');
  img.id = "cc_img_" + name;
  img.onload = function() { cc.loaded(this); };
  img.src = url;
  $('#cc-zone').append($(img));
}

function start_test() {
  // start the countdown
  $('#cc-countdown').countdown({
      seconds: 10,
      callback: 'cc.test_results();'
  });

  // this object is used to associate users with their caching DNS resolver
  load_test_img('clientid', 'http://' + client_id
      + '.test.censura.tophost.it/test.gif');

  // load each test object
  $.each(tests, function(key, value) {
    value.loaded = false;
    load_test_img(key, value.url);
  });
}

// this function is called at the end of the countdown
pub.test_results = function() {
  send_info();
  update_table();
  cache_results();
}

// save the results in a cookie
function cache_results() {
  var res = [];
  $.each(tests, function(key, test) {
    res.push(key + ':' + (test.loaded == 1 ? '1' : '0'));
  });
  $.cookie('cc_cache', '1 ' + res.join('|'), { expires: 1 });
}

function get_cached_results() {
  //return 'aa:1|ab:1|ba:1|bb:0'; //XXX
  var cookie = $.cookie('cc_cache');
  if (!cookie) return;

  var cached = cookie.split(' ');
  if (cached[0] != '1') return; // discard data saved by older versions
  return cached[1];
}

function display_cached(cached) {
  var s = cached.split('|');
  for (var i = 0; i < s.length; i++) {
    var x = s[i].split(':');
    tests[x[0]].loaded = x[1];
  }

  update_table();
}

function update_table() {
  var score = 0;
  var total = 0;
  $.each(tests, function(key, test) {
    var el = $('#cc-td-' + key);
    el.attr({ title: test.name });
    if (test.loaded == 1) {
      set_ok(el);
    } else {
      set_no(el);
      score++;
    }
    total++;
  });

  var text;
  var color;
       if (score == total) { text = 'CENSURA TOTALE';   color = 'red'; }
  else if (score >= 1)     { text = 'QUALCHE PROBLEMA'; color = '#FF6600'; }
  else                     { text = 'NIENTE CENSURA'; }

  $('#cc-countdown-text').html(text);
  if (color) {
    $('#cc-countdown-text').css('color', color);
  }

  // plugin...
  if (pub.test_results_extra) { pub.test_results_extra(tests) }
}

function send_info() {
  var results = {};
  $.each(tests, function(i, value) {
    results[value.url] = value.loaded;
  });
  var date = new Date();

  var send = {
    results: results,
    client_id: client_id,
    browser: navigator.userAgent,
    source: '' + window.location,
    tzoffset: date.getTimezoneOffset()/60
  };

  $.post('/cgi-bin/logger', $.toJSON(send));
}

function guid() {
  function S4() {
    return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
  }
  return (S4()+S4()+S4()+S4()+S4()+S4()+S4()+S4());
}

function set_ok(el) { el.addClass('cc-ok'); el.html('&#9786;'); }
function set_no(el) { el.addClass('cc-no'); el.html('&#9785;'); }

function create_results_table(container) {
  $('head').append('<style type="text/css">' +
'#cc-widget { width: 90px }' +
'#cc-widget table {' +
  'border: 0 none;' +
  'border-collapse: collapse;' +
  'text-align: center;' +
  'width: 100%;' +
'}' +
'#cc-widget th {' +
  'padding: 0; ' +
'}' +
'#cc-widget td {' +
  'border: 1px solid black;' +
  'background-color: yellow;' +
  'color: black;' +
  'padding: 0; ' +
  'font-size: 24pt;' +
  'font-family: Verdana, sans-serif;' +
//  'height: 45px;' +
//  'width: 44px;' +
  'width: 50%;' +
  'line-height: 100%;' +
'}' +
'#cc-widget td.cc-ok { background-color: #00FF44 }' +
'#cc-widget td.cc-no { background-color: red }' +
'#cc-widget #cc-head {' +
  'background-color: white;' +
  'border: 0;' +
  'font-size: 10pt;' +
  'font-family: Verdana, sans-serif;' +
  'font-weight: normal;' +
  'text-align: center;' +
'}' +
'#cc-widget #cc-head a { color: black; text-decoration: none; }' +
'#cc-widget #cc-head a:visited { color: black; text-decoration: none; }' +
'#cc-widget #cc-countdown-text {' +
  'background-color: white;' +
  'border: 0;' +
  'font-size: 10pt;' +
  'font-family: Verdana, sans-serif;' +
'}' +
'</style>');

  container.html(
'<table>' +
'<thead>' +
'<tr><th colspan="2" id="cc-head">' +
'<a href="http://censura.tophost.it/">MISURA LA CENSURA!</a>' +
'</th></tr>' +
'</thead>' +
'<tbody>' +
'<tr><td id="cc-td-aa">?</td><td id="cc-td-ab">?</td></tr>' +
'<tr><td id="cc-td-ba">?</td><td id="cc-td-bb">?</td></tr>' +
'<tr><td id="cc-td-ca">?</td><td id="cc-td-cb">?</td></tr>' +
'</tbody>' +
'<tfoot>' +
'<tr><td colspan="2" id="cc-countdown-text">' +
'Test in corso... <span id="cc-countdown"></span>' +
'</td></tr>' +
'</tfoot>' +
'</table>'
);

  container.click(function() { location.href = $('#cc-head a').attr('href') });
  container.mouseover(function() { $(this).css({cursor: 'pointer'}) });
}


// after the page has been fully loaded, add an invisible span element
// which will contain the test images
$(window).load(function() {
  $('body').append('<span id="cc-zone" style="display:none"></span>');

  // set a cookie to track the user among different tests
  client_id = $.cookie('cc_guid');
  if (!client_id) {
    client_id = guid();
  }
  $.cookie('cc_guid', client_id, { expires: 90 });

  var cached_status = get_cached_results();
  if (cached_status) {
    display_cached(cached_status);
  } else {
    start_test();
  }
});

pub.init = function() {
  var container = $('#cc-widget');
  if (container.length == 0) {
    document.write('<div id="cc-widget"></div>');
    container = $('#cc-widget');
  }
  create_results_table(container);
}

return pub;
}();

cc.init();

// vim: sw=2
cc.test_results_extra = function(tests) {
  var list = $('#cc-results');
  if (!list) return;

  $.each(tests, function(key, test) {
    var markup = '<li>' + test.name + ': ' + (test.loaded == 1 ?
        '<span class="ok">ACCESSIBILE</span>' :
        '<span class="no">CENSURATO</span>'
      ) + '</li>';
    list.append(markup);
  });

  list.show();
}

// vim: sw=2

