var count = 0;
var anim_step = 3000;
var current = parseInt(flakes[0]['time']);
var map;
var play = false;

var delay = 0; //delay in between plots

var all = flakes.length - 2;

//alert( all );

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

$(document).ready( function(){ 
  
  $("#copy").tabs();
  
  $("#pp_button").click( start_stop );
  
  $("#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),
    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.centerAndZoom(new GPoint(-3.955078125, 54.16243396806781), 12);
  map.setCenter(new GLatLng(54.16243396806781, -3.955078125), 5);
  
  $("#get_full").click( function(){
    // jQuery Ajax call
    var myTrigger;
    var progressElem = $('#progressCounter');
    $.ajax({
      type      : 'GET',
      dataType  : 'json',
      url       : 'flakes.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?");
      },
      beforeSend: function (thisXHR){
	myTrigger = setInterval(function(){
	  if (thisXHR.readyState > 2){
	    var totalBytes  = thisXHR.getResponseHeader('Content-length');
	    var dlBytes     = thisXHR.responseText.length;
	    (totalBytes > 0) ? 
	      progressElem.html(
		Math.round ((dlBytes / totalBytes) * 100) + "%"
	      ) : 
	      progressElem.html(Math.round (dlBytes / 1024) + "K");
	  }
	}, 200);
      },
      complete  : function(){
	clearInterval (myTrigger);
      },
      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;
  });
  
  $("#loading").ajaxStart(function(){
    play = false;
    $(this).show();
  });
  $("#loading").ajaxStop(function(){
    $(this).hide();
  });
  
  //Enter the main loop
  plot(); 

});


function plot(){
  if(count >= all){
    start_stop();
    play = false;
    return;
  }  
  
  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++;
	var 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);
    count++;
    //$('#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() );    
        
    
    prev_time = current;
    current = parseInt(flakes[count]['time']);
    flake_window = parseInt(anim_step / (current - prev_time));
    
    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="http://spiurl.appspot.com/' + handle + '" /><div class="tweet_body">' + 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);
  //map.clearOverlays();
  
  map.clearOverlays();
  
  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 : dump()
 * Arguments: The data - array,hash(associative array),object
 *    The level - OPTIONAL
 * Returns  : The textual representation of the array.
 * This function was inspired by the print_r function of PHP.
 * This will accept some data as the argument and return a
 * text that will be a more readable version of the
 * array/hash/object that is given.
 * Docs: http://www.openjs.com/scripts/others/dump_function_php_print_r.php
 */
function dump(arr,level) {
	var dumped_text = "";
	if(!level) level = 0;
	
	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j=0;j<level+1;j++) level_padding += "    ";
	
	if(typeof(arr) == 'object') { //Array/Hashes/Objects 
		for(var item in arr) {
			var value = arr[item];
			
			if(typeof(value) == 'object') { //If it is an array,
				dumped_text += level_padding + "'" + item + "' ...\n";
				dumped_text += dump(value,level+1);
			} else {
				dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
			}
		}
	} else { //Stings/Chars/Numbers etc.
		dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	return dumped_text;
}