var count = 0;
var anim_step = 3000;
var current = parseInt(flakes[0]['time']);
var map;
var satmap;
var play = false;
var current_hour = 'llanllwni!';
var my_date = 0;
var gMEM_flush_count = 0;
var delay = 0; //delay in between plots
var cloud_flag = false;
var unscored_flag = false;

var all = flakes.length - 1;

//alert( all );

var old_edge; //the oldest visible plot in terms of mtgt id

$(document).ready( function(){ 
  
  $("#copy").tabs();
  
  $("#pp_button").click( start_stop );

  $("#cloud_switch input").click( function(){
    cloud_flag = $(this).is(':checked');
    if(cloud_flag){
      current_sat_image();
      unscored_flag = false;
      $("#unscored input").attr('checked', '');
    }else{
      if(map !== null) map.clearOverlays();
    }
  });

  $("#unscored input").click( function(){
    unscored_flag = $(this).is(':checked');
  });
  
  $("#step").slider({ 
    min: 1,
    max: 60,
    value: 60,
    step: 1,
    slide: changeStep
  });
  
  $("#delay").slider({ 
    min: -1000,
    max: 1000,
    step: 10,
    slide: changeDelay
  });
  
  $("#count").slider({ 
    min: 0,
    max: all,
    step: parseInt(all/500) + 1,
    slide: changeCount
  });
  
  map = new GMap2(document.getElementById("map"));
  map.setMapType(G_SATELLITE_MAP);
  map.addControl(new GLargeMapControl3D());
  map.addControl(new GMapTypeControl());
  map.addMapType(G_PHYSICAL_MAP);
  map.enableScrollWheelZoom();
  map.enableContinuousZoom();
  map.setCenter(new GLatLng(54.16243396806781, -3.955078125), 5);

  $(".get_full").click( function(){

    //whcih archive to load
    var year = $(this).attr('rel');
    if(year == 'current') year = '';

    // jQuery Ajax call
    var myTrigger;
    var progressElem = $('#progressCounter');
    $.ajax({
      type      : 'GET',
      dataType  : 'json',
      url       : 'flakes'+year+'.array',
      error     : function (xhr, ajaxOptions, thrownError){
        alert(xhr.responseText);
        alert(thrownError);
        alert("Pooh! There was an error activating the archive. Maybe try reloading the page?");
      },
      xhr: function()
      {
        var xhr = new window.XMLHttpRequest();
        //Download progress
        xhr.addEventListener("progress", function(evt){
          if (evt.lengthComputable) {
            var percentComplete = evt.loaded / evt.total;
            progressElem.html(Math.round(percentComplete * 100) + "%");
          }
        }, false);
        return xhr;
      },
      beforeSend: function()
      {
        play = false;
        $('#loading').show();
      },
      complete  : function(){
        $("#loading").hide();
      },
      success   : function(json){
        flakes = eval(json);
        count = 0;
        //alert(all);
        all = flakes.length - 1;
        //var time = new Date( flakes[count][0]*1000 );
        //alert(time.toUTCString());
        //alert(all);
        $('#count').slider('option', 'value', count);
        $("#count_value").html(count);
        //changeCount();

        $('[id*=mtgt_unnamed]').hide();

        current = parseInt(flakes[count]['time']);

        var time = new Date( flakes[count]['time']*1000 );
        $('#time').html( time.toUTCString() );

        $('#count').slider('option', 'max', all);
        $('#count').slider('option', 'step', parseInt(all/500));
        //alert( parseInt(flakes[3000][0]) );
      }
    });
    return false;
  });

  //Just set the date of the first flake above the slider
  var time = new Date( flakes[0]['time']*1000 );
  $('#time').html( time.toUTCString() );

});


function plot(){
  var skip = false;
  
  if(count > all){
    start_stop();
    return;
  }
  
  //skip low snow tweets when the map's on
  if( !unscored_flag && flakes[count]['score'] < 1 ){
    count++;
    skip = true;
  } 
  
  var prev_time = 0;
  var flake_id = 0;
  var real_delay;
  var old_edge;
  
  if( delay < 0 ){
    var delay_positive = parseInt(delay * -1);
    var rand_no = Math.random();
    rand_no = rand_no * 1000;
    if( Math.ceil(rand_no) < delay_positive ){      
      if( play === true ){
        count++;
        skip = true;
      }    
    }
    real_delay = 0;
  }else{
    real_delay = delay;
  }
  
  if( (skip !== true) ){
    
    var point = new GPoint(flakes[count]['lng'], flakes[count]['lat']);
    
    var marker = createMarker(point, flakes[count]['handle'], flakes[count]['content'], flakes[count]['score']);
    map.addOverlay(marker);
    //$('#mtgt_unnamed_' + count).hide().fadeIn();
    
    //update the slider
    $('#count').slider('option', 'value', count);
    $("#count_value").html(count);
    
    var time = new Date( flakes[count]['time']*1000 )
    $('#time').html( time.toUTCString() );

    //Little hack to keep things running smoothly
    flush_interval = (cloud_flag) ? 10 : 500;
    if(gMEM_flush_count > flush_interval){
      map.clearOverlays();
      if(cloud_flag) map.addOverlay(satmap);
      gMEM_flush_count = 0;
    }
    gMEM_flush_count++;
    //--
    
    if(cloud_flag) current_sat_image();
    
    prev_time = current;
    current = parseInt(flakes[count]['time']);
    flake_window = parseInt(anim_step / (current - prev_time));
    count++;
    
    var population  = $('[id*=mtgt_unnamed]:visible').length;
    
    if( population > flake_window ){
                
      for(flake_id=0; flake_id <= (population - flake_window); flake_id++){
        $('[id*=mtgt_unnamed]:visible:eq(' + flake_id + ')').hide();
      }
      
    }    
    
    
    if (play === true) setTimeout( plot, real_delay );
    
  }else{
    //map.clearOverlays(marker);
    //alert(step);
    if( play === true ) plot();    
  }
}

function createMarker(point, handle, content, score) {
 
    var icon = new GIcon();
    var marker = new GMarker(point, icon);
    
    var size = parseInt( (3 * score) + 5);
    var middle = parseInt( size / 2 );
    icon.image = "/images/snow10.png";
    //icon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
    icon.iconSize = new GSize(size, size);
    //icon.shadowSize = new GSize(22, 20);
    icon.iconAnchor = new GPoint(middle, middle);
    icon.infoWindowAnchor = new GPoint(5, 1);
 
    var html = '<img class="profile_pic" src="https://api.twitter.com/1/users/profile_image/' + handle + '" /><div class="tweet_body"><strong class="handle">'+handle+'</strong> ' + stripslashes(content) + '</div>';
    GEvent.addListener(marker, "click", function(){
        marker.openInfoWindowHtml(html);
    });
    return marker;
}
 
function changeStep(){
  anim_step = $('#step').slider('option', 'value') * 60;
  $("#step_value").html(anim_step / 60);
}

function changeDelay(){
  delay = $('#delay').slider('option', 'value');
  $("#delay_value").html(delay);
}

function changeCount(){
  if( $('#count').slider('option', 'value') >= all ){
    count = all;
    //$('#count').slider('option', 'value', all);
  }else{
    count = $('#count').slider('option', 'value');
  }
  $("#count_value").html(count);

  current = parseInt(flakes[count]['time']);
    
  var time = new Date( flakes[count]['time']*1000 );
  $('#time').html( time.toUTCString() );
  
}

function start_stop(){
  if(play === false){
    //PLAY
    if( count >= all ){
      $('#count').slider('option', 'value', '1');
      changeCount();
    }
    play = true;
    $("#pp_button").css('background', "url('/images/pause_38.png')");
    map.clearOverlays();
    plot();
  }else{
    //PAUSE
    play = false;    
    $("#pp_button").css('background', "url('/images/play_38.png')");
  }  
  return false;
}

function current_sat_image(){
  //return;
  if(flakes[count]['time'] < 1288051200) return; //there's no sattelite images available before this time.
  
  var time = new Date( flakes[count]['time']*1000 );
  old_date = my_date;
  my_date = pad(time.getDate(), 2) + '-' + pad(time.getMonth()+1, 2) + '-' + time.getFullYear() + '--' + pad(time.getHours(), 2) + '00';
  if(my_date != old_date){
    var sat_image_path = '/sat_images/' + my_date + '.jpg';
    var boundaries = new GLatLngBounds(new GLatLng(44.5,-21), new GLatLng(62, 12));
    satmap = new GGroundOverlay(sat_image_path, boundaries);
    map.addOverlay(satmap);
  }
}


function pad(number, length) {
  var str = '' + number;
  while (str.length < length) {
    str = '0' + str;
  }
  return str;
}

function stripslashes(str) {
  if(str==null) return;
  str=str.replace(/\\'/g,'\'');
  str=str.replace(/\\"/g,'"');
  str=str.replace(/\\0/g,'\0');
  str=str.replace(/\\\\/g,'\\');
  return str;
}
