function detach_attachments_counts(file){
  rcmail.http_post('plugin.dta_counts', '_file=' + encodeURIComponent(file) + '&_hash=' + rcmail.env.user_hash);
}

function detach_attachments_callback(response){
  if(response == '?'){
    document.getElementById('messagepartframe').contentWindow.document.body.innerHTML = '<span>' + rcmail.gettext('detach_attachments.filenotfound') + '</span>';
  }
  else{
    document.getElementById('messagepartframe').contentWindow.document.getElementById('downloads').innerHTML = response;
  }
  document.getElementById('messagepartframe').contentWindow.document.body.style.display = 'block';
}

function detach_attachments_download(link){
  if(!confirm(rcmail.gettext('detach_attachments.downloadquestion'))){
    if(confirm(rcmail.gettext('detach_attachments.deleteconfirmation'))){
      var href = link.split('&_dla=');
      rcmail.http_post('plugin.dla_delete', '_file=' + encodeURIComponent(href[1]) + '&_hash=' + rcmail.env.user_hash);
    }
  }
  else{
    link = link + '&_delete=' + rcmail.env.user_hash;
    document.getElementById('messagepartframe').contentWindow.document.getElementById('counts').innerHTML = '';
    document.location.href = link;
  }
  return false;
}

$(window).load(function(){
  var attachment = document.getElementById('messagepartframe').contentWindow.document.getElementById(rcmail.env.user_hash);
  if(attachment && attachment.href){
    $('.download-link').remove();
    //document.getElementById('messagepartframe').contentWindow.document.body.style.display = 'none';
    var body = document.getElementById('messagepartframe').contentWindow.document.body.innerHTML;
    var html = '<div id="counts"><div><p><a onclick="return parent.detach_attachments_download(\'' + attachment.href + '\')" href="' + attachment.href + '&_delete=' + rcmail.env.user_hash + '" target=_self>' + rcmail.gettext('detach_attachments.deletelink') + '</a>&nbsp;[<span id="downloads">0</span>&nbsp;download(s)]</p></div>';
    var html = html + '<div><p><small>' + rcmail.gettext('detach_attachments.hint') + '</small></p></div>';
    html = html + '</div></body>';
    body = body + html;
    document.getElementById('messagepartframe').contentWindow.document.body.innerHTML = body;
    var href = attachment.href.split('&_dla=');
    rcmail.addEventListener('plugin.dta_counts', detach_attachments_callback);
    detach_attachments_counts(href[1]);
  }
});