// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

$(function(){
  function open_flash_box() {
    var binded = true;

    function kill_me() {
      if(binded) {
        $('#flash_messages').slideUp(200)
        binded = false;
      }
    }

    $('#flash_messages').slideDown(200, function() {
      var counter = 5,
          couner_obj =

          $('#flash_messages').append('<div id="flash-counter">' +
            counter + '</div>').find('#flash-counter');

      (function count_down() {
        if(counter > 1 && binded) setTimeout(count_down, 1000);
        couner_obj.text(counter--);
      })();

      setTimeout(kill_me, (counter + 1) * 1000);
    });

    $('#flash_messages').hover(
      function() { $(this).fadeTo(200, 0.2); },
      function() { $(this).fadeTo(200, 0.96); }
    ).click(function() {
      kill_me();
    });
  }

  if($('#flash_messages').length) {
    open_flash_box();
  }

  $('form#image_upload input').change(function(){
    $(this).parents('form').find('.loader').show();
    $(this).parents('form').iframe_upload({
      load: function(data) {
        $('form#image_upload input').val('');
        $('form#image_upload .loader').hide();
/*        if (data.error)
        {
          alert('Upload error');
          return false;
        }*/
        tpl = $('.uploaded-image-template').html();
        tpl = tpl.replace(/IMGID/g, data.id).replace(/<p>/, '<p id="ui'+data.id+'i">!'+data.url+'!');
        $('.uploaded-images').append('<li class="uploaded-image" id="ui'+data.id+'">'+tpl+'</li>');
        $('#ui'+data.id+' img').attr('src', data.small_url);//.attr('alt', data.url);
      }
    });
  });
  $('#load-uploaded-images').click(function(){
    $('#uploaded-images-list').load('/photos');
    return false;
  });
});
$('.image-delete').live('click', function(){
  if (confirm('Are you sure?')) {
    image_id = $(this).attr('image_id');
    $.post('/photos/'+image_id, {'_method': 'delete', 'id': image_id}, function(data){
      $('#image'+data.id).remove();
    }, 'json');
    return false;
  }
});

