/*
* Javascript utils
*/

var ag=navigator.userAgent.toLowerCase();

var isOpera=ag.indexOf("opera")!=-1;
var isIE = ag.indexOf("msie")!=-1&&(document.all&&!isOpera);
var isGecko = ag.indexOf("gecko")!=-1;

var storage = {};

function $(id) {
        return document.getElementById(id);
}

function ce(id) {
        return document.createElement(id);
}

function ct(text) {
        return document.createTextNode(text);
}


function cc(id) {
	var doc = document.createElement(id);
        if(arguments[1]) doc.className = arguments[1];
        return doc;
}

function ctd(text)
{
    var td = document.createElement('td');
    if(arguments[1]) {
        td.style.width = arguments[1] + 'px';
    }

    if(arguments[2]) {
        td.style.textAlign = arguments[2];
    }

    td.innerHTML = text;

    return td;
}


function hi(id) {
	id.style.display = 'none';
}

function sh(id) {
	id.style.display = '';
}

function getPos (element)
{
	var coords = { x: 0, y: 0 };
	while (element)
	{
		coords.x += element.offsetLeft;
		coords.y += element.offsetTop;
		element = element.offsetParent;
	}
	return coords;
}


function addEvent(obj, evType, fn){
 if (obj.addEventListener){
    obj.addEventListener(evType, fn, true);
    return true;
 } else if (obj.attachEvent){
    var r = obj.attachEvent("on"+evType, fn);
    return r;
 } else {
    return false;
 }
}

function dbi(tag) {
 return document.getElementById(tag);
}


function setCookie(cookieName,cookieValue,nDays)
{
        var pth = arguments[3] ? arguments[3] : '/';
	var today = new Date();
	var expire = new Date();
	if (nDays==null || nDays==0) nDays=1;
	expire.setTime(today.getTime() + 3600000*24*nDays);
	document.cookie = cookieName + "=" + escape(cookieValue) + ";path=" + pth +";expires=" + expire.toGMTString();
}

function getCookie(name)
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++)
	{
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}


function nodeText(node)
{
	var r = node.nodeValue != null ? node.nodeValue : '';
	var i;

	if( node.childNodes.length ) {
		for(i=0; i<node.childNodes.length; i++) {
			r = r + nodeText(node.childNodes[i]);
		}
	}
	return r;
}


function loadXML(file, func) {

         // YUI Support
         if(YAHOO.util.Connect) {

            var params = {};
            if( typeof(func) != 'function' ){
               eval("params['success'] = " + func + ";")
            }else{
               params['success'] = func;
            }

            params['failure'] = (arguments[2] ? arguments[2] : yui_failureHandler);

            var request = YAHOO.util.Connect.asyncRequest('GET', file, params );
            return true;
         }

         var objXMLFile = jsXML.createDOMDocument();
         objXMLFile.onreadystatechange = function() {
		 		if (objXMLFile.readyState == 4) {
					eval( func + '(objXMLFile)' );
				}
			};
         objXMLFile.load(file);
}

function yui_failureHandler(o)
{
	if(window.top.onXMLLoadError && typeof(window.top.onXMLLoadError) == 'function' ){
                window.top.onXMLLoadError();
        }
}

function dummy2( xmlDoc2 )
{
	if( xmlDoc2 != null )
	{
		if(window.top.onXMLLoad && typeof(window.top.onXMLLoad) == 'function' ){
                        window.top.onXMLLoad();
                }

                var resp = xmlDoc2.documentElement ? xmlDoc2.documentElement : (xmlDoc2.responseXML ? xmlDoc2.responseXML.documentElement : null);
		if( resp != null && resp.nodeName == 'response')
		{
			var n;
			for(n=0; n < resp.childNodes.length; n++)
			{
				//alert( xmlDoc2.xml );
				var el = resp.childNodes[n];
				if( el.nodeType == 1 )
				{
					if( el.nodeName == 'update' ){
						var c = nodeText(el);
						var id = el.getAttribute('id');
						var obj = dbi(id);
						if(obj) obj.innerHTML = c;
					}
					else if( el.nodeName == 'uattr' ){
						var c = nodeText(el);
						var id = el.getAttribute('id');
						var attr = el.getAttribute('attr');
						var obj = dbi(id);
						if(obj) obj.setAttribute(attr, c);
					}
					else if( el.nodeName == 'msg' ){
						var c = nodeText(el);
						alert(c);
					}
					else if( el.nodeName == 'script' ){
						var c = nodeText(el);
						eval(c);
					}
				}
			}// for
		}

	}

}


function hidein(id, time)
{
   setTimeout('_dohide("' + id + '")', time);
}

function _dohide(id)
{
   var block = dbi(id);
   __opacity(id, 100, 0, 800);
   setTimeout('dbi("' + id + '").style.display="none";', 850);
}


function __opacity(id, opacStart, opacEnd, millisec)
{

    var speed = Math.round(millisec / 100);
    var timer = 0;

   if(opacStart > opacEnd) {
        for(i = opacStart; i >= opacEnd; i--) {
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
            timer++;
        }
   } else if(opacStart < opacEnd) {
        for(i = opacStart; i <= opacEnd; i++)
            {
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
            timer++;
        }
   }
}

function changeOpac(opacity, id) {
    var object = id.style ? id.style : document.getElementById(id).style;
    object.opacity = (opacity / 100);
    object.MozOpacity = (opacity / 100);
    object.KhtmlOpacity = (opacity / 100);
    object.filter = "alpha(opacity=" + opacity + ")";
}


function sprintf()
{
        if (!arguments || arguments.length < 1 || !RegExp)
        {
                return;
        }
        var str = arguments[0];
        var re = /([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X)(.*)/;
        var a = b = [], numSubstitutions = 0, numMatches = 0;
        while (a = re.exec(str))
        {
                var leftpart = a[1], pPad = a[2], pJustify = a[3], pMinLength = a[4];
                var pPrecision = a[5], pType = a[6], rightPart = a[7];

                //alert(a + '\n' + [a[0], leftpart, pPad, pJustify, pMinLength, pPrecision);

                numMatches++;
                if (pType == '%')
                {
                        subst = '%';
                }
                else
                {
                        numSubstitutions++;
                        if (numSubstitutions >= arguments.length)
                        {
                                alert('Error! Not enough function arguments (' + (arguments.length - 1) + ', excluding the string)\nfor the number of substitution parameters in string (' + numSubstitutions + ' so far).');
                        }
                        var param = arguments[numSubstitutions];
                        var pad = '';
                               if (pPad && pPad.substr(0,1) == "'") pad = leftpart.substr(1,1);
                          else if (pPad) pad = pPad;
                        var justifyRight = true;
                               if (pJustify && pJustify === "-") justifyRight = false;
                        var minLength = -1;
                               if (pMinLength) minLength = parseInt(pMinLength);
                        var precision = -1;
                               if (pPrecision && pType == 'f') precision = parseInt(pPrecision.substring(1));
                        var subst = param;
                               if (pType == 'b') subst = parseInt(param).toString(2);
                          else if (pType == 'c') subst = String.fromCharCode(parseInt(param));
                          else if (pType == 'd') subst = parseInt(param) ? parseInt(param) : 0;
                          else if (pType == 'u') subst = Math.abs(param);
                          else if (pType == 'f') subst = (precision > -1) ? Math.round(parseFloat(param) * Math.pow(10, precision)) / Math.pow(10, precision): parseFloat(param);
                          else if (pType == 'o') subst = parseInt(param).toString(8);
                          else if (pType == 's') subst = param;
                          else if (pType == 'x') subst = ('' + parseInt(param).toString(16)).toLowerCase();
                          else if (pType == 'X') subst = ('' + parseInt(param).toString(16)).toUpperCase();
                }
                str = leftpart + subst + rightPart;
        }
        return str;
}

function infin(n) {
        return n != 0 ? n : '&infin;';
}

function select(form, pfx, state)
{
        var f = $(form);
        for( i=0; i < f.elements.length; i++ )
        {
                if(f.elements[i].name.match('^' + pfx)){
                        f.elements[i].checked = state;
                }
        }
}

function nOfSelected(form, pfx)
{
        var n = 0;
        var f = $(form);
        for( i=0; i < f.elements.length; i++ )
        {
                if(f.elements[i].name.match('^' + pfx)){
                        if( f.elements[i].checked ) n++;
                }
        }

        return n;
}

function set_cbx(state)
{
	var f = arguments[1] ? arguments[1] : document.forms['table'];
	var rex =  arguments[2] ? arguments[2] : /^r/;
	for(var s in f.elements)
	{
		var e = f.elements[s];

		if(e && e.type == 'checkbox' && e.name.match(rex)){
			e.checked = state;
		}
	}
}

function getColOver(a, where, className)
{
    var vi = $(where);
    var cont;
    for(var i=0;i<vi.childNodes.length;i++)
    {
        cont = vi.childNodes[i];
        if(cont.className == className){
            var cd = getPos(cont);
            var wid = cont.offsetWidth;
            var heg = cont.offsetHeight;

            if( (a.clientY > cd.y && (a.clientY < cd.y + heg)) &&  (a.clientX > cd.x && (a.clientX < cd.x + wid)) )
            {
                return cont;
            }

        }

    }

    return null;
}

function getElementUnder(a, parent, classname)
{

    for(var i=0;i<parent.childNodes.length;i++)
    {
        var cont = parent.childNodes[i];
        if(cont.className.match(classname)){
            var cd = getPos(cont);
            var wid = cont.offsetWidth;
            var heg = cont.offsetHeight;

            if( (a.clientY > cd.y && (a.clientY < cd.y + heg)) &&  (a.clientX > cd.x && (a.clientX < cd.x + wid)) )
            {
                return cont;
            }

        }

    }

    return null;
}
