var UploadDialogController = function()
{
  var dialog = null;  
  var button = null;
  var file_list_tpl = new Ext.Template(
    "<div class='file-list-entry'>File {name} successfuly uploaded.</div>"
  );
  file_list_tpl.compile();

  function hideLoadingMask()
  {
    var loading = Ext.get('loading');
    var mask = Ext.get('loading-mask');
    mask.remove();
    loading.remove();
    Ext.get(document.body).setStyle('overflow', 'visible');
  }

  function getDialog()
  {
    if (!dialog) {
      dialog = new Ext.ux.UploadDialog.Dialog({
        url: 'upload-dialog-request.php',
        reset_on_hide: false,
        allow_close_on_upload: true,
        upload_autostart: false, //true,
        post_var_name: 'upload',
        base_params: { action : 'uploadfile', resptype: 'json' }
      });

      dialog.on('uploadsuccess', onUploadSuccess);
			//dialog.on('beforefileuploadstart', onBeforeFileUploadStart);
			dialog.on('uploadcanceled', function() { console.log('cancel');});
    }
    return dialog;
  }
  
  function showDialog(button)
  {
    getDialog().show(button.getEl());
  }
  
  function onUploadSuccess(dialog, filename, resp_data, record)
  {
    var parts = filename.split(/\/|\\/);
    if (parts.length == 1) {
      filename = parts[0];
    }
    else {
      filename = parts.pop();
    }
    file_list_tpl.append('file-list', {name: filename});
  }

	function onBeforeFileUploadStart(dialog, filename, record)
	{
    var store = dialog.getQueueStore();
    store.each(function(r, id) {
      r.set('params', {extra: id});
    });
	}
  
  return {
    init : function()
    {
      Ext.QuickTips.init();

      button = new Ext.Button({
        renderTo: 'show-dialog-btn',
        id: 'show-button',
        text: 'Show dialog',
        handler: showDialog
      });

      hideLoadingMask();
      Ext.get(document.body).setStyle('overflow', 'auto');
    }
  }
}();

Ext.BLANK_IMAGE_URL = '../ExtJS/resources/images/default/s.gif';
Ext.onReady(UploadDialogController.init);