// basic no record selected message
function messageNoRecordSelected() {
    var msg = PTJS_HANDLE_OBJECTS_MESSAGE_NO_RECORD_SELECTED_TEXT;

    if((arguments.length > 0) && arguments[0] != "") {
        msg = arguments[0];
    }

    Ext.MessageBox.hide();
    return Ext.Msg.show({
       title: PTJS_HANDLE_OBJECTS_MESSAGE_NO_RECORD_SELECTED_TITLE,
       msg: msg,
       width: 350,
       buttons: Ext.MessageBox.OK,
       multiline: false,
       icon: Ext.MessageBox.INFO
    });
}

// basic start transactions message
function messageStartTransaction() {
    var msg = PTJS_HANDLE_OBJECTS_MESSAGE_START_TRANSACTION_TEXT;

    if((arguments.length > 0) && arguments[0] != "") {
        msg = arguments[0];
    }

    return Ext.MessageBox.show({
        title: PTJS_HANDLE_OBJECTS_MESSAGE_START_TRANSACTION_TITLE,
        msg: msg,
        width:240,
        wait: true,
        progress:true,
        closable:false
    });
}

// basic success transactions message
function messageSuccessTransaction() {
    var msg = PTJS_HANDLE_OBJECTS_MESSAGE_SUCCESS_TRANSACTION_TEXT;

    if((arguments.length > 0) && arguments[0] != "") {
        msg = arguments[0];
    }

    Ext.MessageBox.hide();
    return Ext.Msg.show({
       title: PTJS_HANDLE_OBJECTS_MESSAGE_SUCCESS_TRANSACTION_TITLE,
       msg: msg,
       width: 350,
       buttons: Ext.MessageBox.OK,
       multiline: false,
       icon: Ext.MessageBox.INFO
    });
}

// basic failure transactions message
function messageFailureTransaction() {
    var msg = PTJS_HANDLE_OBJECTS_MESSAGE_FAILURE_TRANSACTION_TEXT;

    if((arguments.length > 0) && arguments[0] != "") {
        msg = arguments[0];
    }

    Ext.MessageBox.hide();
    return Ext.Msg.show({
       title: PTJS_HANDLE_OBJECTS_MESSAGE_FAILURE_TRANSACTION_TITLE,
       msg: msg,
       width: 350,
       buttons: Ext.MessageBox.OK,
       multiline: false,
       icon: Ext.MessageBox.WARNING
    });
}

// basic invalid transactions message
function messageInvalidTransaction() {
    var msg = PTJS_HANDLE_OBJECTS_MESSAGE_INVALID_TRANSACTION_TEXT;

    if((arguments.length > 0) && arguments[0] != "") {
        msg = arguments[0];
    }

    Ext.MessageBox.hide();

    return Ext.Msg.show({
       title: PTJS_HANDLE_OBJECTS_MESSAGE_INVALID_TRANSACTION_TITLE,
       msg: msg,
       width: 350,
       buttons: Ext.MessageBox.OK,
       multiline: false,
       icon: Ext.MessageBox.WARNING
    });
}

// load record data in form
function loadFormData(url, form, record, windowName) {
    var gridName = null;

    if(arguments.length==5) {
      gridName = arguments[4];
    }

    showWindowFormPanel(url, form, windowName, gridName);
    form.getForm().loadRecord(record);
}

// load form in blank
function newFormData(url, form, windowName, record) {
    var gridName = null;

    if(arguments.length==5) {
      gridName = arguments[4];
    }

    if(record!=null) {
        var tmp = record.copy();

        if(tmp!=null) {
            for(var i in tmp.data) {
                if(Ext.getCmp(i) && !Ext.getCmp(i).readOnly)
                    tmp.set(i, '');
            }

            loadFormData(url, form, tmp, windowName, gridName);
        }
        else {
            showWindowFormPanel(url, form, windowName, gridName);
        }
    }
    else {
        showWindowFormPanel(url, form, windowName, gridName);
        form.getForm().reset();
    }
}

// delegate to submit data form users
var submitPanelForm = function (args) {
    var basicForm = this.getForm();

    var url              = null;
    var nameWindowHandle = null;
    var nameGridHandle   = null;

    if(args.url) url = args.url;
    if(args.nameWindowHandle) nameWindowHandle = args.nameWindowHandle;
    if(args.nameGridHandle) nameGridHandle = args.nameGridHandle;

    messageStartTransaction();

    if(basicForm.isValid()) {
        basicForm.submit({
            url: url,
            method: 'post',
            scope: this,
            params: {},

            success: function(response, action) {
                 obj = Ext.util.JSON.decode(action.response.responseText);
                 if(obj.message) {
                     messageSuccessTransaction(obj.message);
                 }
                 else {
                     messageSuccessTransaction();
                 }

                 if(Ext.getCmp(nameWindowHandle).isVisible()) {
                     Ext.getCmp(nameWindowHandle).hide();
                     if(nameGridHandle!=null) {
                         var tmp = Ext.getCmp(nameGridHandle).getStore();
                         tmp.reload();
                     }
                 }
            },

            failure: function(response, action) {
                obj = Ext.util.JSON.decode(action.response.responseText);
                if(obj.message) {
                    messageFailureTransaction(obj.message);
                }
                else {
                    messageFailureTransaction();
                }

                if(Ext.getCmp(nameWindowHandle).isVisible()) {
                    Ext.getCmp(nameWindowHandle).hide();
                    var tmp = Ext.getCmp(nameGridHandle).getStore();
                    tmp.reload();
                }
            }
        });
    }
    else {
        messageInvalidTransaction();
    }
}

// function to show window form
function showWindowFormPanel(url, item, nameWindowHandle) {
    var title = PTJS_HANDLE_OBJECTS_FORMPANEL_TITLE;
    var nameGridHandle = null;

    if(arguments.length==4) {
        nameGridHandle = arguments[3];
        title += ' - [' + Ext.getCmp(nameGridHandle).title + ']';
    }

    args = {
        url: url,
        nameWindowHandle: nameWindowHandle,
        nameGridHandle: nameGridHandle
    };

    if(Ext.getCmp(nameWindowHandle)==null) {
        var windowPanel = new Ext.Window ({
            id: nameWindowHandle,
            title: title,
            layout: 'fit',
            width: 510,
            height: 380,
            closeAction: 'hide',
            plain: true,
            modal: true,
            buttonAlign: 'center',
            resizable: false,
            items: item,
            buttons: [
                {
                    id: 'windowButtonFormSend',
                    text: PTJS_HANDLE_OBJECTS_FORMPANEL_BUTTON_SUBMIT,
                    icon: '../public/images/icons/icon-save.gif',
                    iconCls: 'icon-save',
                    handler: submitPanelForm.createDelegate(item, [args])
                },

                {
                    id: 'windowButtonFormClose',
                    text: PTJS_HANDLE_OBJECTS_FORMPANEL_BUTTON_CLOSE,
                    icon: '../public/images/icons/icon-close.png',
                    iconCls: 'icon-close',
                    handler: function() {
                        Ext.getCmp(nameWindowHandle).hide();
                    }
                }
            ],

            listeners: {
                show: function() {
                    item.fireEvent('show', item);
                }
            }
        });
    }

    Ext.getCmp(nameWindowHandle).show();
}

// assyncronous call
function assyncronousCall(url, params, func) {
    messageStartTransaction();

    // Basic request
    var conn = Ext.Ajax.request({
        url: url,
        success: function(response, action) {
            obj = Ext.util.JSON.decode(response.responseText);
            if(obj.message) {
                messageSuccessTransaction(obj.message);
            }
            else {
                messageSuccessTransaction();
            }
        },

        failure: function(response, action) {
            obj = Ext.util.JSON.decode(response.responseText);
            if(obj.message) {
                messageFailureTransaction(obj.message);
            }
            else {
                messageFailureTransaction();
            }
        },
        params: params
    });

    Ext.Ajax.on('requestcomplete',
        function() {
            if(!Ext.Ajax.isLoading(conn)) {
                Ext.Ajax.purgeListeners();
                Ext.Ajax.abort(conn);
            }

            if(typeof(func)=='function') {
                func();
            }
        },
        this
    );

    return conn;
}

// result procedure
function resultProcedure(btn, func) {
    if(btn=='ok' || btn=='yes') {
        if(typeof(func)=='function') {
            func();
        }
    }
}

// question procedure
function questionProcedure(title, msg, func) {
    Ext.Msg.show({
        title: title,
        msg: msg,
        buttons: Ext.Msg.YESNO,
        fn: function(btn) {
            resultProcedure(btn, func);
        },
        icon: Ext.MessageBox.QUESTION
    });
}

// set values for combobox
function setValueComboBox(cmp, fieldValue) {
  if(arguments.length == 3) {
      displayValue = arguments[2];
  }
  else {
      displayValue = fieldValue;
  }

  try {
      Ext.getCmp(cmp).setValue(displayValue);
      Ext.getCmp(cmp).setRawValue(displayValue);

      Ext.getCmp(cmp).hiddenField.value = fieldValue;
  }
  catch(e) {
      //Ext.getCmp(cmp).setRawValue(value);
  }
}

// letti namespace
Ext.namespace('Ext.letti');

// tree combobox
Ext.letti.TreeCombobox = function(config) {
    var defaultConfig = {
        store: new Ext.data.SimpleStore({
            fields:[],
            data:[[]]
        }),

        // important! url to getting nodes
        dataUrl: '',

        editable: false,
        shadow: false,
        mode: 'local',
        triggerAction: 'all',
        maxHeight: 200,
        tpl: '<tpl for="."><div style="height:200px"><div id="tree1"></div></div></tpl>',
        selectedClass: '',
        anchor: '95%',
        onSelect: Ext.emptyFn
    };

    Ext.letti.TreeCombobox.superclass.constructor.call(this, Ext.apply(defaultConfig, config));

    this.on('expand', this._expand);
    this.on('render', this._render);
}

Ext.extend(Ext.letti.TreeCombobox, Ext.form.ComboBox, {
    // prevent infinite circular references
    ownersLoaded: new Array(),

    tree1: new Ext.tree.TreePanel({
        ownerId: 'letti-treecomboxbox',

        preloadChildren: true,

        loader: new Ext.tree.TreeLoader({
            dataUrl: '',

            listeners: {
                beforeload: function(treeLoader, node) {
                    treeLoader.baseParams.id = node.attributes.id;
                }
            }
        }),

        border: false,

        root: new Ext.tree.AsyncTreeNode({
            text: PTJS_HANDLE_OBJECTS_TREECOMBOBOX_ROOT_TEXT,
            id: 'null'
        }),

        listeners: {
            click: function(node, event) {
                Ext.getCmp(this.ownerId).setValue(node.text);
                Ext.getCmp(this.ownerId).hiddenField.value = node.id;
                Ext.getCmp(this.ownerId).collapse();

                Ext.getCmp(this.ownerId).fireEvent('select');
            },

            beforeexpandnode: function(node) {

            },

            expandnode: function(node) {
                var ow = this.ownerId;

                node.eachChild(function (childNode) {
                    if(Ext.getCmp(ow).ownersLoaded.in_array(childNode.id)) {
                        //childNode.disable();
                    }
                    else {
                        Ext.getCmp(ow).ownersLoaded[Ext.getCmp(ow).ownersLoaded.length] = childNode.id;
                        //childNode.expand(false, true);
                    }
                });

                if(parseInt(Ext.getCmp(ow).getValue())) {
                    var node = this.getNodeById(Ext.getCmp(ow).getValue());

                    if(node) {
                        Ext.getCmp(ow).setValue(node.text);
                        Ext.getCmp(ow).hiddenField.value = node.id;
                    }
                }
            }
        }
    }),

    initSelf: function() {

    },

    _render: function() {
        this.tree1.ownerId = this.getId();
        this.tree1.loader.dataUrl = this.dataUrl;
    },

    _expand: function() {
        this.tree1.render('tree1');
        //this.tree1.root.expand(false, true);

        this.ownersLoaded.length = 0;
    }
});
Ext.ComponentMgr.registerType('treecombobox', Ext.letti.TreeCombobox);

// refresh input file type
function refreshUploader(who) {
    try {
        var who2= who.cloneNode(false);

        who2.onchange= who.onchange;
        who.parentNode.replaceChild(who2, who);
    }
    catch(e) {

    }
}

/**
 * show layer image
 *
 * imageProps.uploaderID = input file component ID
 * imageProps.imgID = img component ID
 * imageProps.layerID = layer (container) ID
 * imageProps.removeID = checkbox to remove image
 * imageProps.imagePath = image path (directory)
 * imageProps.imageFile = image file
 *
 * action (hide, show)
 *
 **/
function showLayerImage(imageProps, action) {
    try {
        refreshUploader(Ext.getDom(imageProps.uploaderID));

        switch(action) {
            case 'show':
                if(imageProps.imageFile) {
                    Ext.getDom(imageProps.imgID).src = imageProps.imagePath + imageProps.imageFile;
                    Ext.getCmp(imageProps.layerID).show();

                    Ext.getCmp(imageProps.removeID).setValue(false);
                    Ext.getCmp(imageProps.removeID).show();
                }
                else {
                    showLayerImage(imageProps, 'hide');
                }

                break;

            case 'hide':
            default:
                Ext.getDom(imageProps.imgID).src = "";
                Ext.getCmp(imageProps.layerID).hide();

                Ext.getCmp(imageProps.removeID).setValue(false);
                Ext.getCmp(imageProps.removeID).hide();
                break
        }
    }
    catch(e) {

    }
}



