/*
* 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 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 flash_errors(_err)
{
	if(_err) {
		var id;
		for( id in _err ) {
			var _obj = dbi(id);
			var _msg = document.createElement('div');
			_msg.setAttribute('id', id + '_msg');
			_msg.className = 'errmsg';
			_msg.innerHTML = _err[id];
			_obj.parentNode.appendChild(document.createElement('br'));
			_obj.parentNode.appendChild(_msg);
			_obj.oldbg = _obj.style.backgroundColor;
			_obj.style.backgroundColor = '#ffffc0';
		}
	}
}

function load_post(_post)
{
	if(_post) {
		var id;
		for( id in _post ) {
			var _obj = dbi(id);
			if( _obj != null && (_obj.tagName.toUpperCase() == 'INPUT' || _obj.tagName.toUpperCase() == 'TEXTAREA' || _obj.tagName.toUpperCase() == 'SELECT')  )
			{
				if(_obj.type.toUpperCase()=='CHECKBOX') {
					_obj.checked = _post[id] ? true : false;
				}else {
					_obj.value = _post[id];
				}
			}
		}
	}
}

function setCookie(cookieName,cookieValue,nDays)
{
	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) + ";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)
{
}

function dummy2( xmlDoc2 )
{
	if( xmlDoc2 != null )
	{
		var resp = xmlDoc2.documentElement ? xmlDoc2.documentElement : xmlDoc2.responseXML.documentElement;
		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 = document.getElementById(id).style;
    object.opacity = (opacity / 100);
    object.MozOpacity = (opacity / 100);
    object.KhtmlOpacity = (opacity / 100);
    object.filter = "alpha(opacity=" + opacity + ")";
}



// dymaic windows

function buildWindow()
{
   var _top = document.documentElement.scrollTop !='undefined' ? document.documentElement.scrollTop : window.pageYOffset;
   if( isGecko ) _top = 0;


   var id = arguments[0];
   var w = arguments[1];
   var h = arguments[2];
   var left = arguments[3];
   var top = arguments[4];
   var parent = arguments[5];
   var before = arguments[6];
   

   var win = ce('div');

   win.id = id;
   win.style.display = 'block';
   
   
   if( w != 'auto')
   {
	win.style.position = isGecko ? 'fixed' : 'absolute';
	win.style.width = w + 'px';
	win.style.height = h + 'px';
   }else{
	win.style.marginBottom = '8px';
	win.style.marginTop = '8px';
   }

   hi(win);

   // header
   win.hdr = ce('table');
   win.hdr.cellSpacing = 0;
   win.hdr.cellPadding = 0;
   win.hdr.width = '100%';
   win.hdr.border= 0;
   win._onclose= arguments[7];

   var b = ce('tbody');
   var r = ce('tr');

   win.hdr.left = cc('td', 'winleft');
   win.hdr.right = cc('td', 'winright');
   win.hdr.left.style.height = '24px';

   r.appendChild(win.hdr.left);
   r.appendChild(win.hdr.right);
   b.appendChild(r);
   win.hdr.appendChild(b);
   win.appendChild(win.hdr);

   win.body = cc('div', 'bwin');
   win.body.style.height = (h - 24 - 6) + 'px';
   win.appendChild(win.body);

   // footer
   win.ftr = ce('table');
   win.ftr.cellSpacing = 0;
   win.ftr.cellPadding = 0;
   win.ftr.width = '100%';
   win.ftr.border= 0;

   b = ce('tbody');
   r = ce('tr');

   win.ftr.left = cc('td', 'winleft-b');
   win.ftr.right = cc('td', 'winright-b');
   win.ftr.left.style.height = '6px';

   r.appendChild(win.ftr.left);
   r.appendChild(win.ftr.right);
   b.appendChild(r);
   win.ftr.appendChild(b);
   win.appendChild(win.ftr);

   win.close = function() { if(win._onclose){ win._onclose(); }  $(win.id).parentNode.removeChild($(win.id));   }


   if( w != 'auto')
   {
	   // close b
	   win.hdr.cb = ce('img');
	   win.hdr.cb.src = window.img + '/close-b.gif';
	   win.hdr.cb.width = 15;
	   win.hdr.cb.height = 15;
	   win.hdr.cb.style.cursor = 'pointer';
	   win.hdr.cb.onclick = function(){ win.close();  }
	   win.hdr.right.appendChild(win.hdr.cb);
   }

   // position window
   if( w != 'auto' )
   {
	if(  left == null && top == null )
	{
	   var wh = window.innerHeight ? window.innerHeight : ( document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight )  ;
	   var ww = window.innerWidth ? window.innerWidth : ( document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.clientWidth )  ;

	   left = parseInt(( ww - w ) / 2);
	   top = parseInt(( wh - h ) / 2);
	}

	win.style.left = left + 'px';
	win.style.top = (_top + top) + 'px';
   }

   if( parent )
   {
	if( before )
	{
		parent.insertBefore(win, before);
	}
	else
	{
		parent.appendChild(win);
	}
   }
   else{
	document.body.appendChild(win);
   }

   return win;
}

function ajustWindow(win, h)
{
   var _top = document.documentElement.scrollTop !='undefined' ? document.documentElement.scrollTop : window.pageYOffset;
   if( isGecko ) _top = 0;

   if( h =='auto')
   {
        var t1 = getPos(win);
        var t2 = getPos(arguments[2]);
        h = t2.y - t1.y + 8;
   }

   win.style.height = h + 'px';
   win.body.style.height = (h - 24 - 6) + 'px';


   var wh = window.innerHeight ? window.innerHeight : ( document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight )  ;
   var top = parseInt(( wh - h ) / 2);

   win.style.top = (_top + top) + 'px';

}


function addButton(text, cls )
{
   var bt = ce("input");
   bt.className  = cls;

   bt.type = arguments[2] ? arguments[2] : 'button';
   bt.value = text;

   if(arguments[3])
   {
      bt.onclick = arguments[3];
   }

   return bt;
}


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;
}
