var globe_x = 0;
var map_width = 707;
var globe_radius = 231;
var test_diff = 20;
var test_radius = globe_radius - test_diff;
var globe_holder_x;
var spin = true;
var increment = .2;

var markers = [
  {x:376, y:158, href:'/med'},//albania 
  {x:209, y:338, href:'/ar'},//argentina
  {x:522, y:197, href:'/bd'},//bangladesh
  {x:388, y:124, href:'/cee'},//belarus
  {x:372, y:149, href:'/bar'},//bosnia 
  {x:387, y:154, href:'/cee'},//bulgaria
  {x:194, y:329, href:'/cl'},//chile
  {x:542, y:165, href:'http://www.genyuya.org.cn/cn/proshow.php?tag=2&tpid=27&tid=77'},//china
  {x:160, y:230, href:'/cr'},//costa rica
  {x:367, y:149, href:'/bar'},//croatia
  {x:402, y:173, href:'/med'},//cyprus
  {x:354, y:118, href:'/dk'},//denmark
  {x:395, y:194, href:'/med'},//egypt
  {x:383, y:109, href:'/cee'},//estonia
  {x:384, y:94, href:'http://www.1010finland.fi'},//finland
  {x:342, y:145, href:'http://www.1010.fr'},//france
  {x:357, y:132, href:'/de'},//germany
  {x:379, y:161, href:'/med'},//greece
  {x:380, y:143, href:'/hu'},//hungary
  {x:407, y:182, href:'/med'},//israel
  {x:363, y:156, href:'/it'},//italy
  {x:381, y:117, href:'/cee'},//latvia
  {x:379, y:121, href:'/cee'},//lithuania
  {x:379, y:157, href:'/bar'},//macedonia 
  {x:366, y:173, href:'/med'},//malta
  {x:129, y:197, href:'/mx'},//mexico
  {x:390, y:141, href:'/cee'},//moldova 
  {x:374, y:155, href:'/bar'},//montenegro
  {x:348, y:129, href:'/nl'},//netherlands
  {x:671, y:382, href:'/nz'},//new zealand
  {x:373, y:128, href:'/cee'},//poland
  {x:322, y:164, href:'/pt'},//portugal
  {x:385, y:146, href:'/cee'},//romania
  {x:501, y:79 , href:'/ru'},//russia
  {x:378, y:151, href:'/bar'},//serbia
  {x:374, y:139, href:'/cee'},//slovakia
  {x:366, y:145, href:'/bar'},//slovenia 
  {x:330, y:161, href:'/es'},//spain
  {x:405, y:162, href:'/med'},//turkey
  {x:333, y:128, href:'/uk'},//uk
  {x:396, y:135, href:'/cee'}//ukraine
];

$(
  function(){
    if(jQuery.browser.msie && parseInt(jQuery.browser.version, 10) < 8){
      $("#container").css("marginTop", "50px");
    }

    // $("#about_us").click(function(){
    //   $("img", $(this)).fadeOut();
    //   $("ul", $(this)).fadeIn();
    // });
    // 
    // $("#about_us").bind('mouseleave', function(){
    //   $("img", $(this)).fadeIn();
    //   $("ul", $(this)).fadeOut();
    // });

    setupGlobe();
    setupNews();
    //setupTwitter();
  }
);

var news_index = 0;
function setupNews(){
  setInterval("nextNews();", 8000);
}

function nextNews(){
  $("#news_feed li").eq(news_index).fadeOut(300);
  news_index++;
  if(news_index == $("#news_feed li").length) news_index = 0;
  $("#news_feed li").eq(news_index).animate({"opacity":1},310,"linear", function(){$(this).fadeIn(300);});
}

var tweet_index = 0;
function setupTwitter(){
  var now = new Date(); 
  var hb = now.getTime();
  var term = '#1010';
  var url = 'http://search.twitter.com/search.json?q='+escape(term)+'&rpp=25&callback=twitterCallback&_='+hb;
  var sc = document.createElement('script');
  sc.setAttribute('src',url);
  document.body.appendChild(sc);
}

function twitterCallback(data){
  for(i in data.results){
    var text = data.results[i].text;
    text = text.replace(/http:\/\/(\S+)/g,'<span class="link"><a target=_blank href="http://$1">http://$1</a></span>');
    text = text.replace(/#(\w+)/g,'<span class="hash"><a target=_blank href="http://twitter.com/search?q=%23$1">#$1</a></span>');
    text = text.replace(/@(\w+)/g,'<span class="user"><a target=_blank href="http://twitter.com/$1">@$1</a></span>');
     
    var img = "<img src='" + data.results[i].profile_image_url + "'/>";
    var from = "<span class='user'><a target='_blank' href='http://twitter.com/" + data.results[i].from_user + "'>" + data.results[i].from_user + "</a>: </span>";
    
    $('#twitter_feed ul').append($('<li>' + from + img + text + '</li>'));
  }
  $('#twitter_feed ul li').hide().eq(0).show();
  setInterval("nextTweet();", 8000);
}

function nextTweet(){
  $("#twitter_feed li").eq(tweet_index).fadeOut(300);
  tweet_index++;
  if(tweet_index == $("#twitter_feed li").length) tweet_index = 0;
  $("#twitter_feed li").eq(tweet_index).animate({"opacity":1},310,"linear", function(){$(this).fadeIn(300);});
}

function setupGlobe(){
  setInterval("moveGlobe()", 30);
  $('#globe_holder').bind('dragstart', function(e){ return false; })  
  $('#globe_holder').bind('mousedown', function(e){startDrag(e);})  
  $('#globe_holder img').bind('mousedown', function(e){e.preventDefault();}) 
  $('#globe_holder').bind('mouseup', function(e){stopDrag(e);})
  $(document).bind('mouseup', function(e){stopDrag(e);});
  globe_holder_x = $('#globe_holder').position().left;

  var clusters = {};
  for(i = 0; i < markers.length; i++){
    if(markers[i].href == '/global/countries/comingsoon') continue;
    if(!clusters[markers[i].href]){
      clusters[markers[i].href] = [];
    }
    clusters[markers[i].href].push(markers[i]);
  }
  
  for(href in clusters){
    var x_tot = 0; var y_tot = 0;
    for(j = 0; j< clusters[href].length; j++){
      x_tot += clusters[href][j].x; y_tot += clusters[href][j].y;
    }
    
    var x_ave = Math.floor(x_tot/clusters[href].length);
    var y_ave = Math.floor(y_tot/clusters[href].length);
    $('#marker_map').append("<a class='marker marker_cluster' style='left:" + x_ave + "px;top:" + y_ave + "px;z-index:" + y_ave + "' href='" + href + "'></a>");
  }
  
  for(i = 0; i < markers.length; i++){
    var m_class = markers[i].href == "/global/countries/comingsoon" ? ' marker_coming_soon' : ' marker_country';
    $('#marker_map').append("<a id='m" + i + "' class='marker" + m_class + "' style='visibility:hidden;left:" + markers[i].x + "px;top:" + markers[i].y + "px;' href='" + markers[i].href + "'></a>");
  }

  $(".marker_cluster").bind("mouseover", function(){showMarker(this);})
              .bind("mouseleave", function(){hideMarker(this);})
              .bind("click", function(){clickMarker(this);});
  if ($.browser.msie && parseInt($.browser.version) < 7) {
    $(".marker").supersleight({"shim": "/sites/all/themes/1010/x.gif"});
  }

  $(".country").bind("mouseover", function(){
    if($(this).attr("id") == "c") return;
    var index = $(this).attr("id").replace("c","");
    var marker = $("#m" + index);

    $(".marker").css("visibility","hidden");
    marker.css("visibility","visible");
    is_drag=true;
    marker_pos = parseInt(marker.css("left"));
    drag_to = -1*marker_pos + globe_radius;
  });

  $("#countries_holder").bind("mouseleave", function(){
    is_drag = false;
    on_list = false;
    drag_to = globe_x;
    increment = 0;
    $(".marker_country").css("visibility","hidden");
    $(".marker_cluster").css("visibility","visible");
  });
}

function showMarker(el){
  var href = $(el).attr('href');
  $('#countries_holder a[href=' + href + ']').addClass('selected');
}

function hideMarker(el){
  $('#countries_holder a').removeClass('selected');
}

function clickMarker(el){
  spin = false;
}

function moveGlobe(){
  if(!spin) return;
  if(is_drag){
    increment = (drag_to - globe_x)*.2;
  }else{
    if(Math.abs(increment) > .2){     
      increment *= .90;
    }else{
      increment = .2;
    }
  }
  globe_x +=increment;

  if(globe_x > 0){
    globe_x -= map_width;  
    drag_to -= map_width;
    start_drag_left -= map_width;
  }else if(globe_x < -1*map_width){
    globe_x += map_width;     
    drag_to += map_width;   
    start_drag_left += map_width;
  }

  updateMarkers();

  $('#globe_map').css("left", globe_x);
  $('#marker_map').css("left", globe_x + 15);
}

function updateMarkers(){
  $('.marker').each(function(){
    var marker_x = parseInt($(this).css("left"));
    var marker_y = parseInt($(this).css("top"));

    var radial_x = globe_radius - marker_x - globe_x;
    var radial_y = globe_radius - marker_y;

    if(Math.abs(radial_x - map_width) < Math.abs(radial_x)){
      $(this).css({"left":marker_x + map_width});
    }else if(Math.abs(radial_x + map_width) < Math.abs(radial_x)){
      $(this).css({"left":marker_x - map_width});
    }else if((radial_x*radial_x + radial_y*radial_y) > test_radius*test_radius){
      if(!jQuery.browser.msie){
        var diff = (radial_x*radial_x + radial_y*radial_y) - test_radius*test_radius;
        var opacity = diff > 5000 ? 0 : 1-diff/5000;
        $(this).css("opacity", opacity);
      }else if((radial_x*radial_x + radial_y*radial_y) > globe_radius*globe_radius){
        $(this).css("display", "none");
      }
    }else{
      if(!jQuery.browser.msie){
        $(this).css({'opacity':1});
      }else{
        $(this).css({'display':'block'});
      }
    }
  });
}

var start_drag_x;
var drag_x;
var drag_to = 0;
var start_drag_left;
var is_drag = false;

function startDrag(e){
  e.preventDefault();
  $(document).bind('mousemove', function(e){pollMouse(e);});
  start_drag_left = parseInt($('#globe_map').css("left").replace("px",""));
  drag_to = start_drag_left;
  start_drag_x = e.pageX;
  is_drag = true;
}

function stopDrag(e){
  $(document).unbind('mousemove');
  is_drag = false;
}

function pollMouse(e){
  var drag_diff = e.pageX - start_drag_x;
  drag_to = start_drag_left + drag_diff;
}

