jQuery(function($){
    $('#live0,#live1,#live2').load(function(){
      if(top_image >= 0)
        return;
      flag[this.id.substr(4,1)] = 1;
      if(flag[0] && flag[1] && flag[2])
         showLive();        
    }).click(function(){
        getCode(this.src);
    }).mouseover(function(){
      $(this).css('borderColor', '#C80000');
    }).mouseout(function(){
      $(this).css('borderColor', '#FFFFFF');
    });

    $('#tables_caption').mouseover(function(){
        if(hover){
            clearInterval(hover);
        }
        else 
           $('#hover').fadeIn('slow');  
    }).mouseout(function(){
        hover = setInterval("$('#hover').fadeOut('slow');clearInterval(hover);hover=null;", 500);
    });

    tmp_image.onload = function(){
        showLive();
    };

    liveUpdate();
    setInterval('liveUpdate()', 10000);
});

var root = $('base').attr('href');
var hover = null;
var flag = [0, 0, 0];
var images = [];
var images_len = 0;
var images_curr = 0;
var top_image = -1;
var transaction = 0;
var tmp_image = new Image;


function liveUpdate(){
   if(transaction)
      return;
   transaction = 1;
   if(!images_len){
      $.get(
         root + "images.html?" + Math.random(),
         function(msg){
            //console.log(msg);
            images = msg.split("|");
            images_len = images.length;
            images_curr = Math.round(Math.random() * (images_len - 1));
            $('#live0').attr('src', root + 'images/tables/' + images[images_curr % images_len]);
            $('#live1').attr('src', root + 'images/tables/' + images[(images_curr + 1) % images_len]);
            $('#live2').attr('src', root + 'images/tables/' + images[(images_curr + 2) % images_len]);
            images_curr++; 
         }
      );
   }
   else{
      top_image++;
      tmp_image.src = root + 'images/tables/' + images[(images_curr + 2) % images_len];
      images_curr++;
   }
}

function showLive(){
   if(top_image < 0){
      $('#live0').css('visibility', 'visible').fadeIn(
      'slow', function(){$('#live1').css('visibility', 'visible').fadeIn(
      'slow', function(){$('#live2').css('visibility', 'visible').fadeIn('slow', function(){transaction = 0;});});
      });
   }
   else{
      //top_image++;
      //eval('live' + (top_image % 3) + '= 0');
      $('#live' + (top_image % 3)).hide(
      'normal',function(){$('#live' + ((parseInt(top_image) + 1) % 3)).animate(
      {top:8}, 'slow', function(){$('#live' + ((parseInt(top_image) + 2) % 3)).animate(
      {top:174}, 'slow', function(){$('#live' + (top_image % 3)).attr('src', tmp_image.src).css('top', '340px').show('normal', function(){transaction = 0;});});});});
   }
}



function getCode(img){
   document.fcode.src.value = img;
   document.fcode.submit();
}


