
$.widget('ui.uploader', {

	_create: function() {
   	var $this = this;
      var $button = this.element.find('.browse');
      var upload;
      var value;

      $position = $button.position();
      $button.before("<div class=\"uploader-flash\" style=\"position: absolute; left: " + $position.left + "px; z-index: 100;\"><div></div></div>");

      upload = new SWFUpload({
         upload_url: 'http://www.stewartperry.com/assets/js/swfupload/upload.php',
         flash_url: 'http://www.stewartperry.com/assets/js/swfupload/swfupload.swf',
         file_size_limit: '20 MB',
         button_placeholder: $button.prev().find('div')[0],
         button_width: $button.innerWidth(),
         button_height: $button.innerHeight(),
         button_window_mode: 'transparent',
         file_queue_limit: 1,
         file_dialog_complete_handler: function(file) {
         	$this.element.find('.browse').hide();
         	$this.element.find('.uploading').show();
            upload.startUpload();
         },
         upload_progress_handler: function(file, loaded, total) {
            $this.progress(file, loaded, total);
         },
         upload_success_handler: function(file, data, response) {
            if (data == null || String(data).length == 0) {
            	alert('Uploading does not work in your browser. We recommend using FireFox.');
               return;
            }
            $this.uploaded(file, JSON.parse(data));
         },
         post_params: this.options.post,
         button_cursor: SWFUpload.CURSOR.HAND
      });

		this.upload = upload;
      this.files = {};

      this.element.find('.cancel').click(function() {
         upload.cancelQueue();
         $this.cancel();
      });

      this.element.find('.reset').click(function() {
         $this.cancel(true);
      });
      
      value = this.element.find('input[type=hidden]').val();

      if (value.length > 0) this.uploaded(null, JSON.parse(value));
	},

   progress: function(file, loaded, total) {
   	var progress = loaded / total;

      this.element.find('.progress span').css('width', (progress * 100) + '%');
   },

   uploaded: function(file, data) {
      this.progress(file, 1, 1);
      this.element.find('.selected').html("<a href=\"http://www.stewartperry.com/admin/" + data.url + "\" target=\"_blank\">View File</a>");
      this.element.find('.reset').show();
      this.element.find('input[type=hidden]').val(JSON.stringify(data));
      this.cancel();
   },
 
 	cancel: function(cancel) {
   	this.element.find('.browse').show();
   	this.element.find('.uploading').hide();
      
      if (cancel) {
      	this.element.find('input[type=hidden]').val('');
         this.element.find('.reset').hide();
         this.element.find('.selected').html('No File Selected');
   	}
   },
 
   validate: function() {
   	return (this.upload.getStats().files_queued == 0);
   }

});

$.ui.uploader.getter = 'validate'; 


$().ready(function() {
	$('#popup').popup();
});
