$(function () {
  $tw = $('#tw span');
  $.getJSON('tw.php?' + Math.random(), function (data) {
    tw_items = data;
    $tw.html(tw_items.shift());
    $tw.fadeIn();
    setInterval(function () {
      $tw.fadeOut(function () {
        $tw.html(tw_items.shift());
        $tw.fadeIn();
        if (tw_items.length == 5) {
          $.getJSON('tw.php?' + Math.random(), function (data) {
            tw_items = tw_items.concat(data);
          });
        }
      });
    }, 5000);
  });
  $('body').click(function () {
    $('#img').fadeOut();
  });
  $loading = $('#loading');
  $map = $('#map');
  $("a[href='#']").attr('href', 'javascript:void(0)');
  /*
  $map.mousemove(function (e) {
    var offset = $(this).offset();
    var x = e.pageX - offset.left;
    var y = e.pageY - offset.top;
    document.title = 'x = ' + x + ', y = ' + y;
  });
  */
  $map.click(function (e) {
    var offset = $(this).offset();
    var x = e.pageX - offset.left;
    var y = e.pageY - offset.top;
    $loading.show();
    $.getJSON('query.php?x=' + x + '&y=' + y, function(data) {
      var $msgs = $('#msgs');
      var $imgs = $('#imgs');
      $msgs.empty(); $imgs.empty();
      if (data.length == 0) {
        //refreshMap();
        $loading.hide();
        return;
      }
      for (var i in data) {
        var item = data[i];
        $msgs.append('<div id="msgs_' + item.id + '" class="msg">' +
                     '<div class="caption">' + item.time +
                     ' | ' + item.name + '</div>' +
                     item.message + '</div>');
        for (var j in item.imgs) {
          var img = item.imgs[j];
          $imgs.append('<div id="img_' + img +
                       '" class="photo"><img src="uploads/' +
                       img + '_thumb.jpg" alt="" /></div>');
          $('#img_' + img).click(function (uid, name, country) {
            return function () {
              $('#img').fadeOut(function () {
                $('#img img').attr('src', 'uploads/' + uid + '.jpg');
                $('#img_info').html('By ' + name + (country ?
                  ' @ <img src="flags/' + country + '.png" alt="' + country + '" />' :
                  ''));
              });
              return false;
            };
          }(img, item.name, item.country));
        }
      }
      $('#img').hide();
      $('#donate').hide();
      $map.fadeOut(function () {
        $loading.hide();
        $('#see').fadeIn();
      });
    });
  });
  $('#link_back').click(function () {
    $('#see').fadeOut(function () {
      //refreshMap();
      $map.fadeIn();
      $('#donate').show();
    });
  });
  $('#img img').load(function () {
    var $img = $('#img');
    $img.css('margin-left', -$img.width() / 2 + 'px');
    $img.css('margin-top', -$img.height() / 2 + 'px');
    $img.fadeIn();
  });
  $('#link_upload').click(function () {
    if ($('#new').is(':visible')) {
      $('#new').fadeOut(function () {
        //refreshMap();
        $map.fadeIn();
        $('#donate').show();
      });
      return;
    }
    if ($loading.is(':visible'))
      return;
    hideOther(function () {
      $('#link_clear').click();
      $('#photo_uploaderUploader').remove();
      $('#photo_uploader').replaceWith('<div id="photo_uploader"></div>');
      $('#photo_chosen').empty();
      $('#new').fadeIn(function () {
        if ($.browser.msie && $.browser.version == '6.0') {
          $('#new_iefix').css('filter',
            'progid:DXImageTransform.Microsoft.AlphaImageLoader(src=style/new.png)');
        }
        $('#photo_uploader').uploadify({
          'uploader': 'scripts/uploadify.swf',
          /*'script': 'upload.php',*/
          'cancelImg': 'style/cancel.png',
          'multi': true,
          'fileDataName': 'image',
          'fileExt': '*.jpg;*.jpeg;*.JPG;*.JPEG',
          'fileDesc': 'JPEG file (*.jpg, *.jpeg)',
          'buttonImg': 'style/uploader.gif',
          'width': 141,
          'height': 43,
          'wmode': 'transparent',
          'onSelect': function (e, q, f) {
            if (f.size > 2097152) {
              alert('Sorry, you could not upload a image larger than 2MB...');
              return false;
            }
            return true;
          },
          /*
          'onComplete': function (e, q, f, r, d) {
            alert(r);
          },
          */
          'onAllComplete': function () {
            $('#new').fadeOut(function () {
              $loading.hide();
              refreshMap();
            });
          },
          'queueID': 'photo_chosen'
        });
      });
    });
  });
  $('#link_clear').click(function () {
    $('#name').val('');
    $('#msg').val('');
    try {
      $('#photo_uploader').uploadifyClearQueue();
    } catch (e) {}
  });
  $('#link_submit').click(function () {
    if ($loading.is(':visible'))
      return;
    var name = $('#name').val();
    var msg = $('#msg').val();
    if (! $.trim(msg)) {
      alert('Please leave some words for Haiti.');
      return;
    }
    if (! $.trim(name))
      name = 'Anonymous';
    $loading.show();
    $.post('submit.php', {
      'name': name,
      'msg': msg
    }, function (sid) {
      try {
        if (! $.trim($('#photo_chosen').html()))
          throw "No Picture";
        $('#photo_uploader').uploadifySettings('script', 'upload.php?' + sid);
        $('#photo_uploader').uploadifyUpload();
      } catch (e) {
        $('#new').fadeOut(function () {
          $loading.hide();
          $('#map').fadeIn();
          //refreshMap();
        });
      }
    });
  });
  refreshMap();
  setInterval(refreshMap, 300000);
});

function refreshMap() {
  if ($map.is(':visible')) {
    $map.fadeOut(refreshMap);
  } else {
    $loading.show();
    $map.one('load', function () {
      $map.fadeIn(function () {
        $loading.hide();
      });
      $('#donate').show();
    });
    $map.attr('src', 'map.jpg?' + Math.random());
    $.getJSON('count.php', function (data) {
      $('#visitcount').text(data[0]);
      $('#msgcount').text(data[1]);
    });
  }
}

function hideOther(func) {
  var $old;
  if ($map.is(':visible')) {
    $old = $map;
    $('#donate').hide();
  } else if ($('#see').is(':visible')) {
    $old = $('#see');
  } else if ($('#new').is(':visible')) {
    $old = $('#new');
  }
  if ($old) {
    $old.fadeOut(func);
  } else {
    func();
  }
}
