//EMailPanel
EMailPanel = function (newId, newParent, newXPosition, newYPosition, newZIndex, newWidth, newHeight, newVisibility, newMapObject, newMapId)
{
  if (arguments.length > 0)
    this.init(newId, newParent, newXPosition, newYPosition, newZIndex, newWidth, newHeight, newVisibility, newMapObject, newMapId);
};

EMailPanel.prototype = new GuiWidget();
EMailPanel.constructor = EMailPanel;
EMailPanel.superclass = GuiWidget.prototype;

EMailPanel.prototype.init = function (newId, newParent, newXPosition, newYPosition, newZIndex, newWidth, newHeight, newVisibility, newMapObject, newMapId)
{
  EMailPanel.superclass.init.call(this, newId, newParent, newXPosition, newYPosition, newZIndex, newWidth, newHeight, newVisibility, "EMailPanel");

  this.id = newId;
  if (newMapId!=null)
  {
    this.mapObject = OBJECT_MANAGER.getControl(newMapId);
    this.mapId = newMapId;
  }
  else
  {
    this.mapObject = newMapObject;
    this.mapId = newMapObject.id;
  }
  this.config = document.getGuiValueById('emailConfig');
  this.attachments = Array();
  
  var h = 0;
  this.sep = 3;
  this.mainForm  = new GuiWidget(this.id+"mainForm", this.element, 0, 0, 4, this.width(), this.height(), true, "QueryPanel");
    this.mainCaptionElement = new GuiWidget(this.id+"mainCaptionElement", this.mainForm.element, 0, h, 0, this.width(), 20, true, "emailHeader");
      this.mainCaptionElement.element.cbe.innerHtml("E-Mail");
    h += this.mainCaptionElement.height();
    this.headerDivElement = new GuiWidget(this.id+"headerDivElement",this.mainForm.element, 0, h, 0, 300, 90, true, "emailForm");
    this.attachmentCaptionElement = new GuiWidget(this.id+"attachmentCaptionElement", this.mainForm.element, (this.headerDivElement.width()+this.sep), this.mainCaptionElement.top(), 0, this.width(), 20, true, "emailHeader");
      this.attachmentCaptionElement.element.cbe.innerHtml("Attachments");
    this.attachmentDivElement = new GuiWidget(this.id+"attachmentDivElement",this.mainForm.element, (this.headerDivElement.width()+this.sep), h, 0, (this.width()-this.headerDivElement.width()-this.sep-this.sep), this.headerDivElement.height(),true,"emailFormScroll");
    h += this.attachmentDivElement.height();
    this.htmlareaCaptionElement = new GuiWidget(this.id+"htmlareaCaptionElement", this.mainForm.element, 0, h, 0, this.width(), 20, this.config.allowMessageBody, "emailHeader");
      this.htmlareaCaptionElement.element.cbe.innerHtml("Message");
    h += this.htmlareaCaptionElement.height();
    this.htmlareaDivElement = new GuiWidget(this.id+"htmlareaDivElement",this.mainForm.element, 0, h, 0, this.width()-this.sep,(this.height()-h-this.sep), this.config.allowMessageBody, "emailForm");
    
    /* headerDivElements */
    h=0;
    this.headerFromLabelElement = new GuiWidget(this.id+"headerFromLabelElement",this.headerDivElement.element, 3, h, 0, 50, 20, true, "emailHeaderLabel");
      this.headerFromLabelElement.element.cbe.innerHtml('From:');
    this.headerFromInputElement = new GuiWidget(this.id+"headerFromInputElement",this.headerDivElement.element, 60, h, 0, this.headerDivElement.width()-60, 20, true, "");
      this.headerFromInputElement.element.cbe.innerHtml('<input type="text" id="'+this.id+'headerFromInput" size="35" value="">');
    h += this.headerFromLabelElement.height();
    this.headerToLabelElement = new GuiWidget(this.id+"headerToLabelElement",this.headerDivElement.element, 3, h, 0, 50, 20, (!this.config.forceFeedbackMode), "emailHeaderLabel");
    var toHTML = 'To:';
    if (this.config.allowFeedbackButton)
      toHTML+= ' &nbsp;<IMG title="Send Feedback to '+document.getGuiValueById('ApplicationConfig').organization+'" src="'+GuiWidget.THEME_PATH+GuiWidget.THEME+'/images/feedbackButton.png" onclick="document.getWidgetById(\'emailPanel\').feedbackButtonClick();" style="cursor:pointer;">';
      this.headerToLabelElement.element.cbe.innerHtml(toHTML);
    this.headerToInputElement = new GuiWidget(this.id+"headerToInputElement",this.headerDivElement.element, 60, h, 0, this.headerDivElement.width()-60, 20, (!this.config.forceFeedbackMode), "");
      this.headerToInputElement.element.cbe.innerHtml('<input type="text" id="'+this.id+'headerToInput" size="35" value="">');
    if(!this.config.forceFeedbackMode)
      h += this.headerToLabelElement.height();
    this.headerSubjectLabelElement = new GuiWidget(this.id+"headerSubjectLabelElement",this.headerDivElement.element, 3, h, 0, 50, 20, true, "emailHeaderLabel");
      this.headerSubjectLabelElement.element.cbe.innerHtml('Subject:');
    this.headerSubjectInputElement = new GuiWidget(this.id+"headerSubjectInputElement",this.headerDivElement.element, 60, h, 0, this.headerDivElement.width()-60, 20, true, "");
      this.headerSubjectInputElement.element.cbe.innerHtml('<input type="text" id="'+this.id+'headerSubjectInput" size="35" value="">');
    h += this.headerSubjectLabelElement.height();
    var vsep = 3;
    this.headerSendButton = new ImageButton(this.id+"headerSendButton", this.headerDivElement.element, vsep, h+this.sep, 0, 100,20,true,'emailSendButton','');
    this.headerSendButton.EMailPanel = this;
    this.headerSendButton.clickEvent = function(e)
    {
      this.EMailPanel.sendEMail();
    };
    this.headerClearAllButton = new ImageButton(this.id+"headerClearAllButton", this.headerDivElement.element, (vsep+this.headerSendButton.width()+vsep), h+this.sep, 0, 100,20,true,'emailClearAllButton','');
    this.headerClearAllButton.EMailPanel = this;
    this.headerClearAllButton.clickEvent = function(e)
    {
      this.EMailPanel.clearAll();
    };
    h += this.headerSendButton.height();
    
    /* HTMLArea */
    var textAreaHTML = '<TEXTAREA id="'+this.id+'HTMLArea" cols="125" rows="45" class="emailTextArea"></TEXTAREA>';
    this.htmlareaDivElement.element.cbe.innerHtml(textAreaHTML);
};

EMailPanel.prototype.buildEditor = function()
{
  /* HTMLArea stuff goes here */
};

EMailPanel.prototype.feedbackButtonClick = function()
{
  document.getElementById(this.id+'headerToInput').value = document.getGuiValueById('ApplicationConfig').adminEmail;
};

EMailPanel.prototype.URLToFName = function(URL)
{
  var pos = URL.lastIndexOf('/');
  if(pos < 0)
    return(URL);
  var FName = URL.substr(pos+1);
  return(FName);
};

EMailPanel.prototype.URLToHttp = function(URL)  // NEW
{
  var pos = URL.indexOf('//');
  if(pos < 0)
    return(URL);
  var HttpURL = URL.substr(pos+2);
  return(HttpURL);
};


/**********************ATTACHMENTS*******************************/
EMailPanel.prototype.addBodyImageAttachment = function(Name,HandleName,FName)
{
  var pos = this.attachments.length;
  this.attachments[pos] = Array();
  this.attachments[pos].handle = HandleName;
  this.attachments[pos].fname = FName;
  this.attachments[pos].name = Name;
  this.attachments[pos].type = 'bodyImage';
  this.addAttachmentLabel(Name,'bodyImage',pos);
};
EMailPanel.prototype.addFileAttachment = function(Name,HandleName,FName)
{
  var pos = this.attachments.length;
  this.attachments[pos] = Array();
  this.attachments[pos].handle = HandleName;
  this.attachments[pos].fname = FName;
  this.attachments[pos].name = Name;
  this.attachments[pos].type = 'File';
  this.addAttachmentLabel(Name,'File',pos);
};
EMailPanel.prototype.addTextAttachment = function(Name,txt,isHTML)
{
  var pos = this.attachments.length;
  this.attachments[pos] = Array();
  this.attachments[pos].text = txt;
  this.attachments[pos].name = Name;
  var typeStr = '';
  if (isHTML)
  {
    typeStr = 'PlainText';
    this.attachments[pos].type = 'text/html';
  }
  else
  {
    typeStr = 'HTML';
    this.attachments[pos].type = 'text/plain';
  }
  this.addAttachmentLabel(Name,typeStr,pos);
};
EMailPanel.prototype.addAttachmentLabel = function(Name,TypeStr,pos)
{
  var div = document.getElementById(this.id+"attachmentDivElement");
  var BRStr = '';
  if(div.innerHTML != '')
    BRStr = '<BR />';
  div.innerHTML = div.innerHTML+'<SPAN id="'+this.id+'_attachmentLabelNum_'+pos+'">'+BRStr+'<img src="'+GuiWidget.THEME_PATH+GuiWidget.THEME+'/images/deleteAttachment.png" onclick="document.getWidgetById(\''+this.id+'\').removeAttachment('+pos+');" style="cursor:pointer;">&nbsp; '+Name+'</SPAN>';
};
EMailPanel.prototype.removeAttachment = function(pos)
{
  if(this.attachments[pos])
    delete(this.attachments[pos]);
  var label = document.getElementById(this.id+'_attachmentLabelNum_'+pos);
  var nextLabel = label.nextSibling;
  var prevLabel = label.previousSibling;
  label.parentNode.removeChild(label);
  // here it gets convoluted quickly
  if ((nextLabel) && (!prevLabel))  // remove the <br>
  {
    var brs = nextLabel.getElementsByTagName('BR');
    brs[0].parentNode.removeChild(brs[0]);
  }
};
EMailPanel.prototype.clearAttachments = function()
{
  for(var pos in this.attachments)
    this.removeAttachment(pos);
};

/* Send EMail */
EMailPanel.prototype.sendEMail = function()
{
  var emailFilter=/^.+@.+\..{2,3}$/;
  var FromAddr = document.getElementById(this.id+'headerFromInput').value.strtrim();
  var ToAddr = '';
  if (!this.config.forceFeedbackMode)
    ToAddr = document.getElementById(this.id+'headerToInput').value.strtrim();
  else
    ToAddr = document.getGuiValueById('ApplicationConfig').adminEmail.strtrim();
  
  var Subject = document.getElementById(this.id+'headerSubjectInput').value.strtrim();
  var MessageBody = '';
  if (this.config.allowMessageBody)
    MessageBody = this.getMessageBody();

  if (FromAddr == '') { alert('You must fill in the "from" email address field.');  return; }
  if (!(emailFilter.test(FromAddr))) { alert('The "from" email address is invalid.'); return; }

  if (ToAddr == '') { alert('You must fill in the "to" email address field.');  return; }
  if (!(emailFilter.test(ToAddr))) { alert('The "to" email address is invalid.'); return; }

  if (Subject == '')
    if (!confirm("Are you sure you want to send an email without a subject?"))
      return;

  if (this.config.allowMessageBody)
    if (MessageBody == '')
      if (!confirm("Are you sure you want to send an email without a message body?"))
        return;

  var Organization = document.getGuiValue("ApplicationConfig").organization;
  var FromName = Organization+' Freeance User ';
  // if FromName has any commas, take them out as it flips out mail servers
  FromName =FromName.replace(/,/g,'');
  var HTMLMessageBody = MessageBody;
  var HTMLMessageBodyImages = Array();
  var Attachments = Array();
  for(var apos in this.attachments)
  {
    switch(this.attachments[apos].type)
    {
      case 'bodyImage':
          var ipos = HTMLMessageBodyImages.length;
          HTMLMessageBodyImages[ipos] = Array(this.attachments[apos].handle,this.attachments[apos].fname);
          HTMLMessageBody = HTMLMessageBody + '<HR />Attached Image: '+this.attachments[apos].name+'<BR /><IMG src="'+this.attachments[apos].fname+'">';
          break;
      case 'File':
          var ipos = Attachments.length;
          Attachments[ipos] = Array(this.attachments[apos].handle,this.attachments[apos].fname);
          break;
      case 'text/plain':
      case 'text/html':
          var ipos = Attachments.length;
          Attachments[ipos] = Array(this.attachments[apos].name,this.attachments[apos].type,this.attachments[apos].text);
          break;
    }
  }
  if (MessageBody != HTMLMessageBody)  // something html added
  {
    MessageBody = '';  // use the html version? add a config option
  }
  HTMLMessageBody = HTMLMessageBody.replace(/\n/g,"<BR />");
  HTMLMessageBody = '<HTML><BODY>'+HTMLMessageBody + '</BODY></HTML>';
  /* Send */
  makeASyncPostRequest(this,'SendEMail',XMLRPC_URL,'EMail.enhanced.send',ToAddr,FromAddr,FromName,Subject,Organization,MessageBody,HTMLMessageBody,HTMLMessageBodyImages,Attachments);
  /* Get busy */
  this.mapObject.setWaiting(true);
};

/* Message Body */
EMailPanel.prototype.getMessageBody = function()
{
  return(document.getElementById(this.id+'HTMLArea').value);
};
EMailPanel.prototype.setMessageBody = function(newContents)
{
  document.getElementById(this.id+'HTMLArea').value = newContents;
};
EMailPanel.prototype.clearMessageBody = function()
{
  this.setMessageBody('');
};
/* Header */
EMailPanel.prototype.clearHeader = function()
{
  document.getElementById(this.id+'headerFromInput').value = '';
  document.getElementById(this.id+'headerToInput').value = '';
  document.getElementById(this.id+'headerSubjectInput').value = '';
};
/* Misc */
EMailPanel.prototype.clearAll = function()
{
  if (confirm("Ok to clear all?"))
  {
    this.clearHeader();
    this.clearMessageBody();
    this.clearAttachments();
  }
};
/* Resize */
EMailPanel.prototype.resize_headerDivElement = function()
{
  this.mainCaptionElement.resize(this.mainForm.width(),this.mainCaptionElement.height());
};
EMailPanel.prototype.resize_attachmentDivElement = function()
{
  this.attachmentCaptionElement.resize(this.mainForm.width(),this.attachmentCaptionElement.height());
  this.attachmentDivElement.resize((this.width()-this.headerDivElement.width()-this.sep-this.sep),this.headerDivElement.height());
};
EMailPanel.prototype.resize_htmlareaDivElement = function()
{  // note this.mainForm.height instead of this.height
  this.htmlareaCaptionElement.resize(this.mainForm.width(),this.htmlareaCaptionElement.height());
  this.htmlareaDivElement.resize(this.width()-this.sep,(this.mainForm.height()-this.htmlareaDivElement.top()-this.sep));
  if (this.editor)
    this.editor.resize();
};
EMailPanel.prototype.resize = function(newWidth, newHeight)
{
  this.element.cbe.resizeTo(newWidth,newHeight);
  this.mainForm.resize(newWidth,newHeight);
  this.resize_headerDivElement();
  this.resize_attachmentDivElement();
  this.resize_htmlareaDivElement();
};
/* Callbacks */
EMailPanel.prototype.processFaultCallback = function(codeNum,codeStr)
{
  var errMsg = 'Error sending EMail.';
  if ((codeNum != null) && (codeStr != null))
  {
    errMsg = errMsg + "\nReason: Code("+codeNum+"): "+codeStr;
  }
  alert(errMsg);
};
EMailPanel.prototype.callback = function(serverReplyDoc, requestType)
{
  this.mapObject.setWaiting(false);
  /* begin error checks */
  if (serverReplyDoc == null)
  {
    this.processFaultCallback(null,null);
    return (null);
  }
  if (serverReplyDoc.xml == '') 
  {
    this.processFaultCallback(null,null);
    return (null);
  }
  if (serverReplyDoc.documentElement.nodeName == 'parsererror')
  {
    this.processFaultCallback(null,null);
    return (null);
  }
  var clientReply = new XMLRPCResponse();
  //clientReply.setResponseByStr(serverReplyDoc.xml);
  clientReply.setResponseByDoc(serverReplyDoc);
  if (clientReply.isFault())
  {
    this.processFaultCallback(clientReply.getFaultCode(),clientReply.getFaultString());
  }
  else
  {
    switch (requestType)
    {
      case 'SendEMail':
        /* Clear the To Field just for fun, not so spam friendly... */
        document.getElementById(this.id+'headerToInput').value = '< EMail Sent! >';
        alert('EMail Sent');
        break;
      default:
        alert(this.id+'.callback error:\nUnknown request type "'+requestType+'"');
        break;
    }
  }
};

