/**
 *
 *	Initialization ExtJS
 *	ExtJS version: 1.0 Beta 1
 *
 */


Ext.BLANK_IMAGE_URL = "ui/it/resources/s.gif";	// 1x1 picture, by default it is loaded from external site

/**
 * 	update BasicDialog, add a function which adds a delimiter between buttons
 * 	ExtJS version: 1.0 Beta 1
 */
Ext.override(Ext.BasicDialog, {
            addSeparator:function(){
                var dh = Ext.DomHelper;
                if(!this.footer){
                    this.footer = dh.append(this.bwrap.dom, {tag: 'div', cls:'ydlg-ft'}, true);
                }
                if(!this.btnContainer){
                    var tb = this.footer.createChild({
                        tag:'div',
                        cls:'ydlg-btns ydlg-btns-'+this.buttonAlign,
                        html:'<table cellspacing="0"><tbody><tr></tr></tbody></table>'
                    });
                    this.btnContainer = tb.dom.firstChild.firstChild.firstChild;
                }
                var td = document.createElement('td');
                var span = document.createElement('span');
                span.style.width="10px";
                span.style.repeat = "no-repeat";
                span.style.display = "block";
                span.style.overflow = "hidden";
                span.style.cursor = "default";
                span.style.border = "0px";
                td.appendChild(span);
                this.btnContainer.appendChild(td);
            }
});

/**
 * 	update Ext.Grid.GridView, add a condition for display on fields of context menu 'Columns'  with empty header
 * 	ExtJS version: 1.0 Beta, 1.1 RC1
 */
Ext.override(Ext.grid.GridView, {
    beforeColMenuShow : function(){
        var cm = this.cm,  colCount = cm.getColumnCount();
        this.colMenu.removeAll();
        for(var i = 0; i < colCount; i++){
            var header = cm.getColumnHeader(i);
            if  (header != '') {
                this.colMenu.add(new Ext.menu.CheckItem({
                    id: "col-"+cm.getColumnId(i),
                    text: header,
                    checked: !cm.isHidden(i),
                    hideOnClick:false
                }));
            }
        }
    }
});

Ext.override(Ext.grid.RowSelectionModel, {
    onRefresh : function(){
        var ds = this.grid.dataSource, i, v = this.grid.view;
        var s = this.selections;
        s.each(function(r){
            if((i = ds.indexOfId(r.id)) != -1){
                var index = s.indexOf(r);
                s.items[index] = ds.getAt(i);
                v.onRowSelect(i);
            } else {
                s.remove(r);
            }
        });
    }
});

/**
 *
 *	Patch for PagingToolbar.
 *	It will jump to last existen page if missed page has been loaded
 *	ExtJS version: 1.0 Beta 1
 *
 */

// Store original (non-overriden) method in prototype
Ext.PagingToolbar.prototype.onLoad_overriden = Ext.PagingToolbar.prototype.onLoad;

Ext.override(Ext.PagingToolbar, {
    onLoad : function(ds, r, o){

        if ((this.ds.getTotalCount() > 0) && (o.params.start >= this.ds.getTotalCount())) {
            var total = this.ds.getTotalCount();
            var extra = total % this.pageSize;
            var lastStart = extra ? (total - extra) : total-this.pageSize;
            this.ds.load({params:{start: lastStart, limit: this.pageSize}});
            return;
        }
        // Call original (non-overriden) method
        this.onLoad_overriden(ds, r, o);
    }
});


Ext.isEmptyObject = function(obj) {
    for(var i in obj) {
        return false;
    }

    return true;
};

ITechs = {
    displayMessages: function(messages, is_errors, fn, scope, callback_params) {
        var msg = "";
        for(var i=0; i < messages.length; i++) {
            if (i > 0) msg += "<br>";
            msg += messages[i];
        }
        if (msg != "") {
            var title = "Information";
            if (is_errors == true) {
                title = "Error";
            }
            Ext.MessageBox.alert(title, msg, fn, scope);
        } else if (!is_errors && typeof fn == 'function') {
            fn.apply(scope, callback_params);
        }
    },

    /*
    params = [{name: 'field1', value: '12'}]
    successfn = {scope: scopeObj, fn: functionCall}
    */
    request: function(url, params, successfn, oForm) {

        var processResponse = function(opt, result, response) {
            var _maskUnset = function(oForm, is_error, messages) {
                if (is_error == true) {
                    if (oForm.error_btn_ext) {
                        oForm.error_btn_ext.setVisible(true);
                        oForm.error_btn_ext.dom.setAttribute("errorsMessages", Ext.encode(messages));
                    }
                }
                ITechs.setFormMask(oForm, false);
            }

            if (result == true) {
                var res = Ext.decode(response.responseText);
                var cb = {};
                if (res.is_error != true && typeof successfn == 'object') {
                    cb.fn = successfn.fn ? successfn.fn : null;
                    cb.scope = successfn.scope ? successfn.scope : (typeof cb.fn == 'function' ? window : null);
                } else {
                    cb.fn = null;
                    cb.scope = null;
                }
                ITechs.displayMessages(res.messages, res.is_error, cb.fn, cb.scope, [res]);

                if (opt.fromForm) {
                    _maskUnset(opt.fromForm, res.is_error, res.messages);
                }
            } else {
                var messages = ['The requested operation cannot be completed because the connection has been broken.<br />Please try again later.'];
                var c_back = null;
                if (oForm) {
                    c_back = _maskUnset.createCallback(oForm, true, messages);
                };
                ITechs.displayMessages(messages, true, c_back);
            }
        };

        if (!params.length) {
            params = new Array();
        };

        if (oForm) {
            for (var i=0; i<oForm.elements.length; i++){
                oElement = oForm.elements[i];

                if((oElement.disabled || !oElement.name) && oForm.id != "framedTab") {
                    continue;
                }
                switch (oElement.type) {
                    case "radio":
                    case "checkbox":
                        if(!oElement.checked) {
                            break;
                        }
                    case "textarea":
                    case "password":
                    case "text":
                    case "hidden":
                        params.push({name: oElement.name, value: oElement.value});
                        break;

                    case "select-one":
                    case "select-multiple":
                        for(var j=0; j<oElement.options.length; j++){
                            if(oElement.options[j].selected) {
                                if(window.ActiveXObject) {
                                    params.push({name: oElement.name, value: oElement.options[j].attributes["value"].specified ? oElement.options[j].value : oElement.options[j].text});
                                } else {
                                    params.push({name: oElement.name, value: oElement.options[j].hasAttribute("value") ? oElement.options[j].value : oElement.options[j].text});
                                }
                            }
                        }
                        break;

                    /*case "file":
                    case undefined:
                    case "reset":
                    case "button":
                    case "submit":
                        break;*/
                }
            }
        }

        var pstr = "";
        for(i=0; i<params.length; i++) {
            if (pstr != '') {
                pstr += '&';
            }
            if (typeof params[i].value == 'object') {
                pstr += params[i].name + '=' + Ext.urlEncode(params[i].value);
            } else {
                pstr += params[i].name + '=' + encodeURIComponent(params[i].value);
            }
        }
        var conf = {
            method: 'POST',
            url: url,
            params: pstr,
            callback: processResponse,
            fromForm: oForm
        }
        ITechs.setFormMask(oForm, true);
        var Lconnect = new Ext.data.Connection(conf);
        Lconnect.request(conf);
    },

    setFormMask: function(oForm, setTo, returnMaskEl) {
        if (oForm) {
            var mask_el = null;
            if (oForm.getAttribute("setMaskOn")) {
                mask_el = Ext.get(oForm.getAttribute("setMaskOn"));
            }
            if (!mask_el){
                mask_el = Ext.get(oForm.parentNode);
                if (!mask_el) {
                    return false;
                }
            }
            if (setTo == true) {
                oForm.setAttribute("is_masked","true");
                mask_el.mask();
            } else {
                oForm.setAttribute("is_masked","false");
                mask_el.unmask();
            }
            if (returnMaskEl == true) {
                return mask_el;
            } else {
                return true;
            }
        } else {
            return false;
        }
    },

    submitForm: function(oForm, onSuccess) {
        if (!oForm || oForm.getAttribute("is_masked") == "true") {
            return false;
        }

        var error_btn = oForm.getAttribute("error_btn_id");
        if (!error_btn && error_btn != "empty") {
            var r = Ext.DomQuery.select("div.form_error_msg_btn", oForm);
            if (r[0]) {
                error_btn = Ext.id(r[0]);
                r = Ext.get(r[0]);
                r.dom.title = 'Click here to look error messages';
                r.dom.setAttribute("errorsMessages", Ext.encode([]));
                var t = function() {
                    var msgs = Ext.decode(this.getAttribute("errorsMessages"));
                    ITechs.displayMessages(msgs, true);
                }
                r.on('click', t, r.dom);
                r.addClassOnOver('active_el');


                oForm.error_btn_ext = r;

                r.setVisible(false);
                var mask_el = ITechs.setFormMask(oForm, false, true);
                if (mask_el) {
                    r.setXY([mask_el.getX() + mask_el.getWidth() - r.getWidth(), mask_el.getY()]);
                }
            } else {
                error_btn = "empty";
            }
            oForm.setAttribute("error_btn_id", error_btn);
        } else if (error_btn != "empty") {
            oForm.error_btn_ext.setVisible(false);
        }
        if (typeof onSuccess == 'function') {
            onSuccess = {
                fn: onSuccess,
                scope: window
            }
        }
        return ITechs.request(oForm.action, [], onSuccess, oForm);
    },

    getCookie : function(name) {
        var prefix = name + "="
        var cookieStartIndex = document.cookie.indexOf(prefix)
        if (cookieStartIndex == -1)
                return null
        var cookieEndIndex = document.cookie.indexOf(";", cookieStartIndex + prefix.length)
        if (cookieEndIndex == -1)
                cookieEndIndex = document.cookie.length
        return unescape(document.cookie.substring(cookieStartIndex + prefix.length, cookieEndIndex))
    }
}

try {
    if (_Session_info)  {
        if (_Session_info.name != '' && _Session_info.value != '' && !ITechs.getCookie[_Session_info.name]) {
            if (!ITechs.Ajax) ITechs.Ajax = {};
            ITechs.Ajax.realRequest = Ext.lib.Ajax.request;

            Ext.lib.Ajax.request = function(method, url, cb, params) {
                var _a = encodeURIComponent(_Session_info.name) + '=' + encodeURIComponent(_Session_info.value);
                if (method == "POST") {
                    if (params && params != '') params += '&' + _a;
                    else params = _a;
                } else {
                    if(url.indexOf("?") !== -1){
                        url += "&" + _a;
                    }else{
                        url += "?" + _a;
                    }
                }
                return ITechs.Ajax.realRequest(method, url, cb, params);
            };
        }
    }
} catch(e) {};

var GTT = {
    sP: function() {
        alert('Free!');
    }
};

Ext.data.Connection.prototype.handleResponseReal = Ext.data.Connection.prototype.handleResponse;
Ext.override(Ext.data.Connection, {
        handleResponse: function(response)
        {
            if (response.responseText == "LOGOUT") {
                document.location = 'logout.php';
            } else {
                this.handleResponseReal(response);
            }
        }
    }
);
ITechs.tabsManager = function() {
    this.tabs = [];
};
ITechs.tabsManager.prototype = {
    getPanel : function(panelName)
    {
        if (panelName && this.panels[panelName]) {
            return this.panels[panelName];
        }
        return false;
    },

    getTab : function(panelName, tabName)
    {
        if (panelName && tabName && this.panels[panelName]) {
            return this.panels[panelName].getTab(tabName);
        }
        return false;
    },

    banTab : function(tab)
    {
        if (tab) {
            tab.pnode.addClass("blocked_tab");
            tab._blocked = true;
        }
    },

    onTabSelect : function(tabpanel, ev, tab)
    {
        if (tab._blocked) {
            showFChBoxInfo();
            ev.cancel = true;
        }
    }
};

ITechs.gridsManager = function() {
    this.grids = [];
};
ITechs.gridsManager.prototype = {
    getGrid : function(gridName)
    {
        if (gridName && this.grids[gridName]) {
            return this.grids[gridName];
        }
        return false;
    },
    //this -> grid!!!
    loadingWrapper : function()
    {

    }
};
function separateString (str) {
    if (typeof str != 'string') {
        return str;
    }
    var al = str.length;

    if (al > 3) {
        var il = al/3;
        var shift = al - parseInt(il, 10)*3;
        if (shift == 0) {
            shift = 3;
        }

        var res = str.substr(0, shift);

        for (var i=1; i<il; i++) {
            res += ',' + str.substr(shift, 3);
            shift +=3;
        }

        str = res;
    }

    return str;
}
/**
 *
 * 	It does something like htmlspecialchars function in PHP.
 *
 * 	@param string - value
 * 	@return string - safely to show string
 *
 */
function htmlspecialchars(val) {
    if (val) {
        try {
            var res = val.replace(/&/g, "&amp;").
                        replace(/</g, "&lt;").
                        replace(/>/g, "&gt;").
                        replace(/\"/g, "&quot;").
                        replace(/\'/g, "&#039;");
            return res;
        } catch(e) {
            return '';
        }
    } else {
        return "";
    }
}

var showFChBoxInfo = function() {
    var fOpen = function() {
        var t = Ext.getDom('tabPanelSection1');
        Ext.get(t.lastChild).setVisible(false);
    };

    var fClose = function() {
        var t = Ext.getDom('tabPanelSection1');
        Ext.get(t.lastChild).setVisible(true);
    };

    Shadowbox.setup(Ext.getDom('free_info'), {onOpen: fOpen,onClose: fClose});
    Shadowbox.open(Ext.getDom('free_info'));
};

Shadowbox = null;

var linesReadyNotify = function(socket, id){};