function progressBar(ss, perc) {
    return '<div class="indicator"><div class="filled' + ss + '" style="width: ' + (perc / 2).toFixed(0) + 'px;"/></div>';
}

function altEval(body) {
    return eval(body);
}

function jsonPost(url, data, func, arg) {

    var x = new Ajax.Request(url, {
        method: 'post',
        parameters: data,

        onSuccess: function(transport) {
            var response = transport.responseText;
            if (func) {
                func(response, arg, true);
            }
        },
        onFailure: function(transport) {
            func(transport, arg, false);
        }
    });
}

function getURLParameter(paramName, defaultValue) {
    var sURL = document.URL.toString();

    if (sURL.indexOf('?') > 0) {
        var arrParams = sURL.split('?');
        var hIdx = arrParams[1].indexOf('#');
        var hlen = hIdx > 0 ? hIdx : (arrParams[1].length);
        var arrURLParams = arrParams[1].substring(0, hlen).split('&');
        var i = 0;

        for (i = 0; i < arrURLParams.length; i++) {
            var sParam = arrURLParams[i].split('=');

            if (sParam[0].toLowerCase() == paramName.toLowerCase()) {
                if (sParam[1] !== '') {
                    return unescape(sParam[1]);
                } else {
                    return defaultValue;
                }
            }
        }
    }

    return defaultValue;
}


function setStringURLParameter(url, paramName, paramValue) {
    var sURL = url;
    var nURL = '';
    if (sURL.indexOf('?') > 0) {
        var arrParams = sURL.split('?');
        var arrURLParams = arrParams[1].split('&');
        nURL = arrParams[0] + '?';
        var i = 0;
        var found = 0;
        for (i = 0; i < arrURLParams.length; i++) {
            var sParam = arrURLParams[i].split('=');

            if (sParam[0].toLowerCase() == paramName.toLowerCase()) {
                if (sParam[1] !== '') {
                    found = 1;
                    nURL += paramName + '=' + paramValue;
                }
            } else {
                nURL += arrURLParams[i];
            }
            if (i != arrURLParams.length - 1) {
                nURL += '&';
            }
        }
        if (found === 0) {
            nURL += '&' + paramName + '=' + paramValue;
        }
    } else {
        nURL = sURL + '?' + paramName + '=' + paramValue;
    }
    return nURL;
}

function evalParams(input) {
    var re = /(\$|\#)([^\$\#]+)(\$|\#)/g;
    var out = '';
    var li = 0;
    var mat = re.exec(input);
    while (mat !== null) {
        out += input.substr(li, mat.index - li);
        var p = mat[2];
        if (mat[1] == '#') {
            out += urlencode(getHashParameter(p, '_'));
        } else {
            out += urlencode(getURLParameter(p));
        }
        li = mat.index + mat[0].length;
        mat = re.exec(input);
    }
    out += input.substr(li);
    return out;
}


function ajaxTooltip_getTopPos(inputObj) {
    var returnValue = inputObj.offsetTop;
    while ((inputObj = inputObj.offsetParent) !== null) {
        if (inputObj.tagName != 'HTML') {
            returnValue += inputObj.offsetTop;
        }
    }
    return returnValue;
}

function ajaxTooltip_getLeftPos(inputObj) {
    var returnValue = inputObj.offsetLeft;
    while ((inputObj = inputObj.offsetParent) !== null) {
        if (inputObj.tagName != 'HTML') {
            returnValue += inputObj.offsetLeft;
        }
    }
    return returnValue;
}


function setURLParameter(paramName, paramValue) {
    var sURL = document.URL.toString();
    var nURL = '';
    if (sURL.indexOf('?') > 0) {
        var arrParams = sURL.split('?');
        var arrURLParams = arrParams[1].split('&');
        nURL = arrParams[0] + '?';
        var i = 0;
        var found = 0;
        for (i = 0; i < arrURLParams.length; i++) {
            var sParam = arrURLParams[i].split('=');

            if (sParam[0].toLowerCase() == paramName.toLowerCase()) {
                if (sParam[1] !== '') {
                    found = 1;
                    nURL += paramName + '=' + paramValue;
                }
            } else {
                nURL += arrURLParams[i];
            }
            if (i != arrURLParams.length - 1) {
                nURL += '&';
            }
        }
        if (found === 0) {
            nURL += '&' + paramName + '=' + paramValue;
        }
    } else {
        nURL = sURL + '?' + paramName + '=' + paramValue;
    }
    return nURL;
}

function check(cb, rgn, id) {
    PageMethods.CheckItems(rgn, cb.checked, id);
}

function checkall(ch, rgn) {
    var ids = '';
    var tr = ch.parentNode.parentNode.parentNode;
    while ((typeof tr != 'undefined') && (tr !== null)) {
        tr = tr.nextSibling;
        if (tr !== null) {
            if (typeof tr.childNodes[0] != 'undefined') {
                cb = tr.childNodes[0].childNodes[0].childNodes[0];
            } else {
                cb = null;
            }
            if ((cb !== null) && (cb.nodeName == 'INPUT')) {
                if (cb.parentNode.parentNode.parentNode.style.display != 'none') {
                    var re = new RegExp("\\'([^\\']*?)\\'\\)", "gm");
                    var m = re.exec(cb.attributes["onclick"].nodeValue);
                    if (m !== null) {
                        ids += m[1] + ',';
                    }

                    cb.checked = ch.checked;
                }
            }
        }
    }
    if (ids.length > 0) {
        PageMethods.CheckItems(rgn, ch.checked, ids);
    }
}



function allVisibleChecked(ch) {
    var tr = ch.parentNode.parentNode.parentNode;
    while ((typeof tr != 'undefined') && (tr !== null)) {
        tr = tr.nextSibling;
        if (tr !== null) {
            cb = tr.childNodes[0].childNodes[0].childNodes[0];
            if ((cb !== null) && (cb.nodeName == 'INPUT')) {
                if (cb.parentNode.parentNode.parentNode.style.display != 'none') {
                    if (cb.checked === false) {
                        return false;
                    }
                }
            }
        }
    }
    return true;
}


function checkallvisible(ch, root, rgn) {
    var ids = '';
    var inputs = document.getElementsByTagName('input');
    if (!root) {
        root = 'chk';
    }

    for (var i = 0; i < inputs.length; i++) {
        if ((inputs[i].getAttribute('type') == 'checkbox') && inputs[i].id && (inputs[i].id.substring(0, root.length) == root)) {
            if (inputs[i].parentNode.parentNode.style.display != 'none') {
                var re = new RegExp("\\'([^\\']*?)\\'\\)", "gm");
                var m = re.exec(inputs[i].onclick);
                if (m !== null) {
                    ids += m[1] + ',';
                }
                inputs[i].checked = ch.checked;
            }
        }
    }
    if (ids.length > 0) {
        PageMethods.CheckItems(rgn, ch.checked, ids);
    }
}

function showFilter(lblId, tbId, ftbid) {
    document.getElementById(lblId).style.display = 'none';
    document.getElementById(tbId).style.display = 'inline';
    document.getElementById(ftbid).focus();
    return false;
}

function hideFilter(lblId, fId, bd) {
    document.getElementById(lblId).style.display = 'inline';
    document.getElementById(fId).style.display = 'none';
    document.getElementById(bd).style.display = 'inline';
    return false;
}

function showMessage(title, message, type) {
    var url = '/Message.aspx?t=' + title + '&m=' + message + '&ty=' + type;
    var content = '<iframe width=\'350px\' height=\'150px\' src=\'' + url + '\' frameborder=\'0\' scrolling=\'no\'> </iframe>';
    displayStaticMessage(content, '350', '150');
}

function showMessageWSize(title, message, type, width, height) {
    var url = '/Message.aspx?t=' + title + '&ty=' + type + '&w=' + width + '&h=' + height;
    var content = '<form id="pula" name="pula" method="POST" action="' + url + '" target="frame"><input type="hidden" name="imessage" id="imessage" value=\'' + message + '\'/></form>';
    content+='<iframe name=\'frame\' width=\'' + width + 'px\' height=\'' + height + 'px\' frameborder=\'0\' scrolling=\'no\'> </iframe>';
    displayStaticMessage2(content, width, height, false, 'pula');
}

function showUpgradeMessage(title, message, type) {
    var url = '/UpgradeMessage.aspx?t=' + title + '&m=' + message + '&ty=' + type;
    var content = '<iframe width=\'350px\' height=\'250px\' src=\'' + url + '\' frameborder=\'0\' scrolling=\'no\'> </iframe>';
    displayStaticMessage(content, '350', '250');
}

function isChecked(id) {
    var e = document.getElementById(id);
    if (e) {
        return e.checked || (e.style.display == 'none');
    } else {
        return false;
    }
}

function filterRedirect(u, p, f, v) {
    var val = document.getElementById(v).value;
    var url;
    if (u.indexOf('?') >= 0) {
        url = u + '&' + p + 'f' + f + '=' + val;
    } else {
        url = u + '?' + p + 'f' + f + '=' + val;
    }
    window.location = url;
}

function OnItemChange(dropdown, pageParamName) {
    var myindex = dropdown.selectedIndex;
    var SelValue = dropdown.options[myindex].value;
    document.location = setURLParameter(pageParamName, SelValue);
}

function AddPaginationDropdown(host, pageParamName, pageCount, pageSize, maxItemCount) {
    var dd = document.createElement('select');
    var i;
    for (i = 0; i < pageCount; i++) {
        var item = document.createElement('option');
        item.setAttribute('value', i);
        item.innerHTML = (i * pageSize + 1).toString() + ' to ' + Math.min(((i + 1) * pageSize + 1), maxItemCount).toString();
        dd.appendChild(item);
    }
    dd.onchange = function() {
        OnItemChange(this, pageParamName);
    };
    dd.setAttribute('class', 'pagdrop');
    dd.setAttribute('className', 'pagdrop');
    var cPage = getURLParameter(pageParamName);
    if (cPage && (cPage < pageCount)) {
        dd.selectedIndex = cPage;
    }
    document.getElementById(host).appendChild(dd);
}

function AddPageSizeDropdown(host, pageParamName, pageSizes) {
    var dd = document.createElement('select');
    var sizes = pageSizes.split(',');
    var i = 0;
    var cValue = getURLParameter(pageParamName);
    var selectedIndex = 0;
    for (i = 0; i < sizes.length; i++) {
        if ((cValue) && (sizes[i] == cValue)) {
            selectedIndex = i;
        }
        var item = document.createElement('option');
        item.setAttribute('value', sizes[i]);
        item.innerHTML = sizes[i];
        dd.appendChild(item);
    }
    dd.onchange = function() {
        OnItemChange(this, pageParamName);
    };
    dd.selectedIndex = selectedIndex;
    dd.setAttribute('class', 'pagdrop');
    dd.setAttribute('className', 'pagdrop');
    document.getElementById(host).appendChild(dd);
}

function setColumnVisibility(tableId, columns) {
    var t = document.getElementById(tableId);
    var shColumns = columns.split('#');
    var scols, hcols, k, i, j;
    if ((shColumns.length > 0) && (shColumns[0].length > 0)) {
        scols = shColumns[0].split(",");
    }
    if ((shColumns.length > 1) && (shColumns[1].length > 0)) {
        hcols = shColumns[1].split(",");
    }
    var rows = t.tBodies[0].getElementsByTagName('tr');
    for (i = 0; i < rows.length; i++) {
        var headers = rows[i].getElementsByTagName('th');
        for (j = 0; j < headers.length; j++) {
            if (headers[j].id) {
                var thid = headers[j].id.split('-')[1];
                if (scols) {
                    for (k = 0; k < scols.length; k++) {
                        if (scols[k] == thid) {
                            headers[j].style.display = '';
                        }
                    }
                }
                if (hcols) {
                    for (k = 0; k < hcols.length; k++) {
                        if (hcols[k] == thid) {
                            headers[j].style.display = 'none';
                        }
                    }
                }
            }
        }
        var xcolumns = rows[i].getElementsByTagName('td');
        for (j = 0; j < xcolumns.length; j++) {
            if (scols) {
                for (k = 0; k < scols.length; k++) {
                    if (scols[k] == j) {
                        xcolumns[j].style.display = '';
                    }
                }
            }
            if (hcols) {
                for (k = 0; k < hcols.length; k++) {
                    if (hcols[k] == j) {
                        xcolumns[j].style.display = 'none';
                    }
                }
            }
        }
    }
}


function get_cookie(cookie_name) {
    var results = document.cookie.match('(^|;) ?' + cookie_name + '=([^;]*)(;|$)');

    if (results) {
        return (unescape(results[2]));
    } else {
        return null;
    }
}

function set_cookie(name, value, exp_y, exp_m, exp_d, path, domain, secure) {
    var cookie_string = name + "=" + escape(value);

    if (exp_y) {
        var expires = new Date(exp_y, exp_m, exp_d);
        cookie_string += "; expires=" + expires.toGMTString();
    }

    if (path) {
        cookie_string += "; path=" + escape(path);
    }

    if (domain) {
        cookie_string += "; domain=" + escape(domain);
    }

    if (secure) {
        cookie_string += "; secure";
    }

    document.cookie = cookie_string;
}

function delete_cookie(cookie_name) {
    var cookie_date = new Date(); // current date & time
    cookie_date.setTime(cookie_date.getTime() - 1);
    document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString();
}

function nodeNavigation(c, p) {
    var steps = p.split(',');
    var evalString = 'c';
    for (var i = 0; i < steps.length; i++) {
        switch (steps[i].toLowerCase()) {
            case 'p':
                evalString += '.parentNode';
                break;
            case 'ns':
                evalString += '.nextSibling';
                break;
            case 'ps':
                evalString += '.previousSibling';
                break;
            default:

                if (steps[i].toLowerCase().substr(0, 1) == 'c') {
                    evalString += '.childNodes[' + steps[i].substring(1, steps[i].length) + ']';
                }
                break;

        }

    }    
    return eval(evalString);
}

function tableexport(prefix, format, l, d) {
    anylinkcssmenu.hidedivmenu(l, d);
    var div = document.getElementById(d);
    var cb = div.getElementsByTagName('select')[0];
    var newform = document.createElement('form');
    newform.action = window.location;
    newform.method = 'post';

    var opElement = document.createElement('input');
    opElement.setAttribute('type', 'hidden');
    opElement.setAttribute('id', 'export');
    opElement.setAttribute('name', 'export');
    opElement.setAttribute('value', format + cb.selectedIndex + prefix);
    newform.appendChild(opElement);

    document.body.appendChild(newform);
    newform.submit();
}

function showProcessing() {
    displayStaticMessage('<div class="processing">Processing... Please wait<br/><img src="/img/loading.gif" alt=""/></div>', 204, 54);
}

function closeProcessing() {
    closeMessage();
}

function showTutorials(vid) {
    var url = '/Help/Tutorials.aspx?vid=' + vid;
    displayStaticMessage('<div class=\"messageHeader\"><a href="javascript:void(0);" onclick="parentCloseMessage();">Close</a></div><iframe width="1150px" height="600" src="' + url + '" frameborder="0" scrolling="no"></iframe>', '1150', '570', 1);
}

function processingLink(url) {
    window.location = url;
    setTimeout(function() {
        showProcessing();
    }, 100);
}

function selectTableRow(tableId, row, skipRows, color) {
    var tbl = document.getElementById(tableId);
    if (typeof tbl == 'undefined') {
        return;
    }
    var crow = tbl.childNodes[0].childNodes[skipRows];
    var rowidx = 0;
    while (crow) {
        if (rowidx == row) {
            crow.style.backgroundColor = color;
        } else {
            crow.style.backgroundColor = '';
        }
        crow = crow.nextSibling;
        rowidx++;
    }
}

function enterclick(e, dest) {
    if (e && e.which) {
        characterCode = e.which;
    } else {
        e = event;
        characterCode = e.keyCode;
    }

    if (characterCode == 13) {
        document.getElementById(dest).click();
        return false;
    } else {
        return true;
    }

}

function getHashParameter(key, defaultValue) {
    var h = window.location.hash;
    if (h.length > 0) {
        h = h.substring(1, h.length);
    }
    var splits = h.split(',');
    var i = 0;
    for (i = 0; i < splits.length; i++) {
        if (splits[i].length > 0) {
            var ix = splits[i].indexOf('-');
            var xk = splits[i].substring(0, ix);
            var xv = splits[i].substring(ix + 1, splits[i].length);
            if ((key) == xk) {
                return xv;
            }
        }
    }
    return defaultValue;
}

function setHashParameter(key, value) {
    var h = window.location.hash;
    if (h.length > 0) {
        h = h.substring(1, h.length);
    }
    var splits = h.split(',');
    var i = 0;
    var res = '';
    var found = false;
    if (window.location.hash.length === 0) {
        res = '#';
    }
    for (i = 0; i < splits.length; i++) {
        if (splits[i].length > 0) {
            var ix = splits[i].indexOf('-');
            var xk = splits[i].substring(0, ix);
            var xv = splits[i].substring(ix + 1, splits[i].length);
            if ((key) == xk) {
                res += xk + '-' + value + ',';
                found = true;
            } else {
                res += xk + '-' + xv + ',';
            }
        }
    }
    if (!found) {
        res += key + '-' + value + ',';
    }
    window.location.hash = res.substring(0, res.length - 1);
}

function isdefined(variable) {
    return (typeof (window[variable]) == "undefined") ? false : true;
}

function waitfor(v, action) {
    if (!isdefined(v)) {
        setTimeout('waitfor(\'' + v + '\', \'' + action + '\');', 100);
    } else {
        setTimeout('eval(\'' + action + '\')', 100);
    }
}

function urlencode(str) {
    return escape(str).replace(/\+/g, '%2B').replace(/%20/g, '+').replace(/\*/g, '%2A').replace(/\//g, '%2F').replace(/@/g, '%40');
}

function handleError(err, url, line) {
    try {
        var stack = err.stack || arguments.callee.caller || "";
        var message = err;
        var client = navigator.userAgent + ' ' + navigator.appName + ' ' + navigator.appVersion + ' ' + navigator.platform;
        jsonPost('/error.json', {
            "url": url,
            "stack": stack,
            "message": message,
            "windowUrl": window.location,
            "client": client
        }, null);
    }
    catch (e) { }
    return false;
}

function commaNumber(nStr, decimals) {
    nStr += '';
    if (typeof decimals == 'undefined') {
        decimals = 2;
    }
    x = nStr.split('.');
    x1 = x[0];
    x2 = ((x.length > 1) && (decimals > 0)) ? '.' + x[1].substring(0, decimals) : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

function wrapText(text, count) {
    var res = '';
    var i = 0;
    for (i = 0; i < text.length / count; i++) {
        res += text.substring(i * count, (i + 1) * count) + '<wbr/><span class="wbr"></span>';
    }
    return res;
}

window.onerror = handleError;

window.exportDivs = {};

function hideExportDiv(target) {
    var t = target;
    while (t.className !== 'exportDivOuter') {
        t = t.parentNode;
    }
    try {
        jQuery(t).hide("normal", function() {
            t.style.display = 'none';
        });
    }
    catch (e) { }
}

function showExportDiv(anchor, externalVariable, idx, checkboxSelectionField, exports) {
    if (typeof window.exportDivs[externalVariable + '-' + idx] == 'undefined') {
        var outer = document.createElement('div');
        var a = jQuery(anchor);
        outer.className = 'exportDivOuter';
        outer.style.paddingLeft = 0;
        outer.style.paddingTop = 0;

        outer.style.left = a.position().left + 'px';
        outer.style.top = a.position().top + 'px';

        var inner = document.createElement('div');
        inner.className = 'exportDivInner';
        if (checkboxSelectionField != '') {
            var chb = document.createElement('INPUT');
            chb.setAttribute("type", "checkbox");
            chb.setAttribute("class", "checkbox");
            chb.setAttribute("className", "checkbox");
            inner.appendChild(chb);
            theText = document.createTextNode('Selected only');
            inner.appendChild(theText);
            inner.appendChild(document.createElement('br'));
        }

        var input = document.createElement('input');
        input.setAttribute('class', 'button');
        input.setAttribute('className', 'button');
        input.setAttribute('type', 'submit');        
        input.setAttribute('onclick', 'return ' + externalVariable + '.doexport(this, \'txt\', ' + idx + ');');
        input.onclick = new Function(externalVariable + '.doexport.call(' + externalVariable + ', this, \'txt\', ' + idx + ');');
        
        input.setAttribute('value', 'Text');
        inner.appendChild(input);

        input = document.createElement('input');
        input.setAttribute('class', 'button');
        input.setAttribute('className', 'button');
        input.setAttribute('type', 'submit');
        input.onclick = new Function(externalVariable + '.doexport.call(' + externalVariable + ', this, \'xls\', ' + idx + ');');

        input.setAttribute('value', 'Excel');
        inner.appendChild(input);

        document.body.appendChild(outer);
        outer.appendChild(inner);
        window.exportDivs[externalVariable + '-' + idx] = outer;
    }
    var tdiv = window.exportDivs[externalVariable + '-' + idx];
    jQuery(tdiv).show("normal");
    jQuery(tdiv).mouseleave(

	function(event) {
	    jQuery(event.target).unbind();
	    hideExportDiv(event.target);
	});
}
function fixMinWidthForIE(parent) {    
    try {
        if (!document.body.currentStyle) { return } //IE only
    } catch (e) { return }
    var elems;
    if (parent)
        elems = parent.getElementsByTagName("*");
    else
        elems = document.getElementsByTagName("*");        
    for (e = 0; e < elems.length; e++) {
        var eCurStyle = elems[e].currentStyle;
        var l_minWidth = (eCurStyle.minWidth) ? eCurStyle.minWidth : eCurStyle.getAttribute("min-width"); //IE7 : IE6
        if (l_minWidth && l_minWidth != 'auto') {
            var shim = document.createElement("DIV");
            shim.style.cssText = 'margin:0 !important; padding:0 !important; border:0 !important; line-height:0 !important; height:0 !important; BACKGROUND:RED;';
            shim.style.width = l_minWidth;
            shim.appendChild(document.createElement("&nbsp;"));
            if (elems[e].canHaveChildren) {
                elems[e].appendChild(shim);
            } else {
                //??
            }
        }
    }
}