/**
 *
 *	Initialization ExtJS
 *	ExtJS version: 2.2
 *
 */
Ext.BLANK_IMAGE_URL = "ui/it/resources/s.gif";	/* 1x1 picture, by default it is loaded from external site */

/**
 * Check is object have any properties
 *
 * @param {object} obj
 *
 * @return bool
 */
function isEmpty(obj) {
    if (Ext.type(obj) != 'object') {
        return Ext.isEmpty(obj);
    }

    for(var prop in obj) {
        if(obj.hasOwnProperty(prop))
            return false;
    }

    return true;
}


/**
*
*  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 "";
   }
}

/**
 * urlencode the string
 *
 * @param {string} clearString
 * @return {string}
 */
function URLEncode(clearString) {
    if(!clearString){
        return '';
    }
    var clearString = encodeURIComponent(clearString);
    var re = /%20/g;
    return clearString.replace(re, '+');
}

/**
 * build URL by resource and action
 *
 * @param {string} resource
 * @param {string} action
 * @return {string} URL
 */
function buildURL(resource, action, params)
{
    params = params || {};
    if (typeof ROOT == "undefined") {
        ROOT = '';
    }
    if (ROOT != '' && ROOT != '/') {
        var app_root = ROOT + '/';
    } else {
        var app_root = '/';
    }
    if ('' == action) {
        return app_root + resource + '.php' + '?' + Ext.urlEncode(params);
    }
    return app_root + resource + '/' + action + '.php' + '?' + Ext.urlEncode(params);
}

/**
 * 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;
}

/**
 * show error message
 *
 * @param {string} text
 * @param {string} nodeId  Optional. Id of error message box
 * @return
 */
function showError(text, nodeId, commonMessager)
{
    commonMessager = commonMessager || false;
    var errorNode = !Ext.isEmpty(nodeId)
                    ? Ext.get(nodeId)
                    : Ext.get('errors_status_msg');

    if (errorNode && !errorNode.isDisplayed()) {
        errorNode.setDisplayed(true);
        errorNode.child('.cont').update(text);
    } else {
        if (commonMessager) {
            Messager.reset();
        }
        Messager.add(text);
        if (commonMessager) {
            Messager.show();
        }
    }
}

/**
 * show all errors
 *
 * @param {object} errors
 * @param {string} nodeId  Optional. Id of error message box
 *
 * @return
 */
function showErrors(errors, nodeId)
{
    Messager.reset();
    for (var i = 0; i < errors.length; i++) {
        showError(errors[i], nodeId, false);
    }
    Messager.show();
}

/**
 * mark qualified records
 *
 * @param {Ext.form.ComboBox} combo
 */
function markQualified(combo)
{
    var countItems = combo.list.dom.childNodes[0].childNodes.length;
    var dataStore = combo.getStore().data.items;

    for (var i = 0; i < countItems; i++) {
        if (typeof dataStore[i].data.qualified != 'undefined' && dataStore[i].data.qualified) {
            Ext.get(combo.list.dom.childNodes[0].childNodes[i]).addClass('qualified');
        }
    }
}

/**
 * object that contains templates for User, ...
 */
var Tpls = {

    user:   '<table cellspacing="0" cellpadding="0" border="0" align="left">' +
            '<tr>' +
                '<td style="text-align: left; width: 32px;">' +
                    '<tpl>' +
                        '<img src="/profile/download.php?id={photo_id}&size=medium" alt="" />' +
                    '</tpl>' +
                '</td>' +
                '<td style="padding-left:5px; text-align: left; white-space: nowrap;">' +
                    '<div style="text-overflow: ellipsis; overflow: hidden;">' +
                        '<tpl if="title_escaped">' +
                            '{title_escaped} ' +
                        '</tpl>' +
                        '{fname_escaped} {lname_escaped}' +
                    '</div>' +
                    '<div style="text-overflow: ellipsis; overflow: hidden; text-align: left;">' +
                        '<tpl if="Ext.isEmpty(values.is_deleted) || is_deleted==0">' +
                            '<tpl if="position_escaped">' +
                                '{position_escaped}' +
                                '<tpl if="company_escaped">' +
                                    ', ' +
                                '</tpl>' +
                                '<tpl if="!company_escaped">' +
                                    '<tpl if="country_escaped">' +
                                        ', ' +
                                    '</tpl>' +
                                '</tpl>' +
                            '</tpl>' +
                            '<tpl if="company_escaped">' +
                                '{company_escaped}' +
                                '<tpl if="country_escaped">' +
                                    ', ' +
                                '</tpl>' +
                            '</tpl>' +
                            '<tpl if="company_escaped">' +
                                '{country_escaped}' +
                            '</tpl>' +
                        '</tpl>' +
                        '<tpl if="!Ext.isEmpty(values.is_deleted) && is_deleted==1">' +
                            '&nbsp;' +
                        '</tpl>' +
                '</td>' +
            '</tr>' +
            '</table>'

};



Ext.lib.Event.resolveTextNode = Ext.isGecko ? function(node){
    if(!node){
        return;
    }
    var s = HTMLElement.prototype.toString.call(node);
    if(s == '[xpconnect wrapped native prototype]' || s == '[object XULElement]'){
        return;
    }
    return node.nodeType == 3 ? node.parentNode : node;
} : function(node){
    return node && node.nodeType == 3 ? node.parentNode : node;
};

/* Return new array with duplicate values removed */
Array.prototype.unique = function() {
    var a = [];
    var l = this.length;
    for(var i=0; i<l; i++) {
        for(var j=i+1; j<l; j++) {
            /* If this[i] is found later in the array */
            if (this[i] === this[j]) {
                j = ++i;
            }
        }
        a.push(this[i]);
    }
    return a;
};

Ext.override(Ext.form.TriggerField,  {
    onResize : function(w, h){
        Ext.form.TriggerField.superclass.onResize.call(this, w, h);
        var adjustWidth = 0;
        if(typeof w == 'number'){
            w = this.adjustWidth('input', w - this.trigger.getWidth());

            adjustWidth = Ext.isSafari ? 2 : 0;
            w+=adjustWidth;

            this.el.setWidth(w);
        }
        this.wrap.setWidth(this.el.getWidth()+this.trigger.getWidth()-adjustWidth);
    }
});

Ext.override(Ext.form.ComboBox,  {
    onKeyUp : function(e) {
        if (this.editable !== false && (!e.isSpecialKey() || e.getKey() == e.BACKSPACE)){
            if (e.getKey() == e.BACKSPACE) {
                e.stopEvent();
                this.collapse();
            }
            this.dqTask.delay(this.queryDelay);
        }

        e.stopEvent();
    }
});


/**
 * IE fix
 * array map support
 */
if (!Array.prototype.map)
{
  Array.prototype.map = function(fun /*, thisp*/)
  {
    var len = this.length;
    if (typeof fun != "function")
      throw new TypeError();

    var res = new Array(len);
    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in this)
        res[i] = fun.call(thisp, this[i], i, this);
    }

    return res;
  };
};



/**
 * IE fix
 *
 *
 * 0013047: Invitation LiteBox. IE7. browser show an error
 * Description 	1. login as sorriso@pisem.net
 * 2. go to Network->messages
 * 3. click Send Invitation
 * 4. put "asd"
 * 5. don't select user
 * 6. put after "asd" letter "d"
 */
(function(){
    var libFlyweight;

    function fly(el) {
        if (!libFlyweight) {
            libFlyweight = new Ext.Element.Flyweight();
        }
        libFlyweight.dom = el;
        return libFlyweight;
    }
    Ext.lib.Dom.getXY =  function(el) {
        var p, pe, b, scroll, bd = (document.body || document.documentElement);
        el = Ext.getDom(el);
        if(el == bd){
            return [0, 0];
        }
        if (el.getBoundingClientRect) {
            try{                                                 /* LB's code */
                b = el.getBoundingClientRect();
            }catch(ex){
                return [0,0];
            }
            scroll = fly(document).getScroll();
            return [b.left + scroll.left, b.top + scroll.top];
        }
        var x = 0, y = 0;
        p = el;
        var hasAbsolute = fly(el).getStyle("position") == "absolute";
        while (p) {
            x += p.offsetLeft;
            y += p.offsetTop;
            if (!hasAbsolute && fly(p).getStyle("position") == "absolute") {
                hasAbsolute = true;
            }
            if (Ext.isGecko) {
                pe = fly(p);
                var bt = parseInt(pe.getStyle("borderTopWidth"), 10) || 0;
                var bl = parseInt(pe.getStyle("borderLeftWidth"), 10) || 0;
                x += bl;
                y += bt;
                if (p != el && pe.getStyle('overflow') != 'visible') {
                    x += bl;
                    y += bt;
                }
            }
            p = p.offsetParent;
        }
        if (Ext.isSafari && hasAbsolute) {
            x -= bd.offsetLeft;
            y -= bd.offsetTop;
        }
        if (Ext.isGecko && !hasAbsolute) {
            var dbd = fly(bd);
            x += parseInt(dbd.getStyle("borderLeftWidth"), 10) || 0;
            y += parseInt(dbd.getStyle("borderTopWidth"), 10) || 0;
        }

        p = el.parentNode;
        while (p && p != bd) {
            if (!Ext.isOpera || (p.tagName != 'TR' && fly(p).getStyle("display") != "inline")) {
                x -= p.scrollLeft;
                y -= p.scrollTop;
            }
            p = p.parentNode;
        }
        return [x, y];
    }
})();


/**
 * fix bug: if anyMatch !== true then add $ to end regexp
 */
Ext.override(Ext.util.MixedCollection, {
    createValueMatcher : function(value, anyMatch, caseSensitive){
        if(!value.exec){ // not a regex
            value = String(value);
            value = new RegExp((anyMatch === true ? '' : '^') + Ext.escapeRe(value) + (anyMatch === true ? '' : '$'), caseSensitive ? '' : 'i');
        }
        return value;
    }
});

/**
 * update ExtJs library IE fix handleMouseMove function (actually ignore it)
 */
function updateDDMouseUp() {
    if (!Ext.dd.DragDropMgr.initialized) {
        setTimeout(updateDDMouseUp, 10);
    } else {
        Ext.EventManager.removeListener(document, "mousemove", Ext.dd.DragDropMgr.handleMouseMove, Ext.dd.DragDropMgr);
        Ext.dd.DragDropMgr.handleMouseMove = function(e) {
            if (! this.dragCurrent) {
                /* this.stopEvent(e); */
                return true;
            }
            /* check for IE mouseup outside of page boundary*/
            /*
             OUR CHANGES
            if (Ext.isIE && (e.button !== 0 && e.button !== 1 && e.button !== 2)) {
                this.stopEvent(e);
                return this.handleMouseUp(e);
            }
             END OF CHANGES
            */
            if (!this.dragThreshMet) {
                var diffX = Math.abs(this.startX - e.getPageX());
                var diffY = Math.abs(this.startY - e.getPageY());
                if (diffX > this.clickPixelThresh ||
                        diffY > this.clickPixelThresh) {
                    this.startDrag(this.startX, this.startY);
                }
            }

            if (this.dragThreshMet) {
                this.dragCurrent.b4Drag(e);
                this.dragCurrent.onDrag(e);
                if(!this.dragCurrent.moveOnly){
                    this.fireEvents(e, false);
                }
            }

            this.stopEvent(e);

            return true;
        };

        Ext.EventManager.on(document, "mousemove", Ext.dd.DragDropMgr.handleMouseMove, Ext.dd.DragDropMgr);
//        Ext.EventManager.on(document, "mousemove", function(e) { return true; });
//        document.onmousemove = function(e) {
//            Ext.dd.DragDropMgr.handleMouseMove(e);
//        }
    }
};
Ext.onReady(updateDDMouseUp);

