
// ===================== Basic DOM operations (add/remove/show an item) =====================

function isset(varname)
{
  return(typeof(window[varname])!=undefined);
}

function Dom(id)
{
	return (document.all ? document.all[id] : document.getElementById(id));
}

function DomAddNode(parentDivName, childDivName)
{
	var where= Dom(parentDivName);
	if(!where) return null;
	var newdiv = document.createElement('span');
	if(childDivName) newdiv.setAttribute('id',childDivName);
	where.appendChild(newdiv);
	return newdiv;
}

function DomGetLastNode(where)
{
	if(typeof(where)=="string")
		where= Dom(where);
	if(!where) return false;
	var n= where.childNodes.length;
	if(n==0) return null;
	return where.childNodes[n-1];
}

function DomRemoveNode(parentDivName, childDivName)
{
	var where= Dom(parentDivName);
	if(!where) return false;
	var child;
	if(childDivName!='last' && childDivName)
		child= Dom(childDivName);
	else if(childDivName=='first')
		{ var n=where.childNodes.length; if(n==0) return false; child= where.childNodes[0]; }
	else
		child= DomGetLastNode(where);
	if(!child) return false;
	where.removeChild(child);
	return true;
}

function Show(id, state)
{
	if(state==undefined) state=true;
	var o;
	if(typeof(id)=="string") o= Dom(id);
	else o= id;
	if(!o) return;

	{
		dbg= (state?"+Show":"-Hide")+" <span style='color:#"+(state?'22F':'00A')+"'>";
		if(o.id) dbg+= o.id;
		if(o.className) dbg+=" class="+o.className;
	}

	if(state) o.style.display= 'inline';
	else if(!state)
		o.style.display= 'none';
	else if(state=='toggle')
		o.style.display= (o.style.display=='inline') ? 'none' : 'inline';
}
function Hide(id)
{
	Show(id,false);
}
function IsVisible(id)
{
	var o;
	if(typeof(id)=="string") o= Dom(id); else o= id; if(!o) return false;
	return(o.style.display != 'none');
}

function DomAllByClass(classNameRegExp, node)
{
	var classElements= new Array();
	if (node==null) node= document;
	var pattern= new RegExp("(^|\\s)"+classNameRegExp+"(\\s|$)");
	var elts, eltsLen;

	elts= node.getElementsByTagName("div");
	eltsLen= elts.length;
	var i,j;
	for(i= 0, j= 0; i<eltsLen; i++)
		if( pattern.test(elts[i].className) )
			classElements[j++]= elts[i];

	elts= node.getElementsByTagName("span");
	eltsLen= elts.length;
	for(i= 0, j= 0; i<eltsLen; i++)
		if( pattern.test(elts[i].className) )
			classElements[j++]= elts[i];

	return classElements;
	/*
	Usage:
		var ets = DomAllByClass('myClass');
		for ( i=0;i<ets.length;i++ ) do_something_with( ets[i] );
	*/
}


function DomAllById(idNameRegExp, node)
{
	var classElements= new Array();
	if (node==null) node= document;
	var pattern= new RegExp("(^|\\s)"+idNameRegExp+"(\\s|$)");
	var elts, eltsLen;

	elts= node.getElementsByTagName("div");
	eltsLen= elts.length;
	var i;
	var j;
	for(i= 0, j= 0; i<eltsLen; i++)
		if( pattern.test(elts[i].id) )
			classElements[j++]= elts[i];

	elts= node.getElementsByTagName("span");
	eltsLen= elts.length;
	for(i= 0, j= 0; i<eltsLen; i++)
		if( pattern.test(elts[i].id) )
			classElements[j++]= elts[i];

	return classElements;
	/*
	Usage:
		var ets = DomAllByClass('myClass');
		for ( i=0;i<ets.length;i++ ) do_something_with( ets[i] );
	*/
}


//===================== Duplicable sections =====================

function FindLastNonEmptyChild(container)
{
	// Find last (useful) child
	var nbChildren= container.childNodes.length;
	for(var ci=nbChildren-1; ci>0; ci--)
		if(typeof(container.childNodes[ci])!=undefined)
			if(container.childNodes[ci].innerHTML!=undefined)
				return container.childNodes[ci];
	return undefined;
}

function DomParseTree(node, callbackFn)
{
	var n= node.childNodes.length;
	for(var i= 0; i<n; i++)
	{
		var o= node.childNodes[i];
		callbackFn(o);
		if(o.childNodes) DomParseTree(o, callbackFn);	// recursive call if node has children itself
	}
}

function AddOneSectionIn(container)
{
	if(typeof(container)=="string") container= Dom(container);
		
	// Find last (useful) child
	var lastSection= FindLastNonEmptyChild(container);
	if(!lastSection) { alert("AddOneSectionIn: No section found in '"+container.id+"' to clone!"); return; }
	// TODO: bail out if the previous field is still "empty"

	// Clone it
	var newSection= lastSection.cloneNode(true);
	DomParseTree(newSection,
		function(child) // to be incremented, the id must match "[a-zA-Z0-9_]*_k[0-9]+"
		{
			if(typeof(child.value)!='undefined') child.value='';
			if(typeof(child.id)!='undefined')
			{
				var baseId= child.id.replace(/^([A-Za-z0-9_]*_k)[0-9]+$/,'$1');
				var counter= child.id.replace(/^[A-Za-z_0-9]*_k([0-9]+)$/,'$1');
				counter++;
				var newId= baseId+counter;
				child.id= newId;
			}
			if(typeof(child.name)!='undefined')
			{
				var baseId= child.name.replace(/^([A-Za-z0-9_]*_k)[0-9]+$/,'$1');
				var counter= child.name.replace(/^[A-Za-z_0-9]*_k([0-9]+)$/,'$1');
				counter++;
				var newId= baseId+counter;
				child.name= newId;
			}
		}
	);
	container.appendChild(newSection);
}
function RemoveLastSectionFrom(container)
{
	if(typeof(container)=="string") container= Dom(container);
	lastSection= FindLastNonEmptyChild(container);
	
	if(lastSection.innerHTML.match(/id=['"][A-Za-z_0-9]+_k1['"]/)) return;
	if(lastSection) container.removeChild( lastSection );
}

// ===================== Cookies =====================

function CookieHandler()
{

    this.setCookie = function (name, value, seconds)
	{
        var expires= "";
        if(typeof(seconds)!=undefined)
		{
            var date = new Date();
            date.setTime(date.getTime() + (seconds*1000));
            expires= "; expires=" + date.toGMTString();
        }
        document.cookie = name+"="+value+expires+"; path=/";
    };

    this.getCookie = function (name)
	{
        name = name + "=";
        var carray = document.cookie.split(';');
        for(var i=0;i < carray.length;i++)
		{
            var c = carray[i];
            while (c.charAt(0)==' ') c = c.substring(1,c.length);
            if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
        }
        return null;
    };

    this.deleteCookie = function (name)
	{
        this.setCookie(name, "", -1);
    };

}


