(function(){
    //Manipulate a single object

    var Cls = function(opts){
        var obj = opts.init;
        obj.constructor = Cls;
        obj.prototype.constructor = obj;

        return obj;
    }
    

    function _obj(el){
        this.element = '';
        this.storage = {};
        this.cache = {};

        for(var i=0; i < el.length; i++){
            var element = el[i];
            if(typeof element === 'string'){
                if(!this.cache[element]){
                    this.element = document.getElementById(element) ? document.getElementById(element) : '';
                    this.cache[element] = this.element;
                }else{
                    this.element = this.cache[element];
                }
            }else if(typeof element ==='object'){
                this.element = element;
            }
        }
    }

    _obj.prototype = {
        $call: function(fn){
            fn.call(this, this.element);
            return this;
        },

        get: function(){
            return this.element;
        },

        parent: function(){
            return obj(this.element.parentNode);
        },

        properties: function(){
            var width = this.element.offsetWidth;
            var height = this.element.offsetHeight;
            var top = this.element.offsetTop;
            var left = this.element.offsetLeft;
            var id = this.element.id;
            var klass = this.element.className
            var html = this.element.innerHTML

            return {
                width: width,
                height: height,
                top: top,
                left: left,
                id: id,
                klass: klass,
                html: html
            }
        },

        clone: function(){},

        css: function(styles){
            for(var s in styles){
            	if(this.element){
                	this.element.style[s] = styles[s];
                }
            }
            return this;
        },

        get_css: function(prop){
            return this.element.style[prop];
        },

        set_attribute: function(attrib, val){
            this.element[attrib] = val;
            return this;
        },

        get_attribute: function(attrib){
            return this.element[attrib];
        },

        add_event: function(type, fn){
            try{
                if(window.addEventListener){
                    this.element.addEventListener(type, fn, false);
                }else if(window.attachEvent){
                    this.element.attachEvent('on' + type, fn);
                }
                return this;
            }catch(e){}
        },

        remove_event: function(type, fn){
            if(window.removeEventListener){
                this.element.removeEventListener(type, fn, false);
            }else if(window.detachEvent){
                this.element.detachEvent('on' + type, fn);
            }
        },

        destroy: function(){
            try{
                if(this.element.parentNode){
                    this.element.parentNode.removeChild(this.element);
                }
            }catch(e){}
            return this;
        },

        get_dimensions: function(){
            var width = this.element.offsetWidth;
            var height = this.element.offsetHeight;
            return {
                h: height,
                w: width
            };
        },

        get_position: function(){
            var top = this.element.offsetTop;
            var left = this.element.offsetLeft;
            return {
                top: top,
                left: left
            };
        },

        get_coords: function(e){
            if(e || window.event){
                e = evnt.get_event(e);
            	
                return {
                    x: e.pageX ? e.pageX : window.event.clientX + document.body.scrollLeft,
                    y: e.pageY ? e.pageY : window.event.clientY + document.body.scrollTop
                }
            }
        },

        prepend: function(ele){
            this.element.insertBefore(ele);
        },

        append: function(ele){
            this.element.appendChild(ele);
        },
        
        html: function(cont){
            try{
                this.element.innerHTML = cont ? cont : this.element.innerHTML;
                return this.element.innerHTML;
            }catch(e){}
        },

        append_html: function(cont){
            this.element.innerHTML += cont;
        },

        add_class: function(cls){
            this.element.className += ' ' + cls;
        },

        remove_class: function(cls){
            for(var i=0, len=cls.length; i<len; i++){
                var check = new RegExp(cls[i]);
                this.element.className = this.element.className.replace(check, '');
            }
        },

        match: function(){},

        show: function(){
            this.element.style.display = 'block';
        },

        hide: function(){
            this.element.style.display = 'none';
        },

        type: function(){
            return typeof this.element;
        },

        toggle: function(){
            fx.animate(this.element, 'height', 0, this.get_dimensions().h);
        },

        next: function(){
            var next = this.element.nextSibling;
            next ? this.element.parentNode.insertBefore(next, this.element) : this.last();
        },

        previous: function(){
            var previous = this.element.previousSibling;
            previous ? this.element.parentNode.insertBefore(this.element, previous) : this.first();
        },

        first: function(){
            var first = this.element.parentNode.firstChild;
            this.element.parentNode.insertBefore(this.element, first);
        },

        last: function(){
            this.element.parentNode.appendChild(this.element);
        },

        drag: function(dir, container, connected_to, bounds){
            
            drag = this;
            var ele = this.element;
            var selected = '';
            drag.start_left = 0;
            drag.start_top = 0;
            drag.start_x = 0;
            drag.start_y = 0;
            drag.x_offset = 0;
            drag.y_offset = 0;
            drag.parent_x_offset = 0;
            drag.parent_y_offset = 0;
            var rleft;
            var rtop;
            
            if(container != null && bounds == ''){
                var bounds = {
                    left:container.get_position().left - 28,
                    right:((container.get_position().left - 28) + container.get_dimensions().w) - (obj(ele).get_dimensions().w + 8),
                    top:container.get_position().top,
                    bottom:(container.get_position().top + (container.get_dimensions().h - (obj(ele).get_dimensions().h + container.get_position().top)))
                }
            }

            obj(document).add_event('mousedown', function(e){
                e = evnt.get_event(e);
                var target = obj(evnt.get_target(e));

                if(target.get().id == ele.id){
                    selected = true;
                    var y_off;
                    var x_off;

                    if (browser.is_ie) {
                        y_off = e.clientY + document.body.scrollTop;
                        x_off = e.clientX + document.body.scrollLeft;
                    } else {
                        y_off = e.clientY + window.scrollY;
                        x_off = e.clientX + window.scrollX;
                    }
					
					
					
                    drag.y_offset = y_off - target.get_position().top;
                    drag.x_offset = x_off - target.get_position().left;

                    if(container != null){
                        var hextras = target.get_dimensions().h;
                        var wextras = target.get_dimensions().w;
                        var hdiff = container.get_dimensions().h - (connected_to.get_dimensions().h + 10);
                        var wdiff = container.get_dimensions().w - connected_to.get_dimensions().w;
                    }

                    if(connected_to != null){
                        hratio = hdiff * (1/(container.get_dimensions().h - (hextras)));
                        wratio = wdiff * (1/(container.get_dimensions().w - (wextras)));
                    }

                    obj(document).add_event('mousemove', function(e){
                        var target = obj(evnt.get_target(e));

                        if(selected){
                            var left;
                            var top;
                            if(dir == 'horizontal'){
                                rleft = (target.get_coords(e).x - drag.x_offset);
                                if(bounds){
                                    if(rleft < bounds.left){
                                        left = bounds.left + 'px';                                        
                                    }else if(rleft > bounds.right){
                                        left = bounds.right + 'px';
                                    }else{
                                        left = rleft + 'px';
                                    }
                                }else{
                                    left = rleft + 'px';
                                }

                                if(connected_to != null){
                                    connected_to.css({
                                        left: (parseInt(left) - bounds.left) * wratio + 'px'
                                    });
                                }

                                obj(ele).css({
                                    left: left
                                });
                                
                                //obj('debug').html(left);
                            }else if(dir == 'vertical'){
                                rtop = target.get_coords(e).y - drag.y_offset;

                                if(bounds){
                                    if(rtop < bounds.top){
                                        top = bounds.top + 'px';
                                    }else if(rtop > bounds.bottom){
                                        top = bounds.bottom + 'px';
                                    }else{
                                        top = rtop + 'px';
                                    }

                                    if(connected_to != null){
                                        connected_to.css({
                                            top: parseInt(top) * hratio + 'px'
                                        });
                                        //obj('debug').html(connected_to.get_position().top + ' - ' + connected_to.get_dimensions().h);
                                    }
                                }else{
                                    top = rtop + 'px';
                                }

                                obj(ele).css({
                                    top: top
                                });
                            }else{
                                obj(ele).css({
                                    left: (target.get_coords(e).x - drag.x_offset) + 'px',
                                    top: (target.get_coords(e).y - drag.y_offset) + 'px'
                                })
                            }
                        }
                    });

                    obj(document).add_event('mouseup', function(){
                        obj(document).add_event('mousemove', null);
                        selected = false;
                    });
                    
                    evnt.stop_event(e);

                }

                document.body.focus();

                document.onselectstart = function () {
                    return false;
                };

                target.ondragstart = function() {
                    return false;
                };

                return false;

            });

            
        },

        children_by_tag: function(tag){
            return this.element.getElementsByTagName(tag);
        },

        children: function(){
          return this.element.childNodes;
        },

        store_data: function(key, val){
            this.storage[key] = val;
        },

        get_data: function(key){
            alert(this.storage);
        }
    }

    window.obj = function(){
        return new _obj(arguments)
    }

    
    //Get collection by class
    function _by_class(els){
        this.elements = [];

    }

    _by_class.prototype = {}

    window.by_class = function(){
        return new _by_class(arugments);
    }


    //Get collection by tag
    function _by_tag(els){}

    _by_tag.prototype = {}

    window.by_tag = function(){
        return new _by_tag(arugments);
    }


    //Class function, starting only, needs lots of work

    function _class(el){
        this.element = '';
        this.queue = {};
        for(var i=0; i < el.length; i++){
            var element = el[i];
            if(typeof element === 'string'){
                this.element = element
            }else if(typeof element ==='object'){
                this.element = element;
            }
        }
    }

    _class.prototype = {
        set: function(key, val){
            this.queue[key] = val;
        },
        
        get: function(key){
            return this.queue[key];
        },

        create: function(methods, config){
            var proto = new _class('tmp');
            this.extend(proto, methods);
            this.config(proto, config);

            proto.init ? proto.init() : '';
            window[this.element] = proto;
            return window[this.element];
        },

        extend: function(proto, methods){
            for(var name in methods){
                proto[name] = methods[name];
            }
        },

        config: function(proto, config){
            for(var c in config){
                var def = proto.config[c];
                var conf = config[c];
                proto.config[c] = conf ? conf : def;
            }
        }
    }
    
    window.Class = function(){
        return new _class(arguments)
    }


    //Arrays
    function _array(arr){
        this.elements = arr;
    }

    _array.prototype = {
        each: function(fn){
            for(var i = 0, len = this.elements.length; i < len; i++){
                fn.call(this, this.elements[i]);
            }
        },

        map: function(){},

        grep: function(){},

        merge: function(arr1, arr2){},

        get: function(index){},

        set: function(index){},

        remove: function(index, range){},

        css: function(attribs){
            this.each(function(el){
                obj(el).css(attribs);
            });
        },

        add_event: function(type, fn){
            this.each(function(el){
                obj(el).add_event(type, fn);
            });
        }
    }

    window.Collection = function(arr){
        return new _array(arr);
    }

    //Timers
    Class('timer').create({
        config: {
            timers: [],
            timer_id: null
        },

        add: function(fn, interval){
            timer.start(interval);
        },

        stop: function(){
            clearInterval(timer.config.timer_id);
            timer.config.timer_id = 0;
        },

        start: function(interval){
            if(timer.config.timer_id){
                return false;
            }
            
            timer.config.timers.push(fn);

            (function(){
                for(var i = 0; i < timer.config.length; i++){
                    if(timer.config.timers[i]() == false){
                        timer.config.timers.splice(i,1);
                        i--;
                    }
                    timer.config.timer_id = setInterval(arguments.callee, interval);
                }
            })
        }
    })

    //Classes
    Class('xhr').create({
        init: function(){},

        config: {
            url: '/',
            method: 'get',
            callback: function(){},
            querystring: '',
            headers: {}
        },

        readystate: function(http, callback, caller, loader){
            http.onreadystatechange = function(){
                if(http.readyState == 4){
                    callback(http, caller);
                    if(loader){
                        loader.destroy();
                    }
                }
            }
        },

        call : function(qstring, callback, caller){
            var http = xhr.http();
            var url;
            if(xhr.config.method != 'post'){
                url = qstring ? xhr.config.url + '?' + qstring : xhr.config.url;
            }else{
                url = xhr.config.url;
            }
            var loader = '';
            try{
                loader = ui.create_element('', 'div', {id:'loader'}, '<img src="/images/icons/ajax-loader5.gif" />', 'visible');
                ui.center_ele(loader);
                /*var top = evnt.last_clicked.get_position().top + (evnt.last_clicked.get_dimensions().h/2) - (loader.get_dimensions().h/2) + 'px';
                var left = evnt.last_clicked.get_position().left - evnt.last_clicked.get().parentNode.offsetWidth - loader.get_dimensions().w + 'px';
                loader.css({
                    left: left,
                    top: top,
                    position: 'absolute'
                });*/
            }catch(e){}
            
            callback = callback ? callback : xhr.config.callback;
            
            xhr.readystate(http, callback, caller, loader);

            http.open(xhr.config.method, url, true);
            if(xhr.config.method == 'post'){
                http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                http.setRequestHeader("Content-Length", qstring ? qstring.length : 0);
            }
            xhr.headers(http)
            http.send(qstring || null);
        },

        headers: function(http){
            for(var key in xhr.config.headers){
                http.setRequestHeader(key, xhr.config.headers[key]);
            }
        },

        http: function(){
            return window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
        }
    });

    Class('evnt').create({
        last_clicked: '',

        get_event: function(e){
            return e || window.event;
        },
        
        get_target: function(e){
            var ele = e.target || e.srcElement;
            evnt.last_clicked = obj(ele);
            return ele;
        },
        
        stop_propagation: function(e){
            e.stopPropagation ? e.stopPropagation() : e.cancelBubble = true;
        },
        
        prevent_default: function(e){
            e.preventDefault ? e.preventDefault() : e.returnValue = false;
        },
        
        stop_event: function(e){
            evnt.stop_propagation(e);
            evnt.prevent_default(e);
        }
    });

    Class('json').create({
        eval_json: function(json){
            var sani_json;
            try{
                sani_json = eval("(" + json + ")");
            }catch(e){
                sani_json = {
                    error: 'There was an error loading this file.'
                };
            }

            return sani_json;
        },
        
        $try: function(json, val){
            if(!val){
                return json.error;
            }else{
                return val;
            }
        }
    })

    Class('browser').create({
        is_ie : navigator.userAgent.indexOf("MSIE") != -1 ? true : false,
        is_webkit: navigator.userAgent.indexOf(' AppleWebKit/') !== -1 ? true : false
    });

    Class('utils').create({
        get_by_class: function(name,tag){
            var returnArray = [];
            tag = tag || '*';
            var els = document.getElementsByTagName(tag);
            var pattern = new RegExp('(^|\\s)'+ name +'(\\s|$)');
            for (var i = 0; i < els.length; i++) {
                if ( pattern.test(els[i].className) ) {
                    returnArray.push(els[i]);
                }
            }
            return returnArray;
        },

        get_by_tag: function(tag){
            return document.getElementsByTagName(tag);
        },

        now: function(){
            return (new Date).getTime();
        },

        uid: function(){
            var uid = Math.random();
            return Math.round(uid * 100000);
        },

        create_querystring: function(form){
            var form_length = form.length;
            var qstring;
            for(i=0;i<form_length;i++){
                if(form.elements[i].name != '' && form.elements[i].name){
                    if (i > 0) {
                        qstring += "&" + form.elements[i].name + '=' + encodeURIComponent(form.elements[i].value);
                    }else{
                        qstring = form.elements[i].name + '=' + encodeURIComponent(form.elements[i].value);
                    }
                }
            }

            return qstring;
        },

        create_querystring_psuedo: function(form){
            var form_length = form.length;
            var qstring;
            for(i=0;i<form_length;i++){
                if(form[i].name != '' && form[i].name){
                    if (i > 0) {
                        qstring += "&" + form[i].name + '=' + encodeURIComponent(form[i].value);
                    }else{
                        qstring = form[i].name + '=' + encodeURIComponent(form[i].value);
                    }
                }
            }

            return qstring;
        },

        isNest: function(handler, e){
            if(e.type != 'mouseout' && e.type != 'mouseover'){
                return false;
            }

            var reltg = e.relatedTarget ? e.relatedTarget : e.type == 'mouseout' ? e.toElement : e.fromElement;
            while(reltg && reltg != handler){
                reltg = reltg.parentNode;
            }

            return (reltg != handler);
        }
    });

    
    Class('fx').create({
        timer: '',

        config: {
            duration: 600,
            fps: 60,
            tick: 0,
            rfps: Math.round(1000/this.fps)
        },

        animate: function(ele, elm, start, target, callback){
            var unit = (elm == 'opacity') ? '' : 'px';
            ele.style[elm] = start + unit;

            ele.style.overflow = "hidden";
            ele.style.visibility = "visible";
            
            var startTime = utils.now();
            fx.timer = window.setInterval(function(){
                fx.step(fx.config.duration, startTime, target, unit, elm, ele, start, callback)
            }, fx.config.rfps);
        },

        step: function(duration, startTime, target, unit, elm, ele, start, callback){
            elapsedTime = utils.now();
            if(elapsedTime > duration + startTime){
                window.clearInterval(fx.timer);
                if(ele.style[elm] != target){
                    ele.style[elm] = target + unit;
                }
                ele.style.overflow = 'hidden';
                callback ? callback() : false;
            }else{
                var curTime = elapsedTime - startTime;
                var curPos = curTime / duration;
                var diff = (target - start);
                var ease = fx.ease(curPos);
                var val = diff * ease + start;
                fx.increase(ele, elm, val, unit);
            }
        },

        ease: function(curPos){
            return (-(Math.cos(Math.PI * curPos) - 1) / 2);
            //return Math.pow(2, 8 * (curPos - 1));
            //return 1 - Math.sin(Math.acos(curPos));
        },

        increase: function(ele, elm, val, unit){
        	if(elm != 'opacity'){
            	ele.style[elm] = val + unit;
            }else{
            	var dec = val;
            	dec = val/100;
            	
            	obj('debug').html = dec;
            	ele.style.opacity = dec;
            	//ele.style.filter = "alpha(opacity=" + val + ")";
            }
        }
    });

    Class('core').create({
        include: function(path, pos){
            var head = utils.get_by_tag('HEAD')[0] || document.documentElement;

            var script = ui.create_element(head, 'script', {
                src: path,
                'type': 'text/javascript'
            },{},'');
            pos = 'top' ? head.insertBefore(script, head.childNodes[1]) : head.appendChild(script);
        },

        view: function(){
            return location.pathname.split('/')[1];
        }
    });

    Class('ui').create({
        rows: [],
        layers: {},
        zindex: 500000000,
        running: false,
        message: '',
        loaded: false,

        config: function(){
            xhr.config.method = 'get';
            xhr.config.url = '/ui/config';
            xhr.config.callback = function(http){
                var response = json.eval_json(http.responseText);
                window.ui_config = response;
                try{
                    var url = location.pathname.split('/')[1];
                    ui_config.config.view = url;
                    ui.selected(url);

                    if(!obj('site').get()){
                        ui.load_script(url);
                    }
                }catch(e){}
            }
            xhr.call()
        },

        selected: function(url){
            obj(url + '-link').set_attribute('className','selected');
        },

        load_script: function(view){
            core.include('/js/' + view + '.js', 'bottom');
            view.init();
        },

        stripe: function(parent, element, color1, color2, hover){
            if(obj(parent).get()){
                var ele_list = obj(parent).children_by_tag(element);
                for(var i=0, node; node = ele_list[i++];){
                    var color = i%2 == 0 ? 'stripe2' : 'stripe1';
                    if(node.parentNode.id == parent){
                        var ele = obj(node);
                        ele.set_attribute('className', color);
                    }
                }
                i = 0;
            }
        },

        highlights: function(){
            Collection(utils.get_by_tag('INPUT')).add_event('focus', ui.input_highlight);
            Collection(utils.get_by_tag('INPUT')).add_event('blur', ui.input_unhighlight);
            Collection(utils.get_by_tag('SELECT')).add_event('focus', ui.input_highlight);
            Collection(utils.get_by_tag('SELECT')).add_event('blur', ui.input_unhighlight);
        },


        input_highlight: function(e){
            e = e || window.event;
            var rele = e.target || e.srcElement;
            var ele = obj(rele);

            var border_color = '';
            var back_color = '';
            var font_color = '';
            var check = new RegExp('(.*)req(.*)');
            if(check.test(ele.get_attribute('className'))){
                border_color = '#ce7b3d';
                back_color = '#ffe1cb';
                font_color = '#444444';
                ui.message = ui.create_element(ele.get().parentNode,'span',{
                    id:'required_message'
                },'*Required','visible');
                var top = ele.get_position().top - ele.get_dimensions().h + 'px';
                var left = ele.get_position().left + ele.get_dimensions().w - 6 + 'px';
                ui.message.css({
                    top: top + 'px',
                    left: left
                });
            }else{
                border_color = '#9e9999';
                back_color = '#c1c1c1';
                font_color = '#111111';
            }

            ele.css({
                borderColor:border_color,
                backgroundColor: back_color,
                borderWidth: '3px',
                color: font_color
            });
        },

        input_unhighlight: function(e){
            e = e || window.event;
            var rele = e.target || e.srcElement;
            var ele = obj(rele);

            var check = new RegExp('(.*)req(.*)');
            if(check.test(ele.get_attribute('className'))){
                ui.message.destroy();
            }
            ele.css({
                borderColor:'#c8c8c8',
                backgroundColor: '#e8e8e8',
                borderWidth: '3px',
                color: '#636363'
            });
        },

        validate: function(form){
            var form_ele = form.get().elements;
            var errors = [];
            for(var i=0, len=form_ele.lenght; i < len; i++){
                var ele = obj(arr[i]);
                var test = /\="(.*)\req(.*)\"/.test(ele.get(),className);
                if(ele.get().value == '' && test){
                    ele.css({
                        borderColor:'#ce7b3d',
                        borderWidth: '3px'
                    });
                    errors.push(ele.get().name);
                }
            }
            return errors.length > 0 ? errors : true;
        },

        //Create an element or new row

        create_element: function(parent, ele, attrib_arr, cont, visible, pos){
            pos = pos ? pos : 'append';
            visible = visible != 'hidden' ? 'visible' : visible;

            var parentele = parent || document.getElementsByTagName('body')[0];
            var nele 	= document.createElement(ele);

            for (var key in attrib_arr) {
                nele.setAttribute(key, attrib_arr[key]);
            }

            var new_ele = obj(nele);
            new_ele.html(cont);
            if(pos == 'append'){
                obj(parentele).append(nele);
            }else if(pos == 'prepend'){
                obj(parentele).prepend(nele);
            }
            return new_ele;
        },

        center_ele: function(ele){
            eleHeight = ele.get_dimensions().h;
            eleWidth = ele.get_dimensions().w
            ;
            var windowH = window.innerHeight || document.documentElement.clientHeight;
            var parentEleH = Math.round((windowH)/2);
            var parentEleW = Math.round(document.documentElement.offsetWidth/2);
            var vertical = Math.round(eleHeight/2);
            var horizontal = Math.round(eleWidth/2);
            var eleY = parentEleH - vertical;
            var eleX = parentEleW - horizontal;
            var yoffset = document.body.scrollTop || document.documentElement.scrollTop;
            var realY = eleY + (yoffset);
            var top = realY > 0 ? realY +"px" : "20px";
            var left = eleX + "px";
            ele.css({
                top: top,
                left: left
            });
        },
        
        show_trans_back : function(){
			
			var ele = ui.create_element('','div',{id: 'browser_back'},'', 'visible');
	
			var isWebkit = navigator.userAgent.indexOf("Safari") != -1 ? 1 : 0;
			var isFirefox = navigator.userAgent.indexOf("Firefox") != -1 ? 1 : 0;
	
			var iheight;
			if (isWebkit == 1) {
				iheight = window.innerHeight || document.documentElement.clientHeight;
			}else if(isFirefox == 1){
				iheight = window.innerHeight || document.documentElement.clientHeight;
			}else{
				iheight = document.documentElement.clientHeight || document.body.clientHeight;
			}
	
			var yoffset;
			if (isWebkit == 1) {
				yoffset = document.body.scrollTop || document.documentElement.scrollTop;
			}else if(isFirefox == 1){
				yoffset = document.body.scrollTop || document.documentElement.scrollTop;
			}else{
				yoffset = yoffset = document.body.clientHeight || document.documentElement.scrollTop;
			}
	
			var fheight = document.documentElement.scrollHeight > iheight ? document.documentElement.scrollHeight : iheight;
	
			ele.css({
				height: fheight + yoffset +  "px",
				width: document.documentElement.offsetWidth + "px"
			});
			
			return ele;
	
		},


        tabs: function(){
            var tabs = utils.get_by_class('edit_container');
            var tab_attrib_arr = utils.get_by_class('tab_off');
            
            Collection(tab_attrib_arr).add_event('click', function(e){
            	var target = evnt.get_target(e);
                var check_ele = target.id.split('-')[2];
                var check = new RegExp('(.*)\\-(.*)\\-' + check_ele);
                for(var i=0, len=tabs.length; i<len;i++){
                    if(check.test(tabs[i].id)){
                        var tab = tabs[i].id.replace(/cont/, 'tab');
                        var rtab = obj(tab);

                        rtab.get().className = rtab.get().className.replace(/on/, 'off');
                       	tabs[i].className = tabs[i].className.replace(/show/, 'hidden');
                    }
                }
                
                var tcont = obj(target.id.replace(/tab/, 'cont'))
                tcont.get().className = tcont.get().className.replace(/hidden/, 'show');
                if(browser.is_ie){
                	tcont.css({zoom:1});
                	obj('footer').css({zoom: 1, position: 'relative', top: obj('anchor').get_coords().top + 'px'});
                	//obj('footer').css({position: 'relative'});
                }
                target.className = target.className.replace(/off/, 'on');
                ui.tabs();
            });
            this.sub_tabs();
        },

        sub_tabs: function(){
            var tabs = utils.get_by_class('text_edit_container');
            var tab_attrib_arr = utils.get_by_class('texttab_off');

            Collection(tab_attrib_arr).add_event('click', function(){
                var check_ele = this.id.split('-')[2];
                var check = new RegExp('(.*)\\-(.*)\\-' + check_ele);
                for(var i=0, len=tabs.length; i<len;i++){
                    if(check.test(tabs[i].id)){
                        var tab = tabs[i].id.replace(/text/, 'text_tab');
                        var rtab = obj(tab);

                        rtab.get().className = rtab.get().className.replace(/on/, 'off');
                        tabs[i].className = tabs[i].className.replace(/show/, 'hidden')
                    }
                }
                //
                var tcont = obj(this.id.replace(/text_tab/, 'text'))
                tcont.get().className = tcont.get().className.replace(/hidden/, 'show');
                this.className = this.className.replace(/off/, 'on');
                ui.tabs();
            });
        },

        layer: function(parent, styles){
            var uid = 'layer-' + utils.uid();
            var layer = ui.create_element(parent, 'div', {
                'class': 'layer',
                'id': uid
            }, '', 'visible');
            var toolbar = ui.create_element(layer.get(), 'div', {
                'class': 'float_right layer_toolbar',
                id: uid + '-toolbar'
                }, '', 'visible');
            //var minimize = ui.create_element(toolbar.get(), 'img', {'class': 'close pointer margin-right', 'id': uid + '-minimize', 'src': '/images/admin/nav/delete.png'}, '', 'visible');
            var close = ui.create_element(toolbar.get(), 'img', {
                'class': 'close pointer',
                'id': uid + '-close',
                'src': '/images/admin/nav/remove.png'
            }, '', 'visible');
            var inner = ui.create_element(layer.get(), 'div', {
                'class': 'layer_inner'
            }, '', 'visible');
            styles['zIndex'] = ui.zindex++;
            layer.css(styles);
            ui.center_ele(layer);
            ui.layers[uid] = layer;
            
            close.add_event('click', function(){
                delete ui.layers[uid];
                layer.destroy();
            });

            layer.add_event('mousedown', function(ev){
                var targ = obj(evnt.get_target(ev)).get_attribute('className');
                var check = new RegExp('(.*)layer(.*)');
                if(check.test(targ)){
                    layer.css({
                        'zIndex': ui.zindex++
                    });
                }
            });

            layer.drag();
            
            return {
                'layer': inner,
                'toolbar': toolbar
            };
        },

        fly_out: function(){},

        sort: function(parent, type){
            var par = utils.get_by_class(type);
            
            for(var i=0; i<par.length; i++){
                obj(par[i].id).drag("vertical");
            }
        }
    });

    Class('calendar').create({

        target: '',

        config: function(){
            var months = [1,2,3,4,5,6,7,8,9,10,11,12];
            var days = ["S", "M", "T", "W", "T", "F", "S"];
            var tmonths = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
            var cur_date = new Date().getDate();
            var cur_day = new Date().getDay();
            var cur_month = new Date().getMonth();
            var cur_year = new Date().getFullYear();
            var days_this_month = new Date(cur_year, cur_month + 1, 0).getDate()
            var day_offset = 6 - cur_day;
            var first_day = new Date(cur_year, cur_month, 1).getDay();

            return {
                months: months,
                tmonths: tmonths,
                days: days,
                day: cur_day,
                date: cur_date,
                month: cur_month,
                year: cur_year,
                total: days_this_month,
                offset: day_offset,
                first_day: first_day,
                cols: 7,
                rows: 6
            }
        },

        start: function(target){

            var first_day = calendar.config().first_day;
            var total = calendar.config().total;
            var month = calendar.config().month;
            var year = calendar.config().year;
            var date = calendar.config().date;

            this.build_interface(target);
            this.build_calendar(first_day, total, date, month, year);
        },

        build_interface: function(target){
            if(obj('cal').get()){
                obj('cal').destroy();
            }
            calendar.target = target.id;
            var cal = ui.create_element('', 'div', {
                id: 'cal'
            }, '', 'visible');
            var close = ui.create_element(cal.get(), 'img', {
                src: '/images/site/close.png'
            }, '', 'visible');
            ui.center_ele(cal);
            cal.css({
                zIndex: ui.zindex++
            });
            var top =  '2px';
            var right = '2px';
            close.css({
                top: top,
                right: right,
                position: 'absolute',
                zIndex: ui.zindex++,
                cursor: 'pointer'
            });
            close.add_event('click', function(){
                cal.destroy();
                close.destroy();
            })
            cal.drag();
        },

        build_calendar: function(first_day, total, date, month, year){
            var cnt = 0;
            var day = 0;
            var tbl = ui.create_element(obj('cal').get(), 'table', {
                id: 'cal_tbl'
            }, '', 'visible');
            tbl = this.navigation(tbl, month, year);
            for(var row = 0; row<calendar.config().rows; row++){
                var orow = ui.create_element(tbl.get(), 'tr', {}, '', 'visible');
                for(var col = 0; col<calendar.config().cols; col++){
                    cnt++;
                    var real_date = (cnt - first_day);
                    var val = cnt >= first_day && real_date <= total ? day++ : '&nbsp;';
                    var today = real_date == date ? 'selected' : '';
                    var ocol = ui.create_element(orow.get(), 'td', {
                        'class': today
                    }, val, 'visible');
                    ocol.add_event('click', function(e){
                        var target = obj(evnt.get_target(e));
                        var day = target.html();
                        var mnth = month  + 1;
                        var yr = year;
                        if(day != '&nbsp;'){
                            mnth = mnth < 10 ? '0' + mnth : mnth;
                            obj(calendar.target + '_month').set_attribute('value', mnth);
                            obj(calendar.target + '_day').set_attribute('value', day);
                            obj(calendar.target + '_year').set_attribute('value', yr);
                            obj('cal').destroy();
                        }
                    })
                }
            }
        },

        navigation: function(table, mnth, yr){
            month = calendar.config().tmonths[mnth];
            year = yr;
            var current = month + '-' + year;
            var orow = ui.create_element(table.get(), 'tr', {}, '', 'visible');
            var prev = ui.create_element(orow.get(), 'td', {
                'class': 'border_bottom'
            }, '<', 'visible');
            var prev_year = ui.create_element(orow.get(), 'td', {
                'class': 'border_bottom'
            }, '<<', 'visible');
            ui.create_element(orow.get(), 'td', {
                'colspan': '3',
                'class': 'border_bottom header'
            }, current, 'visible');
            var next_year = ui.create_element(orow.get(), 'td', {
                'class': 'border_bottom'
            }, '>>', 'visible');
            var next = ui.create_element(orow.get(), 'td', {
                'class': 'border_bottom'
            }, '>', 'visible');

            var drow = ui.create_element(table.get(), 'tr', {}, '', 'visible');
            for(var h=0; h<calendar.config().days.length; h++){
                ui.create_element(drow.get(), 'td', {
                    'class': 'border_bottom header'
                }, calendar.config().days[h], 'visible');
            }

            next.add_event('click', function(){
                year = mnth == 11 ? yr + 1 : yr;
                month = mnth == 11 ? 0 : mnth + 1;
                var total = new Date(year, month + 1, 0).getDate();
                var date = 1;
                var first_day = new Date(year, month, 1).getDay();
                table.destroy();
                calendar.build_calendar(first_day, total, date, month, year);
            });

            next_year.add_event('click', function(){
                year = yr + 1;
                month = mnth;
                var total = new Date(year, month + 1, 0).getDate();
                var date = 1;
                var first_day = new Date(year, month, 1).getDay();
                table.destroy();
                calendar.build_calendar(first_day, total, date, month, year);
            });

            prev.add_event('click', function(){
                year = mnth == 0 ? yr - 1 : yr;
                month = mnth == 0 ? 11 : mnth - 1;
                var total = new Date(year, month + 1, 0).getDate();
                var date = 1;
                var first_day = new Date(year, month, 1).getDay();
                table.destroy();
                calendar.build_calendar(first_day, total, date, month, year);
            });

            prev_year.add_event('click', function(){
                year = yr - 1;
                month = mnth;
                var total = new Date(year, month + 1, 0).getDate();
                var date = 1;
                var first_day = new Date(year, month, 1).getDay();
                table.destroy();
                calendar.build_calendar(first_day, total, date, month, year);
            });

            return table;
        }
    })


})();

Class('messages').create({
    message_queue: [],

    call: function(fn, url, caller, qstring, method){
        xhr.config.method = method || 'post';
        xhr.config.url = url;
        xhr.call(qstring || '', fn, caller);
    },

    load: function(message){
        var url = '/messages';
        var ele = obj('message_outer').get() ? obj('message_outer') : ui.create_element(obj('tools').get(), 'div', {
            id: 'message_outer'
        }, 'message', 'visible');
        var top = -(ele.get_dimensions().h) + 'px';
        var left = (obj('messages-link').get_position().left) + 'px';
        obj('messages-link').get().className = 'selected';
        ele.css({
            top: top,
            left: left
        });
        ele.add_event('click', function(){
            ele.destroy();
            obj('messages-link').get().className = '';
        })
        messages.call(messages.show, url, ele, 'message=' + message);
    },

    show: function(http, ele){
        ele.html(http.responseText);
        var timer = window.setInterval(function(){
            window.clearInterval(timer);
            timer = null;
            ele.destroy();
            obj('messages-link').get().className = '';
        }, 6000)
    }
});

Class('editor').create({
    get_range: function(e){
        var target = evnt.get_target(e);
        if(target.nodeName == 'TEXTAREA'){
            /*var usersel;
            if(window.getSelection){
                usersel = window.getSelection();
            }else if(document.selection){
                usersel = document.selection();
            }
            var range = document.createRange();
            range.setStart(usersel.anchorNode,usersel.anchorOffset);
            range.setEnd(usersel.focusNode,usersel.focusOffset);
            alert(range)*/

            var range = document.createRange();

        }
        
    }
});

function fire_event(){
    ui.selected(core.view());
    ui.config();
    ui.stripe('user-cont', 'LI', '#7B7373', '#857c7c');
    ui.stripe('row-cont', 'LI', '#7B7373', '#857c7c');
    ui.stripe('config-cont', 'LI', '#7B7373', '#857c7c');
	
	if(browser.is_ie){
		var selects = utils.get_by_tag('SELECT');
		Collection(selects).add_event('change', function(e){alert(this.options[this.selectedIndex].value)});
	}
	
    if(obj('wrapper').get()){
        ui.loaded = true;
        site.load_slideshow();
    }
}

obj(document).add_event("DOMContentLoaded", fire_event);

window.onload = function(){
	if(browser.is_ie){
		sfHover = function() {
			var sfEls = document.getElementById("nav").getElementsByTagName("LI");
			for (var i=0; i<sfEls.length; i++) {
				sfEls[i].onmouseover=function() {
					this.className+=" sfhover";
				}
				sfEls[i].onmouseout=function() {
					this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
				}
			}
		}
		if (window.attachEvent) window.attachEvent("onload", sfHover);
	}
}
