/**
 * @author jwhitcraft
 * $LastChangedDate$
 * $LastChangedRevision$
 */

var UploadDialogController = function()
{
  var dialog = null;
  var button = null;
  var uploadedfiles = 0;
  var file_list_tpl = new Ext.Template(
    "<li class='file-list-entry'><input type='hidden' value='{id}-{name}' name='attachment[]' />{name} <a href='#' title='Remove Attachment' id='attachment{id}'><img src='/images/ext/images/UploadDialog/reset.gif' /></a></li>"
  );
  file_list_tpl.compile();

  function getDialog()
  {
    if (!dialog) {
      dialog = new Ext.ux.UploadDialog.Dialog({
        url: '/talkback/submit/attach',
        reset_on_hide: true,
        allow_close_on_upload: true,
        upload_autostart: false,
        permitted_extensions: ['jpg'],
        max_file_size : '1048576',
        post_var_name: 'upload'
      });

      dialog.on('uploadsuccess', onUploadSuccess);
      dialog.on('filetest', onFileTest);
    }
    return dialog;
  }

  function showDialog(button)
  {
    getDialog().show(button.getEl());
  }

  function onUploadSuccess(dialog, filename, resp_data)
  {
    var el = file_list_tpl.append('file-list', {name: resp_data.name, id: resp_data.id}, true);
    uploadedfiles++;

    el.on('click', onDetachClick, this, {stopEvent: true});
  }

  function onDetachClick(evt, o)
  {
    var srcEl = evt.getTarget().parentNode;
    var id = srcEl.id.replace('attachment', '');

    Ext.Ajax.request({
        url: '/talkback/submit/detach/id/' + id,
        callback : function(opt, success, response) {
            if(success) {
                // remove
                var parent = Ext.fly(srcEl).findParentNode('li.file-list-entry', 5, true);
                parent.setOpacity(0, {callback : function() {
                    this.remove();
                }, scope: parent})
                uploadedfiles--;
            } else {
                // error
                console.log(response);
            }
        },
        scope: this
    })
  }

  function onFileTest(dialog, filename)
  {
      if(typeof max_files != 'undefined') {
          var _max = max_files - uploadedfiles;
          if(_max == dialog.getQueuedCount()) {
            Ext.Msg.alert(
                "File Limit",
                "You are only allow to upload a max of " + max_files + " files"
            );
            return false;
          }
      }

      return true;
  }

  return {
    init : function()
    {
      Ext.QuickTips.init();

      button = new Ext.Button({
        renderTo: 'show-dialog-btn',
        id: 'show-button',
        text: 'Attachment Uploader',
        handler: showDialog
      });

      Ext.get(document.body).setStyle('overflow', 'auto');

      // link any thing that might be there and update the uploaded files count.
      var els = Ext.fly('file-list').select('li.file-list-entry a');
      els.on('click', onDetachClick, this, {stopEvent: true});
      uploadedfiles = els.elements.length;
    }
  }
}();

Ext.onReady(function(){
    Ext.QuickTips.init();

    var editor = new Ext.form.HtmlEditor({
                    id: 't_comment',
					applyTo: 't_comment',
                    enableColors: false,
                    enableFont: false,
                    width: 522, height: 350,
                    enableFontSize : false});

    UploadDialogController.init();
});
