var ShamrockUploader = {};

(function($) {
  var uploading = false;
  
  function beginUpload() {
    uploading = true;
    
    $('#upload_loading').css('display', 'block');
    $('#upload_controls').hide();
  }
  
  function uploadedFile(id, name) {    
    var html = '<li id="file_' + id + '">' + name + ' <a href="#" class="action">Remove</a></li>';
    
    $('#uploaded_files').append(html);
  }
  
  function completedUpload(uploaded) {
    uploading = false;
    $('#upload_loading').hide();
    $('#upload_controls').show();
  }
  
  function submitEntryForm(event) {
    if(uploading) {
      alert('Your files are currently uploading. Please wait...');      
      event.preventDefault();
    }
  }
  
  function onFilesClick(event) {
    if(event.target.nodeName == 'A') {
      var id = $(event.target).parent().attr('id').split('_')[1];      
      $.ajax({ url: '/promotion_files/' + id, data: "_method=DELETE&key=" + _srf, type: 'POST' });      
      $(event.target).parent().fadeOut();
    }
    
    event.preventDefault();
  }  
  
  $.extend(ShamrockUploader, {
    uploadedFile: uploadedFile,
    completedUpload: completedUpload,
    beginUpload: beginUpload
  });
  
  if(swfobject.hasFlashPlayerVersion("9.0.124")) {
    var flashvars = { 
      key: _srf
    };
    
  	var params = {
  		allowFullScreen: "false",
  		allowScriptAccess: "sameDomain",
  		wmode: "transparent"
  	};

  	var attributes = {
  		id: 'promotions_uploader'
  	};

  	swfobject.embedSWF("/_flash/promotions_uploader.swf", "uploader_swf", "300", "21", "9.0.124", false, flashvars, params, attributes);
  	
  	$(function() {
  	  $('#upload_controls').css('display', 'block').click(function(e) { e.preventDefault(); });
    	$('#new_entry_form').bind('submit', submitEntryForm);
    	$('#uploaded_files').bind('click', onFilesClick);
	  });  	
  }
})(jQuery);
