if (!window.Idiom) {
    var Idiom = {};
}


Idiom.Page = Class.create();
Idiom.Page._ = {
    pages:{},
    defaultCls:'idiomPage',
    index:0,
    generatePageID:function(config) {
        config = config || {};
        if (config.pageID) {
            return config.pageID;
        }
        else {
            Idiom.Page.index++;
            return ('idiom_' + (Idiom.Page.index - 1));
        }

    },
    defaultProcessData:function(data, el) {
        el = el || document.createElement('div');
        el.innerHTML = data || '';
        return el;

    }

};

Idiom.Page.prototype = {
    initialize:function(config) {
        var page = this;
        this.config = config || {};


        if (this.config.pageID && Idiom.Page._.pages[this.config.pageID]) {
            throw new Error(this.config.pageID + ' : This pageID already exists');
        }

        this.pageID = Idiom.Page._.generatePageID(this.config);
        [ 'ele', 'url', 'text','before', 'after','processData'].each(function(param) {
            if (page.config[param]) {
                page[param] = page.config[param];
            }
        });

        //processData should be a function which takes data and a targetEle, and returns Processed Ele


        Idiom.Page._.pages[this.pageID] = this;

    },
    getEle:function(callback) {
        var page = this;

        if (!this.ele) {
            this.ele = document.createElement('div');
            Element.addClassName(this.ele, Idiom.Page._.defaultCls);
            if (this.config.cls) {
                Element.addClassName(this.ele, this.config.cls);
            }

            if (this.innerText) {
                this.ele.innerHTML = this.text;
            }
            if (this.url) {
                new Ajax.Request(this.url, {
                    method:'get',
                    onSuccess:function(transport) {

                        page.data = transport.responseText;
                        //                        console.log(page.data);
                        page.ele = (page.processData || Idiom.Page._.defaultProcessData)(page.data, page.ele, page.pageID);
                        callback(page);

                    },
                    onFailure:function(errTran) {
                        console.error(errTran);
                        console.log(errTran.responseText);
                    }
                });
            }
            else if (this.data) {
                page.ele = (page.processData || Idiom.Page._.defaultProcessData)(page.data, page.ele);
                callback(page);
            }
        }
        else {
            callback(page);
        }
        return this.ele;


    },
    refreshEle:function(callback) {
        this.ele = null;
        this.getEle(callback);
    }

};

new Idiom.Page({
    innerText:'please wait, loading page...',
    pageID:'_loading'
});





