/*
Script: common.js
    Contains common page code
*/
var _path = '/';
window.addEvent('domready', function(){
    Tip = new ToolTip();
    Tip.create();
    if (!_path)
        _path = '/';
    Indicator.create();
    //Debug.create();
    //Debug.enabled = false;
    $(document.body).getElements('a.nwpopup').each(function(itm){
        itm.addEvent('click', function(e){
            e = new Event(e);
            var url = this.getProperty('href');
            if (url) {
                window.open(url,'popup','toolbar=0,scrollbars=1,location=0,statusbar=1,menubar=0,resizable=1,width=700,height=600');
            }
            e.stop();
        });
    });
});

// Remote class
var Remote = new Class({
    initialize: function(url,params,method,type,update,evalScripts,evalResponse){
        if (method != 'get' && method != 'post')
            this.method = 'get';
        else
            this.method = method;
        this.params = params;
        this.url = url;
        if (type != 'text' && type != 'xml' && type != 'html' && type != 'json')
            this.type = 'text';
        else
            this.type = type;
        if (update)
            this.update = update;
        else
            this.update = null;
        if (evalScripts)
            this.evalScripts = evalScripts;
        else
            this.evalScripts = true;
        if (evalResponse)
            this.evalResponse = evalResponse;
        else
            this.evalResponse = false;
        this.req = null;
        this.result = null;
        this.processResultFunct = null;
    }
});
Remote.implement({
    send: function(){
        Indicator.update(true);
        this.createReq();
        if (this.type == 'text' || this.type == 'xml') {
            this.req.send(this.params);
        }
        else {
            if (this.type == 'json' && !(this.params instanceof Object))
                this.params = {};
            if (this.method == 'get' && !this.params) {
                this.req.get(this.url);
            }
            else if (this.method == 'post' && (this.params instanceof Object)) {
                this.req.post(this.params);
            }
            else {
                this.req.send(this.params);
            }
        }
    },
    setProcessResultFunct: function(funct){
        this.processResultFunct = funct;
    },
    getRes: function(){
        Indicator.complete(false);
        if (this.processResultFunct) {
            this.processResultFunct(this.result);
        }
        /*if (this.type == 'text' || this.type == 'xml') {
            Debug.dump(this.type+': '+this.result);
        }
        else if (this.type == 'json') {
            Debug.dump(this.type+': '+this.result);
        }
        else {
            Debug.dump(this.type+' - tree: '+this.result.tree);
            Debug.dump(this.type+' - elements: '+this.result.elements);
            Debug.dump(this.type+' - html: '+this.result.html);
            Debug.dump(this.type+' - jscript: '+this.result.jscript);
        }*/
    },
    createReq: function(){
        var obj = this;
        var options = {
            method: this.method,
            url: this.url,
            onRequest: function(){
                Indicator.update(true);
            },
            onFailure: function(){
                Indicator.update(false);
                Indicator.fail(true);
                (function(){Indicator.fail(false)}).delay(2000);
            },
            onException: function(headerName,value){
                Indicator.update(false);
                Indicator.fail(true);
                //Debug.dump(headerName);
                //Debug.dump(value);
                (function(){Indicator.fail(false)}).delay(2000);
            }
        };
        
        if (this.type == 'text' || this.type == 'xml') {
            options.onSuccess = function(text, xml){
                Indicator.update(false);
                Indicator.complete(true);
                if (obj.type == 'xml' && xml)
                    obj.result = xml;
                else
                    obj.result = text;
                obj.getRes();
            };
            this.req = new Request(options);
        }
        else if (this.type == 'json') {
            options.onComplete = function(resp) {
                Indicator.update(false);
                Indicator.complete(true);
                obj.result = resp;
                obj.getRes();
            };
            this.req = new Request.JSON(options);
        }
        else {
            options.update = this.update;
            options.evalScripts = this.evalScripts;
            options.evalResponse = this.evalResponse;
            options.onComplete = function(tree,elements,html,jscript) {
                Indicator.update(false);
                Indicator.complete(true);
                obj.result = {};
                obj.result.tree = tree;
                obj.result.elements = elements;
                obj.result.html = html;
                obj.result.jscript = jscript;
                obj.getRes();
            };
            this.req = new Request.HTML(options);
        }
    }
});

// Indicator class
var Indicator = new Class({
    initialize: function(){
        this.initialised = false;
        
        this.updater = new Element('div', {
            'id': 'updater'
        });
        this.completer = new Element('div', {
            'id': 'completer'
        });
        this.failer = new Element('div', {
            'id': 'failer'
        });
        this.updater.set('text','Updating...');
        this.completer.set('text','Completed successfully');
        this.failer.set('text','Request FAILED!');
    }
});
Indicator.implement({
    update: function(trig){
        if (!this.initialised)
            this.create();
        if (trig)
            this.updater.style.display = 'block';
        else
            this.updater.style.display = 'none';
    },
    complete: function(trig){
        if (!this.initialised)
            this.create();
        if (trig)
            this.completer.style.display = 'block';
        else
            this.completer.style.display = 'none';
    },
    fail: function(trig){
        if (!this.initialised)
            this.create();
        if (trig)
            this.failer.style.display = 'block';
        else
            this.failer.style.display = 'none';
    },
    create: function(){
        if (!this.initialised) {
            this.initialised = true;
            
            this.updater.inject(document.getElement('body'), 'top');
            this.completer.inject(document.getElement('body'), 'top');
            this.failer.inject(document.getElement('body'), 'top');
        }
    }
});
var Indicator = new Indicator();

// Debug class
var Debug = new Class({
    initialize: function(){
        this.initialised = false;
        this.enabled = true;
        
        this.holder = new Element('div', {
            'styles': {
                'font-size': '12px',
                'line-height': '14px',
                'display': 'block',
                'border': 'dashed 1px #ff0000',
                'background-color': '#ffe8e8',
                'cursor': 'pointer'
            }//,
            //'events': {
            //    'click': function(){
            //        this.style.display = 'none';
            //    }
            //}
        });
        this.stat = new Element('pre');
        this.stat.inject(this.holder, 'top');
    }
});
Debug.implement({
    dump: function(text){
        if (this.initialised && this.enabled)
            this.stat.appendText(text+"\n\r");
    },
    create: function(){
        if (!this.initialised) {
            this.initialised = true;
            this.holder.inject(document.getElement('body'), 'bottom');
            var obj = this;
            document.addEvent('keydown', function(event){
                if (event.key == 'f2') {
                    if (obj.holder.style.display == 'none')
                        obj.holder.style.display = 'block';
                    else
                        obj.holder.style.display = 'none';
                }
            });
        }
    }
});
var Debug = new Debug();

// ToolTip class
var ToolTip = new Class({
    initialize: function(){
        this.initialised = false;
        
        this.ttip = new Element('div', {
            'styles': {
                'position': 'absolute',
                'top': '0',
                'left': '0',
                'width': '250px',
                'display': 'none'
            }
        });
        this.ttiptop = new Element('div', {
            'styles': {
                'background': 'url('+_path+'default/images/ttip.gif) no-repeat top left',
                'height': '16px',
                'line-height': '1px',
                'font-size': '1px'
            }
        });
        this.ttiptop.inject(this.ttip, 'top');
        this.ttipbtm = new Element('div', {
            'styles': {
                'background': '#f5eca3',
                'border-right': 'solid 1px #000000',
                'border-bottom': 'solid 1px #000000',
                'border-left': 'solid 1px #000000',
                'padding': '5px',
                'font-size': '11px'
            }
        });
        this.ttipbtm.inject(this.ttip, 'bottom');
        
        this.ttipbtm.set('text','ToolTip Content');
    }
});
ToolTip.implement({
    setCnt: function(cont){
        this.ttipbtm.set('html', cont);
        this.ttip.style.display = 'block';
    },
    setPos: function(x,y){
        this.ttip.setStyles({
            'top': x,
            'left': y
        });
    },
    showIt: function(){
        this.ttip.style.display = 'block';
    },
    hideIt: function(){
        this.ttip.style.display = 'none';
    },
    create: function(){
        if (!this.initialised) {
            this.initialised = true;
            
            this.ttip.inject(document.getElement('body'), 'bottom');
            this.init();
        }
    },
    init: function(){
        var tooltips = $$('a.tip');
        tooltips.each(function(itm){
            // remove all events
            itm.removeEvents();
            itm.addEvent('mouseover', function(e){
                e = new Event(e);
                Tip.setPos((this.getTop()+20),(this.getLeft()-25));
                var ttl = this.getProperty('title');
                this.removeProperty('title');
                if (ttl == 'span') {
                    var tmpElem = this.getElement('span');
                    Tip.setCnt(tmpElem.innerHTML);
                }
                else {
                    Tip.setCnt(ttl);
                }
                itm.addEvent('mouseout', function(ev){
                    ev = new Event(ev);
                    Tip.hideIt();
                    itm.removeEvents('mouseout');
                    itm.setProperty('title', ttl);
                });
            });
            itm.addEvent('click', function(e){
                e = new Event(e).stop();
                e.stop();
            });
        });
    }
});
var Tip;

// Helper class
var Helper = new Class({
    initialize: function(){
    }
});
Helper.implement({
    initButtons: function(elm, elmForm, elmTable, popup, section){
        if (elm) {
            if (!section)
                section = elm.id;
            elm.getElements('div.buttons button').each(function(el){
                el.addEvent('click', function(event){
                    switch (this.get('class')) {
                        case 'view':
                            if (popup) {
                                window.open(_path+'admin/'+section+'/view?'+elmForm.toQueryString(),section,'toolbar=0,scrollbars=1,location=0,statusbar=1,menubar=0,resizable=1,width=700,height=600');
                            }
                            else {
                                window.location = _path+'admin/'+section+'/view?'+elmForm.toQueryString();
                            }
                        break;
                        case 'add':
                            if (popup) {
                                window.open(_path+'admin/'+section+'/add?'+elmForm.toQueryString(),section,'toolbar=0,scrollbars=1,location=0,statusbar=1,menubar=0,resizable=1,width=700,height=600');
                            }
                            else {
                                window.location = _path+'admin/'+section+'/add?'+elmForm.toQueryString();
                            }
                        break;
                        case 'edit':
                            if (popup) {
                                window.open(_path+'admin/'+section+'/edit?'+elmForm.toQueryString(),section,'toolbar=0,scrollbars=1,location=0,statusbar=1,menubar=0,resizable=1,width=700,height=600');
                            }
                            else {
                                window.location = _path+'admin/'+section+'/edit?'+elmForm.toQueryString();
                            }
                        break;
                        case 'delete':
                            if (confirm('Sure to delete?')) {
                                var req = new Remote(_path+'remote/'+section+'/delete',elmForm,'get','html',elmTable);
                                req.send();
                            }
                        break;
                        case 'clone':
                            if (confirm('Sure to clone?')) {
                                var req = new Remote(_path+'remote/'+section+'/cln',elmForm,'get','html',elmTable);
                                req.send();
                            }
                        break;
                        case 'link':
                            if (popup) {
                                window.open(_path+'admin/'+section+'/link?'+elmForm.toQueryString(),section,'toolbar=0,scrollbars=1,location=0,statusbar=1,menubar=0,resizable=1,width=700,height=600');
                            }
                            else {
                                window.location = _path+'admin/'+section+'/link?'+elmForm.toQueryString();
                            }
                        break;
                    }
                });
            });
        }
    },
    getFormValue: function(frm,inputName) {
        var val = 0;
        
        if (!inputName)
            val = 0;
        
        if (!(frm instanceof Object))
            frm = $(frm);
        
        frm.getElements('input[name=' + inputName + ']').each(function(el){
            if(el.get('value'))
                val = el.get('value');
        });
        
        return val;
    }
});
var Helper = new Helper();

var Popup = new Class({
    initialize: function(){
        this.initialised = false;
        
        this.pophold = new Element('div', {
            'styles': {
                'position': 'absolute',
                'top': '0',
                'left': '0',
                'width': '100%',
                'height': '100%',
                'opacity': '0.50',
                'filter': 'alpha(opacity=50)',
                'background': '#666666',
                'z-index': '90'
            }
        });
        var pophold = this.pophold;
        this.popup = new Element('div', {
            'styles': {
                'width': '500px',
                'position': 'absolute',
                'z-index': '100'
            }
        });
        this.popup.inject($(document.body));
        var popup = this.popup;
        var tmpelm = new Element('div', {
            'styles': {
                'height': '10px',
                'background': 'transparent url('+_path+'default/images/popup/bg-bb-t.png) top left no-repeat'
            }
        });
        tmpelm.inject(this.popup);
        var popmdl = new Element('div', {
            'styles': {
                'background': 'transparent url('+_path+'default/images/popup/bg-bb.png) top left repeat-y'
            }
        });
        popmdl.inject(this.popup);
        var tmpelm = new Element('div', {
            'styles': {
                'height': '16px',
                'background': 'transparent url('+_path+'default/images/popup/bg-bb-b.png) top left no-repeat'
            }
        });
        tmpelm.inject(this.popup);
        this.pophead = new Element('div', {
            'styles': {
                'text-align': 'right',
                'padding': '10px 22px 0 0',
                'cursor': 'pointer'
            }
        });
        this.pophead.inject(popmdl);
        var spn = new Element('span', {
            'styles': {
                'font-size': '1px',
                'line-height': '1px',
                'display': 'block',
                'float': 'right',
                'background': 'url('+_path+'default/images/popup/bb-close.jpg) no-repeat top left',
                'width': '16px',
                'height': '16px',
                'cursor': 'pointer'
            },
            'events': {
                'click': function(){
                    window.removeEvents('scroll');
                    pophold.dispose();
                    popup.dispose();
                },
                'mouseover': function(){
                    this.setStyle('background', 'url('+_path+'default/images/popup/bb-close-over.jpg) no-repeat top left');
                },
                'mouseout': function(){
                    this.setStyle('background', 'url('+_path+'default/images/popup/bb-close.jpg) no-repeat top left');
                }
            }
        });
        spn.inject(this.pophead);
        this.titl = new Element('span', {
            'styles': {
                'display': 'block',
                'float': 'right',
                'font': '10px Arial, Helvetica, sans-serif',
                'color': '#929292'
            }
        });
        this.titl.inject(this.pophead);
        var popch = new Element('div', {
            'styles': {
                'font-size': '11px',
                'padding': '10px',
                'clear': 'both'
            }
        });
        popch.inject(popmdl);
        this.content = new Element('div', {
            'styles': {
                'height': '400px',
                'padding': '0 10px 0 0',
                'overflow': 'auto',
                'overflow-x': 'hidden'
            }
        });
        this.content.inject(popch);
        new Drag.Move(this.popup, {'handle': this.pophead, 'container': this.pophold});
        
        this.titl.set('text', 'close ');
    }
});
Popup.implement({
    setTitl: function(title){
        //this.titl.set('text', title);
    },
    setCnt: function(cont){
        this.content.set('html', cont);
    },
    startLoading: function(){
        this.content.addClass('ajax-loading');
    },
    stopLoading: function(){
        this.content.removeClass('ajax-loading');
    },
    create: function(){
        if (!this.initialised) {
            this.initialised = true;
            
            this.pophold.injectInside($(document.body));
            //this.pophold.setStyle( 'top', window.getScrollTop() );
            
            this.popup.setStyle( 'top', window.getScrollTop() );
            
            var popup = this.popup;
            var pophold = this.pophold;
            
            var dim = window.getCoordinates();
            var scrollsize = window.getScrollSize();
            var scrolledto = window.getScroll();
            
            this.pophold.setStyles({
                'top': 0,
                'height': scrollsize.y
            });
            
            var popheight = scrolledto.y + ((dim.height - popup.getStyle('height').toInt()) / 2 );
            if (dim.height < this.popup.getStyle('height').toInt())
                popheight = 5;
            var popwidth = scrolledto.x + ((dim.width - popup.getStyle('width').toInt()) / 2 );
            
            this.popup.setStyles({
               'top': popheight,
               'left': popwidth
            });
            
            window.addEvent('scroll', function(){
                var scrolledto = window.getScroll();
                popup.setStyle( 'top',( scrolledto.y + ((dim.height - popup.getStyle('height').toInt()) / 2 )) );
            });
        }
    }
});
