Ext.BLANK_IMAGE_URL = '/lib/extjs/resources/images/s.gif';

//검색 트리거
Ext.ux.SearchField = Ext.extend(Ext.form.TwinTriggerField, {
    initComponent: function(){
        Ext.ux.SearchField.superclass.initComponent.call(this);
        this.on('specialkey', function(f, e){
            if (e.getKey() == e.ENTER) {
                this.onTrigger2Click();
            }
        }, this);
    },
    
    validationEvent: false,
    validateOnBlur: false,
    trigger1Class: 'x-form-clear-trigger',
    trigger2Class: 'x-form-search-trigger',
    hideTrigger1: true,
    width: 180,
    hasSearch: false,
    paramName: 'searchWord',
    onTrigger1Click: function(){
    },
    onTrigger2Click: function(){
    }
});
Ext.reg('twintrigger', Ext.ux.SearchField);

/**
 * 사이클버튼
 */
Ext.override(Ext.CycleButton, {
    setActiveItem2: function(item, suppressEvent){
        if (item) {
            if (!this.rendered) {
                this.text = this.getItemText(item);
                this.iconCls = item.iconCls;
            }
            else {
                var t = this.getItemText(item);
                if (t) {
                    this.setText(t);
                }
                this.menu.items.itemAt(item.itemIndex).setChecked(true);
                this.setIconClass(item.iconCls);
            }
            this.activeItem = item;
            if (!suppressEvent) {
                this.fireEvent('change', this, item);
            }
        }
    }
});

/**
 * 폼 유효성체크
 */
Ext.form.BasicForm.override({
    isValid: function(){
        var valid = true;
        this.items.each(function(f){
            if (!f.validate() && valid == true) {
                valid = f;
            }
        });
        return valid;
    }
})

//탭닫기 플러그인
Ext.ux.TabCloseMenu = function(){
    var tabs, menu, ctxItem;
    this.init = function(tp){
        tabs = tp;
        tabs.on('contextmenu', onContextMenu);
    }
    
    function onContextMenu(ts, item, e){
        if (!menu) { // create context menu on first right click
            menu = new Ext.menu.Menu([{
                id: tabs.id + '-close',
                text: '탭 닫기',
                iconCls: 'icon-tab-close',
                handler: function(){
                    tabs.remove(ctxItem);
                }
            }, '-', {
                id: tabs.id + '-close-others',
                text: '다른탭 닫기',
                iconCls: 'icon-tab-close-other',
                handler: function(){
                    tabs.items.each(function(item){
                        if (item.closable && item != ctxItem) {
                            tabs.remove(item);
                        }
                    });
                }
            }, {
                id: tabs.id + '-close-all',
                text: '탭 전체닫기',
                iconCls: 'icon-tab-close-all',
                handler: function(){
                    tabs.items.each(function(item){
                        if (item.closable) {
                            tabs.remove(item);
                        }
                    });
                }
            }]);
        }
        ctxItem = item;
        var items = menu.items;
        items.get(tabs.id + '-close').setDisabled(!item.closable);
        var disableOthers = true;
        tabs.items.each(function(){
            if (this != item && this.closable) {
                disableOthers = false;
                return false;
            }
        });
        items.get(tabs.id + '-close-others').setDisabled(disableOthers);
        menu.showAt(e.getPoint());
    }
};

//라디오그룹 setValue 메서드 추가 >> 정리할떄 ext-all.js에 넣자
Ext.override(Ext.form.RadioGroup, {
    getName: function(){
        return this.items.first().getName();
    },
    
    getValue: function(){
        var v;
        
        this.items.each(function(item){
            v = item.getRawValue();
            return !item.getValue();
        });
        
        return v;
    },
    
    setValue: function(v){
        this.items.each(function(item){
            item.setValue(item.getRawValue() == v);
        });
    }
});


//원단위 환산 기능 추가
Ext.apply(Ext.util.Format, {
    wonMoney: function(v){
    
        v = (Math.round((v - 0) * 100)) / 100;
        v = String(v);
        var r = /(\d+)(\d{3})/;
        while (r.test(v)) {
            v = v.replace(r, '$1' + ',' + '$2');
        }
        if (v.charAt(0) == '-') {
            return '-' + v.substr(1);
        }
        return v;
    },
    numToStr: function(v){
        var numUnit1 = ['', '십', '백', '천'];
        var numUnit2 = ['', '만', '억', '조'];
        var numStr = ['', '일', '이', '삼', '사', '오', '육', '칠', '팔', '구'];
        var strAmount = '';
        var tmp;
        var exist = 0;
        for (var i = 0; i < v.length; i++) {
            tmp = v.substr(i, 1);
            if (tmp != 0) {
                strAmount += numStr[tmp] + numUnit1[((v.length - i - 1) % 4)];
                exist++;
            }
            if ((v.length - i - 1) % 4 == 0 && exist > 0) {
                strAmount += numUnit2[((v.length - i - 1) / 4)];
                exist = 0;
            }
        }
        return strAmount;
    }
});

/**
 * 프린트
 */
Ext.override(Ext.Element, {
    printCSS: '/lib/skin/blue/style.css',
    printStyle: false,
    printTitle: document.title,
    print: function(style, pageWidth, pageHeight, elStyle){
		this.printCSS = style;
        var el = Ext.get(this.id).dom;
        var c = document.getElementById('printcontainer');
        var iFrame = document.getElementById('printframe');
        var strTemplate = '<HTML><HEAD><link rel="stylesheet" type="text/css" href="{0}"/><TITLE>{1}</TITLE></HEAD><BODY onload="{2}"><DIV {3}>{4}</DIV></BODY></HTML>';
        var strAttr = '';
        var strFormat;
        var strHTML;
        if (iFrame != null) 
            c.removeChild(iFrame);
        if (c != null) 
            el.removeChild(c);
        for (var i = 0; i < el.attributes.length; i++) {
            if (Ext.isEmpty(el.attributes[i].value) || el.attributes[i].value.toLowerCase() != 'null') {
                strFormat = Ext.isEmpty(el.attributes[i].value) ? '{0}="true" ' : '{0}="{1}" ';
                if (this.printStyle ? this.printStyle : el.attributes[i].name.toLowerCase() != 'style') 
                    strAttr += String.format(strFormat, el.attributes[i].name, el.attributes[i].value);
            }
        }
        strHTML = String.format(strTemplate, Ext.isEmpty(this.printCSS) ? '#' : this.printCSS, this.printTitle, Ext.isIE ? 'document.execCommand(\'print\');' : 'window.print();', strAttr, el.innerHTML);
        c = document.createElement('div');
        c.setAttribute('style', 'width:0px;height:0px;visibility:hidden;');
        c.setAttribute('id', 'printcontainer');
        el.appendChild(c);
        if (Ext.isIE) 
            c.style.display = 'none';
        iFrame = document.createElement('iframe');
        iFrame.setAttribute('id', 'printframe');
        iFrame.setAttribute('name', 'printframe');
        c.appendChild(iFrame);
        iFrame.contentWindow.document.open();
        iFrame.contentWindow.document.write(strHTML);
        iFrame.contentWindow.document.close();
    }
    
});

Ext.override(Ext.Component, {
    printEl: function(config){
        this.el.print(Ext.isEmpty(config) ? this.initialConfig : config);
    },
    printBody: function(config){
        this.body.print(Ext.isEmpty(config) ? this.initialConfig : config);
    }
});
