// JavaScript Document

SendEmail = { 
  currentPopin : "",
  att_i : 0,
  sendEmail : function(formObj)
  {
    if (typeof(CC) != 'undefined' && !CC.usersOnly())
    {
      return;
    }
    
    if (Ext.getDom('sendmessage_attachments') && Ext.getDom('sendmessage_attachments').style.display=='none')
    {
			SendEmail.resetAttachments();
		}
    
    var f_els = Ext.DomQuery.select('#sendemailform input[type=file]');
    var has_att = false;
    if (typeof(f_els) == 'object' && f_els.length > 0)
    {
      for (var i=0;i<f_els.length;i++)
      {
        var f_el = f_els[i];
        if (f_el && f_el.value != '')
        {
          has_att = true;
          break;
        }
      }
    }
    
    if (has_att)
    {
			Grouply.showEl('sendmsg_pb');
      Grouply.hideEl('sendmsg_btn');
      
      if (!SendEmail.post_pb)
      {
        SendEmail.post_pb = new Ext.ProgressBar({
           renderTo: 'sendmsg_pb',
           width: 400
        });
      }
      var pbtext = 'Your attachment is uploading...';
      if (f_els.length > 1)
      {
        pbtext = 'Your attachments are uploading...';
      }
      SendEmail.post_pb.wait({
         interval: 100,
         increment: 15,
         text: pbtext,
         scope: this
      });
		}
		
		Ext.getDom('sendemailform').setdomain.value = document.domain;
		
		var sendparams = SendEmail.getFormParams(Ext.getDom('sendemailform'));
		
    	Ext.getDom('sendemailform').action = CC.address + '/ajax/popin_sendemail.ajax';
      Grouply.ajaxform2('sendemailform',  
      function (options, success, response){
      	Ext.getDom(SendEmail.currentPopin + '_content_res').innerHTML = response.responseText;
      	if (SendEmail.post_pb)
		    {
		      SendEmail.post_pb.reset();
		      SendEmail.post_pb.destroy();
		      SendEmail.post_pb = null;
		      Grouply.showEl('sendmsg_btn');
		      Grouply.hideEl('sendmsg_pb');
		    }
          captcha = Ext.get('pc_captcha_error');
          if (captcha)
          {
            captcha.remove(); // this to prevent isntances where we have 2 captcha divs          
            Grouply.get('captchapopin').get().on('hide', function(){

              Grouply.unregister('captcha_savebutton');
              Grouply.unregister('user_secword');
              Grouply.currentPopin = SendEmail.currentPopin;
              Ext.get('captchapopin' + '_content').dom.innerHTML = "";
            });
            
            Grouply.popin.ajaxShow('captchapopin', CC.address + '/ajax/postcomment.captcha.ajax', '', null,   function() {
              Grouply.renderComponent('captcha_savebutton');
              Grouply.get('captcha_savebutton').setHandler(SendEmail.postCaptcha ,captcha_savebutton_code);
              Grouply.renderComponent('user_secword');
              Grouply.get('user_secword').purgeListeners();
              Grouply.get('user_secword').on('specialkey', function(field, e) {
                if (e.getKey() == 13) {
                    SendEmail.postCaptcha();
                }
              });
            });
          } else
          {
            post_status = Ext.get('pc_status_json');
            if (post_status) {
              post_status_json = Ext.util.JSON.decode(post_status.dom.innerHTML);
              if (post_status_json)
              {
                Ext.get('pc_status_json').remove();

                Grouply.alert(post_status_json['msg'], post_status_json['title']);
                              if (post_status_json['status'] == 1) {
                                  Grouply.popin.hide(SendEmail.currentPopin);
                                  Ext.get(SendEmail.currentPopin + '_content').dom.innerHTML = "";
                              }
                              
                var post_result_detail = Ext.get('post_result_detail');
                
			          if (post_result_detail) {
			            post_result_detail.remove();
			          }
			          
                return;
              }
            }
            
            
            error2 = Ext.get('replyerror_content');
            
            if (error2)
            {
              Ext.MessageBox.show({
                title : 'Cannot reply through Grouply',
                msg : error2.dom.innerHTML,
                buttons: Ext.MessageBox.OK,
                closable:true,
                progress:false,
                modal:true,
                width:300
                });
              Grouply.messageBox.fixYMapOverlap()
              error2.remove();
              return;
            }
            
            error = Ext.get('pc_error');
            
            if (!error){
              Grouply.popin.hide(SendEmail.currentPopin);
              Ext.get(SendEmail.currentPopin + '_content').dom.innerHTML = "";
              Grouply.alert('Your message has been sent.', 'Message Sent');
            } else
            {
              Grouply.alert('Unable to post message at this time.', 'System error');    
            }
            
            var post_result_detail = Ext.get('post_result_detail');
	          if (post_result_detail) {
	            post_result_detail.remove();
	          }
              
          }
          
        
        }, {params: sendparams});

    
    
    
  },
  postCaptcha : function()
  {
    Grouply.ajaxloadform("captchapopin_content", Ext.get("pc_captcha_form").dom, function()
      {
        Grouply.popin.hide('captchapopin');
        
        SendEmail.submitEmailForm();
      });
  },
  clearDefaultText : function (text, el)
  {
    
    if (el.value == text)
    {
      el.value = "";
      el.style.color = "black";
    }
  },
  
  showDefaultText : function (text, el)
  {
    if (el.value == "")
    {
      el.value = text;
      el.style.color = "grey";
    }
  },
  
  openEmailPopin : function(myid, params, customTitle, onhide, onshow)
  {
    if (typeof(CC) != 'undefined' && !CC.usersOnly())
    {
      return;
    }
    
    SendEmail.currentPopin = myid;
    Grouply.currentPopin=myid;
    if (customTitle)
    {
      Grouply.popin.setTitle(myid, customTitle);
    }
    
		Grouply.get(Grouply.currentPopin).get().on('hide', function(){
			if (!Ext.get(myid+'_content').dom.innerHTML) 
			{ 
				return; 
			}
			Ext.get('sendemailbutton').remove();
			Ext.get('cancelemailbutton').remove();
			if (Ext.get(myid + '_defaultcontent_json'))
			{
				Ext.get(myid + '_defaultcontent_json').remove();
			} else if (Ext.get(myid + '_defaultcontent'))
			{
				Ext.get(myid + '_defaultcontent').remove();
			}
      Grouply.unregister('sendemailbutton');
      Grouply.unregister('cancelemailbutton');
      Ext.get(myid+'_content').dom.innerHTML = '';
      if (typeof(onhide) == 'function')
      {
        onhide();
      }
    });
    
    if (!Grouply.get(Grouply.currentPopin).get().hasListener('show'))
    {
			Grouply.get(Grouply.currentPopin).get().on('show', 
            function(){ 
              Grouply.renderEditor(Grouply.currentPopin + "_editor");
              Grouply.renderComponent('sendemailbutton');
              Grouply.renderComponent('cancelemailbutton');
              if (el = document.getElementById(Grouply.currentPopin + '_defaultcontent_json'))
              {
                var data = Ext.util.JSON.decode(el.innerHTML);
                Grouply.editor.setValue(Grouply.currentPopin + '_editor', data.data);
              }
              else if (el = document.getElementById(Grouply.currentPopin + '_defaultcontent'))
              {
                var c = el.innerHTML;
                c = c.replace(/&lt;/g, "<");
                c = c.replace(/&gt;/g, ">");
                Grouply.editor.setValue(Grouply.currentPopin + '_editor', c);
              }
              
              Grouply.popin.resizeToContent(Grouply.currentPopin); 
              if (Grouply.get(Grouply.currentPopin + "_editor") && Grouply.get(Grouply.currentPopin + "_editor").selectText)
							{
								Grouply.get(Grouply.currentPopin + "_editor").selectText(0,0);
							}
             }, 
             Grouply.get(Grouply.currentPopin).get());
		}
    
    
    if (!params || params == '') // params set in component itself.
    {
      Grouply.popin.show(Grouply.currentPopin, document.body, 'c-c', function() { Grouply.popin.resizeToContent(Grouply.currentPopin);});
    } else
    {
      params = Grouply.addParam(params, 'page', myid);    
      Grouply.ajaxload(myid+'_content', CC.address + '/ajax/popin_sendemail.ajax', params, 
        function() {
          Grouply.get(Grouply.currentPopin).loaded=true;
          Grouply.popin.show(Grouply.currentPopin, document.body, 'c-c', function() { setTimeout("Grouply.popin.resizeToContent(Grouply.currentPopin);", 2000); });
        });
    }
    
  },
  
  getFormParams : function(obj) {
  	var params = {};
  	params['message'] = Grouply.editor.cleanValue(Grouply.currentPopin+"_editor");
  	params['sendas'] = eval(Grouply.currentPopin+"_editor"+"_code.style");
  	
    if (obj.copyme && obj.copyme.checked) {
      params['copyme'] = 'yes';
    }
    return params;
  },
  
  hidePopin : function()
  {
    Grouply.popin.hide(Grouply.currentPopin);
  },
  
  submitEmailForm : function(){
    SendEmail.sendEmail(document.getElementById('sendemailform'));
  },
  
  switchRecipient : function(el){
    if (el && el.id == 'send_to_group')
    {
      document.getElementById('sendmessage_subject').disabled=true;
      Grouply.showEl('sendmessage_attachments');
      Grouply.showEl('sendemail_notifymembers_ct');
      Grouply.showEl('sendemail_forcenotify_ct');
    } else
    {
      document.getElementById('sendmessage_subject').disabled=false;
      SendEmail.resetAttachments();
      Grouply.hideEl('sendmessage_attachments');
      Grouply.hideEl('sendemail_notifymembers_ct');
      Grouply.hideEl('sendemail_forcenotify_ct');
    }
    Grouply.popin.resizeToContent(SendEmail.currentPopin);
  },
  toggleNotifyMembers : function(el)
  {
		if (el.checked)
		{
			Grouply.showEl('sendemail_forcenotify_ct');
		} else
		{
			Grouply.hideEl('sendemail_forcenotify_ct');
		}
	},
    addAttachment : function () {
    var dh = Ext.DomHelper;
    dh.append('sendmsg_attachments_div', [
        {tag: 'div', id: 'sendmsg_att'+SendEmail.att_i, children: [
            {tag: 'input', type: 'file', name: 'fupl[]'},
            {tag: 'a', html: '[x]', cls: 'linkBlue11N', href: 'javascript:SendEmail.removeAttachment('+SendEmail.att_i+')'}
          ]
        }
    ]);
    SendEmail.att_i++;
    Grouply.popin.resizeToContent(SendEmail.currentPopin);
  },
  removeAttachment : function(att_i) {
    Ext.removeNode(Ext.getDom('sendmsg_att'+att_i));
  },
  resetAttachments : function() {
    for (var i = 0; i < SendEmail.att_i; i++) {
      SendEmail.removeAttachment(i);
    }
    SendEmail.att_i = 0;
  },
  showOpt : function (tid) {
    Grouply.showEl('edit'+tid);
    Grouply.hideEl('toggler_'+tid);
    Grouply.popin.resizeToContent(SendEmail.currentPopin);
  },
  hideOpt : function (tid, doresize) {
    Grouply.hideEl('edit'+tid);
    Grouply.showEl('toggler_'+tid);
    if (doresize) {
      Grouply.popin.resizeToContent(SendEmail.currrentPopin);
    }
  }
};
