/*
Script: common.js
    Contains common page code
*/
var _path = '/';
$(document).ready(function () {
    Tip.create();
    if (!_path)
        _path = '/';
    Indicator.create();
    Debug.create();
    Debug.enabled = false;
    $('a.nwpopup').each(function(itm){
        $(this).bind("click", function(e){
            var url = $(this).attr('href').toString();
            if (url) {
                window.open(url,'popup','toolbar=0,scrollbars=1,location=0,statusbar=1,menubar=0,resizable=1,width=700,height=600');
            }
            e.preventDefault();
        });
    });
});

var Remote = function(url,params,method,type,update,evalScripts,evalResponse){
        if (method != 'get' && method != 'post')
            this.method = 'GET';
        else
            this.method = method.toUpperCase();
        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.resultMessage = null;
        this.processResultFunct = null;
        this.processResultFunctParams = null;
}
$.extend(Remote.prototype, {
    send: function(){
        this.createReq();
        if (this.req)
            $.ajax(this.req);
    },
    setProcessResultFunct: function(funct, params){
        this.processResultFunct = funct;
        this.processResultFunctParams = params;
    },
    getRes: function(){
        Indicator.complete(true);
        if (this.processResultFunct) {
            this.processResultFunct(this.result, this.processResultFunctParams);
        }
        else if (this.update && (this.type == 'text' || this.type == 'html')) {
            if (typeof(this.update) == 'object')//if (this.update.nodeType == 1)
                this.update.html(this.result);
            else
                $('#'+this.update.toString()).html(this.result);
        }
        if (Debug.enabled){
            Debug.dump(this.resultMessage);
            Debug.dump(this.type+': '+this.result);
        }
        Indicator.complete(false);
    },
    createReq: function(){
        var obj = this;
        if (this.params && typeof(this.params) == 'object')//if (this.params.nodeType == 1)
            this.params = this.params.serialize();
        this.req = {
            type: this.method,
            url: this.url,
            dataType: this.type, //"text","xml","html","json","script","jsonp"
            data: this.params,
            success: function (data, textStatus) {
                obj.result = data;
                obj.resultMessage = textStatus;
                obj.getRes();
            },
            
            async: true,
            cache: true,
            global: true,
            processData: true,
            ifModified: false,
            contentType: "application/x-www-form-urlencoded"
            /*,
            complete: function (XMLHttpRequest, textStatus) {
                this;
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                this;
            },
            beforeSend: function (XMLHttpRequest) {
                this;
            },
            dataFilter: function (data, type) {
                return data;
            },
            scriptCharset:'UTF-8',
            jsonp:'',
            username: '',
            password:'',
            timeout:0,
            xhr:''*/
        };
    },
    stop: function(){
        this.req = null;
    }
});

// Indicator class
var Indicator = function(){
        this.initialised = false;
        
        this.updater = $.create('div',{id: 'updater'});
        this.completer = $.create('div',{id: 'completer'});
        this.failer = $.create('div',{id: 'failer'});
        
        this.updater.text('Loading...');
        this.completer.text('Completed successfully');
        this.failer.text('Request FAILED!');
}
$.extend(Indicator.prototype, {
    update: function(trig){
        if (!this.initialised)
            this.create();
        if (trig)
            this.updater.css('display','block');
        else
            this.updater.css('display','none');
    },
    complete: function(trig){
        if (!this.initialised)
            this.create();
        if (trig)
            this.completer.css('display','block');
        else
            this.completer.css('display','none');
    },
    fail: function(trig){
        if (!this.initialised)
            this.create();
        if (trig)
            this.failer.css('display','block');
        else
            this.failer.css('display','none');
    },
    create: function(){
        if (!this.initialised) {
            this.initialised = true;
            
            this.updater.ajaxStart(function(){
                $(this).css('display','block');
            });
            this.updater.ajaxStop(function(){
                $(this).css('display','none');
            });
            var t = null;
            this.completer.ajaxSuccess(function(evt, request, settings){
                $(this).css('display','block');
                if (t) {
                    clearTimeout(t);
                }
                var tmp = $(this);
                t = setTimeout(function(){
                    tmp.css("display","none");
                }, 1000);
            });
            this.failer.ajaxError(function(event, request, settings){
                $(this).css('display','block');
                $(this).text("Error requesting page " + settings.url);
                if (t) {
                    clearTimeout(t);
                }
                var tmp = $(this);
                t = setTimeout(function(){
                    tmp.css("display","none");
                    tmp.text('Request FAILED!');
                }, 5000);
            });
            
            $('body').prepend(this.updater);
            $('body').prepend(this.completer);
            $('body').prepend(this.failer);
        }
    }
});
var Indicator = new Indicator();

// Debug class
var Debug = function(){
        this.initialised = false;
        this.enabled = true;
        
        this.holder = $.create('div');
        
        var onOff = $.cookie('debug_cookie');
        if (onOff && onOff == 'on')
            this.holder.css('display', 'block');
        else
            this.holder.css('display', 'none');
        
        var tmpHolder = $.create('div');
        tmpHolder.css({
                'font-size': '16px',
                'line-height': '18px',
                'display': 'block',
                'border': 'dashed 1px #53e802',
                'background-color': '#000000',
                'color': '#53e802',
                'height': '300px',
                'overflow': 'auto'
            });
        this.holder.prepend( tmpHolder );
        
        this.stat = $.create('pre');
        tmpHolder.prepend( this.stat );
        
        var note = $.create('div');
        note.css({
                'font-size': '12px',
                'line-height': '14px',
                'display': 'block',
                'border': 'dashed 1px #000000',
                'background-color': '#53e802',
                'font-weight': 'bold',
                'color': '#000000'
            });
        note.text('Use F2 to toggle this screen');
        this.holder.append( note );
}
$.extend(Debug.prototype, {
    dump: function(txt){
        if (this.enabled) {
            var d = new Date();
            this.stat.text( this.stat.text() + txt + "\n\r--------------- " + d.toUTCString() + " ---------------\n\r" );
        }
    },
    create: function(){
        if (!this.initialised) {
            this.initialised = true;
            $('body').prepend(this.holder);
            var obj = this.holder;
            $(window).keydown(function(e){
                if (e.keyCode == '113') {
                    if (obj.css('display') == 'none') {
                        obj.css('display', 'block');
                        $.cookie('debug_cookie', 'on', { expires: 7});
                    }
                    else {
                        obj.css('display','none');
                        $.cookie('debug_cookie', 'off', { expires: 7});
                    }
                }
            });
        }
    }
});
var Debug = new Debug();

// ToolTip class
var ToolTip = function(){
        this.initialised = false;
        this.ttiparchive = [];
        this.ttip = $.create('div');
        this.ttip.css({
                'position': 'absolute',
                'top': '0',
                'left': '0',
                'width': '250px',
                'display': 'none'
            });
        this.ttiptop = $.create('div');
        this.ttiptop.css({
                'background': 'url('+_path+'default/images/ttip.gif) no-repeat top left',
                'height': '16px',
                'line-height': '1px',
                'font-size': '1px'
            });
        this.ttip.prepend(this.ttiptop);
        
        this.ttipbtm = $.create('div');
        this.ttipbtm.css({
                'background': '#f5eca3 url('+_path+'default/images/preloader.gif) no-repeat center center',
                'height': '30px',
                'border-right': 'solid 1px #000000',
                'border-bottom': 'solid 1px #000000',
                'border-left': 'solid 1px #000000',
                'padding': '5px',
                'font-size': '11px'
            });
        this.ttip.append(this.ttipbtm);
        
        //this.ttipbtm.html('ToolTip Content');
}
$.extend(ToolTip.prototype, {
    setCnt: function(cont,handle){
        var tmpTip = this;
        
        if (!handle) {
            handle = cont;
        }
        else if (handle && typeof(handle) == 'object') {
            tmpTip = handle.tipObj;
            handle = handle.handle;
        }
        
        tmpTip.showIt();
        
        if (tmpTip.ttiparchive[handle]) {
            tmpTip.ttipbtm.html( tmpTip.ttiparchive[handle] );
            return;
        }
        
        tmpTip.ttiparchive[handle] = cont;
        
        tmpTip.ttipbtm.html(cont);
    },
    setPos: function(x,y){
        this.ttip.css({
            'top': x,
            'left': y
        });
    },
    showIt: function(){
        this.ttip.css('display','block');
        this.ttipbtm.css({
                'background': '#f5eca3',
                'height': 'auto'
            });
    },
    hideIt: function(){
        this.ttipbtm.html('&nbsp;');
        this.ttip.css('display','none');
        this.ttipbtm.css({
                'background': '#f5eca3 url('+_path+'default/images/preloader.gif) no-repeat center center',
                'height': '30px'
            });
    },
    create: function(){
        if (!this.initialised) {
            this.initialised = true;
            this.ttiptop.css('background', 'url('+_path+'default/images/ttip.gif) no-repeat top left');
            this.ttipbtm.css('background', '#f5eca3 url('+_path+'default/images/preloader.gif) no-repeat center center');
            $('body').append(this.ttip);
            this.init();
        }
    },
    init: function(){
        var tooltips = $('a.tip,a.tiprempte');
        var tmpTip = this;
        tooltips.each(function(itm){
            // remove all events
            $(this).unbind();
            var ttl = $(this).attr("title");
            $(this).hover(
                function(e){
                    var offest = $(this).offset();
                    Tip.setPos((offest.top+20),(offest.left-25));
                    $(this).removeAttr('title');
                    if ($(this).hasClass("tiprempte") && ttl) {
                        if (tmpTip.ttiparchive[ttl]) {
                            tmpTip.setCnt(tmpTip.ttiparchive[ttl]);
                            return;
                        }
                        tmpTip.ttip.css('display','block');
                        var req = new Remote(_path+'remote/helptip/get/'+ttl,'','get','html');
                        req.setProcessResultFunct(tmpTip.setCnt, {'handle':ttl,'tipObj':tmpTip});
                        req.send();
                    }
                    else if (ttl == 'span') {
                        var tmpElem = $(this).find("span");
                        tmpTip.setCnt(tmpElem.html());
                    }
                    else {
                        tmpTip.setCnt(ttl);
                    }
                },
                function(e){
                    tmpTip.hideIt();
                    $(this).attr('title', ttl);
                }
            );
            $(this).bind("click", function(e){
                e.preventDefault();
            });
        });
    }
});
var Tip = new ToolTip();

var Popup = function(){
        this.initialised = false;
        
        this.req = null;
        this.content = $.create('div');
        this.settings = {
            width: 630,
            height: 500,
            minWidth: 200,
            minHeight: 200,
            maxWidth: 1000,
            maxHeight: 1000,
            zIndex: 100,
            position: 'center',
            
            modal: true,
            stack: false,
            hide: null,
            show: null,
            autoOpen: true,
            bgiframe: false,
            draggable: true,
            resizable: true,
            dialogClass: '',
            title: 'Popup window',
            
            buttons: {
                'Submit': function() {
                    var form = $(this).find('form');
                    if (form.attr('action')) {
                        Popup.req = new Remote(form.attr('action'),form,'post','html',Popup.content);
                        Popup.req.send();
                    }
                },
                'Cancel': function() {
                    if (Popup.req)
                        Popup.req.stop();
                    $(this).dialog('close');
                }
            }
        };
        //getter
        //var width = $('.selector').dialog('option', 'width');
        //setter
        //$('.selector').dialog('option', 'width', 460);
}
$.extend(Popup.prototype, {
    setTitl: function(title){
        this.content.dialog('option', 'title', title);
    },
    setCnt: function(cont){
        this.content.html(cont);
    },
    startLoading: function(){
        this.content.addClass('ajax-loading');
    },
    stopLoading: function(){
        this.content.removeClass('ajax-loading');
    },
    create: function(opt){
        if (!this.initialised) {
            this.initialised = true;
            
            $('body').append(this.content);
            this.content.dialog(this.settings);
        }
        if (!opt)
            this.content.empty();
        this.content.dialog('open');
    },
    close: function(){
        this.content.dialog('close');
    }
});
var Popup = new Popup();

var Lder = function(){
    this.initialised = false;
    this.hlder = $.create('div');
    this.loader = $.create('div');
    this.loader.addClass('loaderbg');
    this.hlder.append(this.loader);
    this.loadinholder = $.create('div');
    this.loadinholder.addClass('loadinholder');
    this.hlder.append(this.loadinholder);
    this.loadin = $.create('div');
    this.loadin.addClass('loadin');
    this.loadin.html('<b>Loading...</b><br />Please wait until this screen is completely loaded.')
    this.loadinholder.append(this.loadin);
}
$.extend(Lder.prototype, {
    create: function(boundbox){
        if (!this.initialised) {
            if (!boundbox) {
                boundbox = $('body');
                var win = $(window);
                var ldr = this;
                $(window).bind('load', function(){
                    ldr.remove();
                });
                $(window).bind('beforeunload', function(){
                    ldr.create();
                });
            }
            else {
                boundbox.css('position', 'relative');
                var win = boundbox;
            }
            this.initialised = true;
            if (boundbox.height() > win.height() && boundbox.width()) {
                this.loader.css({
                    'height': boundbox.height(),
                    'width': boundbox.width()
                });
            }
            this.loadinholder.css({
                'top': ( ((win.height() - 42) / 2) + win.scrollTop() ),
                'left': ( ((win.width() - 288) / 2) + win.scrollLeft() )
            });
            boundbox.append(this.hlder);
        }
    },
    remove: function(){
        if (this.initialised) {
            this.hlder.remove();
            this.initialised = false;
        }
    }
});
var Loader = new Lder();
