var cnw_obj;
try{
  if(opener && opener.window && opener.parent && opener.window.parent.rcmail){
    cnw_obj = opener.window.parent;
  }
  else{
    cnw_obj = opener;
  }
}
catch(e){
  cnw_obj = opener;
}

function composenewwindowcommandcaller(command, props, obj){
  switch(command){
    case 'compose':
      var append = '';
      switch(rcmail.env.task){
        case 'mail':
          if(props){
            append = '&_to=' + props;
          }
          opencomposewindow('./?_task=mail&_action=compose&_mbox='+urlencode(rcmail.env.mailbox) + append);
          break;
        case 'addressbook':
          if(props){
            if(props != ' '){
              append = '&_to=' + props;
            }
            opencomposewindow('./?_task=mail&_action=compose' + append);
          }
          else{
            var n, len, a_cids = [];
            if(rcmail.contact_list){
              var selection = rcmail.contact_list.get_selection();
              for(n=0, len=selection.length; n<len; n++)
                a_cids.push(selection[n]);
            }
            if(a_cids.length){
              var url = '_cid=' + a_cids.join(',') + '&_source=' + rcmail.env.source;
              opencomposewindow('./?_task=addressbook&_action=mailto&' + url);
            }
            else{
              rcmail.command(command, props, obj);
            }
          }
          break;
        default:
          opencomposewindow('./?_task=mail&_action=compose');
      }
      break;
    case 'reply-list':
    case 'reply-all':
    case 'reply':
      var uid;
      if(uid = rcmail.get_single_uid()){
        var url = '_reply_uid='+uid+'&_mbox='+urlencode(rcmail.env.mailbox);
        if(command == 'reply-all')
          // do reply-list, when list is detected and popup menu wasn't used 
          url += '&_all=' + (!props && rcmail.commands['reply-list'] ? 'list' : 'all');
        else if (command == 'reply-list')
          url += '&_all=list';
        opencomposewindow('./?_task=mail&_action=compose&' + url);
      }
      break;
    case 'forward-attachment':
    case 'forward':
      var uid, url;
      if(uid = rcmail.get_single_uid()){
        url = '_forward_uid='+uid+'&_mbox='+urlencode(rcmail.env.mailbox);
        if (command == 'forward-attachment' || (!props && rcmail.env.forward_attachment))
          url += '&_attachment=1';
        opencomposewindow('./?_task=mail&_action=compose&' + url);
      }
      if(rcmail.message_list.get_selection().length > 1){
        if(typeof rcmail_forwardatt_url == 'function'){
          url = rcmail_forwardatt_url(props);
          opencomposewindow('./?_task=mail&_action=plugin.forwardatt&' + url);
        }
      }
      break;
    case 'edit':
      cid = rcmail.get_single_uid();
      url = (rcmail.env.mailbox == rcmail.env.drafts_mailbox) ? '_draft_uid=' : '_uid=';
      opencomposewindow('./?task=mail&_action=compose&'+url+cid+'&_mbox='+urlencode(rcmail.env.mailbox))
      break;
    default:
  }
  return false;
}

function opencomposewindow(url) {
  // Window gets centered (more or less)
  var W = Math.min(screen.width - 20, 1400);
  var H = 800;
  if(screen.left)
    var sl = screen.left;
  else
    var sl = 0;
  if(screen.top)
    var st = screen.top;
  else
    var st = 0;
  var L = ( screen.width - W ) / 2 + sl;
  var T = ( screen.height - H ) / 2 + st - 50;
  T = (T<st?st:T);
  L = (L<sl?sl:L);
  url = url.replace('_mbox=undefined', '_mbox=INBOX');
  var childwin = window.open(url,'','scrollbars=no,width='+W+',height='+H+',top='+T+',left='+L);
  childwin.focus();
  return childwin;
}

function opencomposewindowcaller(url){
  if(!window.opener){
    rcmail.env.compose_window = opencomposewindow(url);
  }
  else{
    var ref=opener.document.referrer;
    if(ref.indexOf("_task=mail") >-1){
      var back="./?_task=mail";
    }
    else{
      var back=ref;
    }
    if(
      cnw_obj.rcmail.env.task == rcmail.env.task &&
      cnw_obj.rcmail.env.action == rcmail.env.action
    ){
      window.opener.$("html").html("");
      cnw_obj.location.href = back;
    }
    $(window).bind('blur',function(){
      self.focus();
    });
    $('body').bind('mouseover click keypress', function(){
      $(window).unbind('blur');
    });
    $(window).unload(function(){
      if(cnw_obj.$('#mailboxlist-container').html() || cnw_obj.$('#mailboxcontainer').html())
        cnw_obj.rcmail.list_mailbox(cnw_obj.rcmail.env.mailbox, cnw_obj.rcmail.env.current_page);
      self.close();
    });
    rcmail.addEventListener('actionafter', function(response) {
      if(response.action == 'savedraft'){
        window.setTimeout("cnw_obj.rcmail.command('list');",2000);
      }
    });
  }
}

$(document).ready(function(){
  if(window.rcmail && rcmail.gui_objects.messagelist) {
    rcmail.addEventListener('insertrow', function(data, evt){
      if(rcmail.env.drafts_mailbox == rcmail.env.mailbox){
        $('#rcmrow'+data.uid+' > td').bind('dblclick', function(e){
          rcmail.mddetect = true;
        });
        $('#rcmrow'+data.uid+' > td').bind('mousedown', function(e){
          if(rcmail.dblclick_detect && new Date().getTime() - rcmail.dblclick_detect <= rcmail.message_list.dblclick_time){
            rcmail.dblclick_cancel = true;
            composenewwindowcommandcaller('edit');
            $(document).mousemove(function(){
              $('#rcmdraglayer').css('display','none');
            });
          }
          else{
            rcmail.dblclick_detect = new Date().getTime();
            $(document).unbind('mousemove');
          }
        });
        $('#rcmrow'+data.uid+' > td').bind('mouseup', function(e){
          if(rcmail.dblclick_cancel){
            rcube_event.cancel(e);
            rcmail.dblclick_cancel = false;
          }
        });
      }
    });
  }
});