var dom = document.getElementById;
var iex = document.all;
var ns4 = document.layers;
var ie = false;

/*-------------------------------------*/
/*  Startup functions                  */
/*-------------------------------------*/

var myWidth = 0, myHeight = 0, minWidth = 100, minHeight = 70, obj = null;

function document_resize(event) {
    var newWidth = $(window).width();
    var newHeight = $(window).height();
    if (newWidth < minWidth) myWidth = minWidth;
    if (newHeight < minHeight) myHeight = minHeight;
    if (myWidth != newWidth || myHeight != newHeight) {
        myWidth = $(window).width();
        myHeight = $(window).height();
        if (myWidth < minWidth) myWidth = minWidth;
        if (myHeight < minHeight) myHeight = minHeight;

        createCookie('ScreenHeight',myHeight,365);
        createCookie('ScreenWidth',myWidth,365);
        $(window).trigger('changesize');
        setTimeout("document_resize()",100);
    }
}

function document_reload() {
    myWidth = $(window).width();
    myHeight = $(window).height();
    if (myWidth < minWidth) myWidth = minWidth;
    if (myHeight < maxHeight) myHeight = maxHeight;

    createCookie('ScreenHeight',myHeight,365);
    createCookie('ScreenWidth',myWidth,365);
    location.href=location.href;
}

$(window).bind('resize', document_resize);
$(document).ready(function() {
    document_resize();
    $('button').button();
} );
$(window).load(function() {
    document_resize();
});

/*-------------------------------------*/
/*  Generic functions                  */
/*-------------------------------------*/

function isArray(testObject) {
    return testObject && !(testObject.propertyIsEnumerable('length')) && typeof testObject === 'object' && typeof testObject.length === 'number';
}

function addLoadEvent(func) {
    $(document).ready(func);
}

function urlencode(str) {
    str = escape(str);
    str = str.replace('+', '%2B');
    str = str.replace('%20', '+');
    str = str.replace('*', '%2A');
    str = str.replace('/', '%2F');
    str = str.replace('@', '%40');
    return str;
}

function IntOnly(event) {
    //notice that the check is != null now, as the tab key has a value of 0
    var charCode = ( event.which != null ) ? event.which : event.keyCode
    //charCodes < 32 include tab, delete, arrow keys, etc
    return (charCode < 32 || (charCode >= 48 && charCode <= 57));
}

function createElement(type, attr) {
    var element = document.createElement(type);
    $(element).attr(attr);
    return element;
}

/*-------------------------------------*/
/*  Framework functions                */
/*-------------------------------------*/

function setPreferences(setting, value) {
    var str = 'setting=' + setting + '&value=' + value;
    var aj = $.ajax({
        url: '/global/ajax_setPreferences.php',
        type: 'POST',
        data: str,
        success: function(transport) {
            var result = transport;
            if (typeof(result)=='undefined') {
                dialog_alert(translate('Error'), translate('An error occured when trying to save your preferences') + ':' + transport.responseText, '/images/icons/dialogs/error.png', '');
            }
        },
        error: function(transport) {
            dialog_alert(translate('Error'), translate('An error occured when trying to save your preferences') + ':' + transport.responseText, '/images/icons/dialogs/error.png', '');
        }
    });
}

function translate(word, category) {
    if (!_translation[word]) {
        return word;
    }
    else return _translation[word];
}

/*-------------------------------------*/
/*  Cookie functions                   */
/*-------------------------------------*/

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name,"",-1);
}

/*-------------------------------------*/
/*  Selectable functions               */
/*-------------------------------------*/

function selecting(event) {
    var selectedElement = $(event.target).parents('.selectable').first().addClass('ui-selecting');
    if (event.ctrlKey==0)
        $(".ui-selected").removeClass('ui-selected');
    else
        selectedElement.removeClass('ui-selected');
    if (selectedElement.length > 0) {
        selectedElement.addClass('ui-selecting');
    }
}

function select(event) {
    var selectedElement = $(event.target).parents('.selectable').first().addClass('ui-selected');
    $(".ui-selecting").removeClass('ui-selecting');
    if (event.ctrlKey==0)
        $(".ui-selected").removeClass('ui-selected');
    if (selectedElement.length > 0) {
        selectedElement.addClass('ui-selected');
        if (document.selection) {
            document.selection.clear();
        } else {
            sel=document.getSelection();
            if(sel && sel.removeAllRanges)
                sel.removeAllRanges();
        }
    }
}

function select_action(url) {
    var str = selected;
    $(".ui-selected").each(function(key, item){
        if (str!='') str = str + ',';
        str = str + $(item).attr('id');
    });
    location.href = url + urlencode(str);
}

var selected = '';
function getSelected() {
    selected = '';
    $(".ui-selected").each(function(key, item){
        if (selected!='') selected = selected + ',';
        selected = selected + $(item).attr('id');
    });
}

/*-------------------------------------*/
/*  Popup Menu functions               */
/*-------------------------------------*/

var submenu_image = '';
var popupmenu = [null];
var popupmenu_visible=true;

$(window).click(remove_popups);
//$('#contents').bind('click', remove_popups);

function startPopupMenu(event, menu) {
    if (menu['items'].length>0) {
        var target;
        var level = menu['level'];
        if (event.target) target = event.target;
        else if (event.srcElement) target = event.srcElement;
        var l = level;
        while (popupmenu[l] != null && target != popupmenu[l])
        {
            popupmenu[l].parentNode.removeChild(popupmenu[l]);
            popupmenu[l] = null;
            l++;
        }
        popupmenu_visible=true;
        var position = 'absolute';
        if (ie) position = 'absolute';

        var element = createElement('div', {
            'id' : menu['name'],
            'onmouseover' : 'popupmenu_visible=true; popupmenu_active = true;',
            'onmouseout' : 'popupmenu_visible=false; popupmenu_active = false;'
        });
        $(element).attr('style', 'position: ' + position + '; z-index: ' + (level+menu['layer']) + ';');
        document.body.appendChild(element);
        var root = element;
        element = createElement('div', {
            'id' : menu['name'] + 'Frame',
            'style' : 'position: absolute; top: 1px; left: 0px;'
        });
        root.appendChild(element);
        var parent = element;
        element = createElement('table', {
            'width' : menu['width'],
            'id' : menu['name'] + 'Table'
        });
        $(element).addClass('popupmenu' + level);
        parent.appendChild(element);
        var table = element;

        var height = 0;
        var col = menu['columns'];
        $.each(menu['items'], function(key, value) {
            var item = value;
            if (col==menu['columns']) {
                element = createElement('tr', {
                    'height' : '20',
                    'id' : menu['name'] + 'TR' + height
                });
                $(table).append($(element));
                parent = element;
                col=0;
            }
            col++;
            element = createElement('td', {
                title : item['name']
            });
            $(parent).append($(element));
            //element.appendChild(document.createTextNode(item['contents']));
            $(element).html(item['contents']);
            if (item['submenu']) {
                $(element).bind('click mouseover', item['action']);
                $(element).attr('style', 'padding-right: 14px; background-image: url("' + submenu_image + '"); background-repeat: no-repeat; background-position: 100% 50%;');
            }
            else $(element).bind('click', item['action']);
            height++;
        });
        var top = -1;
        var left = -1;
        if (level==4) top = $(target).outerHeight()-1;
        if (level>4) left = $(target).outerWidth();
        var dim = {
            height: $(table).outerHeight(),
            width: $(table).outerWidth()
        };
        var off = $(target).offset();
        if ((top+dim['height']+off.top)>myHeight || menu['forceup']==true) {
            if (level==4) top = 0 - dim['height'];
            else  top = 0 - dim['height'] + $(target).outerHeight();
        }
        if ((left+dim['width']+off.left)>myWidth) {
            if (level==4) left = 0 - dim['width'] + $(target).outerWidth();
            else left = 0 - dim['width'];
        }
        top = top + off.top;
        left = left + off.left;
        $(root).css({
            top: top + 'px',
            left: left + 'px'
        });
        popupmenu[level]=root;
        if (ie) $(root).show();
        else $(root).fadeIn('fast');
    }
}

function clearPopupMenu(menu) {
    menu['items'] = [];
}

function addItemToMenu(menu, item) {
    menu['items'][menu['items'].length] = item;
}

function remove_popups() {
    for(var l=0;l<popupmenu.length;l++)
    {
        if (popupmenu[l] != null)
        {
            if (popupmenu_visible == false)
            {
                //alert('Vuf!');
                $(popupmenu[l]).fadeOut('slow', function () {
                    popupmenu[l].parentNode.removeChild(popupmenu[l]);
                    popupmenu[l] = null;
                });
            }
            else
                popupmenu_visible = false;
        }
    }
}

/*-------------------------------------*/
/*  Dialog functions                   */
/*-------------------------------------*/

function dialog_hide() {
    $('#FullScreenLayer').fadeOut('slow', function() {
        $('#FullScreenAlertButtons').css({
            display: "none"
        });
        $('#FullScreenConfirmButtons').css({
            display: "none"
        });
        $('#FullScreenQueryButtons').css({
            display: "none"
        });
        $('#dialog_query').css({
            display: "none"
        });
    });
    $('#FullScreenTextOuter').fadeOut('slow');
}

function dialog_alert(title, message, icon, action) {
    $('#dialog_title').html(title);
    $('#dialog_message').html(message);
    $('#FullScreenMessageIcon').attr({
        src: icon
    });
    $('#dialog_ok').bind('click', function(event){
        dialog_hide();
        eval(action);
    });
    if (ie) $('#FullScreenAlertButtons').css({
        'display': "block"
    });
    else $('#FullScreenAlertButtons').css({
        'display': "table-row"
    });
    $('#FullScreenLayer').fadeTo('slow', 0.8);
    $('#FullScreenTextOuter').fadeIn('slow');
}

function dialog_confirm(title, message, icon, action) {
    getSelected();
    $('#dialog_title').html(title);
    $('#dialog_message').html(message);
    $('#FullScreenMessageIcon').attr({
        src: icon
    });
    //$('dialog_yes').writeAttribute("onclick", action + ' dialog_hide();');
    $('#dialog_yes').bind('click', function(event){
        dialog_hide();
        eval(action);
    });
    if (ie) $('#FullScreenConfirmButtons').css({
        display: "block"
    });
    else $('#FullScreenConfirmButtons').css({
        display: "table-row"
    });
    $('#FullScreenLayer').fadeTo('slow', 0.8);
    $('#FullScreenTextOuter').fadeIn('slow');
}

function dialog_query(title, message, icon, link) { 
    $('#dialog_title').html(title);
    $('#dialog_message').html(message);
    $('#FullScreenMessageIcon').attr( {
        src: icon
    } );
    $('#dialog_qok').bind('click', function(event) {
        dialog_hide();
        location.href=link + urlencode($('#dialog_query').val());
    });
    $('#dialog_query').bind('keyup', function(event) {
        var charCode = ( event.which != null ) ? event.which : event.keyCode
        if (charCode == 13)
        {
            dialog_hide();
            location.href=link + urlencode($('#dialog_query').val());
        }
        else
            //charCodes < 32 include tab, delete, arrow keys, etc
            return charCode;
    });

    if (ie) $('#FullScreenQueryButtons').css({
        display: "block"
    });
    else $('#FullScreenQueryButtons').css({
        display: "table-row"
    });
    $('#dialog_query').css({
        display: "block"
    });
    $('#FullScreenLayer').fadeTo('slow', 0.8);
    $('#FullScreenTextOuter').fadeIn('slow');
    $('#dialog_query').focus();
}


/*-------------------------------------*/
/*  Browser detect                     */
/*-------------------------------------*/

if ($.browser=='msie') ie=true;

/*-------------------------------------*/
/*  Gauge functions                    */
/*-------------------------------------*/

function Gauge (id) {
    this.name = id;
    this.height = 30;
    this.progress = 0;
    this.layer = 1;
    this.color = 'Blue';
    this.text = '';
    this.table = null;
    this.root = null;
    this.rollout = function(obj) {
        this.root = obj;
        var element = createElement('table', {
            'height' : this.height
        });
        $(element).css({
            position: 'absolute',
            'z-index': this.layer,
            width: $(obj).innerWidth() + 'px'
        });
        obj.append(element);
        this.table = parent = element;
        element = createElement('tr');
        parent.appendChild(element);
        parent = element;
        element = createElement('td', {
            'id' : this.name + 'text'
        });
        $(element).addClass('center middle');
        $(element).html(this.text);
        parent.appendChild(element);
        element = createElement('table', {
            'id' : this.name,
            'height' : this.height
        });
        $(element).css({
            'width': $(obj).innerWidth() + 'px',
        }).addClass('Gauge');
        obj.append(element);
        var parent = element;
        element = createElement('tr');
        parent.appendChild(element);
        parent = element;
        element = createElement('td');
        parent.appendChild(element);
        parent = element;
        element = createElement('div', {
            'id' : this.name + 'gauge'
        });
        $(element).css({
            width: this.progress + '%',
            height: this.height + 'px'
        });
        parent.appendChild(element);
        this.setColor(this.color);

        var guage = this;
        $(window).bind('changesize', function() {
            guage.redraw();
        });
    };
    this.redraw = function() {
        $(this.table).width($(this.root).innerWidth());
        $('#' + this.name).width($(this.root).innerWidth());
    };
    this.reinitialize = function() {
    };
    this.setText = function(text) {
        $(document).load( function() {
            var source = $('#' + this.name).offset();
            $(this.table).offset({
                top: source.top,
                left: source.left
            });
        });
        $(this.table).height($('#' + this.name).height());
        $(this.table).width($('#' + this.name).width());
        $('#' + this.name + 'text').html(text);
        this.text = text;
        this.reinitialize();
    };
    this.setColor = function(col) {
        $('#' + this.name + 'gauge').removeClass(this.color);
        this.color = col;
        $('#' + this.name + 'gauge').addClass(this.color);
        this.reinitialize();
    };
    this.setProgress = function(pro) {
        if (pro > 100) pro = 100;
        else if (pro < 0) pro = 0;
        this.progress = pro;
        $("#" + this.name + 'gauge').css({
            width: pro + '%'
        });
        this.reinitialize();
    }
};

/*-------------------------------------*/
/*  Columns functions                  */
/*-------------------------------------*/

function Columns (id, configurations) {
    this.name = id;
    this.configurations = configurations;
    this.root = null;
    this.spacing = 10;
    this.redraw = function() {
        var index = 0;
        var usable = false;
        var configuration;
        var configurations = this.configurations;
        var root = this.root;
        var colwidths = [];
        var col = 0;
        var conwidth = 0;
        var colwidth = 0;
        var spacing = this.spacing;
        var length = configurations.length;
        //$(this.root).width('100%');
        while (!usable && index < length) {
            configuration = configurations[index];
            conwidth = 0;
            colwidths = [];
            col = 0;
            $.each(configuration, function(key, column) {
                colwidth = 0;
                $.each(column, function(key, item) {
                    $('#' + item).show();
                    if ($('#' + item).width() > colwidth) colwidth = $('#' + item).width();
                });
                if (conwidth != 0) conwidth += spacing;
                conwidth += colwidth;
                colwidths[col] = colwidth;
                col++;
            });
            if (conwidth < $(root).innerWidth()) {
                usable = true;
            } else index++;
        }
        if (index == length) index--;
        configuration = configurations[index];
        var offset = $(root).offset();
        var left = offset.left;
        //left = 0;
        left += Math.round(($(root).innerWidth()-conwidth)/2);
        var top = offset.top;
        //top = 0;
        
        //var table = $('<table>');
        //$(table).appendTo(this.root);
        //var tr = $('<tr>');
        //$(tr).appendTo(table);

        //$(this.root).width(conwidth);
        col = 0;
        $.each(configuration, function(key, column) {
            //var td = $('<td>');
            if (col != 0) left += spacing;
            colwidth = colwidths[col];
            top = offset.top;
            //top = 0;
            $.each(column, function(key, item) {
                var extraleft = Math.round((colwidth - $('#' + item).width())/2);
                $('#' + item).show();
                var itemoff = $('#' + item).offset();
                $('#' + item).offset({left: (left + extraleft), top: top});
                //$('#' + item).css({left: (itemoff.left - (left + extraleft)), top: (itemoff.top - top)});
                top += $('#' + item).height() + spacing;
            });
            left += colwidth;
            col++;
        });
    };
    this.rollout = function(obj) {
        this.root = obj;
        var columns = this;
        $(window).bind('changesize', function() {
            columns.redraw();
        });
        $(window).load(function() {
            columns.redraw();
        });
    };
};
