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

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

var myWidth = 0, myHeight = 0, obj = null;

function document_resize(event) {
    if (myWidth != $(window).width() || myHeight != $(window).height()) {
        myWidth = $(window).width();
        myHeight = $(window).height();

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

function document_reload() {
    myWidth = $(window).width();
    myHeight = $(window).height();

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

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

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

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;
}

/*-------------------------------------*/
/*  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               */
/*-------------------------------------*/

var selected = [];

function onselect(event) {
    var selectedElement;
    selectedElement = $(event.target).parents('.selectable').first().addClass('selected');
    if (event.ctrlKey==0)
        unselect_all();
    if (selectedElement.length > 0) {    
        selected.push(selectedElement.attr('id'));
        selectedElement.addClass('selected');
        sel=window.getSelection();
        if(sel && sel.removeAllRanges)
            sel.removeAllRanges();
    }
}

$(window).click(onselect);

function unselect_all() {
    $.each(selected, function(key, item) {
        $('#' + item).removeClass('selected');
    });
    selected = [];
}

function select_start(event) {

}

function select_end(event) {

}

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

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

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

$(window).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'],
            'class' : 'popupmenu' + level,
            'id' : menu['name'] + 'Table'
        });
        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']));
            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 = 2;
        if (level==4) top = $(target).outerHeight();
        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;
    }
}

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

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

function remove_popups(event) {
    for(var l=0;l<popupmenu.length;l++)
    {
        if (popupmenu[l] != null)
        {
            if (popupmenu_visible == false)
            {
                popupmenu[l].parentNode.removeChild(popupmenu[l]);
                popupmenu[l] = null;
            }
            else
                popupmenu_visible = false;
        }
    }
}

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

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

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').css({
        display: "block"
    });
    $('#FullScreenTextOuter').css({
        display: "block"
    });
}

function dialog_confirm(title, message, icon, action) {
    $('#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').css({
        display: "block"
    });
    $('#FullScreenTextOuter').css({
        display: "block"
    });
}

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').css({
        display: "block"
    });
    $('#FullScreenTextOuter').css({
        display: "block"
    });
    $('#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.rollout = function(obj) {
        var element = createElement('table', {
            'height' : this.height
        });
        $(element).css({
            position: 'absolute',
            'z-index': this.layer,
            width: '200px'
        });
        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,
            'class' : 'Gauge',
            'width' : '100%',
            'height' : this.height
        });
        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);
    };
    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();
    }
};