/**
 *
 *	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

Ext.DialogManager.zseed = 20000;

/**
 * 	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, display_method) {
		display_method = (display_method) ? display_method : 'alert';
        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';
            }
            
            if(display_method == 'alert') {
            	Ext.MessageBox.alert(title, msg, fn, scope);
            } else if (display_method == 'box') {
            	Management.message.show(msg, null, fn, scope);
            } else {
            	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, failfn, 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 if (typeof failfn == 'object') {
                    cb.fn = failfn.fn ? failfn.fn : null;
                    cb.scope = failfn.scope ? failfn.scope : (typeof cb.fn == 'function' ? window : null);
                }                
                                
                ITechs.displayMessages(res.messages, res.is_error, cb.fn, cb.scope, [res], res.display_method);                

                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 (is_array_empty(params)) {
            params = new Array();
        }

        if (oForm) {
        	if (oForm.grabFields) {
	            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;*/
	                }
	            }
			}

			oForm.grabFields = null;
        }

        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,
            timeout: 60000,
            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('<img src="/ui/live/extjs/resources/images/default/grid/loading.gif" align="top" /> Loading...');
            } 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, onFail, curForm) {
    	if(oForm.constructor == Array && curForm) {
    		var formList = oForm;
    		var varNameList = new Array();
    		var params = new Array();

    		if (formList.length)
    		{
    			for(var k=0; k<formList.length; k++)
    			{
	                for (var i=0; i<formList[k].elements.length; i++)
	                {
	                	oElement = formList[k].elements[i];
	                    if((oElement.disabled || !oElement.name) && formList[k].id != "framedTab") {
	                        continue;
	                    }


	                    switch (oElement.type) {
		                    case "radio":
		                    case "checkbox":
		                        if(!oElement.checked) {
		                            break;
		                        }
		                    case "textarea":
		                    case "password":
		                    case "text":
		                    case "hidden":
		                    case "select-one":
		                    case "select-multiple":
		                    	if(varNameList[oElement.name] !== undefined || oElement.name == 'f[tab_name]')
		                    	{
		                    		break;
		                    	}
		                    	params.push({name: oElement.name, value: Ext.get(oElement).getValue()});
		                    	varNameList[oElement.name] = true;
		                        break;
	                    }

	                }
    			}
            }

            curForm.grabFields = false;

        } else {
        	curForm 		   = oForm;
        	curForm.grabFields = true;
        }

    	if (!curForm || curForm.getAttribute("is_masked") == "true") {
            return false;
        }

        var error_btn = curForm.getAttribute("error_btn_id");
        if (!error_btn && error_btn != "empty") {
            var r = Ext.DomQuery.select("div.form_error_msg_btn", curForm);
            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');


                curForm.error_btn_ext = r;

                r.setVisible(false);
                var mask_el = ITechs.setFormMask(curForm, false, true);
                if (mask_el) {
                    r.setXY([mask_el.getX() + mask_el.getWidth() - r.getWidth(), mask_el.getY()]);
                }
            } else {
                error_btn = "empty";
            }
            curForm.setAttribute("error_btn_id", error_btn);
        } else if (error_btn != "empty") {
            curForm.error_btn_ext.setVisible(false);
        }
        if (typeof onSuccess == 'function') {
            onSuccess = {
                fn: onSuccess,
                scope: window
            }
        }

        if (typeof onFail == 'function') {
            onFail = {
                fn: onFail,
                scope: window
            }
        }

        return ITechs.request(curForm.action, params, onSuccess, onFail, curForm);
    },

    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){};

/**
 * set up mask on page
 */
function maskElement(elementId){
    Ext.get(elementId).mask('<img src="/ui/live/extjs/resources/images/default/grid/loading.gif" align="top" /> Loading...');
    Ext.get(elementId).applyStyles({position: 'static'});
}

/**
 * unmask page
 */
function unMaskElement(elementId){
    Ext.get(elementId).unmask();
}

/**
 * Checks if a value exists in an array
 *
 * @param needle
 * @param haystack
 * @param strict
 * @return bool
 */
function in_array(needle, haystack, strict) {

    var found = false, key, strict = !!strict;

    for (key in haystack) {
        if ((strict && haystack[key] === needle) || (!strict && haystack[key] == needle)) {
            found = true;
            break;
        }
    }

    return found;
}

/**
 * Finds whether a variable is an array
 *
 * @param mixed_var
 * @return
 */
function is_array( mixed_var ) {

    return ( mixed_var instanceof Array );
}

/**
 * Determine whether a variable is empty
 * @param mixed_var
 * @return bool
 */
function empty( mixed_var ) {
    return ( mixed_var === "" || mixed_var === 0   || mixed_var === "0" || mixed_var === null  || mixed_var === false  ||  ( is_array(mixed_var) && mixed_var.length === 0 ) );
}

/**
 * Determine whether a variable is empty array
 * @param mixed_var
 * @return bool
 */
function is_array_empty( mixed_var ) {
    return ( !is_array(mixed_var) || mixed_var.length === 0);
}

/**
 * URL validator
 * 
 * @param url
 * @return bool
 */
function isValidURL(url) {
	var RegExp = /^(http|https|ftp):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(:(\d+))?((\/)?([A-Z0-9_\/.\-=#&@~ ]|%[A-Z0-9]{2,2})*(\?([A-Z0-9_\/=&,.:;~%\-+@!()\[\]|# ]|%[A-Z0-9]{2,2})*)?)$/i;
    if(RegExp.test(url)) {
        return true;
    } else {
        return false;
    }
} 