/**
 * @overview This is an Ext i18n handler I found from http://elmasse.blogspot.com/2008/04/i18n-with-extjs-resource-bundle.html
 * I heavily modified the constructor of i18n.Bundle to be more flexible.
 * added documentation of @cfg params.
 * Chris Scott
 */

/**
 * @namespace Ext.i18n
 *
 */
Ext.namespace('Ext.i18n');

/**
 * Ext.data.PropertyReader
 * @param {Object} response
 */
Ext.data.PropertyReader = Ext.extend(Ext.data.DataReader,{
    propertySeparator: " ",

    read: function(response){
        var propertyFile = response.responseText;
        if (!propertyFile) {
            throw {
                message: "PropertyReader.read: File not found"
            };
        }
        return this.readRecords(propertyFile);
    },

    readRecords: function(propertyFile){
        var totalRecords = 0, success = true;
        var records = [];

        var f = this.readLines(propertyFile);

        for(var i = 0; i < f.length; i++){
            var key, value;
            kLim = f[i].indexOf(this.propertySeparator);
            key = String(f[i].substring(0, kLim));
            value = eval(f[i].substring(kLim+1));

            var record = new Ext.data.Record(value, key);
            records[i] = record;
        }
        return {
              success : success,
              records : records,
              totalRecords : f.length || totalRecords
        };
    },

    //private
    readLines: function(file){
        var aux = String(file).split('\n');
        var lines = new Array();

        for (var i = 0; i < aux.length; i++) {
            if (aux[i].indexOf("#") < 0 || (aux[i].indexOf("#") < aux[i].indexOf("\""))) {
                line = Ext.util.Format.trim(aux[i]);
                if (line.length > 0) {
                    lines.push(Ext.util.Format.trim(aux[i]));
                }
            }
        }
        return lines;
    }
});

/**
 * Ext.i18n.Bundle
 * @param {Object} config
 */
Ext.i18n.Bundle = function(config){
    config.bundle = config.bundle || this.bundle;
    config.path = config.path || this.path;
    config.resourceExt = config.resourceExt || this.resourceExt;
    config.language = this.guessLanguage();

    //this.language = this.guessLanguage();
    var url;
    if (config.path) {
        url = config.path + '/';
    }
    url+=config.bundle;

    // build proxy
    config.proxy = new Ext.data.HttpProxy({
        url: url,
        method: 'GET'
    });

    config.baseParams = {
        lang: config.language,
        extension: config.resourceExt
    };

    // build reader
    config.reader = new Ext.data.PropertyReader();

    // super
    Ext.i18n.Bundle.superclass.constructor.call(this, config);

    // load
    this.load();
    this.on('loadexception', this.loadParent);
};
Ext.extend(Ext.i18n.Bundle, Ext.data.Store,{
    /**
     * @cfg {String} defaultLanguage ['en-US']
     */
    defaultLanguage: 'en-US',

    /**
     * @cfg {Boolean} loadFlag [false]
     */
    loadFlag: false,

    /**
     * @cfg {String} resourceExt [.properties]
     */
    resourceExt: '.properties',

    /**
     * @cfg {String} bundle ['']
     */
    bundle: '',

    /**
     * @cfg {String} path [null]
     */
    path: null,

    /**
     * @cfg {String} id ['i18n']
     */
    id: 'i18n',

    //private
    guessLanguage: function(){
        return (navigator.language || navigator.browserLanguage
            || navigator.userLanguage || this.defaultLanguage);
    },

    getMsg: function(key){
        return this.getById(key)? this.getById(key).data : 'undefined';
    },

    onReady: function(fn){
        this.readyFn = fn;
        this.on('load', this.readyFn);
    },

    loadParent: function(){
        if(!this.loadFlag){
            this.loadFlag=true;
            var url;
            if (this.path) {
                url = this.path + '/';
            }
            url+=this.bundle+this.resourceExt;
            this.proxy = new Ext.data.HttpProxy({
                url: url,
                method: 'POST'
            });
            this.load();
        }
        else {
            throw {message: 'Resource Bundle not found'};
        }
    }
});
// alias method t() to getMsg()
Ext.i18n.Bundle.prototype.t = Ext.i18n.Bundle.prototype.getMsg;

