/*
 * Ext JS Library 3.0 RC1
 * Copyright(c) 2006-2009, Ext JS, LLC.
 * licensing@extjs.com
 *
 * http://extjs.com/license
 */
var emailWaitingMask;

var recordEmailInfo;
var getEmailInfo;
var simpleForm;

var emailWin;
var emailFieldEmailTo;
var emailLabelTo;
var emailFieldAdminEmail;
var emailFieldBCC;
var emailFieldEmailSubject;
var emailFieldEmailTemplate;
var emailFieldEmailMessageHtml;
var emailFieldEmailMessageTxt;
var emailFieldEmailPriority;
var emailFieldEmailConfirmReceipt;
var emailFieldFile;

//Ext.onReady(createEmailWin());

function createEmailWin(){
//  emailTo
    emailFieldEmailTo = new Ext.form.Hidden({
        id:               'emailFieldEmailTo',
        name:             'emailFieldEmailTo',
        value:            '',
        validationEvent:  false
    });
    
//  to
    emailLabelTo = new Ext.form.Label({
        id:         'emailLabelTo',
        name:       'emailLabelTo',
        fieldLabel: lang('To'),
        //labelStyle: "font-weight: bold;",
        text:       ''
        //style:      "font-weight: bold;"
    });
    
//  adminEmail
    emailFieldAdminEmail = new Ext.form.TextField({
        id:               'emailFieldAdminEmail',
        name:             'emailFieldAdminEmail',
        fieldLabel:       lang("From"),
        validationEvent:  false,
        anchor:           '98%',
        border:           false,
        value:            '',
        allowBlank:       false
    });
    
//  bcc
    var helpBCC = lang('Click on this checkbox if you want a BCC, Blind Carbon Copy, of this E-mail sent to you.');
    
    emailFieldBCC = new Ext.form.Checkbox({
        id:               'emailFieldBCC',
        name:             'emailFieldBCC',
        value:            false,
        validationEvent:  false,
        hideLabel:        true,
        boxLabel :        "<span style='text-decoration: underline; top: 0px;' class='tip-target' qtip='" + helpBCC.replace(/'/g, "&#39;") + "'>" + lang('BCC') + "</span>"
    });
    
//  emailSubject
    emailFieldEmailSubject = new Ext.form.TextField({
        id:               'emailFieldEmailSubject',
        name:             'emailFieldEmailSubject',
        fieldLabel:       lang("Subject"),
        validationEvent:  false,
        anchor:           '100%',
        border:           false,
        value:            '',
        allowBlank:       false
    });
    
//  emailtemplate
    templatestore = new Ext.data.JsonStore({
        id:             "templatestore",
        root:           'templates',
        totalProperty:  'totalcount',
        idProperty:     'id',
        remoteSort:     true,
        baseParams:     {
            filter:     "",
            customerid: "0"
        },
        fields:         [
            'templateId',
            'templateName'
        ],
        proxy:          new Ext.data.HttpProxy({
            url:  'index.php?fuse=clients&action=getEmailTemplates'
        })
    });
    
    templatestore.setDefaultSort('id', 'asc');
    
    templatestore.on('load', function(data){
        emailFieldEmailTemplate.setValue('none');
    });
    
    emailFieldEmailTemplate = new Ext.form.ComboBox({
        id:               'emailFieldEmailTemplate',
        name:             'emailFieldEmailTemplate',
        typeAhead:        true,
        triggerAction:    'all',
        lazyRender:       true,
        mode:             'local',
        validationEvent:  false,
        anchor:           '100%',
        fieldLabel:       lang("Template"),
        store:            templatestore,
        valueField:       'templateId',
        displayField:     'templateName',
        value:            'none',
        hiddenId:         'emailFieldEmailTemplateValue',
        hiddenName:       'emailFieldEmailTemplateValue',
        allowBlank:       false,
        blankText:        lang("This field is required"),
        forceSelection:   true,
        editable:         false
    });
    
    //emailFieldEmailTemplate.on('show', processResult(0));
    emailFieldEmailTemplate.on('select', changeTemplateType);
    
    function changeTemplateType(){
        Ext.MessageBox.show({
            title:    lang('Change Template?'),
            msg:      lang('Are you sure you want to change template.'),
            buttons:  Ext.Msg.YESNO,
            fn:       processResult,
            animEl:   'elId',
            icon:     Ext.MessageBox.QUESTION
        });
    }
    
    function processResult(change){
        if(change == 0 || change == 'yes'){
            new Ajax.Request(
                'index.php?fuse=clients&view=GetTemplate_Async',
                {
                    parameters: 'template=' + encodeURIComponent(emailFieldEmailTemplate.getValue()),
                    onComplete: retrieveTemplateSuccess
                }
            );
        }
    }
    
    function retrieveTemplateSuccess(t)
    {
        //get new plan information as well
        var response = t.responseText.split('||');
        if(response.length > 1){
            emailFieldEmailSubject.reset();
            emailFieldEmailSubject.setValue(response[1]);
            emailFieldEmailSubject.clearInvalid();
            
            if(recordEmailInfo != undefined && recordEmailInfo.get('isHtmlMails') == 1){
                emailFieldEmailMessageHtml.reset();
                emailFieldEmailMessageHtml.setValue(response[0]);
            }else{
                emailFieldEmailMessageTxt.reset();
                emailFieldEmailMessageTxt.setValue(response[0]);
            }
        }else{
            Ext.MessageBox.alert(lang("Errors"), lang('Can not retrieve template'));
        }
    }
    
//  emailMessage
    emailFieldEmailMessageHtml = new Ext.form.HtmlEditor({
        id:         'emailFieldEmailMessageHtml',
        name:       'emailFieldEmailMessageHtml',
        value:      '',
        hideLabel:  true,
        anchor:     '100%',
        height:     200,
        x:          5,
        y:          40,
        hideMode:   'offsets'
    });
    
    emailFieldEmailMessageTxt = new Ext.form.TextArea({
        id:         'emailFieldEmailMessageTxt',
        name:       'emailFieldEmailMessageTxt',
        value:      '{ADMINSIGNATURE}',
        hideLabel:  true,
        anchor:     '100%',
        height:     200
    });
    
//  emailpriority
    emailFieldEmailPriority = new Ext.form.ComboBox({
        id:               'emailFieldEmailPriority',
        name:             'emailFieldEmailPriority',
        typeAhead:        true,
        triggerAction:    'all',
        lazyRender:       true,
        mode:             'local',
        validationEvent:  false,
        width:            100,
        fieldLabel:       lang("Priority"),
        store:            new Ext.data.ArrayStore({
            idIndex:  0,
            fields:   [
                'id',
                'emailpriorityname'
            ],
            data:     [
                [
                    5,
                    lang("Low")
                ],
                [
                    3,
                    lang("Normal")
                ],
                [
                    1,
                    lang("High")
                ]
            ]
        }),
        valueField:       'id',
        displayField:     'emailpriorityname',
        value:            3,
        hiddenId:         'emailFieldEmailPriorityValue',
        hiddenName:       'emailFieldEmailPriorityValue',
        allowBlank:       false,
        blankText:        lang("This field is required"),
        forceSelection:   true,
        editable:         false
    });
    
//  emailconfirmreceipt
    emailFieldEmailConfirmReceipt = new Ext.form.ComboBox({
        id:               'emailFieldEmailConfirmReceipt',
        name:             'emailFieldEmailConfirmReceipt',
        typeAhead:        true,
        triggerAction:    'all',
        lazyRender:       true,
        mode:             'local',
        validationEvent:  false,
        width:            100,
        fieldLabel:       lang("Confirm Receipt"),
        store:            new Ext.data.ArrayStore({
            idIndex:  0,
            fields:   [
                'id',
                'emailconfirmreceiptname'
            ],
            data:     [
                [
                    0,
                    lang("No")
                ],
                [
                    1,
                    lang("Yes")
                ]
            ]
        }),
        valueField:       'id',
        displayField:     'emailconfirmreceiptname',
        value:            0,
        hiddenId:         'emailFieldEmailConfirmReceiptValue',
        hiddenName:       'emailFieldEmailConfirmReceiptValue',
        allowBlank:       false,
        blankText:        lang("This field is required"),
        forceSelection:   true,
        editable:         false
    });
    
//  file
    emailFieldFile = new Ext.ux.form.FileUploadField({
        id:               'emailFieldFile',
        name:             'emailFieldFile',
        fieldLabel:       '',
        validationEvent:  false,
        anchor:           '98%',
        labelStyle:       'height:27px;',
        border:           false,
        allowBlank:       true
    });
    
// form
    simpleForm = new Ext.FormPanel({
        //labelAlign:   'top',
        id:           'simpleForm',
        name:         'simpleForm',
        frame:        true,
        hideBorders:  true,
        shadow:       false,
        floating:     false,
        autoHeight:   true,
        title:        '',
        bodyStyle:    'padding:5px 5px 0',
        width:        600,
        items:        [
            emailFieldEmailTo,
            emailLabelTo,
            {
                layout: 'column',
                border: false,
                items:  [
                    {
                        columnWidth:  .9,
                        layout:       'form',
                        border:       false,
                        items:        [
                            emailFieldAdminEmail
                        ]
                    },
                    {
                        columnWidth:  .1,
                        layout:       'form',
                        border:       false,
                        items:        [
                            emailFieldBCC
                        ]
                    }
                ]
            },
            emailFieldEmailSubject,
            emailFieldEmailTemplate,
            emailFieldEmailMessageHtml,
            emailFieldEmailMessageTxt,
            {
                layout: 'column',
                border: false,
                items:  [
                    {
                        columnWidth:  .5,
                        layout:       'form',
                        border:       false,
                        items:        [
                            emailFieldEmailPriority
                        ]
                    },
                    {
                        columnWidth:  .5,
                        layout:       'form',
                        border:       false,
                        items:        [
                            emailFieldEmailConfirmReceipt
                        ]
                    }
                ]
            },
            emailFieldFile
        ]
    });
    
    //simpleForm.render(document.body);
    
// Window
    emailWin = new Ext.Window({
        id:           "emailWindow",
        y:            100,
        layout:       'fit',
        width:        620,
        autoHeight:   true,
        modal:        true,
        //closeAction:  'close',
        closable:     false,
        title:        lang("E-Mail Customer"),
        plain:        true,
        shadow:       false,
        items:        [simpleForm],
        buttons:      [
            {
                text:     'Close',
                handler:  function(){
                    emailWin.hide();
                    emailWin.destroy();
                }
            },
            {
                id:       'btnSendEmail',
                text:     lang("Send E-mail"),
                disabled: false,
                hidden:   false,
                handler:  function(){
                    sendEmail();
                }
            }
        ]
    });
    
    getEmailInfo = function(){
        var emailInfo = new Ext.data.JsonStore({
            id:             "emailInfo",
            root:           'emailinfo',
            totalProperty:  'totalcount',
            idProperty:     'id',
            remoteSort:     true,
            baseParams:     {},
            fields:         [
                'customerEmail',
                'customerName',
                'adminEmail',
                'isHtmlMails',
                'maxFileSize'
            ],
            proxy:          new Ext.data.HttpProxy({
                url: 'index.php?fuse=clients&action=getEmailInfo'
            })
        });
        
        emailInfo.on('load',function(){
            recordEmailInfo = emailInfo.getAt(0);
            
            emailFieldEmailTo.reset();
            emailFieldEmailTo.setValue(recordEmailInfo.get('customerEmail'));
            
            emailLabelTo.setText('"' + recordEmailInfo.get('customerName') + '" <' + recordEmailInfo.get('customerEmail') + '>');
            
            emailFieldAdminEmail.reset();
            emailFieldAdminEmail.setValue(recordEmailInfo.get('adminEmail'));
            
            var helpFile = lang('Max file size') + ': ' + recordEmailInfo.get('maxFileSize') + '<br><br>' + lang('Max file size limit can be changed in php.ini - directive <b>upload_max_filesize</b>');
            emailFieldFile.fieldLabel = "<span style='text-decoration: underline; top: 0px;' class='tip-target' qtip='" + helpFile.replace(/'/g, "&#39;") + "'>" + lang('Attach File') + "</span>";
            
            if(recordEmailInfo.get('isHtmlMails') == 1){
                emailFieldEmailMessageHtml.show();
                emailFieldEmailMessageTxt.hide();
            }else{
                emailFieldEmailMessageHtml.hide();
                emailFieldEmailMessageTxt.show();
            }
            
            emailFieldEmailTemplate.setValue('none');
            processResult(0);
            
            emailWin.enable();
            
            emailWin.show();
            
            // NEED TO CLEAR THE INVALID MESSAGES OF THE "EMAILFIELDADMINEMAIL"  AND "EMAILFIELDEMAILSUBJECT" FIELDS BECAUSE THEY CAN START WITH AN EMPTY VALUE
            emailFieldAdminEmail.clearInvalid();
            emailFieldEmailSubject.clearInvalid();
            
            if(recordEmailInfo.get('isHtmlMails') == 1){
                emailFieldEmailMessageHtml.focus(); // for some reason the focus get lost
            }else{
                emailFieldEmailMessageTxt.focus(); // for some reason the focus get lost
            }
        });
        
        emailInfo.load();
    }
}

function emailCustomer(){
    createEmailWin();
    getEmailInfo();
    templatestore.load();
}

function sendEmail(){
    if(emailFieldAdminEmail.validate()
      && emailFieldEmailSubject.validate()
      && emailFieldFile.validate()){
        
        emailWin.disable();
        
        var emailMessage = '';
        if(recordEmailInfo.get('isHtmlMails') == 1){
            emailMessage = emailFieldEmailMessageHtml.getValue();
        }else{
            emailMessage = emailFieldEmailMessageTxt.getValue();
        }
        
        showEmailWaitingMask();
        
        Ext.Ajax.request({
            form:     simpleForm.getForm().id,
            url:      'index.php?fuse=clients&action=sendEmail',
            isUpload: true,
            method:   'POST',
            params:   {
                adminEmail:           emailFieldAdminEmail.getValue(),
                bcc:                  emailFieldBCC.getValue(),
                emailSubject:         emailFieldEmailSubject.getValue(),
                emailMessage:         emailMessage,
                emailpriority:        emailFieldEmailPriority.getValue(),
                emailconfirmreceipt:  emailFieldEmailConfirmReceipt.getValue()
            },
            success:  onCompleteActionEmail,
            failure:  onCompleteActionEmail
        });
    }else{
        message = '';
        newline = "<br>";
        
        if(!emailFieldAdminEmail.validate()){
            if(message != ''){
                message += newline;
            }
            
            message += lang("From");
        }
        
        if(!emailFieldEmailSubject.validate()){
            if(message != ''){
                message += newline;
            }
            
            message += lang("Subject");
        }
        
        if(!emailFieldFile.validate()){
            if(message != ''){
                message += newline;
            }
            
            message += lang('Attach File');
        }
        
        if(message != ''){
            Ext.MessageBox.alert(lang("Errors"), lang("The following form field(s) were incomplete or incorrect") + ":<br><br>" + message + "<br><br>" + lang("Please complete or correct the form and submit again."));
            return;
        }
    }
}

function onCompleteActionEmail(responseObj){
    var data = Ext.util.JSON.decode(responseObj.responseText);
    
    hideEmailWaitingMask();
    emailWin.enable();
    
    if(data.error){
        if(data.message){
            Ext.MessageBox.alert(lang("Errors"), data.message);
        }else{
            Ext.MessageBox.alert(lang("Errors"), "There was an error performing this action");
        }
        return;
    }else if(data.message){
        msg(data.message,"");
    }else{
        msg(lang("Action have been performed"),"");
    }
    
    emailWin.hide();
    emailWin.destroy();
}

function showEmailWaitingMask(){
    emailWaitingMask = new Ext.LoadMask('emailWindow', {msg:"Please wait..."});
    
    emailWaitingMask.show();
}

function hideEmailWaitingMask(){
    emailWaitingMask.hide();
}