function is_msie()
{
    var ua = navigator.userAgent,
        m = ua.match(/MSIE (\d+(\.\d+)?)/);

    if (ua.indexOf('Opera') == -1 && m)
        return parseFloat(m[1]);
    else
        return 0;
}

function is_opera()
{
    var ua = navigator.userAgent,
        m = ua.match(/Opera.(\d+(\.\d+)?)/);

    if (m)
        return parseFloat(m[1]);
    else
        return 0;
}

function is_mozilla()
{
    var ua = navigator.userAgent,
        m = ua.match(/Gecko/);

    if (m)
        return 1;
    else
        return 0;
}

function setCookie(name, value, expire)
{
    document.cookie = name + "=" + escape(value) + ((expire == null)?"":("; expires=" + expire.toGMTString()))
}

function getCookie(name)
{
    var srch = name + "=";
    if (document.cookie.length > 0) {
        offset = document.cookie.indexOf(srch);
        if (offset != -1) {
            offset += srch.length;
            end = document.cookie.indexOf(";", offset);
            if (end == -1) {
                end = document.cookie.length;
            }
            return unescape(document.cookie.substring(offset, end))
        }
    }
}

var quirksMode = !document.compatMode || document.compatMode == 'BackCompat';

function getClientWidth()
{
    return !quirksMode ? document.documentElement.clientWidth : document.body.clientWidth;
}

function getClientHeight()
{
    return !quirksMode ? document.documentElement.clientHeight : document.body.clientHeight;
}

function getScrollLeft()
{
    return !quirksMode ? 
    	document.documentElement.scrollLeft :
    	document.body.scrollLeft;
}

function getScrollTop()
{
    return !quirksMode ? 
    	document.documentElement.scrollTop :
    	document.body.scrollTop;
}

function getScrollWidth()
{
    return !quirksMode ? 
    	document.documentElement.scrollWidth :
    	document.body.scrollWidth;
}

function getScrollHeight()
{
    return !quirksMode ? 
    	document.documentElement.scrollHeight :
    	document.body.scrollHeight;
}

function scrollTo(sl, st)
{
	if (!quirksMode) {
		document.documentElement.scrollLeft = sl;
		document.documentElement.scrollTop = st;
	} else {
		document.body.scrollLeft = sl;
		document.body.scrollTop = st;
	}
}

function getControlPixelPos(e, ofs_x, ofs_y, w, h, pad)
{
    var l = ofs_x;
    var t = ofs_y;
    var ctl = e;
    if (!pad) pad = 0;
    while (e && e.tagName != 'BODY')
    {
        var p = e.offsetParent;
        l += e.offsetLeft;
        t += e.offsetTop;
        l -= p && p.tagName != 'BODY' ? p.scrollLeft : 0;
        t -= p && p.tagName != 'BODY' ? p.scrollTop : 0;
        e = p;
    }
    if (w > 0 && h > 0) {
        if (l > getClientWidth()+getScrollLeft()-w-pad-1) {
            l += ctl.offsetWidth-w;
            if (l > getClientWidth()+getScrollLeft()-w-pad-1) {
                l = getClientWidth()+getScrollLeft()-w-pad-1;
            }
            if (l < getScrollLeft()+pad+1) {
            	l = getScrollLeft()+pad+1;
           	}
        }
        if (t > getClientHeight()+getScrollTop()-h-pad-1) {
            t = getClientHeight()+getScrollTop()-h-pad-1;
        }
        if (t < getScrollTop()+pad+1) {
        	t = getScrollTop()+pad+1;
       	}
    }
    return new Array(l, t);
}

function add_to_favorites()
{    
    if (typeof(window.external) != "undefined") {
        var url = window.location.href;
        url = url.replace(/&psid=[a-z0-9]+/g, '');
        url = url.replace(/\?psid=[a-z0-9]+&/g, '');
        url = url.replace(/\?psid=[a-z0-9]+/g, '');
        var desc = (document.title? document.title: url);
        window.external.AddFavorite(url, desc);
    }
    else
    {
        alert("Sorry, your browser does not support this feature.");
    }
}

function add_to_fav(url, desc)
{
    if (typeof(window.external) != "undefined") {
        window.external.AddFavorite(url, desc);
    } else {
        alert("Sorry, your browser does not support this feature.");
    }
}

function send_to_friend(url, subj, text)
{
    location.href='mailto:?subject='+escape(subj)+'&body='+escape(text);
}

function open_window(url, attr)
{
    if (attr) {
        window.open(url, '', attr);
    } else {
        window.open(url);
    }
}

function nav_dropdown_change(ctl)
{   
    var url = ctl.options[ctl.selectedIndex].value.replace(/ /g, '');
    if (url) {
        if (m = url.match(/^popup\((\d+),(\d+),(.*)\)$/))
            open_window(m[3], 'scrollbars=yes,resizable=yes,width='+m[1]+',height='+m[2]);
        else if (m = url.match(/^new\((.*)\)$/))
            open_window(m[1], '');
        else  {
            var sf = session_suffix;
            if (sf) {
                if (url.indexOf('?') == -1) url += '?'; else url += '&';
                url += sf;
            }
            location.href = url;
        }
    }
}

function OpenHelp(id, plugin_page) 
{ 
    window.open(plugin_page + '?showhelp=' + id + '&' + session_suffix, '', 'width=600,height=500,scrollbars=yes');
}

function ctl_get_attr(ctl, name)
{
    if (ctl.getAttribute) {
        return ctl.getAttribute(name);
    } else {
        return ctl[name];
    }
}

function ctl_set_attr(ctl, name, value)
{
    if (ctl.setAttribute) {
        ctl.setAttribute(name, value);
    } else {
        ctl[name] = value;
    }
}

function AjaxFrameRefresh(frameId, args, shownd)
{
    if (!frameId) return false;
    var form = getFormByFrame(frameId);
    if (!form) return false;
    var url = window.location.href;
    url += -1 == url.indexOf('?') ? '?' : '&';
    url += 'ajaxdst=' + getPluginByForm(form) + ':' + getInterfaceByForm(form) + ':' + frameId;
    if (args) url += '&' + args;
    for (var i = 0; i < form.elements.length; i++) {
        form.elements[i].disabled = true;
    }
    if (shownd) {
        showWaitWnd();
    }
    AjaxRequest(url);
}

function ajaxPostSubmit(form, action, wait)
{
    if (wait) {
        showWaitWnd();
    }
    if (action) {
        form.submitAction.value = action;
    }
    form.submit();
    if (wait) {
        for (var i = 0; i < form.elements.length; i++) {
            form.elements[i].disabled = true;
        }
    }
}

var waitHidden = new Array(), waitFade = false;

function showWaitWnd(text, width, fade)
{
    var wnd_wait = document.getElementById('wnd_wait');
    if (wnd_wait) {
        if (fade) {
            popup_fade_background(true);
            waitFade = true;
        }
        var wnd_wait_text = document.getElementById('wnd_wait_text');
        wnd_wait_text.innerHTML = text ? text : 'Please wait...';
        var w = width ? width : 150, h = 30;
        wnd_wait.style.width = w + 'px';
        wnd_wait.style.height = h + 'px';
        wnd_wait.style.top = getClientHeight() / 2 - h / 2 + getScrollTop();
        wnd_wait.style.left = getClientWidth() / 2 - w / 2 + getScrollLeft();
        if (is_msie() && is_msie() < 7.0) {
            // shit, it's IE
            waitHidden = new Array();
            var cl = wnd_wait.style.pixelLeft, cr = cl+wnd_wait.style.pixelWidth,
                ct = wnd_wait.style.pixelTop,  cb = ct+wnd_wait.style.pixelHeight;
            var c = document.getElementsByTagName('SELECT');
            for (var i = 0; i < c.length; i++) {
                var cl1 = 0, ct1 = 0, e = c[i];
                while (e) {
                    cl1 += e.offsetLeft;
                    ct1 += e.offsetTop;
                    e = e.offsetParent;
                }
                var cr1 = cl1+c[i].offsetWidth, cb1 = ct1+c[i].offsetHeight;
                if (c[i] && c[i].style.visibility != 'hidden'
                && !(cl1 > cr || cr1 < cl || ct1 > cb || cb1 < ct)) {
                    c[i].style.visibility = 'hidden';
                    waitHidden.push(c[i]);
                }
            }
        }
        wnd_wait.style.display = '';
    }
}

function hideWaitWnd()
{
    var wnd_wait = document.getElementById('wnd_wait');
    if (wnd_wait) {
        wnd_wait.style.display = 'none';
        if (waitFade) {
            popup_fade_background(false);
            waitFade = false;
        }
        for (var i = 0; i < waitHidden.length; i++) {
            if (waitHidden[i]) {
                waitHidden[i].style.visibility = 'visible';
            }
        }
    }
}

function is_valid_email(ctl)
{
    if (window.RegExp) {
        var reg = new RegExp("^([_\.a-zA-Z0-9\-]+@[_a-zA-Z0-9\-]+(\.[_a-zA-Z0-9\-]+)+)?$", "g");
        if (!reg.test(ctl.value)) {
            fviewSetError(ctl.form, ctl.name, "Incorrect email format");
            return false;
        }
    }    
    return true;
}

function form_check_confirmation(f) 
{
    var vNeedConfirm = getControlsByForm(f, 'form_need_confirmation');
    if (vNeedConfirm && vNeedConfirm.length > 0 && vNeedConfirm[0].value == 1) {
        return confirm('Please review the information you entered.\nSelect OK if the information' +
                       ' is accurate, select Cancel to make corrections before submitting.');
    }
    return true;
}

function form_show_wait_msg(f)
{
    var inputs = f.getElementsByTagName('INPUT');
    for (var i = 0; i < inputs.length; i++) {
        if (inputs[i].type == 'file') {
            showWaitWnd('Uploading files, please wait...', 240);
            break;
        }
    }
}

var popupUploadCallback = false;
function popupUploadFilesShow(id, ctl, params, callback)
{
    var sess = session_suffix ? ('&' + session_suffix) : '';
    var url = 'core/file_store/file_upload.php?iID=' + id + '&ctl=' + ctl;
    for (var k in params) {
        url += '&params[' + k + ']=' + escape(params[k]);
    }
    if (callback) { 
        url += '&callback=1';
        popupUploadCallback = callback;
    }
    url += sess;
    var e = document.getElementById('anchor_' + ctl);
    var h = params.max*24 + 150 + (params.enable_java ? 70 : 0);
    if (h > 500) h = 500;
    popup_exec_url(url, e, 400, h, true);
}

function popupUploadDone(id, ctl, num)
{
    if (popupUploadCallback) {
        hide_popup();
        var f = popupUploadCallback;
        popupUploadCallback = false;
        f(id, ctl, num);
    }
} 

function prnt() 
{
    if (window.print) {
        window.print();
    } else {
        alert('Sorry, your browser doesn\'t support this feature.');
    }
}

function _dump(d, l) 
{
    if (l == null) l = 1;
    var s = "";
    if ("object" == typeof(d)) {
        s += typeof(d) + " {\n";
        for (var k in d) {
            for (var i = 0; i < l; i++) s += "  ";
            s += k + ": " + _dump(d[k], l + 1);
        }
        for (var i = 0; i < l - 1; i++) s += "  ";
        s += "}\n"
    } else {
        s += d + "\n";
    }
    return s;
}

function addWindowOnLoad(fnc)
{
    if (is_msie()) {
        window.attachEvent('onload', fnc);
    } else {
        window.addEventListener('load', fnc, false);
    }
}

function fviewSetError(form, item_name, text)
{
    var frameId = form.getAttribute('attr_frame_id');
    if (!frameId) frameId = 0;
    var e = document.getElementById('fview_err_' + frameId + '_' + item_name);
    if (e) e.innerHTML = text ? 
        '<img src="/Images/error_arrow.gif" width="12" height="7" align="baseline">&nbsp;' 
        + text : '';
    e.parentNode.style.display = text ? '' : 'none';
}

function goTo(url)
{
    var p = location.pathname.replace(/^.*\//, '');
    if (!p) p = './';
    if (url != p) {
        if (url.indexOf('?') == -1) url += '?'; else url += '&';
        url += 'prev_url=' + escape(p);
    }
    location.href = url;
}

/**
 * SWFObject v1.5: Flash Player detection and embed - http://blog.deconcept.com/swfobject/
 *
 * SWFObject is (c) 2007 Geoff Stearns and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 */
if(typeof deconcept == "undefined") var deconcept = new Object();
if(typeof deconcept.util == "undefined") deconcept.util = new Object();
if(typeof deconcept.SWFObjectUtil == "undefined") deconcept.SWFObjectUtil = new Object();
deconcept.SWFObject = function(swf, id, w, h, ver, c, quality, xiRedirectUrl, redirectUrl, detectKey) {
    if (!document.getElementById) { return; }
    this.DETECT_KEY = detectKey ? detectKey : 'detectflash';
    this.skipDetect = deconcept.util.getRequestParameter(this.DETECT_KEY);
    this.params = new Object();
    this.variables = new Object();
    this.attributes = new Array();
    if(swf) { this.setAttribute('swf', swf); }
    if(id) { this.setAttribute('id', id); }
    if(w) { this.setAttribute('width', w); }
    if(h) { this.setAttribute('height', h); }
    if(ver) { this.setAttribute('version', new deconcept.PlayerVersion(ver.toString().split("."))); }
    this.installedVer = deconcept.SWFObjectUtil.getPlayerVersion();
    if (!window.opera && document.all && this.installedVer.major > 7) {
        // only add the onunload cleanup if the Flash Player version supports External Interface and we are in IE
        deconcept.SWFObject.doPrepUnload = true;
    }
    if(c) { this.addParam('bgcolor', c); }
    var q = quality ? quality : 'high';
    this.addParam('quality', q);
    this.setAttribute('useExpressInstall', false);
    this.setAttribute('doExpressInstall', false);
    var xir = (xiRedirectUrl) ? xiRedirectUrl : window.location;
    this.setAttribute('xiRedirectUrl', xir);
    this.setAttribute('redirectUrl', '');
    if(redirectUrl) { this.setAttribute('redirectUrl', redirectUrl); }
}
deconcept.SWFObject.prototype = {
    useExpressInstall: function(path) {
        this.xiSWFPath = !path ? "expressinstall.swf" : path;
        this.setAttribute('useExpressInstall', true);
    },
    setAttribute: function(name, value){
        this.attributes[name] = value;
    },
    getAttribute: function(name){
        return this.attributes[name];
    },
    addParam: function(name, value){
        this.params[name] = value;
    },
    getParams: function(){
        return this.params;
    },
    addVariable: function(name, value){
        this.variables[name] = value;
    },
    getVariable: function(name){
        return this.variables[name];
    },
    getVariables: function(){
        return this.variables;
    },
    getVariablePairs: function(){
        var variablePairs = new Array();
        var key;
        var variables = this.getVariables();
        for(key in variables){
            variablePairs[variablePairs.length] = key +"="+ variables[key];
        }
        return variablePairs;
    },
    getSWFHTML: function() {
        var swfNode = "";
        if (navigator.plugins && navigator.mimeTypes && navigator.mimeTypes.length) { // netscape plugin architecture
            if (this.getAttribute("doExpressInstall")) {
                this.addVariable("MMplayerType", "PlugIn");
                this.setAttribute('swf', this.xiSWFPath);
            }
            swfNode = '<embed type="application/x-shockwave-flash" src="'+ this.getAttribute('swf') +'" width="'+ this.getAttribute('width') +'" height="'+ this.getAttribute('height') +'" style="'+ this.getAttribute('style') +'"';
            swfNode += ' id="'+ this.getAttribute('id') +'" name="'+ this.getAttribute('id') +'" ';
            var params = this.getParams();
             for(var key in params){ swfNode += [key] +'="'+ params[key] +'" '; }
            var pairs = this.getVariablePairs().join("&");
             if (pairs.length > 0){ swfNode += 'flashvars="'+ pairs +'"'; }
            swfNode += '/>';
        } else { // PC IE
            if (this.getAttribute("doExpressInstall")) {
                this.addVariable("MMplayerType", "ActiveX");
                this.setAttribute('swf', this.xiSWFPath);
            }
            swfNode = '<object id="'+ this.getAttribute('id') +'" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="'+ this.getAttribute('width') +'" height="'+ this.getAttribute('height') +'" style="'+ this.getAttribute('style') +'">';
            swfNode += '<param name="movie" value="'+ this.getAttribute('swf') +'" />';
            var params = this.getParams();
            for(var key in params) {
             swfNode += '<param name="'+ key +'" value="'+ params[key] +'" />';
            }
            var pairs = this.getVariablePairs().join("&");
            if(pairs.length > 0) {swfNode += '<param name="flashvars" value="'+ pairs +'" />';}
            swfNode += "</object>";
        }
        return swfNode;
    },
    write: function(elementId){
        if(this.getAttribute('useExpressInstall')) {
            // check to see if we need to do an express install
            var expressInstallReqVer = new deconcept.PlayerVersion([6,0,65]);
            if (this.installedVer.versionIsValid(expressInstallReqVer) && !this.installedVer.versionIsValid(this.getAttribute('version'))) {
                this.setAttribute('doExpressInstall', true);
                this.addVariable("MMredirectURL", escape(this.getAttribute('xiRedirectUrl')));
                document.title = document.title.slice(0, 47) + " - Flash Player Installation";
                this.addVariable("MMdoctitle", document.title);
            }
        }
        if(this.skipDetect || this.getAttribute('doExpressInstall') || this.installedVer.versionIsValid(this.getAttribute('version'))){
            var n = (typeof elementId == 'string') ? document.getElementById(elementId) : elementId;
            n.innerHTML = this.getSWFHTML();
            return true;
        }else{
            if(this.getAttribute('redirectUrl') != "") {
                document.location.replace(this.getAttribute('redirectUrl'));
            }
        }
        return false;
    }
}

/* ---- detection functions ---- */
deconcept.SWFObjectUtil.getPlayerVersion = function(){
    var PlayerVersion = new deconcept.PlayerVersion([0,0,0]);
    if(navigator.plugins && navigator.mimeTypes.length){
        var x = navigator.plugins["Shockwave Flash"];
        if(x && x.description) {
            PlayerVersion = new deconcept.PlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/, "").replace(/(\s+r|\s+b[0-9]+)/, ".").split("."));
        }
    }else if (navigator.userAgent && navigator.userAgent.indexOf("Windows CE") >= 0){ // if Windows CE
        var axo = 1;
        var counter = 3;
        while(axo) {
            try {
                counter++;
                axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+ counter);
//              document.write("player v: "+ counter);
                PlayerVersion = new deconcept.PlayerVersion([counter,0,0]);
            } catch (e) {
                axo = null;
            }
        }
    } else { // Win IE (non mobile)
        // do minor version lookup in IE, but avoid fp6 crashing issues
        // see http://blog.deconcept.com/2006/01/11/getvariable-setvariable-crash-internet-explorer-flash-6/
        try{
            var axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
        }catch(e){
            try {
                var axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
                PlayerVersion = new deconcept.PlayerVersion([6,0,21]);
                axo.AllowScriptAccess = "always"; // error if player version < 6.0.47 (thanks to Michael Williams @ Adobe for this code)
            } catch(e) {
                if (PlayerVersion.major == 6) {
                    return PlayerVersion;
                }
            }
            try {
                axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
            } catch(e) {}
        }
        if (axo != null) {
            PlayerVersion = new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));
        }
    }
    return PlayerVersion;
}
deconcept.PlayerVersion = function(arrVersion){
    this.major = arrVersion[0] != null ? parseInt(arrVersion[0]) : 0;
    this.minor = arrVersion[1] != null ? parseInt(arrVersion[1]) : 0;
    this.rev = arrVersion[2] != null ? parseInt(arrVersion[2]) : 0;
}
deconcept.PlayerVersion.prototype.versionIsValid = function(fv){
    if(this.major < fv.major) return false;
    if(this.major > fv.major) return true;
    if(this.minor < fv.minor) return false;
    if(this.minor > fv.minor) return true;
    if(this.rev < fv.rev) return false;
    return true;
}
/* ---- get value of query string param ---- */
deconcept.util = {
    getRequestParameter: function(param) {
        var q = document.location.search || document.location.hash;
        if (param == null) { return q; }
        if(q) {
            var pairs = q.substring(1).split("&");
            for (var i=0; i < pairs.length; i++) {
                if (pairs[i].substring(0, pairs[i].indexOf("=")) == param) {
                    return pairs[i].substring((pairs[i].indexOf("=")+1));
                }
            }
        }
        return "";
    }
}
/* fix for video streaming bug */
deconcept.SWFObjectUtil.cleanupSWFs = function() {
    var objects = document.getElementsByTagName("OBJECT");
    for (var i = objects.length - 1; i >= 0; i--) {
        objects[i].style.display = 'none';
        for (var x in objects[i]) {
            if (typeof objects[i][x] == 'function') {
                objects[i][x] = function(){};
            }
        }
    }
}
// fixes bug in some fp9 versions see http://blog.deconcept.com/2006/07/28/swfobject-143-released/
if (deconcept.SWFObject.doPrepUnload) {
    if (!deconcept.unloadSet) {
        deconcept.SWFObjectUtil.prepUnload = function() {
            __flash_unloadHandler = function(){};
            __flash_savedUnloadHandler = function(){};
            window.attachEvent("onunload", deconcept.SWFObjectUtil.cleanupSWFs);
        }
        window.attachEvent("onbeforeunload", deconcept.SWFObjectUtil.prepUnload);
        deconcept.unloadSet = true;
    }
}
/* add document.getElementById if needed (mobile IE < 5) */
if (!document.getElementById && document.all) { document.getElementById = function(id) { return document.all[id]; }}

/* add some aliases for ease of use/backwards compatibility */
var getQueryParamValue = deconcept.util.getRequestParameter;
var FlashObject = deconcept.SWFObject; // for legacy support
var SWFObject = deconcept.SWFObject;
function checkAll(f, act)
{
    var frameId = f.getAttribute('attr_frame_id');
    var eId = 'active' == act ? 'check_active_id' : 'check_delete_id';
    if (frameId > 0)  {
        var e = getFrameElementById(frameId, eId);
    } else {
        var e = document.getElementById(eId);
    }
    var checked = 'Click to check all' == e.title ? 0 : 1;
    checked = !checked;
    var els = document.getElementsByName(act + 'IdArr[]');
    for (var i = 0; i < els.length; i++) {
        if (!els[i].disabled) {
            els[i].checked = checked;
        }
    }
    if (checked) {
        e.title = 'Click to uncheck all';
    } else {
        e.title = 'Click to check all';
    }
}

function applyClick(f, act)
{
    if ('apply' == act || 'delete' == act) {
        var checkedItems = 0;
        var els = document.getElementsByName('deleteIdArr[]');
        for (i = 0; i < els.length; i++) {
            if (els[i].checked) {
                checkedItems++;
            }
        }
        if (checkedItems) {
            if (checkedItems == 1) {
                var ok = confirm('You are about to delete ' + checkedItems + ' item. Proceed?');
            } else {
                var ok = confirm('You are about to delete ' + checkedItems + ' items. Proceed?');
            }
            if (!ok) {
                return false;
            }
        }
    }
    if ('function' == typeof submit_click) {
        submit_click();
    }
    f.submitAction.value = act;
    f.submit();
}

function listApply(form, action, prompt)
{
    if (!action || action == 'apply' || prompt) {
        var checkedItems = deletedItems = 0;
        for (i = 0; i < form.elements.length; i++) {
            if (form.elements[i].tagName == 'INPUT'
            && form.elements[i].type == 'checkbox'
            && form.elements[i].checked) {
                if (form.elements[i].name.substr(0, 6) == "delete") {
                    deletedItems++;
                }
                checkedItems++;
            }
        }
        if (!checkedItems) {
            alert('Please select at least one item.');
            return false;
        }
        if (deletedItems != 0) {
            var ok = confirm('You are about to delete ' + deletedItems + ' item' + 
                (deletedItems == 1 ? '' : 's') + '. Proceed?');
            if (!ok) {
                return false;
            }
        } else if (checkedItems != 0 && prompt) {
            var ok = confirm(prompt.replace('%n', checkedItems));
            if (!ok) {
                return false;
            }
        }
    }
    if (action && form.submitAction) {
        form.submitAction.value = action;
    }
    form.submit();
    return true;
}

var listCheckFlag_delete = true;
var listCheckFlag_active = false;
var selCounter = new Array();

function listCheckAll(form, action)
{
    var flag = eval('listCheckFlag_' + action);
    eval('listCheckFlag_' + action + ' = !flag');
    selCounter[action] = 0;
    for (var i = 0; i < form.elements.length; i++) {
        if (form.elements[i].name.substr(0, action.length) == action) {
            form.elements[i].checked = flag;
            if (flag) selCounter[action]++;
        }
    }
    refreshSelCounter(form, action, false);
}

function modifySelCounter(form, action, ctl)
{
    if (!selCounter[action]) selCounter[action] = 0;
    var cur = parseInt(ctl.getAttribute('_status'));
    if (cur && !ctl.checked) {
        selCounter[action]--;
    } else if (!cur && ctl.checked) {
        selCounter[action]++;
    }
    ctl.setAttribute('_status', ctl.checked ? 1 : 0);
    refreshSelCounter(form, action, false);
}

function refreshSelCounter(form, action, recalc)
{
    var e = document.getElementById('sel_counter_' + action);
    if (!e) return;
    var c;
    if (recalc) {
        c = 0;
        var els = form.elements;
        for (i = 0; i < els.length; i++) {
            var el = form.elements[i]; 
            if (el.name.substr(0, action.length) == action && el.checked) {
                c++;
            }
        }
        selCounter[action] = c;
    } else {
        c = selCounter[action];
    }
    e.innerHTML = 
        (c == 0 ? 'No' : c.toString()) + ' ' + (c == 1 ? 'item' : 'items') + ' selected.'; 
}

function treeExpandRow(row)
{
	var exp = 1-parseInt(row.getAttribute('_expanded'));
    row.setAttribute('_expanded', exp);
    var img = document.getElementById(row.id + '_img');
    if (img) {
        if (img.src.indexOf('bottom') != -1) {
            img.src = exp ? '/Images/minusbottom.gif' : '/Images/plusbottom.gif';
        } else {
            img.src = exp ? '/Images/minus.gif' : '/Images/plus.gif';
        }
    }
    st = document.getElementById(row.id + '_st');
    if (st) st.value = exp;
    if (row.style.display == 'none') return;
    var level1 = row.getAttribute('_level');
    var rexp = new Array();
    rexp[level1] = 1;
    while (1) {
    	row = row.nextSibling;
    	if (!row) break;
    	if (row.tagName != 'TR' || row.getAttribute('_level') == '' 
    		|| row.getAttribute('_level') == null) continue;
    	var level2 = parseInt(row.getAttribute('_level'));
    	if (level2 <= level1) break;
        var exp1;
        if (!exp) exp1 = 0;
        else {
            rexp[level2] = parseInt(row.getAttribute('_expanded'));
            exp1 = rexp[level2-1];
        }
        row.style.display = exp1 ? '' : 'none';
    }
}

function treeExpandRows(rows)
{
    for (var i=0; i<rows.length; i++) {
        treeExpandRow(rows[i]);
    }
}

var movedRow = null, moveTarget = null, movedRowIndex = 0,  mPos = '', oldNewRG = null, movedRowCC = 1;
function selMovedRow(row, sel)
{
    rows = row.parentNode.parentNode.rows;
    rowIndex = row.rowIndex;
    while (rows[rowIndex].getAttribute('onmouseover') != '' && rows[rowIndex].getAttribute('cc') != '' && parseInt(rows[rowIndex].getAttribute('cc')) == 0){
        rowIndex--;
    }
    movedRowCC = 1;
    if (rows[rowIndex].getAttribute('cc')){
        movedRowCC = parseInt(rows[rowIndex].getAttribute('cc'));
    }
    for(var j=rowIndex; j<rowIndex+movedRowCC; j++){
        rows[j].style.backgroundColor = sel ? '#EEEEEE' : 'transparent';
        for (var i = 0; i < row.cells.length; i++) {
            rows[j].cells[i].style.backgroundColor = sel ? '#EEEEEE' : 'transparent';
        }
    }
}

function startMoving(event)
{
	if (!event) event = window.event;
    movedRow = event.target ? event.target : event.srcElement;
    moveTarget = null;
    while (movedRow && movedRow.tagName != 'TR') movedRow = movedRow.parentNode;
    if (!movedRow) return;
    oldNewRG = null;
    movedRowIndex = movedRow.rowIndex;
    selMovedRow(movedRow, 1);
    document.body.style.cursor = 'move';
    if (is_msie()) {
        document.body.attachEvent("onmouseup", endMoving);
        document.body.attachEvent("onselectstart", movingSelectStart);
    } else {    
        addEventListener("mouseup", endMoving, false);
        event.preventDefault();
    }
}

function moveRow(event)
{
    if (!movedRow) {
        return;
    }
	if (!event) event = window.event;
	if (mPos == event.clientX + ' ' + event.clientY) {
	    return;
	}
	mPos = event.clientX + ' ' + event.clientY;
	
    var newRow = event.target ? event.target : event.srcElement;
    while (newRow && newRow.tagName != 'TR') newRow = newRow.parentNode;
    if (!newRow) {
        return;
    }
    if ('prevPageRow' == newRow.id) {
        if ('function' == typeof moveToPrevPage) {
            moveToPrevPage();
          }
        return;
    }
    if ('nextPageRow' == newRow.id) {
        if ('function' == typeof moveToNextPage) {
            moveToNextPage();
        }
        return;
    }
    if (movedRow.rowIndex == newRow.rowIndex){
        oldNewRG = null;
        return;
    }
    moveTarget = newRow;
    
    var rows = movedRow.parentNode.parentNode.rows;
    // RG - first rowgroup item
    var newRG = newRow.rowIndex;
    while (rows[newRG].getAttribute('onmouseover') != '' && rows[newRG].getAttribute('cc') != '' 
    && parseInt(rows[newRG].getAttribute('cc')) == 0) {
        newRG--;
    }
    var movedRG = movedRow.rowIndex;
    while (rows[movedRG].getAttribute('onmouseover') != '' && rows[movedRG].getAttribute('cc') != '' 
    && parseInt(rows[movedRG].getAttribute('cc')) == 0) {
        movedRG--;
    }
    if (movedRG == newRG) {
        oldNewRG = null;
        return;
    }
    if (rows[newRG] == oldNewRG || rows[newRG].getAttribute('onmouseover') == null) { 
        return;
    }
    oldNewRG = rows[newRG];

    var minRow = Math.min(movedRG, newRG);
    var maxRow = Math.max(movedRG, newRG);
    var maxRowCC = 1;
    if (rows[maxRow].getAttribute('cc')) {
        var maxRowCC = parseInt(rows[maxRow].getAttribute('cc'));
    }
    var first_node = rows[minRow];
    for (j = 0; j < maxRowCC; j++) {
        if (is_msie() && is_msie() <= 6) {
            var move_id = rows[maxRow+j].id;
            var statuses = getCheckBoxStatuses(rows[maxRow+j]);
        }
        movedRow.parentNode.insertBefore(rows[maxRow+j], first_node);
        if (is_msie() && is_msie() <= 6) {
            setCheckBoxStatuses(document.getElementById(move_id), statuses);
        }
    }
    return;
}

function endMoving(event)
{
    if (!movedRow) return;
	if (!event) event = window.event;
    var table = movedRow.parentNode;
    while (null != table && table.nodeName != 'TABLE') {
        table = table.parentNode;
    } 
    document.body.style.cursor = 'auto';
    if (typeof(rowMoved) == "function" && moveTarget
    && moveTarget != movedRow && movedRow.rowIndex != movedRowIndex) {
    	rowMoved(movedRow, moveTarget);
    }
    selMovedRow(movedRow, 0);
    movedRow = null;
    moveTarget = null;
    if (is_msie()) {
        document.body.detachEvent("onmouseup", endMoving);
        document.body.detachEvent("onselectstart", movingSelectStart);
    } else {    
        removeEventListener("mouseup", endMoving, false);
        event.preventDefault();
    }
}

function getCheckBoxStatuses(Element)
{
    var res = new Array();
    if(!Element) return res;
    var els = Element.getElementsByTagName('input');
    for (var i = 0; i < els.length; i++) {
        if (els[i].type=='checkbox') {
            res[els[i].name] = els[i].checked;
        }
    }
    return res;
}

function setCheckBoxStatuses(Element, statuses)
{
    if(!Element) return res;
    var els = Element.getElementsByTagName('input');
    for (var i = 0; i < els.length; i++) {
        if (els[i].type=='checkbox' && statuses[els[i].name] != undefined) {
            els[i].checked = statuses[els[i].name];
        }
    }
}

function movingSelectStart()
{
	return false;
}

var tooltipCtl = null;
var curTipId = '';
function tooltip(ctl, tip_id, event, width)
{
    var tw = width ? width+'px' : '200px'
    if (!tooltipCtl) {
        tooltipCtl = document.createElement('DIV');
        tooltipCtl.style.background = '#FFFFE0';
        tooltipCtl.style.border = 'solid 1px #808080';
        tooltipCtl.style.padding = '4px';
        tooltipCtl.style.visibility = 'hidden';
        tooltipCtl.style.position = 'absolute';
        document.body.appendChild(tooltipCtl);
    }    
    if (tip_id && tooltipCtl.style.width != tw) {
        tooltipCtl.style.width = tw;
    }
    if (!tip_id) {
        tooltipCtl.style.visibility = 'hidden';
        curTipId = '';
    } else {  
        var t = document.getElementById(tip_id);
        if (t) {
            tooltipCtl.style.visibility = 'visible';
            if (curTipId != tip_id) {
                tooltipCtl.innerHTML = t.innerHTML;
                curTipId = tip_id;
            }
            var left = event.clientX + 2 + getScrollLeft(), 
                top = event.clientY + 20 + getScrollTop();
            left = max(min(left, getClientWidth() + getScrollLeft() - 
                tooltipCtl.offsetWidth), 0);
            top = max(min(top, getClientHeight() + getScrollTop() - 
                tooltipCtl.offsetHeight), 0);
            tooltipCtl.style.left = left + 'px';
            tooltipCtl.style.top = top + 'px';
        }
    }
}

var balloonContainers = new Object();
function showBalloon(id, ctl, direction, container, xofs, yofs)
{
    var parent = document.getElementById('balloon_'+id);
    if (parent) {
        parent.style.display = '';
        var container = balloonContainers[id];
        container.style.display = '';
        return;
    }
    var msie = is_msie();
    var ext = msie && msie < 7.0 ? '.gif' : '.png';
    var bw = container.offsetWidth+28, bh = container.offsetHeight+28, bx, by, x, y;
    switch (direction) {
        case 'lt': ox = 5; oy = 5; break;
        case 'lb': ox = 5; oy = ctl.offsetHeight-5; break;
        case 'rt': ox = ctl.offsetWidth-5; oy = 5; break;
        case 'rb': ox = ctl.offsetWidth-5; oy = ctl.offsetHeight-5; break;
    }
    ox += xofs ? xofs : 0;
    oy += yofs ? yofs : 0;
    var a = getControlPixelPos(ctl, ox, oy, 0, 0), x = a[0], y = a[1];
    switch (direction) {
        case 'lt': bx = x-bw-36; by = y-bh-17; break;
        case 'lb': bx = x-bw-34; by = y+17; break;
        case 'rt': bx = x+37; by = y-bh-17; break;
        case 'rb': bx = x+36; by = y+17; break;
    }
    var parent = document.createElement('DIV');
    parent.id = 'balloon_'+id;
    parent.style.position = 'absolute';
    parent.style.left = parent.style.top = parent.style.width = parent.style.height = '0px';
    document.body.appendChild(parent);
    var back = document.createElement('DIV');
    back.style.position = 'absolute'; back.style.left = bx+6+'px'; back.style.top = by+6+'px'; 
    back.style.width = bw-12+'px'; back.style.height = bh-12+'px';
    back.style.background = '#fffde1';
    parent.appendChild(back);
    var img = document.createElement('IMG');
    img.src = '/Images/lt' + ext;
    img.style.position = 'absolute'; img.style.left = bx+'px'; img.style.top = by+'px'; 
    img.style.width = 12+'px'; img.style.height = 12+'px';
    parent.appendChild(img);
    var img = document.createElement('IMG');
    img.src = '/Images/rt' + ext;
    img.style.position = 'absolute'; img.style.left = bx+bw-12+'px'; img.style.top = by+'px';
    img.style.width = 12+'px'; img.style.height = 12+'px';
    parent.appendChild(img);
    var img = document.createElement('IMG');
    img.src = '/Images/lb' + ext;
    img.style.position = 'absolute'; img.style.left = bx+'px'; img.style.top = by+bh-12+'px'; 
    img.style.width = 12+'px'; img.style.height = 12+'px';
    parent.appendChild(img);
    var img = document.createElement('IMG');
    img.src = '/Images/rb' + ext;
    img.style.position = 'absolute'; img.style.left = bx+bw-12+'px'; img.style.top = by+bh-12+'px'; 
    img.style.width = 12+'px'; img.style.height = 12+'px';
    parent.appendChild(img);
    var img = document.createElement('IMG');
    img.src = '/Images/l' + ext;
    img.style.position = 'absolute'; img.style.left = bx+'px'; img.style.top = by+12+'px'; 
    img.style.width = 6+'px'; img.style.height = bh-24+'px';
    parent.appendChild(img);
    var img = document.createElement('IMG');
    img.src = '/Images/t' + ext;
    img.style.position = 'absolute'; img.style.left = bx+12+'px'; img.style.top = by+'px'; 
    img.style.width = bw-24+'px'; img.style.height = 6+'px';
    parent.appendChild(img);
    var img = document.createElement('IMG');
    img.src = '/Images/r' + ext;
    img.style.position = 'absolute'; img.style.left = bx+bw-6+'px'; img.style.top = by+12+'px'; 
    img.style.width = 6+'px'; img.style.height = bh-24+'px';
    parent.appendChild(img);
    var img = document.createElement('IMG');
    img.src = '/Images/b' + ext;
    img.style.position = 'absolute'; img.style.left = bx+12+'px'; img.style.top = by+bh-6+'px'; 
    img.style.width = bw-24+'px'; img.style.height = 6+'px';
    parent.appendChild(img);
    container.style.position = 'absolute'; 
    container.style.left = bx+12+'px';
    container.style.top = by+12+'px';
    container.style.width = bw-24+'px';
    container.style.height = bh-24+'px';
    container.style.background = '#fffde1';
    container.style.zIndex = 10000;
    balloonContainers[id] = container;
    container.style.visibility = 'visible';
    var img = document.createElement('IMG');
    img.style.position = 'absolute'; 
    switch (direction) {
        case 'lt' :
            img.src = '/Images/arrow_rb' + ext;
            img.style.left = x-52+'px'; img.style.top = y-36+'px'; 
            img.style.width = 52+'px'; img.style.height = 36+'px';
            break;
        case 'lb' :
            img.src = '/Images/arrow_rt' + ext;
            img.style.left = x-52+'px'; img.style.top = y+'px'; 
            img.style.width = 52+'px'; img.style.height = 36+'px';
            break;
        case 'rt' :
            img.src = '/Images/arrow_lb' + ext;
            img.style.left = x+'px'; img.style.top = y-36+'px'; 
            img.style.width = 52+'px'; img.style.height = 36+'px';
            break;
        case 'rb' :
            img.src = '/Images/arrow_lt' + ext;
            img.style.left = x+'px'; img.style.top = y+'px'; 
            img.style.width = 52+'px'; img.style.height = 36+'px';
            break;
    }
    parent.appendChild(img);
}

function hideBalloon(id)
{
    var parent = document.getElementById('balloon_'+id);
    if (parent) {
        parent.style.display = 'none';
        var container = balloonContainers[id];
        container.style.display = 'none';
    }
}

var ajaxInRequest = false, ajaxQueue = new Array();
function AjaxRequest(url)
{
    if (ajaxInRequest) {
        ajaxQueue.push(url);
        return;
    }
    ajaxInRequest = true;
    var head = document.getElementsByTagName('head').item(0);
    var old = document.getElementById("AJAXScript");
    if (old) head.removeChild(old);
    var script = document.createElement("SCRIPT");
    script.src = url + "&ajaxrequest=" + Math.random().toString() +
        "&ajaxqs=" + escape(location.search);
    script.type = "text/javascript"
    script.id = "AJAXScript";
    head.appendChild(script);
}

function AjaxEndRequest()
{
    ajaxInRequest = false;
    if (ajaxQueue.length) {
        var url = ajaxQueue.shift();
        AjaxRequest(url);
    } else {
        if (typeof(hideWaitWnd) == "function") hideWaitWnd();
    }
}

function AjaxRefresh(args)
{
    var url = window.location.href;
    if (args) {
    	url += (-1 == url.indexOf('?') ? '?' : '&') + args;
    }
    AjaxRequest(url);
}

function currency_separator(value, sep)
{
    var rem = 0;
    var res = '';
    while (value >= 1000) {
        rem = value % 1000;
        while (rem.toString().length < 3) rem = '0' + rem;
        res = sep + rem + res;
        value = Math.floor(value / 1000);
    }
    return value + res;
}

function currency_format(value, currency)
{
    switch (currency.sep) {
        case ',':
        case 'comma': currency.sep = ','; break;
        case ' ':
        case 'space': currency.sep = ' '; break;
        default: currency.sep = ''; break;
    }
    value = Math.round(value * 100) / 100;
    var str = value.toString();
    var dot = str.indexOf('.');
    if (dot != -1) {
        var v1 = str.substring(0, dot);
        var v2 = str.substring(dot + 1, str.length);
        while (v2.length < 2) {
            v2 += '0';
        }
        return currency.sign + currency_separator(v1, currency.sep) + '.' + v2;
    } else {
        return currency.sign + currency_separator(str, currency.sep) + '.00';
    }
}

function disableControls(form)
{
    for (var i = 0; i < form.elements.length; i++) {
        form.elements[i].disabled = true;
    }
}

/**
 * Base (common / universal) function for search form controls.
 *
 * @param  mixed  aValue       (int) Frame ID if search by Frame
 *                             (int) Interface Instance ID if search by Interface
 *                             (obj) Reference to form
 * @param  string aControlName Control Name
 * @param  string aAttrName    Form attribute name for comparison with "aValue". If "aValue" is reference to form, may be false or unsigned.
 * @return mixed               FALSE if no controls found, control's array otherwise
 * @access private
*/
function _getControlsCommon(aValue, aControlName, aAttrName)
{
    if (!aValue)      return false;
    if (!aControlName) return false;
    var ctls = document.getElementsByName(aControlName);
    if (!ctls || !ctls.length) return false;
    var out        = new Array();
    var form       = false;
    var vNeedValue = false;
    for (var i = 0; i < ctls.length; i++ ) {
        form   = ctls[i].form;
        if (!form) continue;
        if ((aAttrName == 'attr_frame_id') || (aAttrName == 'attr_instance_id')) {
            vNeedValue = form.getAttribute(aAttrName);
            if (vNeedValue == aValue) out[out.length] = ctls[i];
        } else if (!aAttrName) {
            if (form == aValue)       out[out.length] = ctls[i];
        }
    }
    return out.length ? out : false;
}

/**
 * Find form by Frame ID
 * 
 * @param  int    frameId     Frame ID
 * @return mixed              FALSE if form not found, reference to form otherwise
 * @access public
*/
function getFormByFrame(frameId)
{
    if (!frameId) return false;
    var forms = document.getElementsByTagName('FORM');
    var vCnt  = forms.length;
    var vFrameId = false;
    for (var i = 0; i < vCnt; i++ ) {
        vFrameId = forms[i].getAttribute('attr_frame_id');
        if (vFrameId && vFrameId == frameId) return forms[i];
    }
    return false;
}

/**
 * Get interface ID by form
 * 
 * @param  obj    form        Reference to form
 * @return mixed              Interface Instance ID on success, null on failure (attribute is not present)
 * @access public
*/
function getInterfaceByForm(form)
{
    return form.getAttribute('attr_instance_id');
}
function getPluginByForm(form)
{
    return form.getAttribute('attr_plugin_num');
}

/**
 * Get frame ID by form
 * 
 * @param  obj    form        Reference to form
 * @return mixed              Frame ID on success, null on failure (attribute is not present)
 * @access public
*/
function getFrameByForm(form)
{
    return form.getAttribute('attr_frame_id');
}

/**
 * Find form's controls by control Name and form's Frame ID
 * 
 * @param  int    frameId     Frame ID
 * @param  string controlName Control Name
 * @return mixed              FALSE if no controls found, control's array otherwise
 * @access public
*/
function getControlsByFrame(frameId, controlName)
{
    return _getControlsCommon(frameId, controlName, 'attr_frame_id')
}

/**
 * Find form's controls by control Name and form's Instance ID
 * 
 * @param  int    instanceId  Interface Instance ID
 * @param  string controlName Control Name
 * @return mixed              FALSE if no controls found, control's array otherwise
 * @access public
*/
function getControlsByInterface(instanceId, controlName)
{
    return _getControlsCommon(instanceId, controlName, 'attr_instance_id')
}

/**
 * Find form's controls by control Name
 * 
 * @param  obj    form        Reference to form
 * @param  string controlName Control Name
 * @return mixed              FALSE if no controls found, control's collection otherwise
 * @access public
*/
function getControlsByForm(form, controlName)
{
    return _getControlsCommon(form, controlName)
}

/**
 * Find frame element by ID
 * 
 * @param  int    frameId   Frame ID
 * @param  string elementId Element ID without Frame ID postfix.
 * @return mixed            FALSE if no elements found, element otherwise.
 * @access public
*/
function getFrameElementById(frameId, elementId)
{
    if (!frameId)   return false;
    if (!elementId) return false;
    var ctls = document.getElementById(elementId + '_' + frameId);
    return ctls;
}

/**
 * Find frame elements by Name
 * 
 * @param  int    frameId        Frame ID.
 * @param  string elementOldName Element Name without Frame ID postfix.
 * @return mixed                 FALSE if no elements found, element's collection otherwise.
 * @access public
*/
function getFrameElementsByName(frameId, elementOldName)
{
    if (!frameId)        return false;
    if (!elementOldName) return false;
    var ctls = document.getElementsByName(elementOldName + '_' + frameId);
    if (!ctls || !ctls.length) return false;
    return ctls;
}
