Ext.UpdateManager.defaults.indicatorText = '<div class="loading-indicator">טוען עמוד...</div>';

function $(findBy){ return document.getElementById(findBy); }
function $v(findBy){ return $(findBy).value; }
function $trim(findBy) {
    var oEl = $(findBy);
    oEl.value = Ext.util.Format.trim(oEl.value);
    return oEl.value;
}

if(Ext.View){
   Ext.View.prototype.emptyText = "";
}

if(Ext.grid.Grid){
   Ext.grid.Grid.prototype.ddText = "{0} שורות מסומנות";
}

if(Ext.TabPanelItem){
   Ext.TabPanelItem.prototype.closeText = "סגור כרטיסיה זו";
}

if(Ext.form.Field){
   Ext.form.Field.prototype.invalidText = "הערך בשדה זה אינו תקין";
}

if(Ext.LoadMask){
    Ext.LoadMask.prototype.msg = "טוען...";
}

Date.monthNames = [
   "ינואר",
   "פברואר",
   "מרץ",
   "אפריל",
   "מאי",
   "יוני",
   "יולי",
   "אוגוסט",
   "ספטמבר",
   "אוקטובר",
   "נובמבר",
   "דצמבר"
];

Date.dayNames = [
   "א",
   "ב",
   "ג",
   "ד",
   "ה",
   "ו",
   "ש"
];

if(Ext.MessageBox){
   Ext.MessageBox.buttonText = {
      ok     : "אישור",
      cancel : "ביטול",
      yes    : "כן",
      no     : "לא"
   };
}

if(Ext.util.Format){
   Ext.util.Format.date = function(v, format){
      if(!v) return "";
      if(!(v instanceof Date)) v = new Date(Date.parse(v));
      return v.dateFormat(format || "d/m/Y");
   };
}

if(Ext.DatePicker){
   Ext.apply(Ext.DatePicker.prototype, {
      todayText         : "היום",
      minText           : "התאריך הנבחר נמוך מתאריך המינימום המותר",
      maxText           : "התאריך הנבחר גבוהה מתאריך המקסימות המותר",
      disabledDaysText  : "",
      disabledDatesText : "",
      monthNames	: Date.monthNames,
      dayNames		: Date.dayNames,
      nextText          : 'חודש הבא (Control+ימינה)',
      prevText          : 'חודש קודם (Control+שמאלה)',
      monthYearText     : 'בחרו תאריך (על מנת לעבור בין השנים(Control+למעלה/למטה)',
      todayTip          : "{0} (רווח)",
      format            : "d/m/y",
	  okText			: "אישור",
	  cancelText		: "ביטול"
   });
}

if(Ext.PagingToolbar){
   Ext.apply(Ext.PagingToolbar.prototype, {
      beforePageText : "עמוד",
      afterPageText  : "מתוך {0}",
      firstText      : "עמוד ראשון",
      prevText       : "עמוד קודם",
      nextText       : "עמוד הבא",
      lastText       : "עמוד אחרון",
      refreshText    : "רענן",
      displayMsg     : "מציג {0} - {1} מתוך {2}",
      emptyMsg       : 'אין מידע להצגה'
   });
}

if(Ext.form.TextField){
   Ext.apply(Ext.form.TextField.prototype, {
      minLengthText : "האורך המינימלי לשדה זה הינו {0}",
      maxLengthText : "האורך המירבי לשדה זה הינו {0}",
      blankText     : "שדה נדרש",
      regexText     : "",
      emptyText     : null
   });
}

if(Ext.form.NumberField){
   Ext.apply(Ext.form.NumberField.prototype, {
      minText : "הערך המינימלי לשדה זה הינו {0}",
      maxText : "הערך המקסימלי לשדה זה הינו {0}",
      nanText : "{0} אינו מספר תקין"
   });
}

if(Ext.form.DateField){
   Ext.apply(Ext.form.DateField.prototype, {
      disabledDaysText  : "מבוטל",
      disabledDatesText : "מבוטל",
      minText           : "התאריך בשדה זה חייב להיות לאחר {0}",
      maxText           : "התאריך בשדה זה חייב להיות לפני ה- {0}",
      invalidText       : "{0} אינו תאריך חוקי - יש להזין בסגנון הפרומט הבא: {1}",
      format            : "d/m/y"
   });
}

if(Ext.form.ComboBox){
   Ext.apply(Ext.form.ComboBox.prototype, {
      loadingText       : "טוען...",
      valueNotFoundText : undefined
   });
}

if(Ext.form.VTypes){
   Ext.apply(Ext.form.VTypes, {
      emailText    : 'שדה זה הינו שדה דוא"ל אשר צריך להיות מוזן בפורמט הבא: "user@domain.com"',
      urlText      : 'שדה זה הינו שדה כתובת אשר צריך להיות מוזן בפורמט הבא: "http:/'+'/www.domain.com"',
      alphaText    : 'This field should only contain letters and _',
      alphanumText : 'This field should only contain letters, numbers and _'
   });
}

if(Ext.grid.GridView){
   Ext.apply(Ext.grid.GridView.prototype, {
      sortAscText  : "מיון לפי סדר עולה",
      sortDescText : "מיון לפי סדר יורד",
      lockText     : "נעל עמודה",
      unlockText   : "שחרר עמודה",
      columnsText  : "עמודות"
   });
}

if(Ext.grid.PropertyColumnModel){
   Ext.apply(Ext.grid.PropertyColumnModel.prototype, {
      nameText   : "שם",
      valueText  : "ערך",
      dateFormat : "d/m/y"
   });
}

if(Ext.SplitLayoutRegion){
   Ext.apply(Ext.SplitLayoutRegion.prototype, {
      splitTip            : "גרור לשינוי גודל.",
      collapsibleSplitTip : "גרור לשינוי גודל. לחיצה כפולה להסתרה."
   });
}

/* Atarim Plus Code - Avi Malka */

Ext.override(Ext.form.TextField, {
	alignErrorIcon : function() {
		this.errorIcon.alignTo(this.el, 'tr-tl', [-3, 0]);
	}
});

Ext.override(Ext.form.DateField, {
	alignErrorIcon : function() {
		this.errorIcon.alignTo(this.el, 'tr-tl', [-20, 0]);
	}
});

Ext.override(Ext.form.ComboBox, {
	alignErrorIcon : function() {
		this.errorIcon.alignTo(this.el, 'tr-tl', [-20, 0]);
	}
});

Ext.override(Ext.form.Form, {
    render : function(ct){
        ct = Ext.get(ct);
        var o = this.autoCreate || {
            tag: 'div',
            //method : this.method || 'POST',
            id : this.id || Ext.id()
        };
        this.initEl(ct.createChild(o));

        this.root.render(this.el);

        this.items.each(function(f){
            f.render('x-form-el-'+f.id);
        });

        if(this.buttons.length > 0){
            // tables are required to maintain order and for correct IE layout
            var tb = this.el.createChild({cls:'x-form-btns-ct', cn: {
                cls:"x-form-btns x-form-btns-"+this.buttonAlign,
                html:'<table cellspacing="0"><tbody><tr></tr></tbody></table><div class="x-clear"></div>'
            }}, null, true);
            var tr = tb.getElementsByTagName('tr')[0];
            for(var i = 0, len = this.buttons.length; i < len; i++) {
                var b = this.buttons[i];
                var td = document.createElement('td');
                td.className = 'x-form-btn-td';
                b.render(tr.appendChild(td));
            }
        }
        if(this.monitorValid){ // initialize after render
            this.startMonitoring();
        }
        return this;
    }
});

Ext.override(Ext.form.Field, {
    onRender : function(ct, position){
		//return;
        if(this.el){
            this.el = Ext.get(this.el);
            if(!this.target){
                ct.dom.appendChild(this.el.dom);
            }
        }else {
            var cfg = this.getAutoCreate();
            if(!cfg.name){
                cfg.name = this.name || this.id;
            }
            if(this.inputType){
                cfg.type = this.inputType;
            }
            if(this.tabIndex !== undefined){
                cfg.tabIndex = this.tabIndex;
            }
            this.el = ct.createChild(cfg, position);

			//console.log(cfg);
        }
        var type = this.el.dom.type;
        if(type){
            if(type == 'password'){
                type = 'text';
            }
            this.el.addClass('x-form-'+type);
            if (this.qtip) this.el.set({ 'ext:qtip': this.qtip });
            if (this.textBelow) var tmpSpan = Ext.DomHelper.insertAfter(this.el.dom, {"tag": "p", "style": "font-size: 7pt; width: 224px; margin-top: 3px;"}, true).dom.innerHTML = this.textBelow;
        }
        if(!this.customSize && (this.width || this.height)){
            this.setSize(this.width || "", this.height || "");
        }
        if(this.readOnly){
            this.el.dom.readOnly = true;
        }

        this.el.addClass([this.fieldClass, this.cls]);
        this.initValue();
    }
});


Ext.override(Ext.form.Layout, {
    onRender : function(ct, position){
        if(this.el){ // from markup
            this.el = Ext.get(this.el);
        }else {  // generate
            var cfg = this.getAutoCreate();
            this.el = ct.createChild(cfg, position);
        }
        if(this.style){
            this.el.applyStyles(this.style);
        }
        if(this.labelAlign){
            this.el.addClass('x-form-label-'+this.labelAlign);
        }
        if(this.hideLabels){
            this.labelStyle = "display:none";
            this.elementStyle = "padding-right:0;";
        }else{
            if(typeof this.labelWidth == 'number'){
                this.labelStyle = "width:"+this.labelWidth+"px;";
                this.elementStyle = "padding-right:"+((this.labelWidth+(typeof this.labelPad == 'number' ? this.labelPad : 5))+'px')+";";
            }
            if(this.labelAlign == 'top'){
                this.labelStyle = "width:auto;";
                this.elementStyle = "padding-right:0;";
            }
        }
        var stack = this.stack;
        var slen = stack.length;
        if(slen > 0){
            if(!this.fieldTpl){
                var t = new Ext.Template(
                    '<div class="x-form-item {5}">',
                        '<label for="{0}" style="{2}">{1}{4}</label>',
                        '<div class="x-form-element" id="x-form-el-{0}" style="{3}">',
                        '</div>',
                    '</div><div class="x-form-clear-left"></div>'
                );
                t.disableFormats = true;
                t.compile();
                Ext.form.Layout.prototype.fieldTpl = t;
            }
            for(var i = 0; i < slen; i++) {
                if(stack[i].isFormField){
                    this.renderField(stack[i]);
                }else{
                    this.renderComponent(stack[i]);
                }
            }
        }
        if(this.clear){
            this.el.createChild({cls:'x-form-clear'});
        }
    }
});

Ext.override(Ext.menu.Menu, {
    render : function(){
        if(this.el){
            return;
        }
        var el = this.el = new Ext.Layer({
            cls: "x-menu",
            shadow:this.shadow,
            constrain: false,
            parentEl: this.parentEl || document.body,
            zindex:25000
        });

        this.keyNav = new Ext.menu.MenuNav(this);

        if(this.plain){
            el.addClass("x-menu-plain");
        }
        if(this.cls){
            el.addClass(this.cls);
        }
                this.focusEl = el.createChild({
            tag: "a", cls: "x-menu-focus", href: "#", onclick: "return false;", tabIndex:"-1"
        });
        var ul = el.createChild({tag: "ul", cls: "x-menu-list"});
        ul.on("click", this.onClick, this);
        ul.on("mouseover", this.onMouseOver, this);
        ul.on("mouseout", this.onMouseOut, this);
        this.items.each(function(item){
            var li = document.createElement("li");
            li.className = "x-menu-list-item";
            ul.dom.appendChild(li);
            item.render(li, this);
        }, this);
        this.ul = ul;
        this.autoWidth();
    }
});

Ext.override(Ext.data.HttpProxy, {
load : function(params, reader, callback, scope, arg){
		if(this.fireEvent("beforeload", this, params) !== false){
			if (params) params['noCache'] = new Date().getTime();
			var  o = {
				params : params || {noCache: new Date().getTime()},
				request: {
					callback : callback,
					scope : scope,
					arg : arg
				},
				reader: reader,
				callback : this.loadResponse,
				scope: this
			};
			if(this.useAjax){
				Ext.applyIf(o, this.conn);
				if(this.activeRequest){
					Ext.Ajax.abort(this.activeRequest);
				}
				this.activeRequest = Ext.Ajax.request(o);
			}else{
				this.conn.request(o);
			}
		}else{
			callback.call(scope||this, null, arg, false);
		}
	}
});

Ext.override(Ext.DatePicker, {
    createMonthPicker : function(){
        if(!this.monthPicker.dom.firstChild){
            var buf = ['<table border="0" cellspacing="0" style="direction: ltr;">'];
            for(var i = 0; i < 6; i++){
                buf.push(
                    '<tr><td class="x-date-mp-month"><a href="#">', this.monthNames[i].substr(0, 3), '</a></td>',
                    '<td class="x-date-mp-month x-date-mp-sep"><a href="#">', this.monthNames[i+6].substr(0, 3), '</a></td>',
                    i == 0 ?
                    '<td class="x-date-mp-ybtn" align="center"><a class="x-date-mp-prev"></a></td><td class="x-date-mp-ybtn" align="center"><a class="x-date-mp-next"></a></td></tr>' :
                    '<td class="x-date-mp-year"><a href="#"></a></td><td class="x-date-mp-year"><a href="#"></a></td></tr>'
                );
            }
            buf.push(
                '<tr class="x-date-mp-btns"><td colspan="4"><button type="button" class="x-date-mp-cancel">',
                    this.cancelText,
                    '</button><button type="button" class="x-date-mp-ok">',
                    this.okText,
                    '</button></td></tr>',
                '</table>'
            );
            this.monthPicker.update(buf.join(''));
            this.monthPicker.on('click', this.onMonthClick, this);
            this.monthPicker.on('dblclick', this.onMonthDblClick, this);

            this.mpMonths = this.monthPicker.select('td.x-date-mp-month');
            this.mpYears = this.monthPicker.select('td.x-date-mp-year');

            this.mpMonths.each(function(m, a, i){
                i += 1;
                if((i%2) == 0){
                    m.dom.xmonth = 5 + Math.round(i * .5);
                }else{
                    m.dom.xmonth = Math.round((i-1) * .5);
                }
            });
        }
    }
});