//Menu functions

function ShowHide(nr)
{
	if (document.layers)
	{
		current = (document.layers[nr].display == 'none') ? 'block' : 'none';
		document.layers[nr].display = current;
	}
	else if (document.all)
	{
		current = (document.all[nr].style.display == 'none') ? 'block' : 'none';
		document.all[nr].style.display = current;
	}
	else if (document.getElementById)
	{
		vista = (document.getElementById(nr).style.display == 'none') ? 'block' : 'none';
		document.getElementById(nr).style.display = vista;
	}
}

function ShowHideUl(nr)
{
	vista = (document.getElementById(nr).style.display == 'none') ? 'block' : 'none';
	document.getElementById(nr).style.display = vista;
	style = (document.getElementById('mnu'+nr).className == "menuup") ? 'menudown' : 'menuup'
	document.getElementById('mnu'+nr).className = style;
}

function DeSelectAll()
{
	x = document.getElementsByTagName("li");
	for(i=0;i<x.length;i++) {
		style = (x[i].className=='subm' || x[i].className=='submact') ? 'subm' : '';
		x[i].className = style;
		//alert(x[i].id+" "+x[i].className+" "+x[i].style)
	}
}			


function Active(index)
{
	DeSelectAll();
	style = (document.getElementById('item'+index).className == "subm") ? 'submact' : 'menact'
	document.getElementById('item'+index).className = style;
}

function ChangeImg(nr,before,after)
{
	element = document.getElementById(nr);
	ret = (element.src.indexOf(before)>0);
	path = (ret) ? element.src.replace(before,after) : element.src.replace(after,before)
	element.src = path;
	return ret;
}

function SetAllCheckBoxesCustom(FormName, FieldName, checkAll, startIndex)
{
	CheckValue = ChangeImg(checkAll,'ico_selectall.gif','ico_selectnone.gif')
	if(!document.forms[FormName])
		return;
	var objCheckBoxes = document.forms[FormName].elements[FieldName];
	if(!objCheckBoxes)
		return;
	var countCheckBoxes = objCheckBoxes.length;
	if(!countCheckBoxes)
		objCheckBoxes.checked = CheckValue;
	else
		// set the check value for all check boxes
		for(var i = startIndex; i < countCheckBoxes; i++)
			if(!objCheckBoxes[i].disabled)
				objCheckBoxes[i].checked = CheckValue;
}


function SetAllCheckBoxes(FormName, FieldName) {
	SetAllCheckBoxesCustom(FormName, FieldName, "checkAll",  0);
}

function addRowClone(tblId, template, position, parentId, autoDecrementId, idFieldName, parentName, calName)
{
  var tblBody = document.getElementById(tblId).tBodies[0];
  var newNode = tblBody.rows[template].cloneNode(true);
  newNode.style.visibility='visible';
  inputs = newNode.getElementsByTagName('input');
  img = newNode.getElementsByTagName('img');
	 var theBeginningInput =null;
	var theBeginningImg=null;
	 var theEndingInput =null;
	var theEndingImg=null;

  for(i=0;i<inputs.length;i++)
  {
  	if(inputs[i].type=='checkbox')
  		inputs[i].checked=false;
  	//else
	//  	inputs[i].value='';
  	
  	if(inputs[i].name==parentName){
  		inputs[i].value = parentId;
  	}

  	if(idFieldName!=null && inputs[i].name==idFieldName){
  		inputs[i].value = autoDecrementId;
  	}
  	
  	if(calName!=null && (inputs[i].name==calName+'BeginningDate'  || inputs[i].name==calName+'EndingDate')){
  		inputs[i].id = inputs[i].name+"_"+autoDecrementId;
		if(inputs[i].name==calName+'BeginningDate' )			
				theBeginningInput=inputs[i].id ;
			else
				theEndingInput=inputs[i].id ;
		
  	}

	
  	
  }

  for(i=0;i<img.length;i++)
  {
		if(calName!=null && (img[i].name==calName+'BeginningDate_b'  || img[i].name==calName+'EndingDate_b') ){
			img[i].id = img[i].name+autoDecrementId;
			if(img[i].name==calName+'BeginningDate_b' )			
				theBeginningImg=img[i].id ;
			else
				theEndingImg=img[i].id ;

	  	}
  }
  if(position == null){
	  tblBody.appendChild(newNode);
  }
  else {
	  
	  tblBody.insertBefore(newNode, position);


			 
  }

if(theBeginningInput && theBeginningImg) {
Calendar.setup({
                            inputField     :   theBeginningInput, 
                            ifFormat       :    "%d/%m/%Y",
                            showsTime      :    false,
                            button         :  theBeginningImg,
                            singleClick    :    false,
                            step           :    1
                        });
}

if(theEndingInput && theEndingImg) {
Calendar.setup({
                            inputField     :   theEndingInput, 
                            ifFormat       :    "%d/%m/%Y",
                            showsTime      :    false,
                            button         :  theEndingImg,
                            singleClick    :    false,
                            step           :    1
                        });
}

}

function addSimpleRowClone(tblId)
{
  var tblBody = document.getElementById(tblId).tBodies[0];
  var newNode = tblBody.rows[0].cloneNode(true);
  newNode.style.visibility='visible';
  inputs = newNode.getElementsByTagName('input');
  for(i=0;i<inputs.length;i++)
  {
  	if(inputs[i].type=='checkbox')
  		inputs[i].checked=false;
  	else
	  	inputs[i].value='';
  }
  tblBody.appendChild(newNode);
}

function removeRow(tblId, selectedItems) {
	var tblBody = document.getElementById(tblId).tBodies[0];
	inputs = tblBody.getElementsByTagName("input");
	var delRows = new Array();
	var count = 0;
	for(j=0;j<inputs.length;j++) {
		if(inputs[j].name==selectedItems)	{
			count = count + 1;
			if(inputs[j].checked){
				delRows.push(count);
				//alert(inputs[j].value);
			}
		}
	}
	len = delRows.length
	for(i=len-1;i>=0;i--) {
		tblBody.deleteRow(delRows[i]-1);
	}
}

function removeCurrentRow(tblId, theRow) {
	var tblBody = document.getElementById(tblId).tBodies[0];
	tblBody.removeChild(theRow);
}

function removeRowAndChilds(tblId, selectedItems) {
	var tblBody = document.getElementById(tblId).tBodies[0];
	trs = tblBody.getElementsByTagName("tr");

	var delRows = new Array();
	var parentDeleted = false;
	var isChecked = false;
	
	for(i=0;i<trs.length;i++) {
		inputs = trs[i].getElementsByTagName("input");
		
		isChecked = false;
		isSelectedItem = false;
		for(j=0;j<inputs.length;j++) {
			if(inputs[j].name==selectedItems)	{
				isSelectedItem = true;
				parentDeleted = false;
				if(inputs[j].checked){
					isChecked = true;
					break;
				}
			}
		}
		
		if(isSelectedItem){
			if(isChecked){
				delRows.push(i);
				parentDeleted = true;
			}
		}
		else if(parentDeleted){
			delRows.push(i);
		}
	}
	
	len = delRows.length
	for(i=len-1;i>=0;i--) {
		tblBody.deleteRow(delRows[i]);
	}

	
}

function findParentRow(tblId, node, smartChild) {
	var tblBody = document.getElementById(tblId).tBodies[0];
	trs = tblBody.getElementsByTagName("tr");
	var isIndex = false;
	var parentRow = null;
	for(i=0; i < trs.length; i++){
		if(!isIndex){
			if(trs[i] == node)
				isIndex=true;
		}
		else {
			inputs = trs[i].getElementsByTagName('input');
			if(inputs.length>0 && inputs[0].id == smartChild ){
				parentRow = trs[i];
				break;
			}
		}
	}
	return parentRow;
}

function addHeader(tblId, node, template, smartChild) {
	var tblBody = document.getElementById(tblId).tBodies[0];
	var hasHeader = true;
	trs = tblBody.getElementsByTagName("tr");
	var isIndex = false;
	var parentRow = null;
	for(i=0; i < trs.length; i++){
		if(!isIndex){
			if(trs[i] == node) {
				isIndex=true;
				if(i == trs.length - 1){
					hasHeader=false;
				}
			}
		}
		else {
			inputs = trs[i].getElementsByTagName('input');
			if(inputs.length>0 && inputs[0].id == smartChild ){
				parentRow = trs[i];
				hasHeader = false;
			}
			break;
		}
	}
	
	if(!hasHeader){
		addRowClone(tblId, template, parentRow);
	}
}

function findParentId(tr, idFieldName){
	var parentId = null;
	inputs = tr.getElementsByTagName('input');
	for(i=0; i<inputs.length; i++){
		if(inputs[i].name == idFieldName){
			parentId = inputs[i].value;
			break;
		}
	}
	return parentId;
}

function openPopUp(theURL,winName,features, myWidth, myHeight, isCenter) {
	if(window.screen)if(isCenter){
		var myLeft = (screen.width-myWidth)/2;
		var myTop = (screen.height-myHeight)/2;
		features+=(features!='')?',':'';
		features+='left='+myLeft+',top='+myTop+'';
	}
	window.open(theURL,winName, features+((features!='')?',':'')+'resizable=yes, scrollbars=yes, width='+myWidth+',height='+myHeight);
}

function objetus() {
	try {
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
		try {
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (E) {
			xmlhttp = false;
		}
	}
	if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
		xmlhttp = new XMLHttpRequest();
	}
	
	if(xmlhttp){
		return xmlhttp	
	}
	else{
		alert("Disculpe, el navegador que está utilizando no le permitira visualizar correctamente la aplicación");
	}
}

function httpRequest(reqType, url, asynch, respHandle){
    // Navegadores basados en mozilla
    if(window.XMLHttpRequest){
        request = new XMLHttpRequest();
    }
    // Navegador IE
    else if(window.ActiveXObject){
        request = new ActiveXObject("Msxml2.XMLHTTP");
        if(!request){
            request = new ActiveXObject("Microsoft.XMLHTTP");
        }
    }

    if(request){
        if(reqType.toLowerCase() != "post"){
            initReq(reqType, url, asynch, respHandle);
        }
        else{
            var args = arguments[4];
            if(args != null && args.length > 0){
                initReq(reqType, url, asynch, respHandle, args);
            }
        }
    }
    else{
        alert("Disculpe, el navegador que está utilizando no le permitira visualizar correctamente la aplicación");
    }
}

function initReq(reqType, url, asynch, respHandle){
    try{
        /* Especifica la función que gestionará la respuesta HTTP */
        request.onreadystatechange=respHandle;
        request.open(reqType, url, asynch);
        // Si el parámetro reqType es POST, el quinto argumento
        // de la función indica los datos enviados
        if(reqType.toLowerCase() == "post"){
            request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            request.send(arguments[4]);
        }
        else{
            request.send(null);
        }
    }catch(errv){
        alert("La aplicación no puede contactar al servidor en estos momentos.\n"
            +"Por favor, intente en unos minutos.\n"
            +"Detalles del Error: "+errv.message
            );
    }
}
// converts to selector_case
function stringToSelectorCase(str) {
  var outstr = null;
  if(str != null) {
	  for(i=0;i<str.length;i++){
		if(str.charAt(i)==str.charAt(i).toUpperCase()) {
			if(outstr!=null && outstr.length>0)
				outstr=outstr+'_'+str.charAt(i).toLowerCase();
			else
				outstr=str.charAt(i).toLowerCase();

		}
		else {
			outstr=outstr+str.charAt(i);
		}
	  }
  }
return outstr;
}
// converts to CamelCase
function stringToCamelCase(str) {
  var outstr = null;
  if(str != null) {
	  str=str.split('_');
	  outstr = str[0];
	  outstr = str[0].charAt(0).toUpperCase()+str[0].substring(1);
	  for(i=1;i<str.length;i++){
	   outstr=outstr+str[i].charAt(0).toUpperCase()+str[i].substring(1)
	  }
  }


return outstr;
}

