function is_msie()
{
    var m = navigator.userAgent.match(/MSIE (\d+(\.\d+)?)/);
    if (navigator.userAgent.indexOf('Opera') == -1 && m)
        return parseFloat(m[1]);
    else
        return 0;
}

function is_opera()
{
    var m = navigator.userAgent.match(/Opera.(\d+(\.\d+)?)/);
    return m ? parseFloat(m[1]) : 0;
}

function is_mozilla()
{
    var m = navigator.userAgent.match(/Gecko/),
        m1 = navigator.userAgent.match(/AppleWebKit/);
    return m && !m1 ? 1 : 0;
}

function is_webkit()
{
    var m = navigator.userAgent.match(/AppleWebKit/);
    return m ? 1 : 0;
}

function setCookie(name, value, expires, path, domain, secure)
{
    // set time, it's in milliseconds
	var today = new Date();
	today.setTime(today.getTime());
	
	/*
	if the expires variable is set, make the correct 
	expires time, the current script below will set 
	it for x number of days, to make it for hours, 
	delete * 24, for minutes, delete * 60 * 24
	*/
	if (expires) {
	   expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date(today.getTime() + (expires));
	
	document.cookie = name + "=" +escape(value) +
	((expires) ? ";expires=" + expires_date.toGMTString() : "") + 
	((path) ? ";path=" + path : "") + 
	((domain) ? ";domain=" + domain : "") +
	((secure) ? ";secure" : "");
}

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 trim(str, chars) 
{
    return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) 
{
    chars = chars || "\\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) 
{
    chars = chars || "\\s";
    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

function __getComputedStyle(element, style)
{
	var computedStyle;
	if (typeof element.currentStyle != 'undefined') {
		computedStyle = element.currentStyle; 
	} else { 
		computedStyle = document.defaultView.getComputedStyle(element, null); 
	}
	return computedStyle[style];
}

function valueFilter(e, forbidden) 
{ 
    var skip = false, 
        e = e || window.event, 
        key = String.fromCharCode(e.which || e.keyCode); 
 
    for (var i=0; i<forbidden.length; i++) { 
        if(String(forbidden[i]) === key.toLowerCase()) { 
            skip = true; 
            break; 
        } 
    } 
    if (skip) { 
        if(e.preventDefault) e.preventDefault(); 
        e.returnValue = false; 
    } 
    return true; 
} 

function valueFilterAllowed(e, allowed) 
{ 
    var skip = true, 
        e = e || window.event, 
        key = String.fromCharCode(e.which || e.keyCode);
    if ((e.which || e.keyCode) == 8 || (e.which || e.keyCode) == 9 ||
        ((e.which || e.keyCode) >= 35 && (e.which || e.keyCode) <= 40)) 
        return true;
    for (var i=0; i<allowed.length; i++) {
        if(String(allowed[i]) === key.toLowerCase()) { 
            skip = false; 
            break; 
        } 
    } 

    if (skip) { 
        if (e.preventDefault) e.preventDefault(); 
        e.returnValue = false; 
    } 
    return true;  
}

function disable(el, dis)
{
	el.disabled = dis ? true : false;
	el.style.backgroundColor = dis ? '#D4D0C8' : '';
}

hiddenElements = [];
function hideElementsByType(hideIn, showIn, tagname)
{
    var topObjPos = hideIn ? getObjPosition(hideIn) : null;
    var ctls = document.getElementsByTagName(tagname);
    for (var i = 0; i < ctls.length; i++) {
        var ctlPos = getObjPosition(ctls[i]);
        if (!topObjPos || (topObjPos.left <= ctlPos.right && 
            ctlPos.left <= topObjPos.right && 
            topObjPos.top <= ctlPos.bottom && 
            ctlPos.top <= topObjPos.bottom) &&
            ctls[i].style.visibility != 'hidden')
        {
            ctls[i].style.visibility = 'hidden';
            hiddenElements.push(ctls[i]);
        }
    }
    if (showIn) {
        var ctls = showIn.getElementsByTagName(tagname);
        for (i = 0; i < ctls.length; i++) { 
            ctls[i].style.visibility = 'visible';
        }
    }
}

function hideElements(hideIn, showIn)
{
    if (is_msie() && is_msie() < 7) {
        hideElementsByType(hideIn, showIn, 'SELECT');
    }
    hideElementsByType(hideIn, showIn, 'OBJECT');
    hideElementsByType(hideIn, showIn, 'EMBED');
}

function showElements() 
{
    if (document.getElementById('popupFadeBack') && 
        document.getElementById('popupFadeBack').style.display == '' ) return;
    for (var i = 0; i < hiddenElements.length; i++) {
        hiddenElements[i].style.visibility = 'visible';
    }
    hiddenElements = [];
}

function getObjPosition(obj) 
{ 
    var pos = getControlPixelPos(obj, 0, 0, 0, 0, 0);     
    return { left: pos[0], top: pos[1], 
        right: pos[0]+obj.offsetWidth, bottom: pos[1]+obj.offsetHeight, 
        width: obj.offsetWidth, height: obj.offsetHeight }; 
} 

function addWindowOnLoad(fnc)
{
    if (is_msie()) {
        window.attachEvent('onload', fnc);
    } else {
        window.addEventListener('load', fnc, false);
    }
}

// localStorage 
function putToLocalStorage(key, oValue, domain)
{
	if (typeof(localStorage) != "undefined") {
		var lStorage = localStorage[domain?domain:location.hostname];
		lStorage.setItem(key, toJson(oValue));
	} else {
        throw 'LocalStorage is not supported';
    }
}

function getFromLocalStorage(key, domain)
{
	if (typeof(localStorage) != "undefined") {
	   var lStorage = localStorage[domain?domain:location.hostname];
	   return lStorage.getItem(key);
	} else {
    	throw 'LocalStorage is not supported';
    }
}
function isLocalStorageAvailable()
{
	return (typeof(localStorage) != "undefined");
}

function putToSessionStorage(key, oValue)
{
	if (typeof(sessionStorage) != "undefined") {
        var sStorage = sessionStorage;
        sStorage.setItem(key, toJson(oValue));
    } else {
        throw 'SessionStorage is not supported';
    }
}

function getFromSessionStorage(key, domain)
{
    if (typeof(sessionStorage) != "undefined"){
        var sStorage = sessionStorage;
       return sStorage.getItem(key);
    } else {
        throw 'SessionStorage is not supported';
    }
}
function isSessionStorageAvailable()
{
    return (typeof(sessionStorage) != "undefined" && sessionStorage != null);
}

function putToGlobalStorage(key, oValue, domain)
{
    if (typeof(globalStorage) != "undefined") {
        var gStorage = globalStorage[domain?domain:location.hostname];
        gStorage.setItem(key, toJson(oValue));
    } else {
        throw 'GlobalStorage is not supported';
    }
}

function getFromGlobalStorage(key, domain)
{
    if (typeof(globalStorage) != "undefined") {
       var gStorage = globalStorage[domain?domain:location.hostname];
       return gStorage.getItem(key);
    } else {
        throw 'GlobalStorage is not supported';
    }
}
function isGlobalStorageAvailable()
{
    return (typeof(globalStorage) != "undefined");
}

function putToUserDataStorage(key, oValue)
{
    if (document.getElementById('storageElement') != "undefined") {
         putToUserData(key, toJson(oValue));
    } else {
        throw 'userData is not supported';
    }
}

function getFromUserDataStorage(key)
{
    if (document.getElementById('storageElement') != "undefined") {       
       return getFromUserData(key);
    } else {
        throw 'userData is not supported';
    }
}
function isUserDataStorageAvailable()
{
    return (is_msie() >= 5 && is_msie() <= 7 && document.getElementById('storageElement') != "undefined");
}

function toJson(item) 
{
	if (typeof (item.toJson) == 'function') 
       return item.toJson();
	
	var out = '';
    if (typeof(item) == 'number') {
        out = item.toString();
    } else if (typeof(item) == 'boolean') {
        out = item ? 'true' : 'false';
    } else if (typeof(item) == 'object') {
        var first = true;
        if (item.length != 'undefined') {
            // numeric array
            out = '[';
            for (var k = 0; k < item.length; k++) {
                if (!first) out += ', ';
                first = false;
                out += toJson(item[k]);
            }
            out += ']';
        } else {
            // hash
            out = '{';
            for (k1 in item) {
                if (!first) out += ', ';
                first = false;
                out +=  '"' + toJson(k1) + '": ' + toJson(item[k1]);
            }
            out += '}';
        }
    } else {
        // assume a string
        out = quote(item);

    }
    return out;
}

var escapeable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
    meta = {    // table of character substitutions
                '\b': '\\b',
                '\t': '\\t',
                '\n': '\\n',
                '\f': '\\f',
                '\r': '\\r',
                '"' : '\\"',
                '\\': '\\\\'
            };


function quote(string) {
	// If the string contains no control characters, no quote characters, and no
	// backslash characters, then we can safely slap some quotes around it.
	// Otherwise we must also replace the offending characters with safe escape
	// sequences.
    escapeable.lastIndex = 0;
    return escapeable.test(string) ?
        '"' + string.replace(escapeable, function (a) {
            var c = meta[a];
            if (typeof c === 'string') {
                return c;
            }
            return '\\u' + ('0000' +
                    (+(a.charCodeAt(0))).toString(16)).slice(-4);
        }) + '"' :
        '"' + string + '"';
}


// client side storage for ie 5-7
function initUserData()
{
	if (is_msie() >= 5 && is_msie() <= 7) {
		storage = document.getElementById('userDataStorage');
		if (!storage.addBehavior) {
			throw new 'userData is not available';
		} else {
			storage.addBehavior("#default#userData");
			storage.load("userDataStorage");
		}
		return true;
	}
	return false;
}

function putToUserData(sKey, sValue) {
	if (typeof(storage) == "undefined" && initUserData() == false) return;
    storage.setAttribute(sKey, sValue);
    storage.save("userDataStorage");
}
 
function getFromUserData(sKey) {
	if (typeof(storage) == "undefined" && initUserData() == false) return ''; 
    return storage.getAttribute(sKey);
}
 
function removeFromUserData(sKey) {
	if (typeof(storage) == "undefined" && initUserData() == false) return;
    storage.removeAttribute(sKey);
    storage.save("userDataStorage");
}

function get_html_translation_table(table, quote_style) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philip Peterson
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: noname
    // %          note: It has been decided that we're not going to add global
    // %          note: dependencies to php.js. Meaning the constants are not
    // %          note: real constants, but strings instead. integers are also supported if someone
    // %          note: chooses to create the constants themselves.
    // %          note: Table from http://www.the-art-of-web.com/html/character-codes/
    // *     example 1: get_html_translation_table('HTML_SPECIALCHARS');
    // *     returns 1: {'"': '&quot;', '&': '&amp;', '<': '&lt;', '>': '&gt;'}
    
    var entities = {}, histogram = {}, decimal = 0, symbol = '';
    var constMappingTable = {}, constMappingQuoteStyle = {};
    var useTable = {}, useQuoteStyle = {};
    
    useTable      = (table ? table.toUpperCase() : 'HTML_SPECIALCHARS');
    useQuoteStyle = (quote_style ? quote_style.toUpperCase() : 'ENT_COMPAT');
    
    // Translate arguments
    constMappingTable[0]      = 'HTML_SPECIALCHARS';
    constMappingTable[1]      = 'HTML_ENTITIES';
    constMappingQuoteStyle[0] = 'ENT_NOQUOTES';
    constMappingQuoteStyle[2] = 'ENT_COMPAT';
    constMappingQuoteStyle[3] = 'ENT_QUOTES';
    
    // Map numbers to strings for compatibilty with PHP constants
    if (!isNaN(useTable)) {
        useTable = constMappingTable[useTable];
    }
    if (!isNaN(useQuoteStyle)) {
        useQuoteStyle = constMappingQuoteStyle[useQuoteStyle];
    }
    
    if (useQuoteStyle != 'ENT_NOQUOTES') {
        entities['34'] = '&quot;';
    }
 
    if (useQuoteStyle == 'ENT_QUOTES') {
        entities['39'] = '&#039;';
    }
 
    if (useTable == 'HTML_SPECIALCHARS') {
        // ascii decimals for better compatibility
        entities['38'] = '&amp;';
        entities['60'] = '&lt;';
        entities['62'] = '&gt;';
    } else if (useTable == 'HTML_ENTITIES') {
        // ascii decimals for better compatibility
      entities['38']  = '&amp;';
      entities['60']  = '&lt;';
      entities['62']  = '&gt;';
      entities['160'] = '&nbsp;';
      entities['161'] = '&iexcl;';
      entities['162'] = '&cent;';
      entities['163'] = '&pound;';
      entities['164'] = '&curren;';
      entities['165'] = '&yen;';
      entities['166'] = '&brvbar;';
      entities['167'] = '&sect;';
      entities['168'] = '&uml;';
      entities['169'] = '&copy;';
      entities['170'] = '&ordf;';
      entities['171'] = '&laquo;';
      entities['172'] = '&not;';
      entities['173'] = '&shy;';
      entities['174'] = '&reg;';
      entities['175'] = '&macr;';
      entities['176'] = '&deg;';
      entities['177'] = '&plusmn;';
      entities['178'] = '&sup2;';
      entities['179'] = '&sup3;';
      entities['180'] = '&acute;';
      entities['181'] = '&micro;';
      entities['182'] = '&para;';
      entities['183'] = '&middot;';
      entities['184'] = '&cedil;';
      entities['185'] = '&sup1;';
      entities['186'] = '&ordm;';
      entities['187'] = '&raquo;';
      entities['188'] = '&frac14;';
      entities['189'] = '&frac12;';
      entities['190'] = '&frac34;';
      entities['191'] = '&iquest;';
      entities['192'] = '&Agrave;';
      entities['193'] = '&Aacute;';
      entities['194'] = '&Acirc;';
      entities['195'] = '&Atilde;';
      entities['196'] = '&Auml;';
      entities['197'] = '&Aring;';
      entities['198'] = '&AElig;';
      entities['199'] = '&Ccedil;';
      entities['200'] = '&Egrave;';
      entities['201'] = '&Eacute;';
      entities['202'] = '&Ecirc;';
      entities['203'] = '&Euml;';
      entities['204'] = '&Igrave;';
      entities['205'] = '&Iacute;';
      entities['206'] = '&Icirc;';
      entities['207'] = '&Iuml;';
      entities['208'] = '&ETH;';
      entities['209'] = '&Ntilde;';
      entities['210'] = '&Ograve;';
      entities['211'] = '&Oacute;';
      entities['212'] = '&Ocirc;';
      entities['213'] = '&Otilde;';
      entities['214'] = '&Ouml;';
      entities['215'] = '&times;';
      entities['216'] = '&Oslash;';
      entities['217'] = '&Ugrave;';
      entities['218'] = '&Uacute;';
      entities['219'] = '&Ucirc;';
      entities['220'] = '&Uuml;';
      entities['221'] = '&Yacute;';
      entities['222'] = '&THORN;';
      entities['223'] = '&szlig;';
      entities['224'] = '&agrave;';
      entities['225'] = '&aacute;';
      entities['226'] = '&acirc;';
      entities['227'] = '&atilde;';
      entities['228'] = '&auml;';
      entities['229'] = '&aring;';
      entities['230'] = '&aelig;';
      entities['231'] = '&ccedil;';
      entities['232'] = '&egrave;';
      entities['233'] = '&eacute;';
      entities['234'] = '&ecirc;';
      entities['235'] = '&euml;';
      entities['236'] = '&igrave;';
      entities['237'] = '&iacute;';
      entities['238'] = '&icirc;';
      entities['239'] = '&iuml;';
      entities['240'] = '&eth;';
      entities['241'] = '&ntilde;';
      entities['242'] = '&ograve;';
      entities['243'] = '&oacute;';
      entities['244'] = '&ocirc;';
      entities['245'] = '&otilde;';
      entities['246'] = '&ouml;';
      entities['247'] = '&divide;';
      entities['248'] = '&oslash;';
      entities['249'] = '&ugrave;';
      entities['250'] = '&uacute;';
      entities['251'] = '&ucirc;';
      entities['252'] = '&uuml;';
      entities['253'] = '&yacute;';
      entities['254'] = '&thorn;';
      entities['255'] = '&yuml;';
    } else {
        throw Error("Table: "+useTable+' not supported');
        return false;
    }
    
    // ascii decimals to real symbols
    for (decimal in entities) {
        symbol = String.fromCharCode(decimal)
        histogram[symbol] = entities[decimal];
    }
    
    return histogram;
}

function html_entity_decode( string, quote_style ) {
    // http://kevin.vanzonneveld.net
    // +   original by: john (http://www.jd-tech.net)
    // +      input by: ger
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // +   improved by: marc andreu
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // -    depends on: get_html_translation_table
    // *     example 1: html_entity_decode('Kevin &amp; van Zonneveld');
    // *     returns 1: 'Kevin & van Zonneveld'
    // *     example 2: html_entity_decode('&amp;lt;');
    // *     returns 2: '&lt;'
 
    var histogram = {}, symbol = '', tmp_str = '', entity = '';
    tmp_str = string.toString();
    
    if (false === (histogram = get_html_translation_table('HTML_ENTITIES', quote_style))) {
        return false;
    }
 
    // &amp; must be the last character when decoding!
    delete(histogram['&']);
    histogram['&'] = '&amp;';
 
    for (symbol in histogram) {
        entity = histogram[symbol];
        tmp_str = tmp_str.split(entity).join(symbol);
    }
    
    return tmp_str;
}

function addHandler(object, event, handler)
{
  if (typeof object.addEventListener != 'undefined')
    object.addEventListener(event, handler, false);
  else if (typeof object.attachEvent != 'undefined')
    object.attachEvent('on' + event, handler);
  else
    throw "Incompatible browser";
}

function removeHandler(object, event, handler)
{
  if (typeof object.removeEventListener != 'undefined')
    object.removeEventListener(event, handler, false);
  else if (typeof object.detachEvent != 'undefined')
    object.detachEvent('on' + event, handler);
  else
    throw "Incompatible browser";
}

function getXmlHttpRequest()
{
	var req = null;
	if (window.XMLHttpRequest) {
	    req = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
	    try {
	        req = new ActiveXObject("Msxml2.XMLHTTP");
	    } catch (e) {
	        try {
	            req = new ActiveXObject("Microsoft.XMLHTTP");
	        } catch (e) {
	            req = null;
	        }
	    }
	}
    return req;
}

function sendRequest(url)
{
    var xmlHttp = getXmlHttpRequest();
    if (xmlHttp) {
	    xmlHttp.open("GET", url, true);
	    xmlHttp.send(null);
    }
}

String.prototype.toBool = function() {
	return (/^true|1$/i).test(this);
}

function refreshSession()
{
	var matches = location.search.match(/psid=(?:[A-Za-z0-9_\.-]+)/g);
	var psid = (matches && matches[0]) ? matches[0] : (getCookie('psid') ? 'psid=' + getCookie('psid') : '');
	if (psid) {
		var session_url = location.protocol+'//'+location.hostname+'/core/track?'+psid+'&rand='+Math.random();
		sendRequest(session_url);
	}
}    

sessionRefreshTimer = setInterval("refreshSession()", 60*1000);function getUrl()
{
	var link = window.location.toString();
	var reg = /psid=[^&]+/g; 
	link = link.replace(reg, '');
	reg = /sm=[^&]+/g;
	link = link.replace(reg, '');
	reg = /\/preview/;
	link = link.replace(reg, '');
	reg = /&+/g;
	link = link.replace(reg, '&');
	reg = /&$/;
	link = link.replace(reg, '');
	reg = /\?$/;
	link = link.replace(reg, '');
	return link;
}

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 addToFav(ctrl)
{
	var url = ctrl.getAttribute('data-url').replace('%current_url%', getUrl());
    var desc = ctrl.getAttribute('data-desc');
    add_to_fav(url, desc);
}

function add_to_fav(url, desc)
{
    if (typeof(window.external) != "undefined" && 
    	typeof(window.external.AddFavorite) != "undefined") 
    {
        window.external.AddFavorite(url, desc);
    } else {
        alert("Sorry, your browser does not support this feature.");
    }
}

function sendToFriend(ctrl)
{
    var subj = ctrl.getAttribute('data-subj');
    var text = ctrl.getAttribute('data-text').replace(/%current_url%/ig, getUrl());
    send_to_friend('', subj, text);
}

function send_to_friend(url, subj, text)
{
	// url needed for backward compatibility
	var body = text.replace(/\\n/g, "\n").replace(/\\r/g, "\r");
    location.href='mailto:?subject='+escape(subj)+'&body='+escape(body);
}

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,resizable=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;
    }
}

hiddedByAjaxRefresh = new Array();
function AjaxFrameRefresh(frameId, args, shownd, controls)
{
    if (!frameId) return false;
    var form = getFormByFrame(frameId);
    if (!form) return false;
    var url = window.location.href;
    if (controls) {
        if (typeof controls != 'object') controls = [ controls ];
    } else {
        controls = [];
    }
    var i = url.indexOf('#');
    if (i != -1) {
        // deleting anchor from url
       url = url.substring(0, i);
    }
    url += -1 == url.indexOf('?') ? '?' : '&';
    url += 'ajaxdst=' + getPluginByForm(form) + ':' + getInterfaceByForm(form) + ':' + frameId +
        ':' + controls.join('/');
    if (args) url += '&' + args;
    for (var i = 0; i < form.elements.length; i++) {
        if (!form.elements[i].disabled) {
            form.elements[i].disabled = true;
            hiddedByAjaxRefresh.push(form.elements[i]);
        }
    }
    if (shownd) {
        showWaitWnd();
    }
    AjaxRequest(url);
}

function ajaxPostSubmit(form, action, wait, text, no_fade)
{
    if (ajaxPostFrameId) 
        form.target = ajaxPostFrameId;
    if (wait) {
        showWaitWnd(text, !no_fade);
    }
    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, fade)
{
    var w = document.getElementById('waitWindow');
    if (w) {
        if (w.style.visibility == 'visible') return;
        if (fade) {
            popup_fade_background(true);
            waitFade = true;
            hideElements();
        } else {
        	hideElements(w);
        }
        var wtext = document.getElementById('waitWindowText');
        wtext.innerHTML = text ? text : 'Please wait...';
        if (is_msie()) { 
        	w.style.top = getClientHeight() / 2 - w.offsetHeight / 2 + getScrollTop();
        	w.style.left = getClientWidth() / 2 - w.offsetWidth / 2 + getScrollLeft();
        	w.style.position = 'absolute';
        } else {
        	w.style.top = getClientHeight() / 2 - w.offsetHeight / 2;
        	w.style.left = getClientWidth() / 2 - w.offsetWidth / 2;
        	w.style.position = 'fixed';
        }
        if (is_msie() && is_msie() < 7.0) {
            // Go home, IE6!
            waitHidden = new Array();
            var cl = w.style.pixelLeft, cr = cl+w.style.pixelWidth,
                ct = w.style.pixelTop,  cb = ct+w.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]);
                }
            }
        }
        w.style.visibility = 'visible';      
    }
}

function hideWaitWnd()
{
    var w = document.getElementById('waitWindow');
    if (w) {
    	if (w.style.visibility == 'hidden') return;
        w.style.visibility = 'hidden';
        w.style.left = '0px';
        w.style.top = '0px';
        if (waitFade) {
            popup_fade_background(false);
            waitFade = false;
        }
        for (var i = 0; i < waitHidden.length; i++) {
            if (waitHidden[i]) {
                waitHidden[i].style.visibility = 'visible';
            }
        }
        showElements();
    }
}

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...', true);
            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;
    }
    if (params['enable_java'] == 1 && params['default_uploader'] == 'java' && 
        getCookie('use_java_uploader') == '' ) 
    {
    	url += '&use_java=1';
    }
    
    if (getCookie('use_java_uploader') == '1') {
        url += '&use_java=1';
    }
    url += sess;
    popup_exec_url(url, null, 400, 500, true, null, null, null);
}

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 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="/core/form_view/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();
    f.submitAction.value = '';
}

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)
{
    while (row && row.tagName != 'TR') row = row.parentNode;
	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 ? '/core/images/tree/minusbottom.gif' : '/core/images/tree/plusbottom.gif';
        } else {
            img.src = exp ? '/core/images/tree/minus.gif' : '/core/images/tree/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, color)
{
	var clr = color ? color : '#FFFFE0';
    var tw = width ? width == 'auto'? width : width +'px' : '200px'
    if (!tooltipCtl) {
        tooltipCtl = document.createElement('DIV');
        tooltipCtl.style.backgroundColor = clr;
        tooltipCtl.style.border = 'solid 1px #808080';
        tooltipCtl.style.padding = '4px';
        tooltipCtl.style.visibility = 'hidden';
        tooltipCtl.style.position = 'absolute';
        tooltipCtl.onmouseout = tooltipCtl.onclick = function()
	    {
	        tooltipCtl.style.visibility = 'hidden';
	        showElements();
	        curTipId = '';
	    };
        document.body.appendChild(tooltipCtl);
    }
        
    if (tip_id && tooltipCtl.style.width != tw) {
        tooltipCtl.style.width = tw;
    }
    if (!tip_id) {
        if (event.clientX + getScrollLeft() > parseInt(tooltipCtl.style.left) && 
            event.clientX + getScrollLeft() < parseInt(tooltipCtl.style.left) + tooltipCtl.clientWidth &&
            event.clientY + getScrollTop() > parseInt(tooltipCtl.style.top) &&
            event.clientY + getScrollTop() < parseInt(tooltipCtl.style.top) + tooltipCtl.clientHeight)
        return;
        tooltipCtl.style.visibility = 'hidden';
        showElements();
        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 + 20 + getScrollLeft(), 
                top = event.clientY + 20 + getScrollTop();
            left = Math.max(Math.min(left, getClientWidth() + getScrollLeft() - 
                tooltipCtl.offsetWidth), 0);
               
            top = Math.max(Math.min(top, getClientHeight() + getScrollTop() - 
                tooltipCtl.offsetHeight), 0);
            tooltipCtl.style.left = left + 'px';
            tooltipCtl.style.top = top + 'px';
            hideElements(tooltipCtl);
        }
    }
}

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 = '/core/images/balloons/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 = '/core/images/balloons/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 = '/core/images/balloons/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 = '/core/images/balloons/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 = '/core/images/balloons/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 = '/core/images/balloons/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 = '/core/images/balloons/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 = '/core/images/balloons/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 = '/core/images/balloons/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 = '/core/images/balloons/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 = '/core/images/balloons/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 = '/core/images/balloons/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(), onEndAjaxEvents = 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();
        if (typeof(hiddedByAjaxRefresh) == "object") {
            for (var i = 0; i < hiddedByAjaxRefresh.length; i++) {
                var ctl = hiddedByAjaxRefresh[i],
                    t = ctl.getAttribute('ajaxDisabled');
                if (t) ctl.disabled = t == 'yes';
                else ctl.disabled = false;
            }           
            hiddedByAjaxRefresh = [];
        }
        for(var i = 0; i < onEndAjaxEvents.length; i++) {
        	onEndAjaxEvents[i]();
        }
        onEndAjaxEvents = [];
    }
}

function AjaxRefresh(args)
{
    var url = window.location.href;
    if (args) {
    	url += (-1 == url.indexOf('?') ? '?' : '&') + args;
    }
    AjaxRequest(url);
}

function addOnEndAjaxEvent(func) {
	if (typeof(func) == 'function') {
		onEndAjaxEvents.push(func);
	}
}

var defaultLocale = { currency_sign: '$', sign_position: 'before', thousand_sep: ',', 
    decimal_sep: '.', rate: 1  };
var frameLocale = [];

function numberFormat(value, frameId)
{
    var locale = frameId && frameLocale[frameId] ? frameLocale[frameId] : defaultLocale; 
    var str = (Math.round(value * 100) / 100).toFixed(2);
    var dot = str.indexOf('.'), v1, v2;
    if (dot != -1) {
        v1 = str.substring(0, dot);
        v2 = str.substring(dot + 1, str.length);
    } else {
        v1 = str;
        v2 = '00';
    }    
    var rem = 0;
    var res = '';
    while (v1 >= 1000) {
        rem = v1 % 1000;
        while (rem.toString().length < 3) rem = '0' + rem;
        res = locale.thousand_sep + rem + res;
        v1 = Math.floor(v1 / 1000);
    }
    return v1 + res + locale.decimal_sep + v2;
}

function currencyFormat(value, frameId)
{
    var locale = frameId && frameLocale[frameId] ? frameLocale[frameId] : defaultLocale;
    var res = numberFormat(value*locale.rate, frameId);
    var space = locale.currency_sign.length == 3 ? ' ' : '';
    if (locale.sign_position == 'after') res += space + locale.currency_sign;
    else res = locale.currency_sign + space + res;
    return res;
}

function disableControls(form)
{
    for (var i = 0; i < form.elements.length; i++) {
        form.elements[i].disabled = true;
    }
}

preloadImages = [];
function preloadImage(url)
{
    var im = new Image;
    preloadImages.push(im);
    im.src = url;
}

var fileControlName = '';
var fileControlInfo = new Object();    
function fileStoreShow(name, default_dir, type, max_width, max_height, 
    max_images, single, enable_java)
{
    // max_images is used to limit number of items in fileds with multiple values
    if (type == 'image') {
        if (!max_images) max_images = 1;
        if (typeof(single) == 'undefined') single = 1;
    }
    fileControlName = name;
    fileControlInfo = { max_images: max_images, single: single }; 
    var f = document.getElementById(name + '[file]');
    var file_store_url = 'core/file_store/' + (type == 'image' ? 'img' : 'file') + '_store.php?' + 
        session_suffix + 
        '&default_dir=' + escape(default_dir) +
        '&select=' + escape(f ? f.value : '') + 
        '&type=' + escape(type) + 
        '&max_width=' + escape(max_width ? max_width : '') +
        '&max_height=' + escape(max_height ? max_height : '')+
        '&enable_java=' + escape(typeof(enable_java) == 'undefined' ? 1 : enable_java);
    
//    var window_style = 'width='+(getCookie("store_window_width")?getCookie("store_window_width"):'900')+
//                        'px,height='+(getCookie("store_window_height")?getCookie("store_window_height"):'600')+
//                        'px,resizable=yes,scrollbars=no';
    popup_exec_url(file_store_url, null,800, 500, false, null, 'Select ' + (type == 'image' ?'an Image':'a File'));
    popup_show_buttons(false);
    //window.open(file_store_url, 'file_wnd', window_style);
}

function imageBoxRemoveImage(id) 
{
    var box = document.getElementById(id);
    box.parentNode.removeChild(box); 
}

function imageBoxAddImage(name, src, value, max_images, single, disabled) 
{
    // Retrieve images container
    var imageset = document.getElementById(name);
    if (!imageset) {
        return false;
    }
    
    var num = imageset.childNodes.length - 1;
    if (max_images == 1) {
        for (i = 0; i < num; i++) {
            imageset.removeChild(imageset.childNodes[i]);
        }
    } else {
        if (num >= max_images) {
            alert('Sorry, you can\'t add more than ' + max_images + ' images.');
            return false;
        }
    }
    
    // Define current image id and number
    var image_num = imageset.childNodes.length;
    var image_id   = name + '_' + image_num + '_pv';
    var remove_btn_id = name + '_' + image_num + '_remove';
    
    // Create div containing image
    var image_box = document.createElement('span');
    image_box.id = image_id;
    if (!disabled) {
	    image_box.onmouseover = function() { 
	        var span = document.getElementById(remove_btn_id);
	        span.style.visibility = 'visible';
	        var box = span.parentNode.getElementsByTagName('IMG')[0];
	        span.style.left = box.offsetLeft + box.offsetWidth - 25 + 'px'; 
	        span.style.top = box.offsetTop + 1 + 'px';
	    };
    
	    image_box.onmouseout = function() { 
	        var span = document.getElementById(remove_btn_id);
	        span.style.visibility = 'hidden';
	    };
    }
    image_box.className = 'box';
    
    var image = document.createElement('img');
    image.src = src + '&broken=1';
    image_box.appendChild(image);
    
    if (!disabled) {
	    // Create remove button
	    var remove_btn = document.createElement('div');
	    remove_btn.id = remove_btn_id;
	    remove_btn.className = 'imageset_add_button';
	    remove_btn.style.visibility = 'hidden';
	    remove_btn.onclick = function() { imageBoxRemoveImage(image_id); };
	    remove_btn.innerHTML = 'X';
	    image_box.appendChild(remove_btn);
    }
    
    // Create hidden form element
    var hidden = document.createElement('input');
    hidden.type = 'hidden';
    hidden.value = value;
    hidden.name = single ? name : name + '[]';
    hidden.id = name + '_' + image_num;
    image_box.appendChild(hidden);
    
    imageset.insertBefore(image_box, document.getElementById(name + '_add'));
    imageset.insertBefore(document.createTextNode(' '), document.getElementById(name + '_add'));
}

searchFormInfo = {};
function searchFormClear(name)
{
    var visctl = document.getElementById('sf_vis_' + name);
    document.getElementById(name).value = '';
    document.getElementById('sf_id_' + name).value = '';
    document.getElementById(name + '_c').value = '';
    document.getElementById('sf_id_' + name + '_c').value = '';
    visctl.innerHTML = '';
    visctl.innerHTML = '<div name="_empty_">&lt;' + searchFormInfo[name].empty_value + 
        '&gt;</div>';    
}

function searchFormChange(ctl)
{
    if (ctl.type == 'checkbox') {
        var cbs = document.getElementsByName(ctl.name);
        var sel = false;
        for (var i = 0; i < cbs.length; i++) {
            if ((cbs[i].value == 'selected' || cbs[i].value == 'all_except_selected')
            && cbs[i].checked) {
                sel = true;
                break;
            }
        }
    } else {
        sel = ctl.value == 'selected' || ctl.value == 'all_except_selected';
    }
    var list = document.getElementById('sf_list_'+ctl.name);
    if (list) list.style.display = sel ? '' : 'none';
    var list1 = document.getElementById('sf_add_'+ctl.name);
    if (list1) list1.style.display = sel ? '' : 'none';
}

function showSearchForm(name)
{
    if (typeof popup_exec_url == 'function') {
        popup_exec_url(searchFormInfo[name].url, null, 500, 500, true, 
        	searchFormInfo[name]['onClose'] ? searchFormInfo[name]['onClose'] : null, 
            searchFormInfo[name].title, searchFormInfo[name].mode == 'multi' ? 'Apply' : 'Close');
    } else {
        var size = "width=500,height=500,scrollbars=yes,resizable=yes";
        window.open(searchFormInfo[name].url, "search_form", size);
    }
}

function searchFormSelect(name, mode, id, title, code, status, page_id)
{
    var ctl = null, idctl = null, snp = null;
    if (mode == 'p') {
        ctl = document.getElementById(name);
        idctl = document.getElementById('sf_id_' + name);
    } else {
        ctl = document.getElementById(name + '_' + mode);
        idctl = document.getElementById('sf_id_' + name + '_' + mode);
        snp = document.getElementById(name + '_nested_panel');
    }
    var visctl = document.getElementById('sf_vis_' + name);
    if (!ctl || !idctl || !visctl) return;

    var img = '';
    if (mode == 'p') {
        img = '<img src="/core/images/tree/leaf.gif" width="20" height="20" align="absmiddle" border="0"/>';
    } else if (mode == 'c') {
        img = '<img src="/core/images/tree/folder.gif" width="20" height="20" align="absmiddle" border="0"/>';
    }
    title = img + (searchFormInfo[name]['onDisplay'] ? 
    	eval(searchFormInfo[name]['onDisplay']+'(id, title, code)') : title);

    if (searchFormInfo[name].mode == 'single') {
        if (mode == 'p') {
            ctl.value = eval(searchFormInfo[name].key_field);
        } else {
            ctl.value = eval(searchFormInfo[name].cat_key_field);
            if (snp) snp.style.display = ctl.value ? '' : 'none';
        }
        if (id) {
            visctl.innerHTML = title;
        } else {
            visctl.innerHTML = '&lt;' + searchFormInfo[name].empty_value + '&gt;';
        }
        idctl.value = id;
    }

    if (searchFormInfo[name].mode == 'multi') {
        var ctl_id = name;
        var ev = searchFormInfo[name].empty_value;
        var prod_id;
        if (mode == 'p') {
            prod_id = eval(searchFormInfo[name].key_field);
        } else {
            prod_id = eval(searchFormInfo[name].cat_key_field);
        }

        var list = ctl.value.split(',');
        var idlist = idctl.value.split(',');
        var idx = -1;
        for (var i=0; i<idlist.length; i++)
            if (idlist[i] == id)
            {
                idx = i;
                break;
            }
        var ectl = null, pctl = null;
        for (var i=0; i<visctl.childNodes.length; i++) {
            if (visctl.childNodes[i].getAttribute('name') == '_empty_') {
                ectl = visctl.childNodes[i];
            }
            else if (visctl.childNodes[i].getAttribute('name') == mode+'_'+id) {
                pctl = visctl.childNodes[i];
            }
        }
        if (status && idx == -1)
        {
            idlist[list.length] = id;
            list[list.length] = prod_id;
            if (ectl) visctl.removeChild(ectl);
            if (visctl)
                visctl.innerHTML = visctl.innerHTML+
                    '<div name="'+mode+'_'+id+'">'+title+'</div>';
        }
        else if (!status && idx != -1)
        {
            idlist[idx] = '';
            list[idx] = '';
            if (pctl) visctl.removeChild(pctl);
            if (visctl && visctl.innerHTML == '')
                visctl.innerHTML = '<div name="_empty_">&lt;'+ev+'&gt;</div>';
        }
        var s = '';
        for (var i=0; i<list.length; i++)
            if (list[i])
                s += ','+list[i];
        ctl.value = s.substr(1);
        s = '';
        for (var i=0; i<idlist.length; i++)
            if (idlist[i])
                s += ','+idlist[i];
        idctl.value = s.substr(1);
        if (snp) snp.style.display = ctl.value ? '' : 'none';
    }
}

function searchFormAfterLoad(name, w)
{
    if (!searchFormInfo[name]) return;
    if (searchFormInfo[name].mode == 'multi') {
    	var sxa = new Array('p', 'c');
        var np = 0, nc = 0;
        for (var j=0; j<sxa.length; j++) {
            var sx = sxa[j];
            var idctl, idctl_dis;
            if (sx == 'p') {
                idctl = document.getElementById('sf_id_'+name);
                idctl_dis = document.getElementById('sf_dis_ids_'+name);
            } else {
                idctl = document.getElementById('sf_id_'+name+'_'+sx);
                idctl_dis = document.getElementById('sf_dis_ids_'+name+'_'+sx);
            }
            if (!idctl) continue;

            var list = idctl.value.split(',');
            var c = 0;
            for (var i=0; i<list.length; i++) {
                if (list[i]) {
                    var cb = w.document.getElementById(sx+'_check_'+list[i]);
                    if (cb) cb.checked = true;
                    c++;
                }
            }
            if (sx == 'p') np = c;
            if (sx == 'c') nc = c;
            
            if (idctl_dis) {
            	var list = idctl_dis.innerHTML.split(',');
	            for (var i=0; i<list.length; i++) {
	                if (list[i]) {
	                    var cb = w.document.getElementById(sx+'_check_'+list[i]);
	                    if (cb) cb.disabled = true;
	                }
	            }
            }
        }
        w.sf_set_numbers(np, nc);
    } else {
	    var idctl_dis = document.getElementById('sf_dis_ids_'+name+'_c');
        if (idctl_dis) {
	    	var list = idctl_dis.innerHTML.split(',');
	        for (var i=0; i<list.length; i++) {
	            if (list[i]) {
	                var tr = w.document.getElementById('cr_'+list[i]);
	                if (tr) {
		                var a = tr.getElementsByTagName('a');
		                if (a[0]) {
		                	var span = document.createElement('span');
		                	span.innerHTML = a[0].innerHTML;
		                	a[0].parentNode.appendChild(span);
		                	a[0].parentNode.removeChild(a[0]);
		                }
	                }
	            }
	        }
        }
    }
}

dialogWindow = null;
function showDialog(id, fade)
{
    hideDialog();
    var ctl = document.getElementById(id);
    if (ctl) {
    	if (fade) popup_fade_background(true, hideDialog);
        ctl.style.visibility = 'hidden';
        ctl.style.display = '';
        if (is_msie()) {
            ctl.style.position = 'absolute';
        } else {
            ctl.style.position = 'fixed';     
        }
        ctl.style.left = (getClientWidth() - ctl.offsetWidth) / 2 + 
            (is_msie() ? getScrollLeft() : 0) + 'px';
        ctl.style.top = (getClientHeight() - ctl.offsetHeight) / 2 + 
            (is_msie() ? getScrollTop() : 0) + 'px';
        ctl.style.visibility = 'visible';
        dialogWindow = ctl;
        hideElements(ctl, ctl);
        ctl.onmousedown = function (event) { (event || window.event).cancelBubble = true; };
        if (!fade) dialogAttachEvents();
        enableDialogDragging(dialogWindow);
        disableScroll(dialogWindow);
    }
}

function hideDialog()
{
	popup_fade_background(false);
    if (typeof hide_popup == 'function') hide_popup();
    var ctl = dialogWindow;
    if (ctl) {
        ctl.style.display = 'none';
        ctl.style.visibility = 'hidden';
        dialogWindow = null;
        showElements();
        disableDialogDragging(ctl);
    }
    enableScroll();
}

function moveDialog()
{
    var ctl = dialogWindow;
    if (ctl) {
//        ctl.style.left = (getClientWidth() - ctl.offsetWidth) / 2 + 
//            (is_msie() ? getScrollLeft() : 0) + 'px';
        ctl.style.top = (getClientHeight() - ctl.offsetHeight) / 2 + 
            (is_msie() ? getScrollTop() : 0) + 'px';
    }
}

dialogEventsAttached = false;
function dialogAttachEvents()
{
    if (!dialogEventsAttached) {
        dialogEventsAttached = true;
        addHandler(document.body, 'mousedown', hideDialog);
    }
}

function enableDialogDragging(dialogWindow)
{
	dialogWindow.draggingStarted = false;
	var divs = dialogWindow.getElementsByTagName('DIV');
	var dialogHeader = null, closeButton = null;
	for (var i = 0; i < divs.length; i++) {
		if (divs[i].className == 'PopupHeader') {
			dialogHeader = divs[i];
		}
		if (divs[i].id == 'PopupCloseDiv') {
			closeButton = divs[i];
		}
		if (is_msie())
			divs[i].setAttribute('unselectable', 'on');
	}
	if (!dialogHeader) return;
        
	var upperLayer = document.createElement('DIV');
	upperLayer.className = 'dragLayer';
	dialogWindow.appendChild(upperLayer);
	dialogWindow.upperLayer = upperLayer;
	
	dialogHeader.onmousedown = function(event) {
		event = event || window.event;
		dialogWindow.draggingStarted = true;
		dialogWindow.deltaX = event.clientX - parseInt(dialogWindow.style.left);
		dialogWindow.deltaY = event.clientY - parseInt(dialogWindow.style.top);
		upperLayer.style.zIndex = '100';
	};
	upperLayer.onmousemove = dialogHeader.onmousemove = dialogWindow.onmousemove = function(event) {
                if (is_msie()) {
                    closeButton.className = '';
                    closeButton.className = 'PopupCloseButton';
                }
                if (!dialogWindow.draggingStarted) return;
		event = event || window.event;
		dialogWindow.style.top = event.clientY - dialogWindow.deltaY;
		dialogWindow.style.left = event.clientX - dialogWindow.deltaX;
	};
	upperLayer.onmouseup = dialogHeader.onmouseup = dialogWindow.onmouseup = function() {
		if (dialogWindow)
			dialogWindow.draggingStarted = false;
		dialogWindow.upperLayer.style.zIndex = '-1';
	};
	
	addHandler(document.body, 'mousemove', dialogWindow.onmousemove);
//	closeButton.className = '';
//	closeButton.className = 'PopupCloseButton';
}

function disableDialogDragging(dialogWindow)
{
	dialogWindow.removeChild(dialogWindow.upperLayer);
	dialogWindow.upperLayer = null;
	removeHandler(document.body, 'mousemove', dialogWindow.onmousemove);
}

// disable scroll event bubbling
function disableScroll(dialogWindow)
{
    if (!is_mozilla())
        document.body.style.overflow = 'hidden';
}
function enableScroll()
{
    if (!is_mozilla())
	document.body.style.overflow = '';
}
var blackShadowsApplied = false;
function setBlackShadows() {
    if (blackShadowsApplied) return;
    blackShadowsApplied = true;
    var link = document.createElement('link');
    link.setAttribute('rel', 'stylesheet');
    link.setAttribute('href', '/core/wf_getcss.php?css=skins/skin2/css/dialog_dark.css');
    document.getElementsByTagName('head')[0].appendChild(link);
};

function turnPage(pageUrl, frame_id)
{
    var result = true;
    if (typeof(doExtraCheck) == 'function') {
        result = doExtraCheck(frame_id);
    }
    if (result)
        this.location.href = pageUrl;
}

/**
 * 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 fb = document.getElementById('framebox_' + frameId);
    var forms = fb.getElementsByTagName('FORM');
    for (var i = 0; i < forms.length; i++ ) {
        if (frameId != 1) {
            var vFrameId = forms[i].getAttribute('attr_frame_id');
            if (vFrameId && vFrameId == frameId) return forms[i];
        } else {
            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;
}/**
 * A class to parse color values
 * @author Stoyan Stefanov <sstoo@gmail.com>
 * @link   http://www.phpied.com/rgb-color-parser-in-javascript/
 * @license Use it if you like it
 */
function RGBColor(color_string)
{
    this.ok = false;
    color_string = color_string.replace(/"/g,'');
    // strip any leading #
    if (color_string.charAt(0) == '#') { // remove # if any
        color_string = color_string.substr(1,6);
    }

    color_string = color_string.replace(/ /g,'');
    color_string = color_string.toLowerCase();

    // before getting into regexps, try simple matches
    // and overwrite the input
    var simple_colors = {
        aliceblue: 'f0f8ff',
        antiquewhite: 'faebd7',
        aqua: '00ffff',
        aquamarine: '7fffd4',
        azure: 'f0ffff',
        beige: 'f5f5dc',
        bisque: 'ffe4c4',
        black: '000000',
        blanchedalmond: 'ffebcd',
        blue: '0000ff',
        blueviolet: '8a2be2',
        brown: 'a52a2a',
        burlywood: 'deb887',
        cadetblue: '5f9ea0',
        chartreuse: '7fff00',
        chocolate: 'd2691e',
        coral: 'ff7f50',
        cornflowerblue: '6495ed',
        cornsilk: 'fff8dc',
        crimson: 'dc143c',
        cyan: '00ffff',
        darkblue: '00008b',
        darkcyan: '008b8b',
        darkgoldenrod: 'b8860b',
        darkgray: 'a9a9a9',
        darkgreen: '006400',
        darkkhaki: 'bdb76b',
        darkmagenta: '8b008b',
        darkolivegreen: '556b2f',
        darkorange: 'ff8c00',
        darkorchid: '9932cc',
        darkred: '8b0000',
        darksalmon: 'e9967a',
        darkseagreen: '8fbc8f',
        darkslateblue: '483d8b',
        darkslategray: '2f4f4f',
        darkturquoise: '00ced1',
        darkviolet: '9400d3',
        deeppink: 'ff1493',
        deepskyblue: '00bfff',
        dimgray: '696969',
        dodgerblue: '1e90ff',
        feldspar: 'd19275',
        firebrick: 'b22222',
        floralwhite: 'fffaf0',
        forestgreen: '228b22',
        fuchsia: 'ff00ff',
        gainsboro: 'dcdcdc',
        ghostwhite: 'f8f8ff',
        gold: 'ffd700',
        goldenrod: 'daa520',
        gray: '808080',
        green: '008000',
        greenyellow: 'adff2f',
        honeydew: 'f0fff0',
        hotpink: 'ff69b4',
        indianred : 'cd5c5c',
        indigo : '4b0082',
        ivory: 'fffff0',
        khaki: 'f0e68c',
        lavender: 'e6e6fa',
        lavenderblush: 'fff0f5',
        lawngreen: '7cfc00',
        lemonchiffon: 'fffacd',
        lightblue: 'add8e6',
        lightcoral: 'f08080',
        lightcyan: 'e0ffff',
        lightgoldenrodyellow: 'fafad2',
        lightgrey: 'd3d3d3',
        lightgreen: '90ee90',
        lightpink: 'ffb6c1',
        lightsalmon: 'ffa07a',
        lightseagreen: '20b2aa',
        lightskyblue: '87cefa',
        lightslateblue: '8470ff',
        lightslategray: '778899',
        lightsteelblue: 'b0c4de',
        lightyellow: 'ffffe0',
        lime: '00ff00',
        limegreen: '32cd32',
        linen: 'faf0e6',
        magenta: 'ff00ff',
        maroon: '800000',
        mediumaquamarine: '66cdaa',
        mediumblue: '0000cd',
        mediumorchid: 'ba55d3',
        mediumpurple: '9370d8',
        mediumseagreen: '3cb371',
        mediumslateblue: '7b68ee',
        mediumspringgreen: '00fa9a',
        mediumturquoise: '48d1cc',
        mediumvioletred: 'c71585',
        midnightblue: '191970',
        mintcream: 'f5fffa',
        mistyrose: 'ffe4e1',
        moccasin: 'ffe4b5',
        navajowhite: 'ffdead',
        navy: '000080',
        oldlace: 'fdf5e6',
        olive: '808000',
        olivedrab: '6b8e23',
        orange: 'ffa500',
        orangered: 'ff4500',
        orchid: 'da70d6',
        palegoldenrod: 'eee8aa',
        palegreen: '98fb98',
        paleturquoise: 'afeeee',
        palevioletred: 'd87093',
        papayawhip: 'ffefd5',
        peachpuff: 'ffdab9',
        peru: 'cd853f',
        pink: 'ffc0cb',
        plum: 'dda0dd',
        powderblue: 'b0e0e6',
        purple: '800080',
        red: 'ff0000',
        rosybrown: 'bc8f8f',
        royalblue: '4169e1',
        saddlebrown: '8b4513',
        salmon: 'fa8072',
        sandybrown: 'f4a460',
        seagreen: '2e8b57',
        seashell: 'fff5ee',
        sienna: 'a0522d',
        silver: 'c0c0c0',
        skyblue: '87ceeb',
        slateblue: '6a5acd',
        slategray: '708090',
        snow: 'fffafa',
        springgreen: '00ff7f',
        steelblue: '4682b4',
        tan: 'd2b48c',
        teal: '008080',
        thistle: 'd8bfd8',
        tomato: 'ff6347',
        turquoise: '40e0d0',
        violet: 'ee82ee',
        violetred: 'd02090',
        wheat: 'f5deb3',
        white: 'ffffff',
        whitesmoke: 'f5f5f5',
        yellow: 'ffff00',
        yellowgreen: '9acd32'
    };
    for (var key in simple_colors) {
        if (color_string == key) {
            color_string = simple_colors[key];
        }
    }
    // emd of simple type-in colors

    // array of color definition objects
    var color_defs = [
        {
            re: /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/,
            process: function (bits){
                return [
                    parseInt(bits[1]),
                    parseInt(bits[2]),
                    parseInt(bits[3])
                ];
            }
        },
        {
            re: /^(\w{2})(\w{2})(\w{2})$/,
            process: function (bits){
                return [
                    parseInt(bits[1], 16),
                    parseInt(bits[2], 16),
                    parseInt(bits[3], 16)
                ];
            }
        },
        {
            re: /^(\w{1})(\w{1})(\w{1})$/,
            process: function (bits){
                return [
                    parseInt(bits[1] + bits[1], 16),
                    parseInt(bits[2] + bits[2], 16),
                    parseInt(bits[3] + bits[3], 16)
                ];
            }
        }
    ];

    // search through the definitions to find a match
    for (var i = 0; i < color_defs.length; i++) {
        var re = color_defs[i].re;
        var processor = color_defs[i].process;
        var bits = re.exec(color_string);
        if (bits) {
            channels = processor(bits);
            this.r = channels[0];
            this.g = channels[1];
            this.b = channels[2];
            this.ok = true;
        }

    }

    // validate/cleanup values
    this.r = (this.r < 0 || isNaN(this.r)) ? 0 : ((this.r > 255) ? 255 : this.r);
    this.g = (this.g < 0 || isNaN(this.g)) ? 0 : ((this.g > 255) ? 255 : this.g);
    this.b = (this.b < 0 || isNaN(this.b)) ? 0 : ((this.b > 255) ? 255 : this.b);

    // some getters
    this.toRGB = function () {
        return 'rgb(' + this.r + ', ' + this.g + ', ' + this.b + ')';
    }
    this.toHex = function () {
        var r = this.r.toString(16);
        var g = this.g.toString(16);
        var b = this.b.toString(16);
        if (r.length == 1) r = '0' + r;
        if (g.length == 1) g = '0' + g;
        if (b.length == 1) b = '0' + b;
        return '#' + r + g + b;
    }

}

