/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

Ext.BLANK_IMAGE_URL = '/images/s.gif';

Ext.form.DateField.prototype.format = 'd M Y';
Ext.grid.DateColumn.prototype.format = 'd M Y';
Ext.data.Field.prototype.dateFormat = 'd M Y';


Ext.override(Ext.form.NumberField, {
    /**
     * @cfg {Number} fixedPrecision A fixed precision to display after the decimal separator (defaults to -1)
     */
    fixedPrecision: -1,
    setValue : function(v){
        v = typeof v == 'number' ? v : parseFloat(String(v).replace(this.decimalSeparator, "."));
        if(isNaN(v)) {
            v = '';
        } else if(this.fixedPrecision != -1) {
            v = v.toFixed(this.fixedPrecision);
        }
        v = String(v).replace(".", this.decimalSeparator);
        Ext.form.NumberField.superclass.setValue.call(this, v);
    }
});



/****************************************************************/


/**
 * @version 0.4
 * @author nerdydude81
 */
Ext.override(Ext.Element, {
    /**
                     * @cfg {string} printCSS The file path of a CSS file for printout.
                     */
    printCSS: null
    /**
                     * @cfg {Boolean} printStyle Copy the style attribute of this element to the print iframe.
                     */
    ,
    printStyle: false
    /**
                     * @property {string} printTitle Page Title for printout.
                     */
    ,
    printTitle: document.title
    /**
                     * Prints this element.
                     *
                     * @param config {object} (optional)
                     */
    ,
    print: function(config) {
        Ext.apply(this, config);

        var el = Ext.get(this.id).dom;
        var c = document.getElementById('printcontainer');
        var iFrame = document.getElementById('printframe');

        var strTemplate = '<HTML><HEAD>{0}<TITLE>{1}</TITLE></HEAD><BODY onload="{2}"><DIV {3}>{4}</DIV></BODY></HTML>';
        var strLinkTpl = '<link rel="stylesheet" type="text/css" href="{0}"/>'
        var strAttr = '';
        var strFormat;
        var strHTML;

        //Get rid of the old crap so we don't copy it
        //to our iframe
        if (iFrame != null) c.removeChild(iFrame);
        if (c != null) el.removeChild(c);

        //Copy attributes from this element.
        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);
            }
        }

        var strLink ='';
        if(this.printCSS){
            if(!Ext.isArray(this.printCSS))
                this.printCSS = [this.printCSS];

            for(var i=0; i<this.printCSS.length; i++) {
                strLink += String.format(strLinkTpl, this.printCSS[i]);
            }
        }

        //Build our HTML document for the iframe
        strHTML = String.format(
            strTemplate
            , strLink
            , this.printTitle
            , Ext.isIE? 'document.execCommand(\'print\');': 'window.print();'
            , strAttr
            , el.innerHTML
            );

        //I coun't get FF to print a hidden iframe,
        //so I encapsulated it in a hidden div.
        c = document.createElement('div');
        c.setAttribute('style','width:0px;height:0px;' + (Ext.isSafari? 'display:none;': 'visibility:hidden;'));
        c.setAttribute('id', 'printcontainer');
        el.appendChild(c);

        //IE doesn't like style attributes anymore?
        if (Ext.isIE)
            c.style.display = 'none';

        iFrame = document.createElement('iframe');
        iFrame.setAttribute('id', 'printframe');
        iFrame.setAttribute('name', 'printframe');
        c.appendChild(iFrame);

        //Write our new document to the 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);
    }
});











//var defaultCurrency = '<?php echo $user->getCurrencyCode(); ?>';

function currencyRenderer(defaultCurrency) {
//    console.log(defaultCurrency)
    if(defaultCurrency == '2') {
        return 'euMoney';
    }
    else if(defaultCurrency == '3') {
        return 'usMoney'
    }
    else {
        return 'gbMoney';
    }
}
function currencySymbol(defaultCurrency) {


    if(defaultCurrency == '2') {
        return '&euro;';
    }
    else if(defaultCurrency == '3') {
        return '&#36;';
    }
    else {
        return '&pound;';
    }
}

Ext.apply(Ext.util.Format, {
    prettyInt: function(v){
        if(isNaN(parseInt(v))) {
            v = 0;
        }

        var pow, nStr, x, x1, x2;
        var dot = '';
        var rgx = /(\d+)(\d{3})/;
        var decimals = 0;
        //decimals = decimals || 0;
        pow = Math.pow(10, decimals);
        nStr = (parseFloat(Math.round(v*pow)) / pow).toString();
        if(decimals > 0) {
            dot = '.';
        }
        x = nStr.split('.');
        x1 = x[0];
        x2 = x.length > 1 ? x[1] : '';
        while(x2.length < decimals) {
            x2 += '0';
        }
        x2 = dot + x2;
        while (rgx.test(x1)) {
            x1 = x1.replace(rgx, '$1' + ',' + '$2');
        }
        return x1 + x2;
    },
    gbMoney5: function(v) {
        if(isNaN(parseInt(v))) {
            v = 0;
        }

        var pow, nStr, x, x1, x2;
        var dot = '';
        var rgx = /(\d+)(\d{3})/;
        var decimals = 5;
        //decimals = decimals || 0;
        pow = Math.pow(10, decimals);
        nStr = (parseFloat(Math.round(v*pow)) / pow).toString();
        if(decimals > 0) {
            dot = '.';
        }
        x = nStr.split('.');
        x1 = x[0];
        x2 = x.length > 1 ? x[1] : '';
        while(x2.length < decimals) {
            x2 += '0';
        }
        x2 = dot + x2;
        while (rgx.test(x1)) {
            x1 = x1.replace(rgx, '$1' + ',' + '$2');
        }
        return x1 + x2;
    },
    _generalMoney: function(v) {
        if(isNaN(parseInt(v))) {
            v = 0;
        }
        v = (Math.round((v-0)*1000))/1000;
        v = (v == Math.floor(v)) ? v + ".000"
        : (((v*10 == Math.floor(v*10)) ? v + "00"
            : ((v*100 == Math.floor(v*100)) ? v + "0" : v)));
        var ps = v.toString().split('.');
        var whole = ps[0];
        var sub = ps[1] ? '.'+ ps[1] : '.000';
        var r = /(\d+)(\d{3})/;
        while (r.test(whole)) {
            whole = whole.replace(r, '$1' + ',' + '$2');
        }
        v = whole + sub;
        if(v.charAt(0) == '-'){
            return '-#' + v.substr(1);
        }
        return "#" + v;
    },
    usMoney: function(v) {
        v = Ext.util.Format._generalMoney(v);
        return v.replace(/#/, '&#36;');
    },
    gbMoney: function(v) {
        v = Ext.util.Format._generalMoney(v);
        return v.replace(/#/, '&pound;');
    },
    euMoney: function(v) {
        v = Ext.util.Format._generalMoney(v);
        return v.replace(/#/, '&euro;');
    }
});

function addslashes(str) {
    return (str+'').replace(/([\\"'])/g, "\\$1").replace(/\0/g, "\\0");
}
function stripslashes( str ) {
    return (str+'').replace(/\\(.?)/g, function (s, n1) {
        switch(n1) {
            case '\\':
                return '\\';
            case '0':
                return '\0';
            case '':
                return '';
            default:
                return n1;
        }
    });
}




Ext.ns('OPC.util');

Ext.ns('OPC.comboData');

OPC.util.handleException = function(proxy, type, action, o, response, args){
    var msg;
    if(response.responseText) {
        var json = Ext.decode(response.responseText);
        if(json.message) {
            msg = json.message;
        }
    }
    Ext.MessageBox.alert("Error", msg);
}

OPC.util.createWritableComboStore = function(name) {

//            console.log(name + ':' + typeof combos_data[name]);

            return new Ext.data.Store({
                url: '/shared/combo_xhr.php'
                ,reader: new Ext.data.JsonReader({
                    fields: ['data_value', 'data_name', {name: 'count', type:'int'}],
                    idProperty: 'data_value',
                    root: 'data'
                })
                , writer: new Ext.data.JsonWriter({
                    encode: true,
                    writeAllFields: true,
                    listful:true
                })
                , baseParams: { task: name }
                , remoteSort: true
                , autoSave: false
                , data: { data: OPC.comboData[name] || [] }
                , sortInfo: {
                     field: 'data_name',
                     direction: 'ASC'
                }
                , listeners: {
                    exception: OPC.util.handleException
                }
            });
        }
