﻿Ext.onReady(function() {

    /*
    * Custom/Advanced vtypes (for form/field validation)
    */
    Ext.apply(Ext.form.VTypes, {

        /*see http://www.extjs.com/deploy/dev/examples/form/adv-vtypes.html*/
        password: function(val, field) {
            if (field.initialPassField) {
                var pwd = Ext.getCmp(field.initialPassField);
                return (val == pwd.getValue());
            }
            return true;
        },
        passwordText: 'Passwords do not match'

    });

    /*
    * Overrides the setValue function of an Ext ComboBox so you
    * can set both the display and data value without first
    * loading the combos data store. Preserves the hiddenValue also.
    * loadFromStore (optional) (default: false) - try's to get the display value from the 
    *                                             displayValue from the combo's store, based on 
    *                                             value (as the data value).
    */
    Ext.override(Ext.form.ComboBox, {
        setValue: function(value, displayValue, loadFromStore) {
            if (!displayValue) {
                if (loadFromStore) {
                    for (var i = 0; i < this.store.data.items.length; i++) {
                        if (eval('this.store.data.items[i].data.' + this.valueField) == value) {
                            displayValue = eval('this.store.data.items[i].data.' + this.displayField);
                            break;
                        }
                    }
                } else {
                    var si = this.selectedIndex || 0; if (si < 0) { si = 0; };
                    var r = this.getStore().getAt(si);
                    if (r && this.displayField) {
                        displayValue = eval('r.data.' + this.displayField);
                    } else { displayValue = value; };
                }
            }
            Ext.form.ComboBox.superclass.setValue.call(this, displayValue);
            this.lastSelectionText = displayValue;
            this.value = value;
            this.setRawValue(displayValue);
            if (this.hiddenName) {
                this.hiddenValue = value;
                var hiddenField = document.getElementById(this.hiddenName);
                if (hiddenField) { hiddenField.value = value; };
            };
        }
    });

    /* Changes the onclick bahaviour of nested/sub menu's, so that clicking 
    * opens the sub menu as well as hovering (instead of closing the menu down)
    * See http://extjs.com/forum/showthread.php?p=65389
    */
    Ext.override(Ext.menu.Menu, {
        onClick: function(e) {
            var t;
            if (t = this.findTargetItem(e)) {
                if (t.menu) {
                    t.expandMenu();
                } else {
                    t.onClick(e);
                    this.fireEvent("click", this, t, e);
                }
            }
        }
    });

    /*
     * sets every datefield to use a standard british date format "dd/mm/yyyy"
     */
    Ext.override(Ext.form.DateField, {
        format: 'd/m/Y'
//        ,getValue: function() {
//            var d = Ext.form.DateField.superclass.getValue.call(this) || "";
//            if (d.length > 10) { d = d.substring(0, 10); };
//            return d;
//        }
    });

});

/* Returns an object build from a simple JSON data structure */
function getJsonObject(data) {
    try { IbisUI.sessionMgr.resetKeepalive(); } catch (ex) { }
    try {
	    return eval('(' + data + ')');
    } catch (ex) {
	    return null;
    }
}

/*DEPRECATED - Use 'HttpDecode' in 'common.js' instead.*/
/*Decodes a string encoded in .NET with HttpUtility.UrlEncode*/
function decodeHttpUtilUrlEncode(text) {
    try {
	    var re = new RegExp('\\+', 'g');
	    text = text.replace(re, ' ');
	    return decodeURIComponent(text);
    } catch (ex) {
	    //if(debug){throw ex;}
	    return '';
    }
}

/*Shorthand/Wrapper for the Ext Component Manager get functin*/
function getExt(id) { return Ext.ComponentMgr.get(id); }

/* 
* Returns a form item (textfield, combo etc.) from an 
* ExtJs form object, by the items Id.
*/
function getExtFormItem(form, itemId) {
    var items;
    if (form.getForm) { items = form.getForm().items.items; } else { items = form.items.items; }
    for (var i = 0; i < items.length; i++) { if (items[i].id == itemId) { return items[i]; } }
    return null;
}

/*
 * Simple object that loads the HTTPresponse value from an UX.AJAXResponse.OutputType.Simple
 * for client side processing.
 */
SimpleResponse = function(responseObject, connectionParams) {

    this.response = responseObject;

    var r = responseObject.responseText.split('||');

    this.success = r[0];

    this.msg = decodeHttpUtilUrlEncode(r[1]);

    this.exception = decodeHttpUtilUrlEncode(r[2]);

    this.returnValue = decodeHttpUtilUrlEncode(r[3]);

    try {
        this.returnData = getJsonObject(r[4]);
    } catch (ex) {
        this.returnData = null;
    };

    this.params = connectionParams || null;

}

/*Simple AJAX call for common/basic server tasks
*Alerts the standard ActionResponse message on a failure and 
*calls back to a specified handler (optional) on success.
*/
ServerConnection = function(_url, scope, simpleResponse) {

    try { IbisUI.sessionMgr.resetKeepalive(); } catch (ex) { };

    this.conn = new Ext.data.Connection();

    this.url = _url;

    this.scope = scope;

    /* if the successful response is a 'simple' formatted response.
    * if not, the successful reponse wil just provide the entire response
    * text back to the calling success handler.
    * the failure response is always a simple response */
    this.simpleResponse = simpleResponse;

    this.doRequest = function(params, callbackOnSuccess, callbackOnFail) {
        this.conn.request({
            url: this.url,
            callbackScope: this.scope,
            simpleResponse: this.simpleResponse,
            method: 'POST',
            params: params,
            success: function(responseObject, req) {
                if (req.simpleResponse) {
                    var r = new SimpleResponse(responseObject);
                    if (r.success == 'true') {
                        if (callbackOnSuccess) { callbackOnSuccess.call(req.callbackScope, r, req.callbackScope); };
                    } else {
                        var m = r.msg;
                        if (m == undefined) { m = 'Error.'; };
                        Ext.MessageBox.show({ title: 'Error', msg: m, buttons: Ext.MessageBox.OK, icon: Ext.MessageBox.ERROR });
                    }
                } else {
                    if (callbackOnSuccess) { callbackOnSuccess.call(req.callbackScope, responseObject, req.callbackScope); };
                }
            },
            failure: function(responseObject, req) {
                var r = new SimpleResponse(responseObject);
                if (callbackOnFail) {
                    callbackOnFail.call(req.callbackScope, r, req.callbackScope)
                } else {
                    var m = r.msg;
                    if (m == undefined) { m = 'Error.'; };
                    ShowErrorMsg(m);
                }
            }
        });
    }

}

/* Generic Warning/Confirm Message/Prompt
*/
function showWarningPrompt(title, msg, fnCallback, useTable, scope) {

    if (!title) { title = 'Warning'; }

    if (useTable || msg.length > 200) {
	    //additional formatting for long messages
	    msg = '<table><tr><td>' + msg + '</td></tr></table>';
    }

    Ext.MessageBox.show({
	    title: title,
	    msg: msg,
	    buttons: Ext.MessageBox.YESNO,
	    icon: Ext.MessageBox.WARNING,
	    fn: fnCallback,
	    scope: scope
    });

}

/* Generic Error Message
* Includes links to the error reporting service
*/
function ShowErrorMsg(msg, title, err) {

    msg = decodeHttpUtilUrlEncode(msg);
    err = decodeHttpUtilUrlEncode(err);

    if (!title) { title = 'Error'; }

    if (msg.length > 200) {
	    //additional formatting for long messages
	    msg = '<table><tr><td>' + msg + '</td></tr></table>';
    }

    Ext.MessageBox.show({
	    title: title,
	    msg: msg,
	    buttons: { ok: 'Ok' },
	    icon: Ext.MessageBox.ERROR
    });

}

/* 
 * Generic Information Message
 */
function ShowInfoMsg(msg, title) {

    msg = decodeHttpUtilUrlEncode(msg);

    if (!title) { title = 'Information'; }

    if (msg.length > 200) {
	    //additional formatting for long messages
	    msg = '<table><tr><td>' + msg + '</td></tr></table>';
    }

    Ext.MessageBox.show({
	    title: title,
	    msg: msg,
	    buttons: { ok: 'Ok' },
	    icon: Ext.MessageBox.INFO
    });

}

