/**
 * Raxan (Rich Ajax Application) Startup script
 * Copyright (c) 2008 Raymond Irving (http://xwisdomhtml.com)
 *
 * Dual licensed under the MIT and LGPL licenses.
 * See the LICENSE.txt file
 *
 * Release Version: 0.2
 */



html = Raxan = { // html class object
    version: '0.2',
    path:'',
    pluginpath:'',
    csspath:'',
    arraycol: {},
    inc: {},
    rich: {}, //rich plugin namespace

    // initialize system
    init: function() {
        var js,st,m,src,code;
        var pth,tag,tags = document.getElementsByTagName('SCRIPT');
        this.cnt = 0; // set counter
        // get library path
        tag = tags[tags.length-1];
        src = tag.src + '';
        this.msie = navigator.userAgent.indexOf('MSIE')>=0;
        if (tag && (st=src.indexOf('startup.js'))>=0) {
            // setup paths
            pth = this.path = src.substr(0,st);
            this.csspath = pth + 'styles/';
            this.pluginpath = pth + 'plugins/';
            code = this.msie ? tag.text : tag.innerHTML;
            if (code && code.indexOf("\n")<0) { // check if script block is multi-line
                m = (new RegExp("\/(.*)\/")).exec(code);                
                if (m) { // setup main js file
                    if (m[1] && m[1].substr(m[1].length-2)=='/-') {    // support for path/-
                        js = this.filename().split(/\./);
                        js[js.length-1] = 'js';
                        js = m[1].replace(/\/-/,'/') + js.join('.');
                    }
                    else if (m[1] && m[1]!='-') {   //support for multiple comma saparated files
                        js = m[1].split(/,/);
                    }
                    else if(m[0] == '/-/'){
                        js = this.filename().split(/\./);
                        js[js.length-1] = 'js';
                        js = js.join('.');
                    }
                    this.mainScript = typeof js != 'string' ? js[0] : js;
                }
            }
        }
        if (js) this.include(js,true);
        else if (src && code) eval(code);
    },

    // initialize even handling after main scrips have been loaded
    initEvents: function() {
        if (this.pcbk) return this;
        this.pcbk = true;
        if (document.all) this.insertScript(this.path+'callback.js','text/javascript');
        else this.insertScript('html.callback()','text/javascript',true);
        return this;
    },

    // handle event callback
    callback: function(id){
        if (id) { // handle include callbacks
            this.inc[this.inc[id]]();
            return;
        }
        var load = function(e){ var i,l,a=html.collection('load'); l=a.length; for(i=0; i<l; i++) a[i](e); delete a };
        var unload = function(e){ var i,l,a=html.collection('unload'); l=a.length; for(i=0; i<l; i++) a[i](e); delete a };
        var ready = function(e){
            var i,l,a = html.collection('ready');
            l=a.length; for(i=0; i<l; i++) a[i](e); delete a
            a = html.collection('binds');
            l=a.length; for(i=0; i<l; i++) html.handleEvent(a[i][0],a[i][1],a[i][2]); delete a;
        }
        this.handlePageEvents(ready,load,unload);
    },

    // handle event binding
    handleEvent: function(css,evt,fn) {
        if (window.jQuery) jQuery(css).bind(evt,fn);
    },
    // handle page events ready, load, unload
    handlePageEvents: function(rdy,ld,uld) {
        var j,w = window;
        if (j=w.jQuery) {
            j(rdy); j(w).load(ld).unload(uld);
        } else {
            function e(n,f){
                if (w.addEventListener) w.addEventListener( n, f, false );
                else if (w.attachEvent) w.attachEvent( 'on'+n, f );
            }
            e('load',rdy); e('load',ld); e('unload',uld); e = null;
        }
    },

    // returns url parameters
    urlparams: function(){
        var a,o,n,nv;
        if (this._urlparams) return this._urlparams;
        else {
            a = (location+'').split(/\?/);
            o = {_url:a[0],_query:a[1]};
            nv =  a[1] ? a[1].split(/\&/) : null;
            if (nv) for(n in nv){
                a = nv[n].split(/\=/);
                o[a[0]]= a[1] ? unescape(a[1]) : '';
            }
            this._urlparams = o;
            return o;
        }
    },

    // returns html file name
    filename: function() {
        var f = ((location+'').split(/\?/))[0].split(/\//);
        f = f[f.length-1];
        return f;
    },

    // returns array from the collection object
    collection: function(name) {
        var c = this.arraycol;
        return  !c[name] ? c[name] = [] : c[name];
    },

    // register ready event. This is event normally triggered before onload
    ready: function(fn) {
        var a = this.collection('ready');
        a[a.length] = fn;
        return this.initEvents();
    },

    // register page load event
    load: function(fn){
        var a = this.collection('load');
        a[a.length] = fn;
        return this.initEvents();
     },

    // register page unload event
    unload: function(fn){
        var a = this.collection('unload');
        a[a.length] = fn;
        return this.initEvents();
    },

    /**
     * Bind a function to an event
     */
    bind: function(css,evt,fn){
        var a = this.collection('binds');
        a[a.length] = [css,evt,fn];
        return this.initEvents();
    },

    /**
     * Post data to the server
     */
    post: function (url,data){
        var i,f,str = '', id = 'frmWebData';
        var b = document.getElementsByTagName("body");
        if (!b) return this; else b = b[0];
        if (!(f=document.getElementById(id))) {
            f = document.createElement('form');
            f.setAttribute('id',id);
            f.setAttribute('name','frmWebData');
            f.setAttribute('method','post');
        }
        f.action = url;
        if (data) for (i in data)
            str += '<input name="'+i+'" type="hidden" />';
        f.innerHTML = str;
        b.appendChild(f);
        if (f && data) for (i in data) {
            f.elements[i].value = data[i];
        }
        f.submit();
        return this;
    },

    /**
     * Dynamically includes a CSS file
     */
    css:function(src,ext){
        var f,k = 'css'+src;
        if (src && !this.inc[k]) {   // check if already included
            f = !ext ? this.csspath + src + '.css' : src; // check if script is external
            this.insertScript(f,'text/stylesheet');
            if (src.toLowerCase()=='master' && document.all) // apply IE css master fixes
                document.write('<!--[if IE]><link rel="stylesheet" href="'+(this.csspath + src)+'.ie.css" type="text/css" media="screen, projection"><![endif]-->');
            this.inc[k] = true;
        }
        return this;
    },

    /**
     * Dynamically includes a Javascript file
     */
    include: function(src,extrn,fn) {
        var i,l,n,id,url;
        if (typeof src == 'string') src = [src];
        l = src.length;
        for (i=0; i<l; i++) {
            n = src[i] + '';
            if (n && !this.inc[n]) {   // check if already included
                url = !extrn ? this.pluginpath + n + '.js' : n;  // check if script is external
                this.inc[n] = fn ? fn : true;
                id = this.insertScript(url,'text/javascript');
            }
        }

        // trigger callback function
        if (typeof fn == 'function') {
            if (!id) fn();
            else {
                this.inc[id] = n;
                if (document.all) this.insertScript(this.path+'callback.js?'+id,'text/javascript');
                else this.insertScript('html.callback("'+id+'")','text/javascript',true);
            }
        }

        return this;
    },


    /**
     * Insert Script Tag into document
     */
    insertScript:  function(src,type,embedded) {
        var doc = document;
        var elm,id = 'xr'+ this.cnt++;
        var tag,headTag = doc.getElementsByTagName("head")[0];

        type = (type) ? type : 'text/javascript';

        if (headTag && doc.body) {
            // document loaded - append scripts/css
            if (type=='text/stylesheet') {
                elm = doc.createElement("link");
                elm.setAttribute("rel", 'stylesheet');
                elm.setAttribute("href", src);
            }
            else {
                elm = doc.createElement("script");
                elm.setAttribute('type',type);
                if(!embedded) elm.setAttribute("src", src);
                else {
                    if (doc.all) elm.innerHTML = src;
                    elm.appendChild(doc.createTextNode(src));
                }
            }
            elm.setAttribute("id", id);
            headTag.appendChild(elm);
            headTag.removeChild(elm);
        }
        else {
            // document not loaded - write scripts
            if(type=='text/stylesheet') { // css
                if (!embedded) tag = '<link id="'+ id +'" rel="stylesheet" href="'+ src +'"></link>';
                else tag = '<style id="'+ id +'" type="text/stylesheet">'+ src +'</style>';
            }
            else { // javascript
                if (!embedded) tag = '<script id="'+ id +'" type="'+ type +'" src="'+ src +'"><\/script>';
                else tag = '<script id="'+ id +'" type="'+ type +'">'+ src + '<\/script>';
            }
            document.write(tag);
        }

        return id;
    },

    // log to firebug console or window status
    log: function(txt) {
        if (window.console) console.log(txt);
        else status = txt;
    }



}

html.init();
window.rootpath = 'http://keo24.com/';
