//alert('Usted Ha ingresado');
var count1 = 0;
var count2 = 0;

/*
if(typeof dhxWins != 'object')
	dhxWins=null;
	*/
var dhxWins=null;	
var win=null;
var winErrors=null;
var GlobalImgPath='';
var mygrid='';
var currentBrowser='';
var textBuffer=null;
var sClassError			= 'error';
var sClassExito			= 'exito';
var sClassWarning		= 'warning';
var sClassSimpleError	= 'simpleError';
var sClassSimpleWarning = 'simpleWarning';
var sClassNoDisplay = 'nodisplay';
var nErrores		= 0;
var nWarnings		= 0;
var aErrors			=[];
var aWarnings		=[];
var aEventCounter	=[];
var divCreated      =0;
var bDragging       =false;
var sErroresForm	= '';

//var aNumbers=[96,97,98,99,100,101,102,103,104,105,8,37,38,39,40,46,109,188,189];	
/*
[] para array sin definicion de indices
{} para array con definicion de indices
*/
var aPoint		=[190,110];
var	aIntegers	=[48,49,50,51,52,53,54,55,56,57,96,97,98,99,100,101,102,103,104,105,9];	
var	aRanges		=[188,189,109];	
var	aArrows		=[37,38,39,40];	
var	aDeletion	=[8,46];
var aULetters	=[65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90];
var aEmail		=[81];
var aPhone		=[40,41,32,107,65,78,79,88,69,109];
var aSpace		=[32];
var aTexto		=[16,95,45,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90];
var aEnie		=[192];
var aHyphens    =[109,189,95];
var aSlashes    =[47,111];



//var aLLetters	=[97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,1120,121,122];


/* BROWSER DETECTION */
var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			   string: navigator.userAgent,
			   subString: "iPhone",
			   identity: "iPhone/iPod"
	    },
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]
};
BrowserDetect.init();
currentBrowser=BrowserDetect.browser;

currBrowser=BrowserDetect.browser + BrowserDetect.version;

/**Cross-Browser Compatibility Functions*/
/********************************************************/

/*
if(currentBrowser!='Firefox')
{
	if(!document.nativeGetElementById)
	{	
	document.nativeGetElementById = document.getElementById;	
	document.getElementById = function(id)
	{
		var elem = document.nativeGetElementById(id);		
		if(elem)
		{		
			if(elem.attributes['id'].value == id)
			{
				return elem;
			}
			else
			{
				for(var i=1;i<document.all[id].length;i++)
				{
					if(document.all[id][i].attributes['id'].value == id)
					{
						return document.all[id][i];
					}
				}
			}
		}
		
		return null;
	};
	}
	
}
*/


/*
if(!Object.hasOwnProperty)
	Object.prototype.hasOwnProperty=function(propName)
	{	
		/*
		if(window[propName])
			return false;		
		if(!this[propName])
			return false;
		
		alert('e');
	}
*/


if(!document.getElementsByClassName)
	document.getElementsByClassName=function(className)
	{
		var x=0;
		var match=[];
		if(!document.getElementsByTagName)
			alert('getElementsByTagName does not exists!');
		var elements=document.getElementsByTagName('*');
		var numElements=elements.length;
		var cls='';
		var element='';
		for(x=0;x<numElements;x++)
		{
			element=elements[x];
			cls=element.className;	
			if(currentBrowser=='Explorer')	
			{
				if(cls==className)
				{
					match.push(element);
				}			
			}	
		}		
		return match;		
	}





var getElementNextSibling=function(obj)
{
    obj=getElement(obj);
    if(obj)
        return false;
    do
        obj=obj.nextSibling;
    while(obj && obj.nodeType != 1);
    return obj;
}
var getElementPreviousSibling=function(obj)
{
    obj=getElement(obj);
    if(obj)
        return false;
    do
        obj=obj.previousSibling;
    while(obj && obj.nodeType != 1);
    return obj;
}

/*

Object.prototype.nextObject = function() 
{
    var n = this;
    do n = n.nextSibling;
    while (n && n.nodeType != 1);
    return n;
}
Object.prototype.previousObject = function() 
{
    var p = this;
    do p = p.previousSibling;
    while (p && p.nodeType != 1);
    return p;
}
*/

/*if(!)

if(!Object.show)
Object.prototype.show=function()
{
	this.style.display 	= 'inline';
	this.style.visibility= 'visible';	
}
if(!Object.prototype.hide)
Object.prototype.hide=function()
{

	this.style.display 	= 'none';
	this.style.visibility= 'hidden';	
}
*/



if(!String.trim)
String.prototype.trim=function(charlist)
{		
    var whitespace, l = 0, i = 0;    
    str=this;
    str += '';    
    if (!charlist) {        
        whitespace = " \n\r\t\f\x0b\xa0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000";
    } else {        
        charlist += '';
        whitespace = charlist.replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '$1');
    }    
    l = str.length;
    for (i = 0; i < l; i++) {
        if (whitespace.indexOf(str.charAt(i)) === -1) {
            str = str.substring(i);
            break;
        }
    }    
    l = str.length;
    for (i = l - 1; i >= 0; i--) {
        if (whitespace.indexOf(str.charAt(i)) === -1) {
            str = str.substring(0, i + 1);
            break;
        }
    }    
    return whitespace.indexOf(str.charAt(0)) === -1 ? str : '';
}
if(!Function.defaults)
{	
	Function.prototype.defaults = function()
	{
	  var _f = this;
	  var _a = Array(_f.length-arguments.length).concat(
	    Array.prototype.slice.apply(arguments));
	  return function()
	  {
	    return _f.apply(_f, Array.prototype.slice.apply(arguments).concat(
	      _a.slice(arguments.length, _a.length)));
	  }
	}
}	
	


/*
Object.prototype.length=function()
{
	var counter=0;
	for(prop in this)
	{
		if(typeof this[prop]!='function')
			counter++;
	}
	return counter;	
}

Object.prototype.remove=function(mProperty)
{	
	if(!array_key_exists(mProperty,this))
		return false;
	
	if(this.constructor==Array)
	{	
		delete this[mProperty];
		this.splice(mProperty,1);
		//this.length--;		
	}
	else
		if(this.constructor==Object)
			delete this[mProperty];
	
			
}


String.prototype.trim2=function()
{
	this.replace(/^\s+|\s+$/g,'');
}

if(!Object.hasAttributes)
	Object.prototype.hasAttributes=function()
	{
		if(this.attributes.length>0)
			return true;
		return false;		
	}	
if(!Array.indexOf)
{
	
	
	extend(oj,Array);
	//alert('no existe Array.indexOf');
	
	
	/*
	Array.prototype.indexOf = function(str) 
	{		
		for (var x=0;x<this.length;x++) 
			if(this[x] == str) 
				return x;
		return false;
	}
	

}
*/
/********************END COMPATIBILITY**************/	
/*

var extend=function(ob1, ob2) {
    for (property in ob2) {
        if (typeof ob2[property] == 'function') {
            ob1[property] = ob2[property].bind(ob1);
        } else {
            ob1[property] = ob2[property];
        }
    }
    return ob1;
}
    function isBoundFunction(func) {
        return (typeof(func.im_func) == 'function');
    }

    function bind(func, self) {
        var im_func = null;
        if (isBoundFunction(func)) {
            im_func = func.im_func;
        } else {
            im_func = func;
        }
        func = function () {
            return func.im_func.apply(func.im_self, arguments);
        }
        func.im_func = im_func;
        func.im_self = self;
        
        return func;
    }
*/
	
	

/*
function extend2(ob1, ob2) {
    for (property in ob2) {
        if (typeof ob2[property] == 'function') {
            ob1[property] = ob2[property].bind(ob1);
        } else {
            ob1[property] = ob2[property];
        }
    }
    return ob1;
  }  
  function extend(ob1, ob2) {
  return (function(object) {
    for (property in object) {
      this[property] = object[property];
    }
    return this;
  }).apply(ob1, [ob2]);
}
*/





var blinkIt=function(){
	
	
	
	var blinkinElements=document.getElementsByClassName('blink');
	var s;
	
	for(i=0;i<blinkinElements.length;i++)
	{
		s=blinkinElements[i];
		s.style.visibility=(s.style.visibility=='visible')?'hidden':'visible';
	}
	
	/*
 if (!document.all) 
 	return;
 else {
   
   ge
   /*for(i=0;i<document.all.tags('blink').length;i++){
      s=document.all.tags('blink')[i];
      s.style.visibility=(s.style.visibility=='visible')?'hidden':'visible';
   }
   */
}
var addOption=function(parent,id,value,text)
{		
	var parent=getElement(parent);		
	if(!parent)
		return false;
	var option=document.createElement('option');
	var textNode=document.createTextNode(text);
	if(id!='')
		addAttribute(option,'id',id);		
	if(value==undefined)
		value='';
	if(text==undefined)			
		text='--No hay registros--';
	addAttribute(option,'value',value);		
	try
	{
		option.appendChild(textNode);
	}
	catch(e)
	{		
		try {
			parent.options.add(option, true);  
		}
		catch(ex) {
			parent.options.add(option);
		}
	}
	parent.appendChild(option);	
	return true;
};

var validarPatronMeses=function(e,element,patron)
{
	var valor= element.value;	
	//if(validaKey(e)) 
	//	return true;
	
	if(typeof patron=='undefined')
		patron =/^([0-2]{0,1})([0-9]{1})$/;
	
	if(patron.test(valor))
	{	
		return true;			
	}
	else
		if(element.value!='')
			element.value=textBuffer;
		else
			element.value='0';	
}
var validarPatronDecimal=function(e,element,patron)
{
	var valor= element.value;	
	//if(validaKey(e)) 
	//	return true;	
	if(typeof patron=='undefined')
		patron =/^[-|+]?[0-9]+(\.[0-9]{0,2})?$/;
	
	if(patron.test(valor))
	{	
		return true;			
	}
	else
		if(element.value!='')
			element.value=textBuffer;
		else
			element.value='0.00';	
}
var validarPatronTelefono=function(e,element,patron)
{
	var valor= element.value;	
	//if(validaKey(e)) 
	//	return true;	
	if(typeof patron=='undefined')
		patron =/^[0-9]+$/;
	
	if(patron.test(valor))
	{	
		return true;			
	}
	else
		if(element.value!='')
			element.value=textBuffer;
		else
			element.value='';
}

var showChildren=function(obj,showAttributes,tab)
{
	obj=getElement(obj);
	var x=0;	
	if(!tab)
		tab='';
	if(!obj.tagName)
		return;		
	var value=(obj.value ? obj.value : obj.nodeValue);
	var tag=(obj.tagName ? obj.tagName : obj.nodeType);
	var id=(obj.id ? obj.id : obj.nodeName.toLowerCase());
	document.write(tab + '<strong><font color="#002AFF">[' + tag + ']</font><font color="#F2721D">[' + id + ']</font></strong><strong>[</strong>' + value + '<strong>]</strong><br />');
	tab+="|&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
	if(obj.childNodes.length>0)
	{
		for(x; x<obj.childNodes.length;x++)
		{			
			var item = obj.childNodes.item(x);
			//if(item.id == undefined)
			//	item.id=item.nodeName;
			if(item.childNodes.length>0)
				showChildren(item,showAttributes,tab);
			else
			{
				var id=(item.id ? item.id : item.nodeName.toLowerCase());
				var value=(item.innerHTML ? item.innerHTML : item.nodeValue);
				var tag=(item.tagName ? item.tagName : item.nodeType);
				//document.write('TAG:' + value.trim());
				if(tag==3 && value.trim()=='')
				{
					continue;
				}	
				if(tag==3)
					tag='INNERHTML';
				document.write(tab + '<strong><font color="#002AFF">[' + tag + ']</font><font color="#F2721D">[' + id + ']</font></strong><strong>[</strong>' + value + '<strong>]</strong><br />');
				if(showAttributes)
					document.write(tab + show_all(item,tab + tab) +  '<br />');						
			}			
		}
	}	
}

/**   para actualizar los id de elementos clonados*/
var clonedIds=[];


var renameChildren=function(obj)
{
	var patronId		=/^([a-z_|a-z\-]+[\[]?[\d]+[\]]?)/i;
	var patronTexto		=/^[a-z_|a-z\-]+[\[]?/i;
	var patronNumero	=/[\d]+/;
	var hijos			=getChildren(obj,'',true);
	var id				=null;
	
	textoPadre	=patronTexto.exec(id);			
	numeroPadre	=patronNumero.exec(id);
	
	for(var x=0;x<hijos.length;x++)
	{
		if(!hijos[x].id)
			continue;
		id=hijos[x].id;			
		if(!patronId.test(id))
			continue;
							
		newTexto	=patronTexto.exec(id);			
		newNumero	=patronNumero.exec(id);
		
		clonedIds[newTexto]=parseInt(newNumero)+1;
		
	}	
	clonedIds[textoPadre]=parseInt(numeroPadre)+1;	
}


/*Permite crear los ids y resetear los valores de un elemento clonado incluyendo hijos*/
var updateChildren=function(obj,clearEvents,clearValues,clearClasses,clearStyles)
{
    obj=getElement(obj);
    if(!obj)
        return false;
    var elements    =getChildren(obj,false);     
    var numElements =0;
    var matchesLen  =0;
    var matches;
    var x           =0;
    var y           =0; 
    var z           =0;
    var text;
    var number;
    var storedNumber;
    var item;
    var newId='';
    var newName='';
    var oldId='';  
    var oldName='';
    var itemType;
    var itemTag;
    var flagName=0;
    if(!elements)
        var elements=[];
    else
        numElements=elements.length;    
    elements[numElements]=obj;
    numElements++;    
    var patternId	= /(^([a-zA-Z_\-]+)([\d]+)$)|(^([a-zA-Z_\-]+[\d]?\[)+([\d]+)\]$)|(^([a-zA-Z_\-\d]+\[)+([\d]+)\]$)|(^([a-zA-Z_\-\d\[\]]+\[)+([\d]+)\]$)|(^([a-zA-Z_\-\d]+)([\d]+)$)/;   
    
    



    
    
    
    var patternEvent=/^(on\w)/;
    var attribName  ='';
    var attribValue ='';  
    var newElements =[];	
	var newTexts    =[];
    while(x<numElements)
    {
        item=elements[x++]; 
        if(!(oldId=item.id))
            continue;
		if(oldId==='')
			continue;
        y           = 0;  
        matchesLen  = 0;
        itemType    = '';                      
        matches     = oldId.match(patternId); 
        if(!matches)
        {
            item.removeAttribute('id');           
		    continue;
        }         
        matchesLen=matches.length;
        while(matchesLen)
        {            
           if(matches[matchesLen])
           {
                if(y===0)                                
                    number=matches[matchesLen];                
                else                    
                {
                    text=matches[matchesLen];
                    break;
                }    
                y++;
            }
           matchesLen--;            
        }      
        number  = (+number);        
		if(!clonedIds[text])
            clonedIds[text]=0;
        storedNumber=(+clonedIds[text]); 	
		if(number>=storedNumber)
			clonedIds[text]=number+1;
        newElements[z]=item;       
        newTexts[z]=text;       
        z++;
      }  
      numElements=newElements.length;
      x=0;
      while(x<numElements)  
      {  
        item    =newElements[x];
        oldId   =item.id;
        text    =newTexts[x];
        number  =clonedIds[text];        
        newId=text + number;	
        clonedIds[text]++;
        
        if(item.type)
            itemType=item.type;    
        if(item.type)
            itemTag=item.tagName;
        if(newId.indexOf('[')>=0)
            newId+= ']';
        
        //if(text=='radio') 
            //alert('Name: ' + item.name+ '=> Id: ' + oldId); 
        if((oldName=item.name)===oldId)
        {
            //item.name=newId;
            addAttribute(item,'name',newId);
            flagName=0;
            
        }
        else
            if(oldName===text)
            {
                if(!flagName)
                {
                    number  =clonedIds[text];
                    newName=text + number;
                    clonedIds[text]=number+1;
                    flagName=1;   
                    
                }
                addAttribute(item,'name',newName);
                //item.name=newName;
                
      
                
                
                //if(text=='radio') 
                  //  alert('Name: ' + item.name+ '=> Id: ' + oldId);  
                
            }
            /*
            if(oldName===oldId)
            {
               item.name=newId; 
               
            }
            else
            {
                if(itemTag==='INPUT' && itemType==='radio' && oldName===text)
                {
                    //alert(oldName+ '=> ' + text);    
                    
                    /*
                    if(!clonedIds[text + '_'])
                        number=0;
                    else
                        number  =clonedIds[text];                       
                    newName=text + number;
                    clonedIds[text]=number+1;     
                    flagName=1;               
                }    
                
                
            }*/
     
        /*
        if(text=='radio')    
            alert(item.name + '=> ' + text);    
        if(item.name!==item.id && itemTag==='INPUT' && itemType==='radio')
        {
            //alert(item.name + '=> ' + text);
            if((item.name===text)||((item.name)===(text + '[]')))
            {
                
                if(!flagName)
                {
                    alert(item.name + '=> ' + text);
                    if(item.name===text )
                    {
                        if(!clonedIds[text])
                            number=0;
                        else
                            number  =clonedIds[text];                       
                        newName=text + number;
                        clonedIds[text]=number+1;                        
                    }
                    else
                        if(item.name===(text+'[]'))
                        {
                            //alert(item.name + '=> ' + text);
                            if(!clonedIds[text + '[]'])
                                number=0;
                            else
                                number  =clonedIds[text + '[]'];
                            newName=text + number + '[]';
                            clonedIds[text+'[]']=number+1;
                            
                        }
                    
                    flagName=1;
                }
                item.name=newName;                
            }
        }    
        else    
        {
            item.name=newId;
            flagName=0;
        } 
        */
        
        
        
        if(newId)       
            item.id=newId;             
        if(clearValues)
		{
		  //alert(item.id+'=>'+itemType);
    	    if(itemTag==='INPUT' || itemTag==='SELECT' || itemTag==='TEXTAREA')
            {	      
    		      switch(itemType)
                  {
                    
                    case 'text':
                        if(typeof item.value!='undefined')
    					   item.value='';
                    break;
                    case 'hidden':
                        if(typeof item.value!='undefined')
    					   item.value='';
                    break; 
                    case 'textarea':
                        if(typeof item.value!='undefined')
    					   item.value='';
                    break;             
                    case 'radio':
                        if(typeof item.checked!='undefined')
        					item.checked=false;	
                    break;
                    case 'checkbox':
                        if(typeof item.checked!='undefined')
        					item.checked=false;	
                    break;
                    case 'select-one':                        
                        if(typeof item.options!='undefined')
        				{
        					if(item.selectedIndex>=0)
        						item.options[item.selectedIndex].selected = false;
        				}
                    break;
                    case 'select-multiple':
                        if(typeof item.options!='undefined')
                					if(item.options.length>0)	
                						for(var z=0;z<item.options.length;z++)
                							if(item.options[z].selected)
                								item.options[z].selected=false;
                    break;                    
                  }  
            }
            else
            {
                if(itemTag==='IMG')
                {
                   if(item.src)
                        item.src=''; 
                }
                //else
                  //  item.innerHTML='';
            }
            
         }      
        if(clearEvents)
		{		
			var numAttrib=item.attributes.length;
			if(numAttrib===0)
				continue;
            y=0;
			while(y<numAttrib)
			{
				if(!item.attributes[++y])
					continue;
				attribName	=item.attributes[y].name;
				attribValue	=item.attributes[y].value;				
				if(patternEvent.test(attribName) && attribValue)
				    //delAttribute(item,attribName);
                    item.removeAttribute(attribName);	
			}
		}
        if(clearClasses)
            removeClasses(item)
        if(clearStyles)
            removeStyles(item);
        x++;          
    }

}.defaults(null,false,true,false,false);



/*Permite clonar un elemento*/
var cloneElement=function(obj,parent,useParent,cloneChildren,clearEvents,clearValues,clearClasses,clearStyles)
{
	
    obj	= getElement(obj);
    if(!obj)
        return false;
	if(useParent)
		parent		= obj.parentNode;	
	else	
		parent		= getElement(parent);
	var clone		= obj.cloneNode(cloneChildren);
	if(!clone)
		return false;
	updateChildren(clone,clearEvents,clearValues,clearClasses,clearStyles);	
	if(parent)
	{
		parent.appendChild(clone);
		return clone;	
	}	
	return clone;	
}.defaults(null,null,false,true,false,true,false,false);

var getLastChildObject=function(obj)
{
    var childNodes=obj.childNodes.length;
    if(!childNodes)
        return false;
    var elements=obj.childNodes;      
    var x=0;
    var currItem;
    while(x<childNodes)
    {
        var item = obj.childNodes.item(x++);
        if(item.nodeType!==3)
        {
            currItem=item;
        } 
    }
    return currItem;
}
var getFirstChildObject=function(obj)
{
    var childNodes=obj.childNodes.length;
    if(!childNodes)
        return false;
    var elements=obj.childNodes;      
    var x=0;
    var currItem;
    while(x<childNodes)
    {
        var item = obj.childNodes.item(x++);
        if(item.nodeType!==3)
        {
            currItem=item;
            return currItem;
        } 
    }
    return;
}

var getNextChildObject=function(obj)
{
    var childNodes=obj.childNodes.length;
    if(!childNodes)
        return false;
    var elements=obj.childNodes;      
    var x=0;
    while(x<childNodes)
    {
        var item = obj.childNodes.item(x++);
        if(item.nodeType!==3)
            return item; 
    }
    return false;
} 

 
var getLastSiblingObject=function(obj)
{
    obj	= getElement(obj);
    if(!obj)
        return false;
    var element;
    var temp;
    if(obj.nextSibling)
        temp=obj.nextSibling;
   while(temp)
   {                
        if(temp.nodeType!==3)
            element=temp;
        temp=temp.nextSibling;
    }        
    return element || obj;     
}   

var getFirstSiblingObject=function(obj)
{
    obj	= getElement(obj);
    if(!obj)
        return false;
    var element;
    var temp;
    if(obj.previousSibling)
        temp=obj.previousSibling;
    while(temp)
    {            
        if(temp.nodeType!==3)
            element=temp;
        temp=temp.previousSibling;
    }        
    return element || obj;    
}

var getNextSiblingObject=function(obj,index)
{
    obj	= getElement(obj);
    if(!obj)
        return false;
    var element;
    var temp;
    var x=0;
    if(obj.nextSibling)
        temp=obj.nextSibling;
    while(temp)
    {            
        if(temp.nodeType!==3)
        {   
            x++;
            if(index)
            {
                if(index==x)
                {
                    element=temp;
                    break;
                }
            }
            else
            {        
                element=temp;
                break;
            }
        }
        temp=temp.nextSibling;
        
    }        
    if(!index)
        return element || obj;
    else
        return element;
}
var getPreviousSiblingObject=function(obj,index)
{
    obj	= getElement(obj);
    if(!obj)
        return false;
    var element;
    var temp;
    var x=0;
    if(obj.previousSibling)
        temp=obj.previousSibling;
    while(temp)
    {            
        if(temp.nodeType!==3)
        {
            
            if(index)
            {
                x++;
                if(index==x)
                {
                    element=temp;
                    break;
                }
                
            }
            else
            {        
                element=temp;
                break;
            }
        }
        temp=temp.previousSibling;        
    }        
    if(!index)
        return element || obj;
    else
        return element;  
}

var getSiblings=function(obj,tag,type,attrib,value,inner)
{
    var elements=[];
    var temp=getFirstSiblingObject(obj);
    while(temp)
    {            
        if(temp.nodeType!==3)
            elements.push(temp);
        temp=temp.nextSibling;
    }
    return elements;
}
var getpreviousSibling=function(obj)
{
    var element;
    var temp;
    if(obj.previousSibling)
        temp=obj.previousSibling;
    while(temp)
    {            
        if(temp.nodeType!==3)
        { 
            element=temp;
            break;
        }
        temp=temp.previousSibling;
    }       
    return element || obj;
}


/*devuelve el primer elemento hermano no texto*/
/*
var getFirstSiblingObject=function(obj)
{
    var element=obj.nextSibling;
    if(element.nodeType===3)
        element=getNextSiblingObject(element);        
    return element;        
}
*/
/*
var getLastSiblingObject=function(obj)
{
    var element=obj.nextSibling;
    if(element.nodeType===3)
        element=getNextSiblingObject(element);        
    return element;        
}
*/

/*devuelve el primer elemento hermano no texto*/
/*
var getNextSiblingObject=function(obj)
{
    var element=obj.nextSibling;
    if(element.nodeType===3)
        element=getNextSiblingObject(element);        
    return element;        
}
*/
/*devuelve el primer elemento hermano no texto*/
/*
var getPreviousSiblingObject=function(obj)
{
    var element=obj.previousSibling;
    if(element.nodeType===3)
        element=getPreviousSiblingObject(element);        
    return element;        
}
*/
/*Devuelve los hijos de un elemento*/
var getChildren=function(obj,filter,deep,_regexp,_flag)
{ 
    if(!_flag)
       obj=getElement(obj);
    if(!obj)
        return false;
    if(!obj.tagName)
        return false;
    var childNodes;
    var subChildren; 
    if(!_flag)
    {
        if(filter)
        {
            if(!_regexp)
            {
                if(filter.indexOf('|')>0)
                {
                    var _regexp = new RegExp(filter,'i');
                    filter='';
                }
            }
        }
    }
    if(!_flag && deep)
    {
        if(document.getElementsByTagName)
        {            
            if(!filter)
                subChildren = obj.getElementsByTagName('*');  
            else
                subChildren = obj.getElementsByTagName(filter);
            if(!_regexp)
                return subChildren;  
        }       
        childNodes=subChildren.length;
    }
    else
    {
        childNodes=obj.childNodes.length;
        _flag=true;        
    }
    if(!childNodes)
        return false;
    var children=[];    
    var y=0;  
    var x=0;           
    var item;
    while(x<childNodes)
    { 
        if(!_flag)
            item=subChildren[x++];
        else
            item = obj.childNodes.item(x++);
        if(item.nodeType===3)
            continue; 
        if(!_regexp && !filter)
            children[y++]=item;                
        else
        {
            if(_regexp)
            {                        
                if(_regexp.test(item.tagName))                        
                    children[y++]=item;                        
            }    
            else
            {          
                if(filter)
                    if(item.tagName===filter)                            
                        children[y++]=item;
            }
        }         
        if(item.childNodes.length && _flag && deep)
        {   
            subChildren=getChildren(item,filter,deep,_regexp,true);
            if(subChildren)
            {
                var l=subChildren.length;
                var z=0;                    
                while(z<l)
                    children[y++]=subChildren[z++];
            }                        
        }            
    }
    return children;
}.defaults(null,'',true,false,false);   


var validaPatron=function(e,element,tipo)
{
	var valor= element.value;
	var patron='';
	switch(tipo)
	{
		case 'double': patron=/^[-|+]?\d+(\.\d{0,2})?$/;break;
		case 'double1': patron=/^[-|+]?\d+(\.\d{0,1})?$/;break;
		case 'double2': patron=/^[-|+]?\d+(\.\d{0,2})?$/;break;
		case 'double3': patron=/^[-|+]?\d+(\.\d{0,3})?$/;break;
		case 'double4': patron=/^[-|+]?\d+(\.\d{0,4})?$/;break;		
		case 'integer': patron=/^[-|+]?\d+$/;break;
		case 'text': patron=/^[-|+]?\d+(\.\d{0,2})?$/;break;
		case 'date': patron=/^[-|+]?\d+(\.\d{0,2})?$/;break;
		default: patron=/\W|\w/;   break;
		
		
		
	}
	 
	if(patron.test(valor))
	{	
		return true;			
	}
	else
		if(element.value!='')
			element.value=textBuffer;
		else
			element.value='0.00';	
}
var checkDate=function(mObj)
{
    var valor=checkObjectValue(mObj);
   	if(!valor)
		return false;
 	var sPatron = /^((0[1-9])|([1-2][0-9])|(3[0-1]))(\-|\/|\.)((0[1-9])|(1[0-2]))(\-|\/|\.)([1-2]{1}[\d]{3})$/;	
	if(sPatron.test(valor))
	{	
		if(typeof mObj =='object')
			setError(mObj,'',false);
		return true;
	}	
	if(typeof mObj =='object')
		setError(mObj,'Fecha Inválida');
	return false;
    
}


var checkMail=function(mObj)
{
	var valor=checkObjectValue(mObj);
	if(!valor)
		return false;
 	//sPatron = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	//var sPatron = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;	
	//var sPatron = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*\.(\w{2}|(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum))$/	;
  var sPatron =/^([*+!.&#$¦\'\\%\/0-9a-z^_`{}=?~:-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,4})$/i;
	
    if(sPatron.test(valor))
	{	
		if(typeof mObj =='object')
			setError(mObj,'',false);
		return true;
	}	
	if(typeof mObj =='object')
		setError(mObj,'Correo Inválido');
	return false;
}
var checkForm=function(obj)
{	
	obj=getElement(obj);
	var children=getChildren(obj,'INPUT|SELECT|TEXTAREA');
	var len=children.length;
	var x=0;
	var element;
	var error=0;
	while(x<len)
	{
		element=children[x++];
		if(readAttribute(element,'mandatory')==='1')
		{			
			if(!element.value)
			{
				element.className='error';
				error++;				
			}
			else			
				element.className='';
		}
	}
	if(error)
		alert('Debe completar los campos marcados');
	else
		obj.submit();	
}


var checkEnterprise=function(mObj)
{	
	
	var valor=checkObjectValue(mObj);
	if(!valor)
		return false;
	var sPatron = /^([0-9]*[a-zA-Z_\s\.\-\xD1\xF1]+[0-9]*)+$/	;	
	if(sPatron.test(valor))
	{
		if(typeof mObj =='object')
			setError(mObj,'',false);
		return true;
	}	
	if(typeof mObj =='object')
		setError(mObj,'Empresa Inválida');	
	return false;	
}
var checkName=function(mObj)
{
	var valor=checkObjectValue(mObj);
	if(!valor)
		return false;
	var sPatron = /^[a-zA-Z\s\xF1]+$/	;	
	if(sPatron.test(valor))
	{
		if(typeof mObj =='object')
			setError(mObj,'',false);
		return true;
	}			
	if(typeof mObj =='object')
		setError(mObj,'Nombre Inválido');	
	return false;
	
}
var checkText=function(mObj)
{	
	var valor=checkObjectValue(mObj);	
	if(!valor)
		return false;
	var sPatron = /^[0-9a-zA-Z_\s\.\-]+$/	;
	
	if(sPatron.test(valor))
	{
		if(typeof mObj =='object')
			setError(mObj,'',false);
		return true;
	
	}
	if(typeof mObj =='object')
		setError(mObj,'Texto inválido');
	return false;	
}


var checkCurrency=function(mObj)
{   
   	var valor=checkObjectValue(mObj);
	if(!valor)
		return false;	
	var  sPatron = /^[-+]?\d*(\.\d{1,2})?$/;	
	if(sPatron.test(valor))
	{
		if(typeof mObj =='object')
			setError(mObj,'',false);
		return true;
	}
	if(typeof mObj =='object')
		setError(mObj,'Monto Inválido');	
	return false;    
    
    
}

var checkInteger=function(mObj)
{
	var valor=checkObjectValue(mObj);
	if(!valor)
		return false;	
	var sPatron = /^([0-9]+)$/;	
	if(sPatron.test(valor))
	{
		if(typeof mObj =='object')
			setError(mObj,'',false);
		return true;
	}
	if(typeof mObj =='object')
		setError(mObj,'Número Inválido');	
	return false;
}
var checkPhone=function(mObj)
{
    //alert(mObj);
	var valor=checkObjectValue(mObj);
	if(!valor)
		return false;
        //sPatron = /^(\d{3}-\d{4})|(\d{7})|(\d{9})$/;
	//var sPatron = /^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,5})|(\(?\d{2,6}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$/;
	var sPatron = /^((\({1}((\+){0,1}[0-9]{1,3}\){1})|((\+){0,1}[0-9]{1,3}))(-|\s){1})?(([0-9]{6,7}){1}|(9[0-9]{8}){1})+((\s{1}(ext|anexo){1}(\s){1}){1}(\d){1,4})?$/;	
	if(sPatron.test(valor))
	{
	   if(typeof mObj =='object')
			setError(mObj,'',false);
		return true;
	}
    
   
    
    
	if(typeof mObj =='object')
    {        
        setError(mObj,'Número Inválido');
    }    	
	return false;
}

var checkObjectValue=function(mObj)
{	
	if(!mObj)
		return mObj;

	if(typeof mObj== 'object')
	{		
		var obj=getElement(mObj);
		if(!obj)
			return mObj;
		else
			if(!obj.value)	
				return false;
			else
				return obj.value;	
	}
	return mObj;
}
var checkDocument = function(mObj)
{
	var valor=checkObjectValue(mObj);
	if(!valor)
		return false;		
	var sPatron = /^[0-9]{8,9}$/;	
	if(sPatron.test(valor))
	{
		if(typeof mObj =='object')
			setError(mObj,'',false);
		return true;
	}	
	if(typeof mObj =='object')
		setError(mObj,'N° Documento inválido!');	
	return false;
}
var checkDNI = function(mObj)
{
	var valor=checkObjectValue(mObj);
	if(!valor)
		return false;		
	var sPatron = /^[0-9]{8,9}$/;	
	if(sPatron.test(valor))
	{
		if(typeof mObj =='object')
			setError(mObj,'',false);
		return true;
	}	
	if(typeof mObj =='object')
		setError(mObj,'N° Documento inválido!');	
	return false;
}
var checkRUC = function(mObj)
{	
	var valor=checkObjectValue(mObj);
	if(!valor)
		return false;
	var sPatron = /^[0-9]{11}$/;		
	if(!sPatron.test(valor))
	{
		if(typeof mObj =='object')
			setError(mObj,'RUC inválido!');
		return false;
	}
				
	var factores	= [5,4,3,2,7,6,5,4,3,2];
	var x		= 0;
	var suma	= 0;
	var residuo = 0;
	var resta    =0;
	var chequeo	 =parseInt(valor.charAt(10));
	while(x<10)
	{		
		suma+=parseInt(valor.charAt(x))* factores[x];
		x++;		
	}
	residuo = suma % 11;
	resta  = 11 - residuo;
	
	
	if(resta==10)
		resta=0;
	else
		if(resta==11)
			resta=1;	
	if(chequeo==resta)
	{
		if(typeof mObj =='object')
			setError(mObj,'',false);
		return true;
	}
	if(typeof mObj =='object')
		setError(mObj,'RUC inválido!');		
	return false;
}

var validaTabKey=function(e,element)
{
	
	var tecla_codigo=getKeyStroke(e); 
	
	if(tecla_codigo==13)
	{
		alert(element.next.id);		
		
		return cancelEvent(e);
		}
	else
	return cancelEvent(e);
}

var validarTexto = function(e,element)
{
	var valor= element.value;
	var tecla_codigo=getKeyStroke(e);
	var keyCodes=[];	
	//alert(tecla_codigo);
	keyCodes=array_merge(aIntegers,aSpace,aPoint,aTexto,aArrows,aDeletion,aEnie,aHyphens);
	keyCodes=array_unique(keyCodes);
	
	if(in_array(tecla_codigo,keyCodes))
	{
		textBuffer=	element.value;
		return true;		
	}
	else
	{	
		return cancelEvent(e);
	}		
} 
var validarNombre= function(e,element)
{
	var valor= element.value;
	var tecla_codigo=getKeyStroke(e);
	var keyCodes=[];	
	keyCodes=array_merge(aSpace,aULetters,aArrows,aDeletion,aEnie);
	keyCodes=array_unique(keyCodes);
	if(in_array(tecla_codigo,keyCodes))
	{	
		textBuffer=	element.value;
		return true;		
	}
	else
	{	
		return cancelEvent(e);
	}	
	
}
var validarDNI = function(e,element)
{
	var valor= element.value;
	var tecla_codigo=getKeyStroke(e);
	var keyCodes=[];	
	keyCodes=array_merge(aIntegers,aArrows,aDeletion);
	keyCodes=array_unique(keyCodes);
	if(in_array(tecla_codigo,keyCodes))
	{	
		textBuffer=	element.value;
		return true;
		
	}
	else
	{	
		return cancelEvent(e);
	}		
}
var validarDocumento = function(e,element)
{
	var valor= element.value;
	var tecla_codigo=getKeyStroke(e);
	var keyCodes=[];	
	keyCodes=array_merge(aIntegers,aArrows,aDeletion);
	keyCodes=array_unique(keyCodes);
	if(in_array(tecla_codigo,keyCodes))
	{	
		textBuffer=	element.value;
		return true;
	}
	else
	{	
		return cancelEvent(e);
	}		
}  
var validarRUC = function(e,element)
{
	var valor= element.value;
	var tecla_codigo=getKeyStroke(e);
	var keyCodes=[];	
	keyCodes=array_merge(aIntegers,aArrows,aDeletion);
	keyCodes=array_unique(keyCodes);
	if(in_array(tecla_codigo,keyCodes))
	{	
		textBuffer=	element.value;
		return true;
		
	}
	else
	{	
		return cancelEvent(e);
	}		
} 
var validarFecha=function(e,element)
{
	var valor= element.value;
	var tecla_codigo=getKeyStroke(e);
	var keyCodes=[];	
	keyCodes=array_merge(aIntegers,aSlashes,aDeletion,aArrows);
	keyCodes=array_unique(keyCodes);
	if(in_array(tecla_codigo,keyCodes))
	{	
		textBuffer=	element.value;
		return true;
		
	}
	else
	{	
		return cancelEvent(e);
	}	
}
var validarCorreo=function(e,element)
{
	var valor= element.value;
	var tecla_codigo=getKeyStroke(e);
	var keyCodes=[];	
	keyCodes=array_merge(aIntegers,aULetters,aPoint,aEmail,aArrows,aDeletion,aHyphens);
	keyCodes=array_unique(keyCodes);
	if(in_array(tecla_codigo,keyCodes))
	{	
		textBuffer=	element.value;
		return true;
		
	}
	else
	{	
		return cancelEvent(e);
	}	
}
var validarTelefono=function(e,element)
{
	var valor= element.value;
	var tecla_codigo=getKeyStroke(e);
	var keyCodes=[];	
	keyCodes=array_merge(aIntegers,aPhone,aArrows,aDeletion);
	keyCodes=array_unique(keyCodes);
	if(in_array(tecla_codigo,keyCodes))
	{	
		textBuffer=	element.value;
		return true;		
	}
	else
	{	
		return cancelEvent(e);
	}	
}
var validarDecimal=function(e,element)//keydown
{
	var valor= element.value;
	var tecla_codigo=getKeyStroke(e);

	var keyCodes=[];	
	keyCodes=array_merge(aIntegers,aArrows,aDeletion,aPoint);
	keyCodes=array_unique(keyCodes);
	if(in_array(tecla_codigo,keyCodes))
	{	
		textBuffer=	element.value;
		return true;
		
	}
	else
	{	
		return cancelEvent(e);
	}
}
var validarEntero=function(e,element)  //usar return y en el evento keydown
{
	var valor= element.value;
	var tecla_codigo=getKeyStroke(e);
	
	var keyCodes=[];	
	keyCodes=array_merge(aIntegers,aArrows,aDeletion);
	keyCodes=array_unique(keyCodes);
	if(in_array(tecla_codigo,keyCodes))
	{	
		textBuffer=	element.value;
		return true;
		
	}
	else
	{	
		return cancelEvent(e);
	}
}




var cancelEvent=function(e)
{
	if(!e)
        if(window.event)
		  e = window.event; 
		else	
		  return false;			
	if(e.preventDefault)
		e.preventDefault();
	else
		if(e.returnValue)
			e.returnValue = false;						
		else
			return false;	
}

var getKeyStroke=function(e) {
	//var tecla_codigo = (document.all) ? e.keyCode : e.which;
	//var character = String.fromCharCode(tecla_codigo);
	//alert('Character was ' + character);
	//	writeData(evt.type);
	var keyStroke;
	try {
		if (!e) 
		{
			if(window.event)
				var e = window.event; 
			else	
				return false;
		}
		if (e.keyCode)
			keyStroke = e.keyCode; 
		else if (e.which) 
			keyStroke = e.which; 
		else
			keyStroke = e.charCode;
		return keyStroke;
	}
	catch(err) 
	{
		//alert(err.description);
        return false;
	}
}
var show_all=function(obj,tab,print)
{	
	
	var val;
	var html='';
	try{	
		if(!tab)
			tab='';		
		if(typeof obj=='object')
		{
			try
			{			
				if(obj.name)
					html+='<br/><strong>' + obj.name + '</strong><br />';
			}
			catch(e)
			{
				html+='<br/><strong>' + obj + '</strong><br />';
			}
		}
		else
			html+='<br/><strong>' + typeof obj + '</strong><br />';
		html+=tab+ '----------------------<br />';

		var index='';
		for(e in obj)
		{
			
			index=e.toString();
			try{
				
				if(!obj[index])
					continue;
				
			}
			catch(err)
			{				
				continue;
			}
			if(typeof e !='object')
			{
				if(typeof obj[index]!='object' )
				{
					val=htmlentities(obj[index].toString(),"'");
				}
				else
				{
					val='';
					//tab+="&nbsp;&nbsp;";
					//show_all(obj[e],tab);
				}
			}			
			else
				val='';	
			
		
			if(val.indexOf('function()')>=0 || val.indexOf('function ')>=0)
				html+=tab + '<strong><font color="#002AFF">[function]</font>&nbsp<font color="#F2721D">[' + e + ']</font></strong>=<strong>[</strong>' + val + '<strong>]</strong><br/>';
			else
				html+=tab + '<strong><font color="#002AFF">[' +  typeof e + ']</font>&nbsp<font color="#F2721D">[' + e + ']</font></strong>=<strong>[</strong>' + val + '<strong>]</strong><br/>';
					
				
		}
	}
	catch(err)
	{
			
			alert(err.description);
	}
	
	if(print)
		document.write(html);
	else
		return html;	
	
	
}
var OnKeyRequestBuffer = 
	{
		functionname: "",
        bufferText: false,
        bufferTime: 500,        
        modified : function(strId)
        {
        	setTimeout('OnKeyRequestBuffer.compareBuffer("'+strId+'","'+getElement(strId).value+'");', this.bufferTime);
        },
        compareBuffer : function(strId, strText)
        {
            if (strText == getElement(strId).value && strText != this.bufferText)
            {
                this.bufferText = strText;
                OnKeyRequestBuffer.makeRequest(strId);
            }
        },
        makeRequest : function(strId)
        {
			eval(OnKeyRequestBuffer.functionname);
        	//function(OnKeyRequestBuffer.functionname) { (OnKeyRequestBuffer.functionname) };        
        }
    };    
   // OnKeyRequestBuffer.compareBuffer("txtRegex","~^(([0-9]+)([.]{1}([0-9]{1,2}))(s)%)$~");
    

    
var delayKeyUp=function(sId,sFunction,nDelay)
{	
	if(typeof nDelay=='undefined')
		nDelay=500;		
	OnKeyRequestBuffer.functionname=base64_decode(sFunction);

	OnKeyRequestBuffer.modified(sId);		
	OnKeyRequestBuffer.bufferTime=nDelay;
	return false;
}	
var attachCSS = function(cssFile)
{
	var cssNode = document.createElement('link');
	cssNode.setAttribute('rel', 'stylesheet');
	cssNode.setAttribute('type', 'text/css');
	cssNode.setAttribute('href', cssFile);
	document.getElementsByTagName('head')[0].appendChild(cssNode);
};
var attachJS = function(id,jsFile)
{
	var scriptNode = document.createElement('script');	
	scriptNode.type='text/javascript';	
	//scriptNode.language='javascript';
	scriptNode.src=jsFile; 
	scriptNode.charset='UTF-8'; 
	var heads=document.getElementsByTagName("head")
	var head=heads[0];	
	alert(jsFile);
	head.appendChild(scriptNode);
};
var openDhtmlxWindow=function(id,title,html,width,height,top,left,center,type,modal,maximized,header,resizable)
{
	/*
	var aDefaultParameters={"width":400,"height":400,"modal":"true","resizable":"no","left":400,"top":250};
	var parameters = '';	
		for(val in aDefaultParameters)
		if(typeof aparameters[val] == 'undefined')
			sparameters = sparameters + val + "= " + aDefaultParameters[val] + ",";
		else
			sparameters = sparameters + val + "= " + aparameters[val] + ",";
	require_once('../common/classes/dhtmlxsuite/dhtmlxWindows/codebase/dhtmlxcommon.js');
	require_once('../common/classes/dhtmlxsuite/dhtmlxWindows/codebase/dhtmlxwindows.js');
	*/
	/*
		var scriptNode = document.createElement('script');
	document.getElementsByTagName("head")[0].appendChild(scriptNode);
	scriptNode.language='javascript';
	scriptNode.src=jsFile; 
		var scriptNode = document.createElement('script');
	document.getElementsByTagName("head")[0].appendChild(scriptNode);
	scriptNode.language='javascript';
	scriptNode.src=jsFile; 
	*/
	//attachCSS('../common/classes/dhtmlxsuite/dhtmlxWindows/codebase/dhtmlxwindows.css');
	//attachCSS('../common/classes/dhtmlxsuite/dhtmlxWindows/codebase/skins/dhtmlxwindows_dhx_blue.css');
	//require_once('../../dhtmlxsuite/dhtmlxWindows/codebase/dhtmlxcommon.js');
	//require_once('../../dhtmlxsuite/dhtmlxWindows/codebase/dhtmlxwindows.js');
	if(typeof left=='undefined' || !is_numeric(left) )
		left=300;
	if(typeof top=='undefined' || !is_numeric(top) )
		top=100;
	if(typeof width=='undefined' || !is_numeric(width) )
		width=500;
	if(typeof height=='undefined' || !is_numeric(height) )
		height=500;	
	if(typeof center=='undefined' || !is_numeric(center) )
		center=1;
	if(typeof type=='undefined' || !is_numeric(type) )
		type=1;	
	if(typeof modal=='undefined' || !is_numeric(modal) )
		modal=1;	
	if(typeof maximized=='undefined' || !is_numeric(maximized) )
		maximized=0;	
	if(typeof header=='undefined' || !is_numeric(header) )
		header=1;
 	if(typeof resizable=='undefined' || !is_numeric(resizable) )
		resizable=1;	
	if(modal==1)
		modal=true;
	else
		modal=false;	
	html=base64_decode(html);
	
	
	try
	{			
	   
		if(!dhxWins)
		{
			dhxWins= new dhtmlXWindows();
			dhxWins.enableAutoViewport(true);
		}
		if(dhxWins==null)
			win = parent.dhxWins.createWindow(id, left, top, width, height);
		else
			win = dhxWins.createWindow(id, left, top, width, height);			
		win.setText(title); 		
		win.setModal(modal);
        if(resizable)
            win.allowResize();
        
         //win.setEffect("move", true);
		if(type==1)
			win.attachHTMLString(html);
		else
			win.attachURL(html);		
		
		if(maximized)
			win.maximize();
		if(header)
			win.showHeader();
		else
			win.hideHeader();	
		switch(center)
		{
			case 1:
				win.centerOnScreen();
			break;
			case 2:
				win.center();
			break;
		}
		//win.setDimension(200);	
		//win.progressOn();
		//win.center();	
	}
	catch(e)
	{
		alert(e.description);
	}
    try
    {
        window[id]=win;
    }
    catch(e)
    {
        return win;
    }
	return win;
};
var openDhtmlxWindow2=function(sId,sTitle,sSource,aParameters)
{
	var aDefaultParameters={"width":400,"height":400,"modal":"true","resizable":"no","left":400,"top":250};
	//var parameters = '';	
	for(mVal in aDefaultParameters)
		if(!array_key_exists(mVal,aParameters))
			alert('No existe: ' + mVal);
			//sparameters = sparameters + mVal + "= " + aDefaultParameters[mVal] + ",";
		else
			//sparameters = sparameters + val + "= " + aparameters[val] + ",";
			alert(mVal);
			alert(aParameters['left']);
	dhxWins= new dhtmlXWindows();
	dhxWins.enableAutoViewport(true);
	win = dhxWins.createWindow(sId, aParameters['left'], top, width, height);  
	win.setText(title); 		
	win.setModal(true);	
	if(type==1)
		win.attachHTMLString(html);
	else
		win.attachURL(html);
	return;
	require_once('../common/classes/dhtmlxsuite/dhtmlxWindows/codebase/dhtmlxcommon.js');
	require_once('../common/classes/dhtmlxsuite/dhtmlxWindows/codebase/dhtmlxwindows.js');
	/*
		var scriptNode = document.createElement('script');
	document.getElementsByTagName("head")[0].appendChild(scriptNode);
	scriptNode.language='javascript';
	scriptNode.src=jsFile; 
		var scriptNode = document.createElement('script');
	document.getElementsByTagName("head")[0].appendChild(scriptNode);
	scriptNode.language='javascript';
	scriptNode.src=jsFile; 
	*/
	//attachCSS('../common/classes/dhtmlxsuite/dhtmlxWindows/codebase/dhtmlxwindows.css');
	//attachCSS('../common/classes/dhtmlxsuite/dhtmlxWindows/codebase/skins/dhtmlxwindows_dhx_blue.css');
	//require_once('../../dhtmlxsuite/dhtmlxWindows/codebase/dhtmlxcommon.js');
	//require_once('../../dhtmlxsuite/dhtmlxWindows/codebase/dhtmlxwindows.js');
	/*
	if(typeof left=='undefined' || !is_numeric(left) )
		left=300;
	if(typeof top=='undefined' || !is_numeric(top) )
		top=100;
	if(typeof width=='undefined' || !is_numeric(width) )
		width=500;
	if(typeof height=='undefined' || !is_numeric(height) )
		height=500;	
	if(typeof center=='undefined' || !is_numeric(center) )
		center=1;
	if(typeof type=='undefined' || !is_numeric(type) )
		type=1;	
	*/	
	html=base64_decode(html);
	try
	{			
	switch(center)
	{
		case 1:
			win.centerOnScreen();
		break;
		case 2:
			win.center();
		break;
	}
	//win.setDimension(200);	
	//win.progressOn();
	//win.center();	
		}
	catch(e)
	{
		alert(e.description);
	}
};
var createDhtmlxGrid=function(id,columns,width,height,imgPath)
{
	var names='';
	var widths='';
	var types='';
	var aligns='';
	
	

	
	var div=getElement(id);
	if(typeof width=='undefined')
		var width='500px';
	if(typeof height=='undefined')
 		var height='500px';		
	if(is_string(columns))
	{
		columns=base64_decode(columns);	
		var columns=json_decode(columns);
	}
	if(typeof columns['names']=='undefined')
	{
		alert('No ha especificado columnas para la tabla');
		return false;		
	}
	var hlong=columns['names'].length;
	var x;
	if(imgPath==undefined)
		imgPath='../../dhtmlxsuite/dhtmlxgrid/codebase/imgs/';
	mygrid = new dhtmlXGridObject(id);
	mygrid.setImagePath(imgPath); 
	mygrid.setSkin('light');
	for(x=0;x<hlong;x++)
	{
		names+=columns['names'][x]+',';
		if(columns['widths']==undefined)
			widths+='80'+',';	
		else
			widths+=columns['widths'][x]+',';
		if(columns['aligns']==undefined)
			aligns+='center'+',';	
		else
			aligns+=columns['aligns'][x]+',';
		if(columns['types']==undefined)
			types+='ro'+',';	
		else
			types+=columns['types'][x]+',';	
	}	
	names=rtrim(names,',');
	widths=rtrim(widths,',');
	aligns=rtrim(aligns,',');
	types=rtrim(types,',');	
	mygrid.setHeader(names);
	mygrid.setInitWidths(widths);
	mygrid.setColAlign(aligns);
	mygrid.setColTypes(types);
	mygrid.enableAutoWidth(true,width,width);		
	mygrid.enableAutoHeight(false,height,height);
	mygrid.enableMultiselect(true);
	mygrid.init();	
};

var setGlobalImgPath=function(path)
{
	GlobalImgPath=path;	
	return;
};
var getIndex= function(id)
{	
	var pos=0;
	var index=null;		
	var pos=id.indexOf('[');		
	id=id.substr(pos+1,id.length);
	index=id.substr(0,id.length-1);
	return parseInt(index,10);		
};
var getArrayName = function(id)
{
	var arrayName=null;
	var pos=id.indexOf('[');
	arrayName=id.substr(0,pos);
	return arrayName;	
};
var nextId=function(id)
{
	var index =getIndex(id);
    var arrayName = getArrayName(id);
    var nextID = '';
    var indexString = '';
	index++;
	indexString =index.toString();		
	nextID=arrayName + '[' + indexString + ']';
	return nextID;
};
var changeElement = function(objeto,theEvent)
{	
	var evento = window.event || theEvent;			
	var keynum = (evento.keyCode) ?  evento.keyCode : ((evento.which) ? evento.which : false);
	var nextID = nextId(objeto.id);	   
	if(keynum==13  && objeto.value.length > 0 )
	{
		nextElement=document.getElementById(nextID)
		nextElement.focus();
	}
};
var validate_chk_value = function(obj,frm,falseValue)
{
	var mychk=getElement(obj);
	var orig_name=mychk.id;
	var myform=getElement(frm);
	var new_name=orig_name.substring(1,orig_name.length);	
	if(!getElement(new_name))
	{	
		var myhidden=document.createElement('input');
		myhidden.setAttribute('id',new_name);
		myhidden.setAttribute('name',new_name);			
		myhidden.setAttribute('type','hidden');
		myform.appendChild(myhidden);			
	}
	else
		var myhidden=getElement(new_name);
	if(mychk.checked==true)		
		addAttribute(myhidden,'value',mychk.value);	
	else	
		addAttribute(myhidden,'value',falseValue);	
		//myhidden.setAttribute('value',falseValue);
};
var selectAllText = function(obj)
{	
	var obj = getElement(obj);
	if(!obj)
		return false;	
	if(!obj.select)
		return false;
	try{
		obj.select();
	}
	catch(e)
	{
		return false;
	}
};
var lista_fila=function()
{
 	var frmElements=document.getElementById('form1').elements;
  	for(i=0; i<frmElements.length; i++)
  		document.write(frmElements[i].id + "\n");
};
var refresh_iframes = function(url,refresh_parent,close_child,btn_name)
{
	if(url.length==0)
		return false;
	try{
		var iFrames=window.opener.document.getElementsByTagName('iFrame');
		for(var x=0;x<iFrames.length;x++){
			var url=iFrames[x].src;
			var new_url='';
			var pos=url.indexOf('?');
			if(pos>0){
				for(var i=0;i<pos;i++)
					new_url=new_url + url[i];
				iFrames[x].src=new_url;
				}
			}
			for(var x=0;x<iFrames.length;x++){
				iFrames[x].src=iFrames[x].src + '?' + url;
			}
		if(btn_name.length>0)
		{	
			try{
				document.getElementById(btn_name).disabled=true;
			}
			catch(ex){
				alert('Given button does not exist!');
				return false;
			}
		}
		if(close_child)
		{
			try{
				window.opener.document.location=window.opener.document.location;
			}
			catch(ex){
				alert('Cannot refresh opener\'s window location!');
				return false;
			}
		}
		if(refresh_parent)		
		{
			try{
				window.close();
			}
			catch(ex){
				alert('Cannot close current window!');
				return false;
			}
		}
	}
	catch(ex){
		alert('There is no opener window!');
		return false;
	}
};
/*
var whichKeyPressed =function(e) {
	var code;
	if (!e) var e = window.event;
	if (e.keyCode) code = e.keyCode;
	else if (e.which) code = e.which;
	var character = String.fromCharCode(code);
	alert('Character was ' + character);
}
var whichMouseButton=function(e) {
	var rightclick;
	if (!e) var e = window.event;
	if (e.which) rightclick = (e.which == 3);
	else if (e.button) rightclick = (e.button == 2);
	alert('Rightclick: ' + rightclick); // true or false
}
*/


 var privacity = function(msg, e)
{
	
	document.oncontextmenu= function() {alert(msg);return false;};
	document.onmouseover=function() { window.status='';return true; };
	document.onmouseout=function() { window.status='';return true; };

	//document.onkeydown=function() { if(window.event.altKey) return cancelEvent(window.event); ;


	
	//window.onblur =function() { return cancelEvent(window.event);};
	//window.onfocus =function() { return cancelEvent(window.event);};
	
	
	



	
	
	//document.onblur =function() { return cancelEvent(event); };
	
	//document.onclick=function() { alert('hola');}
	/*	
	var mouseListener:Object = new Object();
	mouseListener.onMouseDown = function() {
	trace('pressed');
	};
	mouseListener.onMouseUp = function() {
    trace('released');
	};
	Mouse.addListener(mouseListener);
	*/
	/*
evt.behaviorCookie = 0
evt.behaviorPart = 0
evt.bookmarks = null
evt.boundElements = [object]
evt.button = 1
evt.cancelBubble = false
evt.clientX = 72
evt.clientY = 31
evt.contentOverflow = false
evt.ctrlKey = false
evt.ctrlLeft = false
evt.dataFld = empty
evt.dataTransfer = null
evt.fromElement = null
evt.keyCode = 0
evt.nextPage = empty
evt.offsetX = 57
evt.offsetY = 11
evt.propertyName = empty
evt.qualifier = empty
evt.reason = 0
evt.recordset = null
evt.repeat = false
evt.returnValue = undefined
evt.screenX = 379
evt.screenY = 245
evt.shiftKey = false
evt.shiftLeft = false
evt.srcElement = [object]
evt.srcFilter = null
evt.srcUrn = empty
evt.toElement = null
evt.type = 'mousedown'
evt.wheelDelta = 0
evt.x = 72
evt.y = 31
evt.altKey = false
evt.bubbles = true
evt.button = 0
evt.cancelBubble = false
evt.cancelable = true
evt.clientX = 59
evt.clientY = 18
evt.ctrlKey = false
evt.currentTarget = [object HTMLInputElement]
evt.detail = 1
evt.eventPhase = 2
evt.explicitOriginalTarget = [object HTMLInputElement]
evt.getPreventDefault = function getPreventDefault() { [native code] }
evt.initEvent = function initEvent() { [native code] }
evt.initMouseEvent = function initMouseEvent() { [native code] }
evt.initUIEvent = function initUIEvent() { [native code] }
evt.isChar = false
evt.isTrusted = true
evt.layerX = 60
evt.layerY = 19
evt.metaKey = false
evt.originalTarget = [object HTMLInputElement]
evt.pageX = 59
evt.pageY = 18
evt.preventBubble = function preventBubble() { [native code] }
evt.preventCapture = function preventCapture() { [native code] }
evt.preventDefault = function preventDefault() { [native code] }
evt.rangeOffset = 7
evt.rangeParent = [object Text]
evt.relatedTarget = null
evt.screenX = 468
evt.screenY = 209
evt.shiftKey = false
evt.stopPropagation = function stopPropagation() { [native code] }
evt.target = [object HTMLInputElement]
evt.timeStamp = 21599218
evt.type = 'click'
evt.view = [object Window]
evt.which = 1
...and for all browsers:

alert("HTML tag = " + obj.tagName
"\nHTML ID value = " + obj.id
"\nHTML NAME value = " + obj.name
"\nHTML CLASS value = " + obj.className +
((obj.tagName=="INPUT" ||obj.tagName=="SELECT" || obj.tagName=="TEXTAREA") ?
"\nFORM Element type = " + obj.type : ""));
*/	
};
var count_limited_chars=function(source_control,counter_control,maxlimit) 
{
	var counter_control=document.getElementById(counter_control);	
	if (source_control.value.length > maxlimit) // if too long...trim it!
	{
		source_control.value = source_control.value.substring(0, maxlimit);		        
        alert('El texto ingresado se limitará a ' + maxlimit + ' caracteres');
        setError(source_control,'Ha superado el número máximo de caracteres permitidos!');
	}
	else
    {
		counter_control.innerHTML = maxlimit - source_control.value.length;
        setError(source_control,'',0);
    }    
};
 var count_chars = function(source_control,counter_control)
{
	//var counter_control=document.getElementById(counter_control);
    var counter_control=getElement(counter_control);    
	counter_control.innerHTML = source_control.value.length;
};
var count_words = function(source_control,counter_control)
{
	//var counter_control=document.getElementById(counter_control);
    var counter_control=getElement(counter_control);
	var control_value=source_control.value;
	var a=control_value.replace(/\s/g,' ');
	var words=a.split(' ');
	var current_words=0;
	for (x=0; x<words.length; x++)
		if (words[x].length > 0) 
			current_words++;
	counter_control.innerHTML=current_words;	
};
var count_limited_words = function(source_control,counter_control,maxlimit)
{
	//var counter_control=document.getElementById(counter_control);
    var counter_control=getElement(counter_control);    
	var control_value=source_control.value;
	var current_words = 0;
	var a=control_value.replace(/\s/g,' ');
	var words=a.split(' ');
	var x=0;
	var extra_length=0;
	for (x=0; x<words.length; x++)
		if (words[x].length > 0) 
			current_words++;
	if(current_words>maxlimit)
	{
		for (x=maxlimit; x<words.length; x++) 
			extra_length=words[x].length+extra_length+1;		
		source_control.value = source_control.value.substring(0,source_control.value.length-extra_length);
		alert('Ha superado el maximo numero de palabras permitidas!');
	}	
	else
		counter_control.innerHTML=maxlimit-current_words;
}; 
var postUrl=function(url,data) {
  var myForm = document.createElement("form");
  myForm.method="post" ;
  myForm.action = url ;
  for (var k in data) {
    var myInput = document.createElement("input") ;
    myInput.setAttribute("name", k) ;
    myInput.setAttribute("value", data[k]);
    myForm.appendChild(myInput) ;
  }
  document.body.appendChild(myForm) ;
  myForm.submit() ;
  document.body.removeChild(myForm) ;
}

var open_calendar = function(server_address,control_id,language,dateformat,firstDayOfWeek,preselectedDate,startMonth,startYear)
{
	var ControlId=null;
	var url = server_address + "/common/classes/datepicker/includes/datepicker.php?preselectedDate=" + preselectedDate + "&month=" + startMonth + "&year=" + startYear + "&controlName=" + control_id + "&dateFormat=" + dateformat + "&firstDayOfWeek=" + firstDayOfWeek + "&clearDateButton=1&language=" + language + "&template=default";
	var parameters= "width=180,height=210,scrollbars=no,toolbar=no,menubar=no,location=no,alwaysraised=yes,modal=yes,resizable=no,screenX=200,screenY=200,left=400,top=250,titlebar=no,status=no";
	//ControlId=getElement(control_id);
	openWindow("datepicker",url,parameters);
};
var get_date= function()
{
	day = new Date();
	id = day.getTime();
};



var getEvents=function(obj,print)
{
	var eventos=[];
	var objEventName;
	var objEventValue;
	obj	= getElement(obj);
	if(!obj)
		return false;
	if(!existsAttribute(obj,'attributes'))
		return false;
	var numAttrib= obj.attributes.length;
	if(!numAttrib)
		return false;
	var eventId	= 0;
	var x		= 0;
	var patron	= /^(on|e_on)[a-zA-Z0-9]+$/;
	for(e in obj)
	{		
		if(!e)
			continue;					
		if(window[e])
			continue;
            
            /*
		if(!patron.test(e))
			continue;
            */
		if(!obj[e])		
			continue;			
		eventos[x]={'event':e,'func':obj[e]};		
		x++;	
	}
	if(!count(eventos))
		return false;	
	if(print)
	{			
		for(evento in eventos)
		{
			if(!eventos.hasOwnProperty)
				document.write(evento+'=>' + eventos[evento] + '<br/>');
			if(eventos.hasOwnProperty(evento))	
				document.write(evento+'=>' + eventos[evento] + '<br/>');
		}	
		return true;			
	}
	return eventos;		
}.defaults('',false);
var showElement=function(obj)
{
	obj=getElement(obj);
	if(!obj)
		return false;		
	removeClass(obj,sClassNoDisplay);
	replaceStyle(obj,'display','inline');
	//replaceStyle(obj,'visibility','visible');
}
var hideElement=function(obj,tipo,timeout)
{
	obj=getElement(obj);
	if(!obj)
		return false;	
    switch(tipo)
    {    
        case 1:
            if(timeout)   
            {         
	           fadeElement(obj,timeout);   
               //return;            
            }
            else
               addClass(obj,sClassNoDisplay);	  
                        
        break;
        case 2:
            if(timeout)
	           fadeElement(obj,timeout);
            else
               replaceStyle(obj,'display','none');
        break;
        default:
            if(timeout)
	           fadeElement(obj,timeout);
            else
            {   
            addClass(obj,sClassNoDisplay);
            replaceStyle(obj,'display','none');
         }
        break;
            
    }
    
	//replaceStyle(obj,'visibility','hidden');	
}

var setClass=function(obj,sClass)
{
    obj=getElement(obj);
	if(!obj)	
		return true;
	if(!existsAttribute(obj,'className'))
		return false;	
    obj.className = sClass;
    return true;
}


var addClass=function(obj,sClass)
{
	obj=getElement(obj);
	if(!obj)	
		return true;
	if(!existsAttribute(obj,'className'))
		return false;	
	if(!obj.className)
	{
		obj.className = sClass;
		return true;
	}			
	var classes=obj.className;	
	var patron = new RegExp("(" + sClass + ")+");	
	if(patron.test(classes))
		return false;	
	if(classes.length>0)	
		obj.className += ' ' + sClass;
	else
		obj.className = sClass;	
	return true;
	
}
var replaceClass=function(obj,sOldClass,sNewClass)
{
	obj=getElement(obj);
	if(!obj)	
		return false;
	if(!existsAttribute(obj,'className'))
		return false;	
	if(!obj.className)
	{
		addClass(obj,sNewClass);
		return true;		
	}				
	var classes=obj.className;    
	var patron = new RegExp("(" + sOldClass + ")+");
    
    //alert("Reemplazar _" + sOldClass + '_ por _' + sNewClass + '_' );
    
	if(!patron.test(classes))	
		return addClass(obj,sNewClass);	
	else
	{
	   
      // alert('se encontro la clase: ' + sOldClass);
		classes = classes.replace(patron,sNewClass);
		obj.className = classes;
	}	
	return true;
}
var existClass=function(obj,sClass)
{
    //return true;
    
	obj=getElement(obj);
	if(!obj)	
		return false;

	if(!existsAttribute(obj,'className'))
		return false;	

	if(!obj.className)
		return false;		
	
	var sClassObj = obj.className; 
	var patron = new RegExp("(" + sClass + ")+");
	if(!patron.test(sClassObj))	
		return false;	
	else
		return true;

        
}
var removeClasses=function(obj)
{
	obj=getElement(obj);
	if(!obj)
		return false;	
	if(!existsAttribute(obj,'className'))		
		return false;	
	if(!obj.className)
		return false;						
	obj.className='';
	return true;	
}   
var removeClass =function(obj,sClass) 
{
	obj=getElement(obj);
	if(!obj)
		return false;	
        
     	
	if(!existsAttribute(obj,'className'))		
		return false;
	if(!obj.className)
		return false;
	var classes=obj.className;
	var reg = "((\s)?(" + sClass + ")+){1}|((" + sClass + ")+(\s)?){1}";
	var patron = new RegExp(reg,'g');	
	classes = classes.replace(patron,'');
	if(classes.trim)
		classes=classes.trim();
	obj.className = classes;
	return true;
}
var addStyle=function(obj,sStyle,mValue)
{
	obj=getElement(obj);
	if(!obj)
		return false;
	if(!sStyle)
	{
		obj.style.cssText=mValue;
		return true;
	}					
	if(!existsAttribute(obj.style,sStyle))
		return false;
	if(!obj.style[sStyle])
		obj.style[sStyle]=mValue;
	else
		obj.style[sStyle]+=mValue;	
	return true;	
}
var replaceStyle=function(obj,sStyle,mValue)
{
	obj=getElement(obj);
	if(!obj)
		return false;
	if(!sStyle)
	{
		obj.style.cssText=mValue;
		return true;
	}	
	if(!existsAttribute(obj.style,sStyle))
		return false;		
	obj.style[sStyle]=mValue;
	return true;	
}
var removeStyle=function(obj,sStyle)
{
	obj=getElement(obj);
	if(!obj)
		return false;	
	if(existsAttribute(obj.style,sStyle))
	{		
		obj.style.background='';			
	}

}
var removeStyles=function(obj)
{
	obj=getElement(obj);
	if(!obj)
		return false;
	if(obj.style)		
		delAttribute(obj,'style');
}

var existsAttribute=function(obj,attrib)
{  	
    obj=getElement(obj);
	if(!obj)
		return false;
	if(!attrib)
		return false;
    if(attrib in obj)
        return true;
    else
        if(eval( "typeof obj." + attrib + "!='undefined'"))
            return true; 
            
                
    if(obj.hasAttribute)
    {  
        if(obj.hasAttribute(attrib))  
            return true;
    }    
    else
        if(obj.getAttribute)
        {
            if(obj.getAttribute(attrib)!=null && obj.getAttribute(attrib)!=undefined )
                return true;
         }   
        else
            if(obj[attrib])
                return true;            
                
    return false;         
}

var readAttribute=function(obj,attrib)
{	
    obj=getElement(obj);
    if(!obj)
		return false;
	if(!existsAttribute(obj,attrib))
    {
        //alert('No existe el atributo');
		return false;
    }    
	try
	{	   
		if(!obj.getAttribute)
        {
            
            //alert('obj.attribute');
			return eval(obj + "." + attrib);
        }    			
		else
        {
            //alert(attrib + '=>' + obj.getAttribute(attrib));
			return obj.getAttribute(attrib);
        }    			
	}
	catch(e)
	{
		return false;
	}
}

var addAttribute = function(obj,attrib,value)
{
	obj=getElement(obj);
	if(!obj)
		return false;	
	try
	{
		if(!obj.setAttribute)
		{
			eval(obj + "." + attrib + "=" + value);	
			return true;		
		}	
		else
		{
			obj.setAttribute(attrib,value);
			return true;		
		}
	}
	catch(e)
	{
		return false;
	}
};

var delAttribute=function(obj,attrib)
{
	obj=getElement(obj);
	if(!obj)
		return false;
        
        
        	
	if(!existsAttribute(obj,attrib))
		return false;		
	try
	{
    	if(!obj.removeAttribute)
		{			
			eval(obj + "." + attrib + "='';");
			return true;		
		}	
		else
		{			  
			
            obj.removeAttribute(attrib);            	
			     return true;            		
		}	
	}
	catch(e)
	{
	   
		return false;
	}	
}
 var isObject=function(mixed)
 {  
    
    if(/*mixed.constructor !== Object ||*/ typeof mixed !== 'object')
	   return false;  
    return true;  
 }
 var isString=function(mixed)
 {
    if(/*mixed.contructor !== String ||*/ typeof mixed !== 'string')
        return false;
    return true;
    
 }
 
var getElement= function(obj)
{	
   
    if(!obj)
		return false;       
    if(isObject(obj))
        return obj;
        
    
    if(!document.getElementById)
		return false;
 	
    
    if(isString(obj))
	{
		var id	= obj;
		obj		= document.getElementById(obj);
        
	}
    //var realId=readAttribute1(obj,'id');
    /*if(!realId)
		return false;
        	if(obj.id!=id)
	{			
		if(!document.all[id])					
			return false;
		obj=false;	
		for(var x=1;x<document.all[id].length;x++)
		{			
			if(document.all[id][x].id == id)
			{
				obj=document.all[id][x];
				break;
			}
		}
	}
	if(typeof obj == 'object')
		return obj;
	return false;
        */
    return obj; 
};


var collapseAll=function(obj)
{
    
    var hijos=getChildren(obj,'TABLE');
    var longitud=hijos.length;
    var item;
    var x=0;
    while(x<longitud)
    {
       replaceClass(hijos[x++].parentNode.parentNode,'childRowVisible','childRowHidden');
      
    }
    
    
    
}
var expandAll=function(obj)
{
    var hijos=getChildren(obj,'TABLE');
    var longitud=hijos.length;
    var item;
    var x=0;
    while(x<longitud)
    {
        replaceClass(hijos[x++],'childRowHidden','childRowVisible');
    }  
}

var showChart =function(obj)
{
    if(obj.parentNode.parentNode.parentNode.nextSibling.nextSibling.lastChild.tagName=='TR')
        var hermano=obj.parentNode.parentNode.parentNode.nextSibling.nextSibling.lastChild;
    else
       var hermano=obj.parentNode.parentNode.parentNode.nextSibling.nextSibling.nextSibling.nextSibling.lastChild.previousSibling; 
       
       
       
    if(!existsAttribute(hermano,'child'))
        return false;
    if(existClass(hermano,'childRowHidden'))
     {
        replaceClass(hermano,'childRowHidden','childRowVisible');
        //alert(hermano.firstChild.nextSibling);
        //expandAll(hermano.firstChild.nextSibling);
     }   
    else
    {
        replaceClass(hermano,'childRowVisible','childRowHidden');
        //collapseAll(hermano.firstChild.nextSibling);
        
        
    }
    
}





var showTable =function(obj)
{
    
    var padre=obj.parentNode.parentNode;
    
    
    if(padre.nextSibling.tagName!='TR')
        var hermano=padre.nextSibling.nextSibling;
    else
        var hermano=padre.nextSibling;
    
    if(!existsAttribute(hermano,'child'))
        return false;
    
    if(existClass(hermano,'childRowHidden'))
     {
        replaceClass(hermano,'childRowHidden','childRowVisible');
        //alert(hermano.firstChild.nextSibling);
        expandAll(hermano.firstChild.nextSibling);
     }   
    else
    {
        replaceClass(hermano,'childRowVisible','childRowHidden');
        collapseAll(hermano.firstChild.nextSibling);
        
        
    }
  
     
}

var autoCreateElement=function(obj,tag)
{
	
	if(!window.document.createElement)
		return false;
	if(typeof obj=='string')
		var id=obj;			
	obj=getElement(obj);
	if(obj)
		return obj;		
	var obj=document.createElement(tag);	
	addAttribute(obj,'id',id);	
	return obj;	
};
var deleteElement=function(obj,parentObj,useParent){
	
	obj=getElement(obj);
	if(!obj)
		return false;	
	if(useParent)
		parentObj=obj.parentNode;
	else
		parentObj=getElement(parentObj);
	
	if(!parentObj)
		return false;				
	parentObj.removeChild(obj);		
}.defaults(null,'',true);

var getFunctionName=function(func)
{	
	try
	{
		func=func.toString();
	}
	catch(err)
	{
		func=new String(func);
		
	}
		
	for(e in window)
	{
		try
		{			
			if(window[e]==func)				
				return	e;
		}
		catch(err)
		{			
			continue;	
		}
	}
	return func;
};
var addEvent= function(obj,eventName,func,spread) 
{
	obj=getElement(obj);
	if(!obj)
		return false;
	var funcName;			
	patronTest 	= /^on[a-zA-Z]+$/;
	patronRep	= /^(on)/;	
	if(patronTest.test(eventName))
		eventName=eventName.replace(patronRep,'');			
	if(typeof func=='string')
	{
		if(is_callable(func,false))
		{
			var funcName=func;				
			func=window[func];
		}
		else
			if(typeof func!='function')
				eval("func=function(){" + func + "}");
	}
	else
	{
		funcName=getFunctionName(func);
		funcName=(funcName ? funcName : func);
	}				
	if(typeof func!='function')
		return false;	
		
	if(obj.addEventListener)  
    	obj.addEventListener(eventName,func,false);   
    else
    	if(obj.attachEvent) 
			var r = obj.attachEvent("on"+eventName,func);
		else
			obj['on' + eventName] = func;			
	
	if(!aEventCounter[obj.id + '_e_on' + eventName])
		var number=1;
	else		
		var number=aEventCounter[obj.id + '_e_on' + eventName]+1;	
    aEventCounter[obj.id + '_e_on' + eventName]=number;    	
	obj['e_on' + eventName + number]=func;	
	return true;
	
}.defaults(null,'',null,true);
var removeElement=function(obj)
{
    
    var obj=getElement(obj);
    
	if(!obj)
		return false;        
    var parentElement=obj.parentNode;

    parentElement.removeChild(obj);
    return true;
}
var removeEvent=function(obj,eventName,funcName)
{
	var obj=getElement(obj);
	if(!obj)
		return false;
	//var funcName;	
	var patronTest 	= /^on[a-zA-Z]+$/;
	var patronRep	= /^(on)/;	
	var x			= 0;
	var event		= '';
	var ok			= 0;
	var func;
	
	if(patronTest.test(eventName))
		eventName=eventName.replace(patronRep,'');	
	var eventos	= getEvents(obj);
	if(count(eventos)>0)
	{			
		for(x=eventos.length-1;x>=0;x--)
		{	
			if(eventos.indexOf(eventName))		
			{	
				func		=eventos[x]['func'];
				event		=eventos[x]['event'];
				if(funcName)
				{
					if(eventos[x]['func']==funcName)
						ok=1;					
				}
				else
					if(event != ('on' + eventName) && event != (eventName))
					{
						
						ok=1;
					}
				if(ok==1)
				{				
					delete obj[event];	
					aEventCounter[obj.id + '_e_on' + eventName]--;			
					break;
				}
			}
		}	
	}
	
	if(!ok)
	{
	   if(obj['on' + eventName])
		{				
			obj['on' + eventName]='';
			return true;
		}	
		return true;		
	}
	if(!func)
		return false;
	
	if(obj.removeEventListener) 
		obj.removeEventListener(eventName,eval(func),false);
    else
    	if(obj.detachEvent) 
			var r=obj.detachEvent("on"+eventName,eval(func));
		else
			delAttribute(obj,"on" + eventName);		
	return false;
	
}
var insertBefore=function(newChild, refChild){
    var refChild=getElement(refChild);
    	if(typeof newChild=='string')
	{
		var newChild=getElement(newChild);		
		if(newChild)
			return false;	
	}	
	if(!refChild || !newChild)
		return false;
    refChild.parentNode.insertBefore(newChild,refChild);
}
var insertAfter=function(newChild, refChild) { 
	
    
    
	var refChild=getElement(refChild);
	if(typeof newChild=='string')
	{
		var newChild=getElement(newChild);		
		if(newChild)
			return false;	
	}	
    
   
	if(!refChild || !newChild)
		return false;		
 	refChild.parentNode.insertBefore(newChild,refChild.nextSibling);
	 
} 

var openDialog= function(id,url,aparameters)
{
	var sparameters='';	
	aDefaultParameters={"width":180,"height":210,"scrollbars":"auto","toolbar":"no","menubar":"no","location":"no","alwaysraised":"yes","modal":"yes","resizable":"no","screenX":200,"screenY":200,"left":400,"top":250,"titlebar":"no","status":"no"};
	for(val in aDefaultParameters)
		if(typeof aparameters[val] == 'undefined')
			sparameters = sparameters + val + "= " + aDefaultParameters[val] + ",";
		else
			sparameters = sparameters + val + "= " + aparameters[val] + ",";
	var parameters=sparameters.substring(0,sparameters.length-1);
	var new_window = window.showModalDialog(url,id,parameters); 
	if (new_window.focus) 
	{new_window.focus();} return false;  
};

var openDhtmlxCalendar=function(sId,mValue,mParameters)
{
    
    var aDefaultParameters={"bEditMonth":true,"bEditYear":true};
	//var parameters = '';	
	for(mVal in aDefaultParameters)
    
		if(!array_key_exists(mVal,aParameters))
			alert('No existe: ' + mVal);
			//sparameters = sparameters + mVal + "= " + aDefaultParameters[mVal] + ",";
		else
			//sparameters = sparameters + val + "= " + aparameters[val] + ",";
			alert(mVal);
			alert(aParameters['left']);
            
     var cal = new dhtmlxCalendarObject(sId,false,{isMonthEditable: bEditMonth, isYearEditable: bEditYear}); 
     cal.loadUserLanguage(sLang);
     cal.setSkin(sSkin);
     cal.setDateFormat(sFormat); 
     cal.setYearsRange(nYearFrom, nYearTo);  
     cal.setDate(mValue); 
     cal.draw();    
}

var openWindow= function(sId,mSource,mParameters)
{    
    
	var sParameters='';	
	var nType=0;	
	var aDefaultParameters=
	{
		"center": "yes",
		"width":250,
		"height":300,
		"scrollbars":"yes",
		"toolbar":"no",
		"menubar":"no",
		"location":"no",
		"alwaysraised":"yes",
		"modal":"yes",
		"resizable":"no",
		"screenX":200,
		"screenY":200,
		"left":100,
		"top":50,
		"titlebar":"no",
		"status":"no",
		"fullscreen":"no"
	};
	if(aDefaultParameters['center']=='yes')
	{
		aDefaultParameters['top']=(screen.height/2)-((aDefaultParameters['height'])/2);
		aDefaultParameters['left']=(screen.width/2)-((aDefaultParameters['width'])/2);
	}
	if(typeof mParameters=='undefined')
		nType=0;
	else
	{
		if(is_string(mParameters))
		{
			if(mParameters.length>0)
				nType=1;
		}
		else
		{
			if(is_array(mParameters))
			{
				if(array_key_exists('center',mParameters))
					if(mParameters['center']=='yes')
					{
						if(!array_key_exists('height',mParameters))
							mParameters['height']=aDefaultParameters['height'];
						if(!array_key_exists('width',mParameters))	
							mParameters['width']=aDefaultParameters['width'];						
						mParameters['top']=(screen.height/2)-((mParameters['height'])/2);
						mParameters['left']=(screen.width/2)-((mParameters['width'])/2);
					}
				nType=2;
			}	
		}			
	}	
	switch(nType)
	{
		case 0:
			for(mVal in aDefaultParameters)					
				sParameters = sParameters + mVal + "= " + aDefaultParameters[mVal] + ",";
			sParameters=sParameters.substring(0,sParameters.length-1);				
		break;	
		case 1: 
			sParameters=mParameters;		
		break;
		case 2: 
			for(mVal in aDefaultParameters)	
				if(!array_key_exists(mVal,mParameters))
					sParameters = sParameters + mVal + "= " + aDefaultParameters[mVal] + ",";
				else
					sParameters = sParameters + mVal + "= " + mParameters[mVal] + ",";
			sParameters=sParameters.substring(0,sParameters.length-1);		
		break;
	}
	if(!is_string(mSource))
		return false;
	var new_window = window.open(mSource,sId,sParameters);
	if(new_window) 
		if (new_window.focus) 
			new_window.focus();
	return false;
};
var createCallFunction=function(name)
{
	try
	{
		eval(name);
	}
	catch(e)
	{
		setMsg('Error while trying to call function ' + name,'status','visible');
	}	
	return;
};
var centerObject= function(obj)
{
	var obj=getElement(obj);
	if(obj)
	{
		obj.style.position='absolute';
  		obj.style.top=0;
   		obj.style.right=0;
    	obj.style.margin=0;
    	obj.style.padding=0;
    	obj.style.paddingRight='25px'; 	
  	}
	return;
};
var setMsg=function(msg,cls,visibility)
{
    if(!SHOWPROGRESS)
        return;
    
	var div_status=getElement('divStatus');
	var img_status=getElement('imgStatus');
	var text_status=getElement('textStatus');
	var divChk=div_status;
	var imgChk=img_status;
	var textChk=text_status;
	if(!divChk)
		var div_status=autoCreateElement('divStatus','div',false);	
	if(!imgChk)
		var img_status=autoCreateElement('imgStatus','img',false);	
	if(!textChk)
		var text_status=autoCreateElement('textStatus','span',false);
	if(GlobalImgPath==undefined || GlobalImgPath=='')
		GlobalImgPath='../common/classes/ludwig/img/';
	img_status.src=GlobalImgPath + 'ajax-loader.gif';	
	text_status.innerHTML=msg;
	text_status.style.fontSize='9px';
	text_status.style.fontFamily='sans-serif';	
	//div_status.style.backgroundColor='#FFFFAA';
	div_status.style.width='100px';
	div_status.ClassName=cls;
	img_status.ClassName=cls;
	text_status.ClassName=cls;
	//div_status.style.left='-50px';
	div_status.style.display=visibility;
	//div_status.style.top='0%';
	//text_status.style.textDecoration='blink';	
	if(!imgChk)
		div_status.appendChild(img_status);
	if(!textChk)
		div_status.appendChild(text_status);
	if(!divChk)
		document.body.appendChild(div_status);
	//centerObject(div_status);
	//addAttribute(text_status,'style.color','#B4B4B4');
	//addAttribute(div_status,'style.display','block');
	//addAttribute(div_status,'style.width','350px');
};	
function Pause(duration, busy)
{
      this.duration= duration * 1000;
      this.busywork = null; // function to call while waiting.
      this.runner = 0;
      if (arguments.length == 2) {
         this.busywork = busy;
      }
      this.pause(this.duration);
   } // Pause class
function pause_l(millis)
{
	var date = new Date();
	var curDate = null;
	do 
	{ 
		curDate = new Date(); 
	}
	while(curDate-date < millis);
};
var agrega_fila = function(filterName,hiddenName,fieldNames,fieldOrigNames,conditions)
	{
		var vId=document.getElementById(hiddenName);
		var vNewId=parseInt(vId.value)+1;
		var vNewRowId='r' + vNewId;
		vId.value=vNewId;		
		var vNewFieldId='field' + vNewId;
		var vNewConditionId='condition' + vNewId;
		var vNewCriteriaId='criteria' + vNewId;
		var vNewSearchId='search' + vNewId;
		var vNewRemoveId='remove' + vNewId;			
		var filter_tbody =document.getElementById(filterName);		
		var new_row=document.createElement('tr');
		var new_col=document.createElement('td');
		var new_div = document.createElement('div');	
		//var new_text=document.createTextNode(vNewRowId);
		var new_field = document.createElement('select');
		var new_condition = document.createElement('select');
		var new_criteria = document.createElement('select');
		var new_search= document.createElement('input');
		var new_remove = document.createElement('input');	
		new_row.setAttribute('id',vNewRowId);
		new_row.setAttribute('name',vNewRowId);
		new_field.setAttribute('id',vNewFieldId);
		new_field.setAttribute('name',vNewFieldId);
		new_condition.setAttribute('id',vNewConditionId);
		new_condition.setAttribute('name',vNewConditionId);
		new_criteria.setAttribute('id',vNewCriteriaId);
		new_criteria.setAttribute('name',vNewCriteriaId);
		new_search.setAttribute('id',vNewSearchId);
		new_search.setAttribute('name',vNewSearchId);
		new_search.setAttribute('type','textbox');
		new_remove.setAttribute('id',vNewRemoveId);		
		new_remove.setAttribute('name',vNewRemoveId);	
		new_remove.setAttribute('value','-');
		new_remove.setAttribute('type','button');
		new_remove.setAttribute('onClick','xajax_removeFilter("' + vNewRowId + '");return false;');
		var new_opt= document.createElement('option');
		new_opt.value='';
		new_opt.innerHTML='--campos--';
		new_field.appendChild(new_opt);
		var new_opt= document.createElement('option');
		new_opt.value='AND';
		new_opt.innerHTML='Y';
		new_criteria.appendChild(new_opt);
		var new_opt= document.createElement('option');
		new_opt.value='OR';
		new_opt.innerHTML='O';
		new_criteria.appendChild(new_opt);
		var index=0;
		for(h in fieldNames)
		{
			var new_opt= document.createElement('option');
			new_opt.value=fieldOrigNames[index];
			new_opt.innerHTML=fieldNames[index];
			new_field.appendChild(new_opt);
			index++;
		}
		for(h in conditions)
		{
			var new_opt= document.createElement('option');
			new_opt.value=h;
			new_opt.innerHTML=conditions[h];
			new_condition.appendChild(new_opt);
		}
		new_div.appendChild(new_field);
		new_div.appendChild(new_condition);
		new_div.appendChild(new_search);
		new_div.appendChild(new_criteria);
		//new_div.appendChild(new_text);
		new_div.appendChild(new_remove);
		new_col.appendChild(new_div);
		new_row.appendChild(new_col);
		filter_tbody.appendChild(new_row);
	return;
	}
	
	
var errorMsg=function(id,group,insertBr)
{
	var obj=getElement(id);
	if(!obj)
		return false;	
	if(!group)
		var span=autoCreateElement("error_msg_" + id,'span',true);
	else	
		var span=autoCreateElement("error_msg_" + group,'span',true);
	
	if(!span)
		return false;
	
	var br=document.createElement('br');	
		
	addAttribute(span,"style","display:none");
	if(!group)
	{
		if(getElement('helper_'+id))
			insertAfter(br,'helper_'+id);
		else
			insertAfter(br,id);

		insertAfter(span,br);
	}	
	else
	{	
		var lastObj=getLastSibling(id,obj.type,'group_elements',group);
		insertAfter(br,lastObj);
		insertAfter(span,br);	
	}	
}.defaults('',false);		
		
function loadMap() {
	map = new GMap2(document.getElementById("map"));
	map.addControl(new GLargeMapControl());
	map.addControl(new GMapTypeControl());
	map.setCenter(new GLatLng( -77.02955867503071, -11.5576171875), 5);
	map.setMapType(G_NORMAL_MAP);
	icon0 = new GIcon();
	icon0.image = "http://www.google.com/mapfiles/marker.png";
	icon0.shadow = "http://www.google.com/mapfiles/shadow50.png";
	icon0.iconSize = new GSize(20, 34);
	icon0.shadowSize = new GSize(37, 34);
	icon0.iconAnchor = new GPoint(9, 34);
	icon0.infoWindowAnchor = new GPoint(9, 2);
	icon0.infoShadowAnchor = new GPoint(18, 25);
    
    
};
function addPoints() {
	newpoints[0] = new Array(-77.0304718, -12.04678726   , icon0, 'Lima', 'LIMA'); 
	for(var i = 0; i < newpoints.length; i++) {
		var point = new GPoint(newpoints[i][1],newpoints[i][0]);
		var popuphtml = newpoints[i][4] ;
		var marker = createMarker(point,newpoints[i][2],popuphtml);
		map.addOverlay(marker);
	}
};
function createMarker(point, icon, popuphtml) {
	var popuphtml = "<div id=\"popup\">" + popuphtml + "<\/div>";
	var marker = new GMarker(point, icon);
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(popuphtml);
	});
	return marker;
};
var isArray =function(obj)
{
	if(typeof obj=='object')
		if(obj instanceof Array)
			return true;
		else
			return false;	
};
var checkFileSize=function(objFile,maxSize,errormsg,showMsg) 
{
	if(typeof showMsg == 'undefined')
		var showMsg=1;
	if(typeof errormsg == 'undefined')
		var errormsg='El archivo es muy grande';
	if(typeof maxSize == 'undefined')
		var maxSize=0;	
	//var objFile=obj;
	//alert(obj);
	/*
	if(typeof obj!='object')	
	else
		var obj=objFile;
			*/
	if(typeof objFile !='object')
		var objFile=getElement(objFile);	
	if(objFile.files)
	{
		var fileSize=objFile.files.item(0).fileSize;
		if(maxSize>0)
			if(fileSize>maxSize)
				if(showMsg==1)
				{
					alert(errormsg);
					objFile.value='';
				}
				else	
					return false;	
		return fileSize;
	}	
	else
	{
		if(objFile.value)
		{
			try
			{
				var oas = new ActiveXObject("Scripting.FileSystemObject");
				var e = oas.getFile(objFile.value);
				var f = e.size;
				if(f>maxSize)
					if(showMsg==1)
					{
						alert(errormsg);
						objFile.value='';
					}
					else	
						return false;
				return f;			
			}
			catch(e)
			{
				alert("Asegurese que el tamaño de los archivos no supere el maximo permitido \r\n de lo contrario el servidor mostrara un error!");
			}
			return true;
		}
	}
	return false;
};
var setGenericErrorMsg=function(mElement, sMsje, sClass)
{
    
	var sIdElement = '';
	var bCreated	=0; 
	
	if(typeof mElement =='string')
		sIdElement = mElement;
	else
	{
		mElement	= getElement(mElement);
		sIdElement  = mElement.id;
	}
    
    				
	var sIdContenedorError 	= 'error_msg_'+sIdElement;
	var oContenedorError	= getElement(sIdContenedorError);	
	if(!oContenedorError)
	{
		oContenedorError	= document.createElement('SPAN');
		oContenedorError.id	= sIdContenedorError;		
		oBR					= document.createElement('BR');					
		bCreated=1;
	}
    
    	
	if(oContenedorError)
	{			
		removeClasses(oContenedorError);
		oContenedorError.innerHTML=sMsje;
		
        
        
		if(sClass)
		{			
			//addClass(oContenedorError,'mensaje');
			addClass(oContenedorError,sClass);			
			showElement(oContenedorError);			
			//delAttribute(oContenedorError,'class');			
		}        
		else
		{
			hideElement(oContenedorError);			
		}	
		if(bCreated)
		{			
			
			mElement.parentNode.appendChild(oBR);
			mElement.parentNode.appendChild(oContenedorError);
		}		
		
        
	}
    
}.defaults(null,'','');
var setError=function(obj,msg,tipo)
{
    obj=getElement(obj);
    if(!obj)
        return false;
	if(tipo==1)
	{	
		addClass(obj,'fieldError');		
        setGenericErrorMsg(obj, msg,sClassSimpleError);
		//if(obj.focus)
		//	obj.focus();        
        aErrors[obj.id]=1;
        
       // alert(obj.id);
	}	
	else
	{	
		setGenericErrorMsg(obj,'',false);
		removeClass(obj,'fieldError');	
		//aErrores.remove(obj.id);
		array_remove_key(aErrors,obj.id); 
	}
}.defaults(null,'',1);
var setWarning=function(obj,msg,tipo)
{
	if(tipo==1)
	{	
		addClass(obj,'fieldWarning');
		setGenericErrorMsg(obj,msg,sClassSimpleWarning);
		if(obj.focus)
			obj.focus();
		aWarnings[obj.id]=1;	
	}	
	else
	{	
		setGenericErrorMsg(obj,'',false);
		removeClass(obj,'fieldWarning');
		array_remove_key(aWarnings,obj.id); 
	}
				
		
		
}.defaults(null,'',1);
var validateByType=function(sType, oElement)
{    
    oElement=getElement(oElement);   
    if(!oElement)
        return false;     
	var sPatron 	= '';
	var sValue		= oElement.value;//value;//(oElement,'value');
	var sTagName	= oElement.tagName;
	var bDisabled	= oElement.disabled;
	var sMsjeError  = readAttribute(oElement,'error_msg');
	var sMsjeExito  = '';
	var sMsjWarning = '';
    
    var sMsg='';
    
    //alert(oElement  + '  => ' + oElement.id + '=> ' + sType + ' value: ' + sValue);
    if(sValue=='' || sValue==null)
    {    
        //alert(oElement.id + '=>' + sValue);
        setError(oElement,sMsjeError);
        return false;
        
    }
    
    switch(sType)
    {
        case 'email':		
            return checkMail(oElement);
		break;
        case 'integer':			
            return checkInteger(oElement);
		break;
        case 'currency':
		    return checkCurrency(oElement);      
		break;
        case 'phone':
			return checkPhone(oElement);
		break;
        case 'date':
			return checkDate(oElement);
		break;  
        case 'radio':
				var sGroupRadio = readAttribute(oElement, 'group_elements');
				var nMarks = validateMarkGroup(sGroupRadio);
				if(nMarks==0)
				{					
					sMsjeError = 'Debe selccionar una opci&oacute;n';					
                    setError(oElement,sMsjeError);
					return false;
				}				
		break;     
		case 'checkbox':
				var sGroupCheckBox = readAttribute(oElement, 'group_elements');
				var nMarks = validateMarkGroup(sGroupCheckBox); 
				if(nMarks==0)
				{
					oElement = getElement('error_msg_'+sGroupCheckBox);
					sMsjeError = 'Debe selccionar al menos una opci&oacute;n';				
                    setError(oElement,sMsjeError);
					return false;
				}
		break;
        
        
    }
    setError(oElement,'',0);
    return true;
	
	
}

var selectOptionByValue= function(obj,value,bDebug)
{
	var obj=getElement(obj);
    if(!obj)
        return false; 
    var x=0;
    var aOptions;
    var nOptions;    
    if(obj.options)
    {  
        aOptions=obj.options;
        nOptions=aOptions.length;
    }
    while(x<nOptions)
    {  
        if(aOptions[x].value==value)
        {            
            aOptions[x].selected=true;
			break;
		}
        x++;
    }
   //if(obj.selectedIndex)
  //  aOptions[obj.selectedIndex].selected=false;    
  //if(aOptions[x].selected)
}



var getOptionTextByValue=function(obj,value)
{
    obj=getElement(obj);
    if(!obj)
        return false;
   var selectedIndex=obj.selectedIndex;
   var text=obj.options[selectedIndex].text;   
   return text;
}


var getOptionIndexByValue=function(obj,value)
{
	var obj=getElement(obj);
    if(!obj)
        return false;
	var aOptions=obj.options;
	var nOptions=aOptions.length;
	var x;
	for(x=0; x<nOptions;x++)
	{		
		if(aOptions[x].value==value)
		{
			return x;
		}		
	}  
    
    
}

var removeOptionsByValue=function(obj,value)
{
  
	var obj=getElement(obj);
    if(!obj)
        return false;
	var aOptions=obj.options;
	var nOptions=aOptions.length;
	var x;
	for(x=0; x<nOptions;x++)
	{		
		if(aOptions[x].value==value)
		{
			//if(aOptions[x].selected)
            
            obj.removeChild(aOptions[x]);
            
			//	aOptions[x].remove selected=true;
			break;
		}		
	}  
    
    
}
/*

var removeOptionsByValues=function(obj,values)
{
     
    
	var obj=getElement(obj);
    if(!obj)
        return false;
        
     
    if(!is_array(values))
        return false;
  
    var cantidad= count(values);
       
    if(cantidad==0)
        return false;
        
     
    for(var x=0;x<cantidad;x++)
    {
        removeOptionsByValue(obj,values[x]);        
    }
    
}
*/

var validateFormFields=function(sFrmName,debug_mode)
{
    //var oContainer 		= getElement(sFrmName);

	var aDatos 			= getChildren(sFrmName,'INPUT|TEXTAREA|SELECT');
	var oElement 		= '';
	var sTypeValidation = '';
	var	nError			= 0;
	var aRadio			= [];
	var aGroupsMark		= [];
	var sGroup			= '';
	var testMsjs 		= '';
	//var sIdSpanError	= "error_msg_";
	var sIdElement		= '';        
    var bErrorMsg       = '';
    var sType           = '';  
		//if(!getElement(sIdSpanError+sIdElement))
		//	continue;
    var longitud=aDatos.length;    
    var xIndex=0;
    while(xIndex<longitud)
    {	
		oElement		= aDatos[xIndex++];
		sIdElement		= oElement.id;        
        bErrorMsg       = readAttribute(oElement,'error_msg');
        sType           = oElement.type;         
        if(!bErrorMsg || oElement.disabled)
            continue;
        sTypeValidation = readAttribute(oElement, 'val_type');
        
        //alert(sIdElement + '=>' + oElement.tagName + '=>' + sType);
        
		switch(oElement.tagName)
		{
			case 'INPUT':
				if(sType=='text')
				{
					if(!validateByType(sTypeValidation, oElement))
					{
						testMsjs 	 +='ELEMENTO=>'+sIdElement+' | TIPO_VAL=>'+sTypeValidation+'<br />';
						sErroresForm += bErrorMsg + '\n';
						nError++;
					}							
				}
				else
				{
					if(sType=='radio' || sType=='checkbox')
					{
						sGroup = readAttribute(oElement, 'group_elements');
						if(sGroup)
							aGroupsMark[sGroup] = sType;
					}
				}
			break;
			
			case 'TEXTAREA':
            
               
				if(!validateByType(sTypeValidation, oElement))
				{
					testMsjs 	 +='ELEMENTO=>'+sIdElement+'<br />';
					sErroresForm += bErrorMsg + '\n';
					nError++;
				}
			break;
			
			case 'SELECT':
            
                
				if(sType=='select-one')
				{
					sTypeValidation='select-one';
					if(!validateByType(sTypeValidation, oElement))
					{
						testMsjs 	 +='ELEMENTO=>'+sIdElement+' SELECTED INDEX=>'+oElement.selectedIndex+'<br />';
						sErroresForm += bErrorMsg + '\n';
						nError++;
					}
				}
				if(sType=='select-multiple')
				{
					//Not implemented yet
				}
			break;
		}
	
	}
	var msj='';
	var nMarks=0;
	if(sGroupRadio)
	{
		for(var sGroupRadio in aGroupsMark)

		{
			nMarks=validateMarkGroup(sGroupRadio, aGroupsMark[sGroupRadio]);
			if(nMarks==0)
			{
				if(aGroupsMark[sGroupRadio]=='radio')
					sMsjeError = 'Debe selccionar una opci&oacute;n.';
				else
					sMsjeError = 'Debe selccionar al menos una opci&oacute;n de la lista.';
					
				setGenericErrorMsg(sGroupRadio, sMsjeError, sClassError);
				nError++;
			}
			else
			{
				sMsjeExito = '';
				setGenericErrorMsg(sGroupRadio, sMsjeExito, sClassExito);
			}
		}
	}

	if(getElement('debug'))
	{
		var debug_mode = getElement('debug').value;
		if(debug_mode)
		{
			var oAyuda;
				oAyuda =autoCreateElement('ayuda','DIV');
				oAyuda.innerHTML = testMsjs;
				oAyuda.style.display = 'inline';
			//document.body.appendChild(oAyuda);
		}
	}
	return nError>0 ? false : true;
}

var validateMarkGroup=function(sGroupElements, sType)
{
	var aElements = document.getElementsByTagName('INPUT');
	var oElement  = '';
	var bMark 	  = 0;
	
	for(var xIndex=0; xIndex<aElements.length; xIndex++)
	{
		oElement= aElements[xIndex];
		if(oElement.type != sType)
			continue;

		sGroup	= readAttribute(oElement, 'group_elements');
		if(sGroup==sGroupElements && oElement.checked && oElement.type == sType)
			bMark++;
	}
	return bMark;
}

var getLastSibling2=function(obj,tag,attrib,value)
{
	obj=getElement(obj);	
	if(!obj)
		return false;
	var lastSibling=false;		
	if(tag || (attrib && value))
	{		
		var children=getChildren(obj.parentNode,tag);
		var x=0;
		var childValue;		
		for(x=children.length-1;x>0;x--)
		{
			if(tag=='INPUT')
			{
				if(children[x].type!=type)
					continue;
			}			
			if(attrib)
			{				
				childValue=readAttribute(children[x],attrib);
				if(childValue===value)
				{
					lastSibling=children[x];
					break;
				}					
			}			
			lastSibling=children[x];
			break;
		}	
	
	}
	else
	{	
		lastSibling=obj.parentNode.lastChild;
		if(!lastSibling || lastSibling.nodeType!=1)
			lastSibling=obj;
	}	
	return lastSibling;		
}.defaults(null,'','','');


var getLastSibling=function(obj,type,attrib,value)
{
	var obj=getElement(obj);	
	if(!obj)
		return false;	
		
		
	var aElements = document.getElementsByTagName(obj.tagName);
	var oElement  = false;
	var bMark 	  = 0;
	
	for(var xIndex=0; xIndex<aElements.length; xIndex++)
	{
		
		elemAttrbValue= readAttribute(aElements[xIndex], attrbName);
		if(aElements[xIndex].type != type && elemAttrbValue!=attrbValue)
			continue;
		else
			oElement= aElements[xIndex];
	}
	
	return oElement;
}



if(typeof xajax != 'undefined')
{
	xajax.callback.global.onRequest = function(){setMsg(' enviando...','status','inline')};
	xajax.callback.global.onWaiting = function(){setMsg(' esperando...','status','inline')};
	xajax.callback.global.onProcessing = function(){setMsg(' procesando...','status','inline')};
	xajax.callback.global.onComplete = function(){setMsg(' completo','status','none')};
	xajax.callback.global.onResponseDelay = function(){setMsg(' procesando...','status','inline')};
	xajax.callback.global.onSuccess = function(){setMsg(' exito','status','inline')};
	xajax.callback.global.onReadyStateChange = function(){setMsg(' cambio de estado...','status','block')};
	xajax.callback.global.onFailure = function(){setMsg(' error...','status','inline')};
	xajax.callback.global.onExpiration = function(){setMsg(' expiro...','status','none')};
}

/*
		//return cancelEvent(e);
		
	/*	if(!e)
			var e = window.event;
		*/	
		/*	 
		if(e)
		{
			
			e.cancelBubble = true;
			
			//alert('stopPropagation');	
		}
		else
			if(e.stopPropagation)
			{
				e.stopPropagation();
			//alert('cancelBubble');
			}	
		*/
		//alert(e.explicitOriginalTarget);
		/*	e.altKey = false;
			e.altLeft = false;*/
			
			
		//var objMsg=autoCreateElement('spanError','SPAN',1);
	/*	
		var objMsg=getElement('error_msg_' + obj.id);
		obj.style.display='inline';
		obj.innerHTML='error';
*/	











var addEvent2=function(element, event, func)
{
	if(typeof func=="string")
	{
		func=window[func];
	};
	if(typeof element=="string")
	{
		element=document.getElementById(element);
	};
	if(!element || typeof event!="string" || typeof func!="function"){return false;};
		event=event.toLowerCase();
	if(typeof element['addEventListener']!="undefined"){
		if(event.indexOf('on')>-1){event=event.replace(/^on/, '');};
	element.addEventListener(event, func, false);
	return true;
	}
else if(typeof element['attachEvent']!="undefined"){
	if(event.indexOf('on')!=0){event='on'+event;};
element.attachEvent(event, func);
return true;
}
else{
	if(event.indexOf('on')!=0){event='on'+event;};
element[event]=func;
};
return false;

	
}

/*
for(elementEvent in children[x])
{				
	//var evento=elementEvent.replace(/^(on)/g,'');
	//if(children[x][elementEvent])				
	//	removeEvent(children[x],evento,children[x][elementEvent]);
	
	document.write(children[x].eventList + '<br/>');	
	continue;
	
	
	var ok=0;
	if(patron.test(elementEvent))
		ok=1;
	else
	{
		//var patron=/^(function)/;				
		//if(getFuncName(elementEvent))
		//	ok=1;	
		
		document.write(elementEvent + '<br/>');				
	}			
	if(ok && children[x][elementEvent])
	{
		
		document.write(elementEvent + '<br/>');
		continue;
		
		var func=children[x][elementEvent];
		//var patron=/(selectAllText)/;
		/*
		
		if(patron.test(func))
		{
		document.write(func + '<br/>');
			continue;
		}
		
							
		var evento=elementEvent.replace(/^(on)/g,'');					
		removeEvent(children[x],evento,func);
		children[x][elementEvent]=null;					
		
	}*/
				
/*
var count=function(aArray)
{
	var counter=0;
    var prop;    
	if(aArray.constructor===Array)
		return aArray.length;      
	if(aArray.constructor!==Object)
		return false;	
	for(prop in aArray)
	{	   
		if(typeof aArray[prop]=='function')
		  continue;
        counter++;
        
	}
	return counter;		
}
*/
var array_remove_key=function(aArray,mProperty)
{
	if(!array_key_exists(mProperty,aArray))
		return false;	
		
	
	if(aArray.constructor===Array)
	{	
		delete aArray[mProperty];
		aArray.splice(mProperty,1);
				
	}
	else
		if(aArray.constructor===Object)
			delete aArray[mProperty];
	return aArray;
				
}


//alert($);
   
            
//window.onbeforeunload=function(){
    
  //  alert(getKeyStroke(event));
    
   // if(!confirm("Si cierra la ventana se perderá toda la información no guardada. \n Desea Continuar?"))
     //   window.onunload=false;
    
    
//}    
var orderPrint=function()
{
    if(window.print)
    {
        window.print();           
    }    
    else
        alert('Su navegador no soporta impresión');    
}
var disabledOptions=function(obj, mValue)
{
	obj = getElement(obj);
	if(!obj)
		return false;
	var aChildren = getChildren(obj,'OPTION');
    var nChildren =aChildren.length;
    var item;
    var x=0;
	while(x<nChildren)
	{
	   item=aChildren[x++];
		if(!mValue)
		{
			item.disabled = false;
		}
		else
		{
			if(mValue!=item.value)
				item.disabled = true;
		}
	}
	selectOptionByValue(obj.id,mValue);
}
var ajaxRequest=function(id,sURL,sVars,method,json,sync,func,returnResponse) 
{
    var ok=false;
    if(!id)
        return false;
    if(!sVars)
        sVars='';
    var xmlHttpReq = false;   
    //var self = this;        
    var regExp=/^(POST|GET)$/i;    
    if(!regExp.test(method))
    {        
        alert('Only POST or GET method allowed!');
        return false;
    }
    method=method.toUpperCase();    
    if(!method)
        method='POST';
    if(!sync)
        async=true;
    else
        async=false;
    if(!json)
        json=true;
    else
        json=false;
    try
    { 
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (e) 
    {
        try
        {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        } 
        catch (E) 
        {
            xmlhttp = false;
        }
    }
    if (!xmlhttp && typeof XMLHttpRequest!='undefined') 
    {
    	try
        {
		  xmlhttp = new XMLHttpRequest();
	   } 
       catch (e) 
       {
	       xmlhttp=false;
	   }
    }
    if (!xmlhttp && window.createRequest) 
    {
	   try
        {
		  xmlhttp = window.createRequest();
	   } 
       catch (e) 
       {
	       xmlhttp=false;
	   }
    }
    
    try
    {
        xmlhttp =xmlhttp;
        xmlhttp.open(method, sURL, async);
        xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');        
        xmlhttp.onreadystatechange = function() 
        {
            ok=true;
            var status=xmlhttp.status;  
            switch(status)
            {
                case 100: msg='Continue';break;
                case 101: msg='Switching Protocols';break;
                case 200: msg='OK';break;
                case 201: msg='Created';break;
                case 202: msg='Accepted';break;
                case 203: msg='Non-Authoritative Information';break;
                case 204: msg='No Content';break;
                case 205: msg='Reset Content';break;
                case 206: msg='Partial Content';break;
                case 400: msg='Bad Request';break;
                case 401: msg='Unauthorized';break;
                case 402: msg='Payment Required';break;
                case 403: msg='Page <strong>'+ sURL + '</strong> Forbidden';break;
                case 404: msg='Page <strong>'+ sURL + '</strong> Not Found';break;
                case 405: msg='Method Not Allowed';break;
                case 406: msg='Not Acceptable';break;
                default : msg='unknown error'; break;
            }
            
            if(status<200 || status>299)
            {
                if(!returnResponse) 
                    updatepage(id,msg,false);
                return false;
            }
            switch(xmlhttp.readyState)  
            {
                case 0: break;
                       case 0: break;
                case 1: 
                    if(!returnResponse) 
                        updatepage(id,'loading...',false);
                break;
                case 2: 
                    if(!returnResponse)                 
                        updatepage(id,'loaded!',false);
                break;
                case 3: 
                    if(!returnResponse) 
                        updatepage(id,'retrieving data...',false);
                break;            
                case 4: 
                    if(!returnResponse)                 
                        updatepage(id,xmlhttp.responseText,json);
                    else
                    {
                        if(json)
                            eval('{' + xmlhttp.responseText + '}');
                        else
                            return xmlhttp.responseText;
                    }
                break;
                
            } 
        }
        if(!ok)
        {
            msg='Could not retrieve data perhaps because async mode is: <strong>'+async+'</strong>';
            if(!returnResponse) 
                updatepage(id, msg,false);
        }
        
        xmlhttp.send(sVars);    
    }
    catch(ee)
    {
        alert(ee.description);
    }
    
}
var updatepage=function(id,str,json)
{

    var element =getElement(id);
    if(json)
    {
        var data=eval('(' + str + ')');
    }
    else
        if(existsAttribute(element,'innerHTML'))
            element.innerHTML=str;
        else 
        {
            if(existsAttribute(element,'value'))
                element.value=str;
            else
                return false;
        }
        
}

var converToSwfUpload=function(id,url,size_limit,types,types_desc,usebutton,path,dest,debug,showalert,multiple,encrypt,events,upload_limit,queue_limit,buttonPath,wmode)
 {       
    
    /*
    if(!FlashDetect.versionAtLeast(10))
    {
	   //loadModalAJAX('elementoVentana','../common/_mensaje_generico.php?id=13',550,250);
       alert("Recuerde que debe tener adobe flash player instalado para poder utilizar la opción de carga de archivos");
       return false;
    }
    */
    
    var swfu; 
    if (typeof(SWFUpload) === "undefined") 
    {
        alert('SWFUpload no definido');
		return false;
    }    
    if(!path)
	{
        /*path='http://172.16.10.4/common/classes/swfupload2/swfupload/';*/
        path='http://sistemaenlinea.fincyt.gob.pe/common/classes/swfupload2/swfupload/';
    }
	else
        path=base64_decode(path);    
        
    dest	= base64_decode(dest);   
    url 	= base64_decode(url); 
    types	= base64_decode(types);   
    

    if(debug)
        debug=true;
    if(!upload_limit)
        upload_limit= 0;
    if(!queue_limit)
        queue_limit= 10;
    if(!buttonPath)
        buttonPath= path + "upload_button.png";
    if(!size_limit)
        size_limit='2 MB';
    if(!types)
        types ="*.*";   
    if(!types_desc)
        types_desc ="Todos los archivos";
    if(!showalert)
        showalert=false;
    if(!encrypt)
        encrypt=0;
    else
        encrypt=1;
      
     if(!wmode)
        wmode=SWFUpload.WINDOW_MODE.TRANSPARENT;
     else
        wmode=eval(wmode);  
    
    if(!events)
        events='';  
    else        
    {
        events=base64_decode(events);        
        events=eval(" (" + events + ")");
    }

	if(events['showprogress'])
        var showprogress=events['showprogress'];
     else
        var showprogress=false;
 
    var filetxt=document.createElement('INPUT');
    filetxt.id 					= 'upload_'+id;
    filetxt.name 				= 'upload_'+id;
    filetxt.type				= 'text';
    filetxt.disabled			= false;
    filetxt.readOnly			= true;
    filetxt.style.marginRight	= '3px';
    filetxt.width				= '100';
    insertBefore(filetxt,id);
    
    /*
    var sizehidden=document.createElement('INPUT');
    sizehidden.id 			= 'sizeinfo_'+id;
    sizehidden.name 		= 'sizeinfo_'+id;
    sizehidden.type			= 'hidden';
    insertAfter(sizehidden,id);
    
    var typehidden=document.createElement('INPUT');
    typehidden.id 			= 'typeinfo_'+id;
    typehidden.name 			= 'typeinfo_'+id;
    typehidden.type			= 'hidden';
    insertAfter(typehidden,id);
    */
    
    var pattern=/([\d]+(\.[\d]+)?)+(\s+(bytes|Kb|Mb|Gb)+)*/i;    
    var maxFileSize=size_limit.match(pattern);    
    if(!maxFileSize[1])
        return false;    
    if(maxFileSize[4])
    {
        var sizeUnit=maxFileSize[4];
        sizeUnit=sizeUnit.toUpperCase();        
        maxFileSize=parseFloat(maxFileSize[1]);
        switch(sizeUnit)
        {
            case 'BYTES': maxFileSize*=1; ; break;
            case 'KB': maxFileSize*=1024;  break;
            case 'MB':maxFileSize*=1024*1024; break;
            case 'GB': maxFileSize*=1024*1024*1024; break;
        }
    }
    else
        maxFileSize=maxFileSize[1];

    //,"MAX_FILE_SIZE":maxFileSize

    var settings_object = {
        loaded                      : false,
        upload_url                  : url, 
        flash_url                   : path + "swfupload.swf", //*/"http://www.swfupload.org/swfupload.swf",
        file_post_name              : "Filedata",    
        post_params                 : {"dest" : dest, "detect_enc": 1, "encrypt": encrypt},         
        use_query_string            : false, 
        requeue_on_error            : false, 
        http_success                : [200,201,202],
        assume_success_timeout      : 0,
        prevent_swf_caching         : true,
        preserve_relative_urls      : false, 
        debug                       : debug,
        //file settings
        file_types                  : types, 
        file_types_description      : types_desc, 
        file_size_limit             : maxFileSize + ' B', /*size_limit,*/ 
        file_upload_limit           : upload_limit, 
        file_queue_limit            : queue_limit,   
        //button settings
        button_placeholder_id       : id,    
        button_image_url            : (usebutton ? buttonPath : ""),
       	button_width                : (usebutton ? '61' : '70'),
        button_height               : "22",
        button_text                 : (usebutton ? '' : '<button>Examinar...</button>'),
        button_text_style           : ".theFont{font-size: 18; background: gray;}",
        button_text_left_padding    : 12,
        button_text_top_padding     : 3,
        button_action               : multiple ? SWFUpload.BUTTON_ACTION.SELECT_FILES : SWFUpload.BUTTON_ACTION.SELECT_FILE,    
        button_disabled             : false,
        button_cursor               : SWFUpload.CURSOR.HAND, 
        button_window_mode          : wmode,
        //button_window_mode          : SWFUpload.WINDOW_MODE.OPAQUE,

        //events
        swfupload_loaded_handler    : fileLoaded, 
        //mouse_click_handler         : mouse_click_function, 
        //mouse_over_handler          : mouse_over_function, 
        //mouse_out_handler           : mouse_out_function, 
        file_dialog_start_handler   : fileDialogStart, //ok 
        file_queued_handler         : fileQueued,  //ok 
        file_queue_error_handler    : fileQueueError, //ok 
        file_dialog_complete_handler: fileDialogComplete, //ok 
        upload_start_handler        : uploadStart, //ok 
        upload_progress_handler     : (showprogress ? uploadProgress : false), 
        upload_error_handler        : uploadError, 
        upload_success_handler      : uploadSuccess, //ok
        uload_complete_handler      : uploadCompleted, //ok
        //debug_handler               : debug_function, 
        //custom settings

        custom_settings             : 
        {
            fileinfoTag : filetxt,
            //sizeinfoTag : sizehidden,
            //typeinfoTag : typehidden,
            showalert   : showalert,
            filehash    :'',
            filemime    :'',
            filesize    :0,
            fileuploaded:false,
            fileduplicated:false,
            postname    :"Filedata",
            events      : events,
            data        : {}
        } 
        
    };
    swfu = new SWFUpload(settings_object);        
    return swfu; 
 }

var fileLoaded=function(obj)
{
    //alert(obj);
}
var fileDialogStart=function() //when dialog shows
{
    this.cancelUpload();
}
var fileDialogComplete=function() //when dialog hides
{        

}
var fileQueued=function(file) //after file has been selected
{   
    file = this.unescapeFilePostParams(file);
    if(this.customSettings.fileinfoTag)
      this.customSettings.fileinfoTag.value=file.name;
    if(this.customSettings.sizeinfoTag)                  
      this.customSettings.sizeinfoTag.value=file.size;
    if(this.customSettings.typeinfoTag)
      this.customSettings.typeinfoTag.value=file.type;
           		    
}
var fileQueueError = function(file, errorCode, message)
{        
    //alert('FileQueueError: ' + message + ' code: '+ errorCode);
    switch(errorCode)
    {
        case -110: alert('El tamaño del archivo excede el máximo permitido');break;
        default: alert('Ocurrio un error en la carga del archivo. Codigo error: ' + errorCode + ' '+message);break;            
    }      
}
var uploadStart = function(file)
{   
    //alert('Iniciando la carga...');     
   try
   {  
     this.startUpload();
   }
   catch(errr)
   {
    //alert(errr.description);
    this.debug(errr);
   }       
    //this.callFlash("StartUpload", file.id);        
} 

var redirect=function(url,msg)
{
    
    if(!url)
        return false;
    if(!msg)
        document.location.href=url;
    else if(confirm(msg))    
        document.location.href=url; 
}

var openModal=function(id,source,html,title,width,height,center)
{
    var modalContainer = autoCreateElement('modalContainer','DIV');
    var modalWindow    = autoCreateElement('modalWindow','DIV');
    var modalHead      = autoCreateElement('modalHead','DIV');
    var modalBody      = autoCreateElement('modalBody','DIV');
    var modalTitle     = autoCreateElement('modalTitle','DIV');
    var modalButtons   = autoCreateElement('modalButtons','DIV');
    var modalClose     = autoCreateElement('modalClose','A');
    var modalMax       = autoCreateElement('modalMax','A');
    
    modalTitle.innerHTML    = title ? title : 'untitled';
    modalContainer.className= 'modalContainer';
    modalWindow.className   = 'modalWindow';   
    modalHead.className     = 'modalHead';
    modalBody.className     = 'modalBody';
    modalTitle.className    = 'modalTitle';
    modalButtons.className  = 'modalButtons';    
    modalClose.className    = 'modalClose';
    modalMax.className    = 'modalClose';    
    
    
    var docWidth=getDocWidth();
    var docHeight=getDocHeight();

    modalContainer.style.width  = docWidth;
    modalContainer.style.height = docHeight; 
    //alert(typeof source);
    modalWindow.style.width = width ? width : '300px';
    modalWindow.style.height= height ? height : '80px';    
    if(typeof source =='object')
        modalBody.appendChild(source);
    else if(typeof source =='string' && html)    
        modalBody.innerHTML=source;        
    else
    {
        var modalIframe=autoCreateElement('modalIframe','IFRAME');
        modalIframe.src=source;
        modalIframe.className="modalIframe";
        modalBody.appendChild(modalIframe);
    }
    
    //alert(source);
    
    modalMax.innerHTML      = '&nbsp;&nbsp;&nbsp;O';
    modalMax.href         = 'javascript:';
    modalMax.style.zIndex = 9999;
    addEvent(modalMax,'onclick',function(){
        
        var viewport=getViewportDimensions(); 
        modalMax.innerHTML      = '&nbsp;&nbsp;&nbsp;_';  
        modalWindow.style.top=0;
        modalWindow.style.left=0;
        modalWindow.style.height=viewport.height;
        modalWindow.style.width=viewport.width;
    });     
    
    modalClose.innerHTML    = '&nbsp;&nbsp;&nbsp;X';
    modalClose.href         = 'javascript:';
    modalClose.title        = 'Cerrar';    
    modalClose.style.zIndex = 9999;
 
    addEvent(modalClose,'onclick',function(){
        
        fadeElement(modalWindow,250);
        fadeElement(modalContainer,180);
        removeElement(modalWindow);
        removeElement(modalContainer);  
        //removeEvent(window,'onclick');
    });     
      
      
    modalButtons.appendChild(modalMax);
    modalButtons.appendChild(modalClose);    
    modalHead.appendChild(modalTitle);
    modalHead.appendChild(modalButtons);    
    modalWindow.appendChild(modalHead);
    modalWindow.appendChild(modalBody);
    if(parent.window)
    {
        parent.window.document.body.appendChild(modalContainer);
        parent.window.document.body.appendChild(modalWindow);        
    }    
    else
    {
        document.body.appendChild(modalContainer);
        document.body.appendChild(modalWindow);    
    }
    centerElement(modalWindow);
            
    //modalContainer.onresize=function(){alert('resizing')};
    //addEvent(document.body,'mousemove',function(e){moveModal(modalWindow,e,1);},1); 
    //modalWindow.onmousedown=function(e){moveModal(modalWindow,e,2);};
    //modalWindow.onmouseup=function(e){moveModal(modalWindow,e,3);};    
    //modalHead.onmousedown=function(e){dragStart(e,modalHead.parentNode)};
    ///moveModal(modalWindow);
    //modalContainer.onclick=function(){alert(this); };    
    //modalContainer.onmousemove=function(){moveModal(this);};  
}

var centerElement=function(obj,parentElement)
{
    obj=getElement(obj);
    if(!obj)
        return false;
    var viewport=getViewportDimensions();    
    
    if(!parentElement)
    {
        if(parent.window.document.body)
            parentElement=parent.window.document.body;
        else if(window.document.body)
            parentElement=window.document.body;
        else
            return false;
    } 
    
    var left = (viewport.width == 0) ? 50 : parseInt((viewport.width - obj.offsetWidth) / 2, 10);
    var top = (viewport.height == 0) ? 50 : parseInt((viewport.height - obj.offsetHeight) / 2, 10);

    obj.style.left = left + 'px';
    obj.style.top = top + 'px';
    obj.style.position='relative';
    window.onresize=function(){ centerElement(obj); };
    viewport=left=top=elem = null;      
       
    //alert('offsetWidth: '+ parentElement.offsetWidth );
    /*
    obj.style.left=((parentElement.offsetWidth-obj.offsetWidth)/2)+20;
    obj.style.top=((parentElement.offsetHeight-obj.offsetHeight)/2)+200;
    */    
}
function getViewportDimensions() {
    var intH = 0, intW = 0;
    
    if(self.innerHeight) {
       intH = window.innerHeight;
       intW = window.innerWidth;
    } 
    else {
        if(document.documentElement && document.documentElement.clientHeight) {
            intH = document.documentElement.clientHeight;
            intW = document.documentElement.clientWidth;
        }
        else {
            if(document.body) {
                intH = document.body.clientHeight;
                intW = document.body.clientWidth;
            }
        }
    }

    return {
        height: parseInt(intH, 10),
        width: parseInt(intW, 10)
    };
}



var hideModal=function(obj)
{
    /*
    getElement('blockingLayer').style.display='none';
    getElement('modalLayer').style.display='none'; 
    */
    
   //obj.style.display='none'; 
   
   alert(obj.firstSibling);
   
   //removeElement(obj);
   //removeElement(obj.firstSibling);
   
}
var showModal=function(obj)
{
    //getElement('blockingLayer').style.display='inline';
    //getElement('modalLayer').style.display='inline'; 
    
}
var hideSubMenu=function(obj){
    
    obj.style.display='none';
    
    
    //var classes=obj.className;
    //hideElement(obj);
    
    
    //alert(obj.className);
    //
    //'this.style.display="none";this.className="submenu two-columns"'
    
}
var mouseX;
var mouseY;
var dragObj = new Object();
dragObj.zIndex = 0;



var dragStart=function(event,obj)
{
    var el;
    var x, y;
    var isIE,isFF;    
    if(obj)
        dragObj.elNode = getElement(obj);
    else 
    {
        switch(currentBrowser)
        {
            case 'Explorer':
                dragObj.elNode = window.event.srcElement;
                isIE=true;
            break;
            case 'Firefox':
                dragObj.elNode = event.target;
                isFF=true;
            break;
            default:
                alert('Browser not supported!');
                return false;
            break;
            
        }            
        if (dragObj.elNode.nodeType == 3)
            dragObj.elNode = dragObj.elNode.parentNode;
    }
    
   
         
    if (isIE) 
    {
        x = window.event.clientX + document.documentElement.scrollLeft + document.body.scrollLeft;
        y = window.event.clientY + document.documentElement.scrollTop + document.body.scrollTop;
    }
    else if(isFF)
    {  
        x = event.clientX + window.scrollX;
        y = event.clientY + window.scrollY;
    }
    dragObj.cursorStartX = x;
    dragObj.cursorStartY = y;
    
    dragObj.elStartLeft  = parseInt(dragObj.elNode.style.left, 10);
    dragObj.elStartTop   = parseInt(dragObj.elNode.style.top,  10);
    
     
    if (isNaN(dragObj.elStartLeft)) 
        dragObj.elStartLeft = 0;
      
    if (isNaN(dragObj.elStartTop))  
        dragObj.elStartTop  = 0;
        
    //return;     
    //dragObj.elNode.style.zIndex = ++dragObj.zIndex;
    
    
  if (isIE)  {
    document.attachEvent("onmousemove", dragGo);
    document.attachEvent("onmouseup",   dragStop);
    window.event.cancelBubble = true;
    window.event.returnValue = false;
  }
  else if(isFF) {
    document.addEventListener("mousemove", dragGo,   true);
    document.addEventListener("mouseup",   dragStop, true);
    event.preventDefault();
  }

    
}
var dragStop=function()
{
    switch(currentBrowser)
    {
        case 'Explorer':
            document.detachEvent("onmousemove", dragGo);
            document.detachEvent("onmouseup",   dragStop);
            isIE=true;
        break;
        case 'Firefox':
            document.removeEventListener("mousemove", dragGo,   true);
            document.removeEventListener("mouseup",   dragStop, true);
            isFF=true;
        break;
        default:
            alert('Browser not supported!');
            return false;
        break;
    } 
    
}
var dragGo=function()
{
    var x, y;
    switch(currentBrowser)
    {
        case 'Explorer':
            x = window.event.clientX + document.documentElement.scrollLeft + document.body.scrollLeft;
            y = window.event.clientY + document.documentElement.scrollTop + document.body.scrollTop;
            isIE=true;
        break;
        case 'Firefox':
            x = event.clientX + window.scrollX;
            y = event.clientY + window.scrollY;
            isFF=true;
        break;
        default:
            alert('Browser not supported!');
            return false;
        break;
        
    } 
  // Move drag element by the same amount the cursor has moved.
  dragObj.elNode.style.left = (dragObj.elStartLeft + x - dragObj.cursorStartX) + "px";
  dragObj.elNode.style.top  = (dragObj.elStartTop  + y - dragObj.cursorStartY) + "px";
  if (isIE) {
    window.event.cancelBubble = true;
    window.event.returnValue = false;
  }
  if (isFF)
    event.preventDefault(); 
}



var moveModal=function(obj,event,type)
{



    if(type==1)
    {
        if(!event)
            event = window.event;
        if(event.offsetX || event.offsetY) { 
            mouseX=event.offsetX;
            mouseY=event.offsetY;
        }
        else { //For FireFox
            mouseX=event.pageX;
            mouseY=event.pageY;
        }
       
       
       if(bDragging)
       {
        obj.style.left = mouseX +'px';
        obj.style.top = mouseY +'px';
        //obj.innerHTML="x=" + mouseX + '  y=' + mouseY;
       }
        //
    } 
    
    
     
    if(type==2 )
    {
        bDragging=1;
       
        //alert(obj);
        //obj.style.left = mouseX +'px';
        //obj.style.top = mouseY +'px';
        
        
        //bDragging=1;
        //obj.innerHTML="x=" + mouseX + '  y=' + mouseY;
    }
    if(type==3)
        bDragging=0;
    
    
    
    //obj.innerHTML+=event.clientX+ "<br/>";
    //obj.innerHTML="x=" + x + '  y=' + y + '<br/>';
    
    //alert(x + ' ' + y );
    
}


var uploadProgress=function(file,uploadedBytes,totalBytes)
{

    var div1    =autoCreateElement('blockingLayer','DIV');            
    var div2    = autoCreateElement('modalLayer','DIV');                    
    var span1   = autoCreateElement('progress','SPAN');
    var div3    = autoCreateElement('progressBarContainer','div');
    var div4    = autoCreateElement('progressBar','div');
    
    var x       = 100*(uploadedBytes/totalBytes);   
    x=x.toFixed(0);        
    div4.style.width=x + '%';
    span1.innerHTML='progreso de la carga: '+ x +  '%';    
    if(!divCreated)
    {        
        div1.className='blockingLayer';
        div2.className='modalLayer';
        /*div2.style.width="250px";
        div2.style.height="30px";*/
        div3.className='progressBarContainer';
        div4.className='progressBar';
        div3.appendChild(div4);        
        span1.style.fontWeight='bold';
        div2.appendChild(span1);  
        div2.appendChild(div3);                 
        document.body.appendChild(div1);
        document.body.appendChild(div2);
        divCreated=1; 
    }        
}
var uploadCompleted=function(file)
{    
    alert('Archivo(s) cargado(s)!');
}
var uploadError = function(file,code,msg)
{    
    if(code!=-280)
      alert('ocurrio un error: ' + code + ' -> ' + msg);    
}
var uploadSuccess=function(file,server_data,received_response)
{    
    if(divCreated)
    {
        getElement('blockingLayer').style.display='none';
        getElement('modalLayer').style.display='none';            
    }
    if(server_data)
         var data=eval('(' + server_data + ')');
    
    this.customSettings.fileuploaded=data['uploaded'];   
    if(this.customSettings.events)
    {
       var events=this.customSettings.events;       
       if(events['onuploaded'])
            var onuploaded=base64_decode(events['onuploaded']);
       if(events['onduplicated'])
            var onduplicated=base64_decode(events['onduplicated']);
       if(events['onerror'])
            var onerror=base64_decode(events['onerror']);
    }
    if(data)
        this.customSettings.data=data;
   
    if(data['uploaded']===true)
    {        
        /*alert(this.customSettings.data['filetype']);
        this.customSettings.filemime=data['type'];
        this.customSettings.filesize=data['size'];
        this.customSettings.filehash=data['hash'];
        this.customSettings.filename=data['filename'];*/
        if(onuploaded)
            eval(onuploaded);
        else if(this.customSettings.showalert)
            alert('Archivo "'+ file.name +'" cargado exitosamente!');
    }
    else
        if(data['duplicated'])
        {
            var duplicates=data['dupfiles'];            
            this.customSettings.fileduplicated=data['duplicated'];
            if(onduplicated)
                eval(onduplicated);
            else if(this.customSettings.showalert)    
                alert('El archivo "'+ file.name +'" ya se encuentra cargado! '  );
                
        }
        else
        {
            if(onerror)
                eval(onerror);
            else if(this.customSettings.showalert)
                alert('Archivo "'+ file.name +'" no pudo ser cargado!');
                
        }            
}





var getFloat=function(mValue)
{
 	mValue	= str_replace(',','',mValue);	
	mValue	= floatVal(mValue);
    return mValue;
}

var getInt=function(mValue)
{
 	mValue	= str_replace(',','',mValue);	
	mValue	= floatVal(mValue);
    return mValue ;  
}






function getElementAbsoluteLeft(htmlObject){
	var xPos = htmlObject.offsetLeft;
	var temp = htmlObject.offsetParent;

	while (temp != null){
		xPos+=temp.offsetLeft;
		temp=temp.offsetParent;
	}
	return xPos;
}
if(!getFloatValue)
{
	var getFloatValue=function(obj, bType)
	{	
		var mValue	= getElement(obj);
		if(!mValue)
			return 0;
	
	    if(bType==true)
	        mValue	= mValue.value;
	    else
		   mValue	= mValue.innerHTML;
	
		mValue	= str_replace(',','',mValue);	
		mValue	= floatVal(mValue);
		return mValue;	
	}
}
/**
  *     @desc: Calculate absolute position of html object
  *     @type: private
  *     @param: htmlObject - html object
  *     @topic: 0  
  */
function getElementAbsoluteTop(htmlObject){
	var yPos = htmlObject.offsetTop;
	var temp = htmlObject.offsetParent;

	while (temp != null){
		yPos+=temp.offsetTop;
		temp=temp.offsetParent;
	}
	return yPos;
    
}
var showDhtmlxCalendar=function(obj,link,datevalue,format,skin,lang)
{
    if(link)    
    {
        if(obj.parentNode.firstChild.nodeType==3)
            var id=obj.parentNode.childNodes.item(1).id;
        else
            var id=obj.parentNode.firstChild.id;
    }
    else
        var id=obj.id;
    
    if(getElement(id).disabled===true)
    {
        if(getElement(id).value==="")
            alert('Si desea modificar alguna de las fechas vuelva a ingresar el número de ruc');
        else
            alert('No es posible modificar un valor ya ingresado');
        return false;
    }       
    if(!editMonth)
        var editMonth=true;    
    if(!editYear)
        var editYear=true;
            
    var calendarId='dhtmlxCalendar_'+ id;
    calendarId=calendarId.replace(/\[|\]/g,'');
    if(!window[calendarId])
    {    
        var cal = new dhtmlxCalendarObject(id,false,{isMonthEditable: editMonth, isYearEditable: editYear});
        cal.loadUserLanguage(lang);
        cal.setSkin(skin);
        cal.setDateFormat(format);           
        cal.setDate(datevalue); 
        cal.draw();        
        window[calendarId]=cal;        
    }
    if(window[calendarId].isVisible())
        window[calendarId].hide();
    else
    { 
        window[calendarId].show();
        fixCalendarPos(id);        
    }  
    //$sNewEvent;
}.defaults('',0,'','%d/%m/%Y','SilverLight','es');	
var fixCalendarPos=function(objId)
{
    
    
    
	var obj		    = getElement(objId);
    var objParent   = getElement('calendarParentDiv'+objId);
    var objChild    = getElement('container_' + objId);
    var classes     = objChild.className;   
    
    objParent.style.zIndex=99;
    //obj.parentNode.appendChild(objParent);
    removeClasses(objChild);
    removeStyles(objChild);    
    
    
    
    //alert(getElementAbsoluteTop(obj));
    //objParent.style.top=obj.style.top;
    
    
    //objChild.style.position='relative';
    
    
    //insertAfter(objParent,obj.nextSibling);
    
    //alert(obj.nextSibling);
    
    //objParent.style.top=getElementAbsoluteTop(obj);
    
    //alert(getElementAbsoluteTop(obj));
    
    
    //objChild.className=classes;
    
    
    //obj.parentNode.appendChild(objParent);
    
    
    
    
    
}
 var showParent=function(sChildId)
 {
 	var obj			= getElement('container_'+sChildId);
 	var objParent	= obj.parentNode;
	//alert(obj.parentNode);
	addAttribute(obj.parentNode, 'style', '');
 	//removeStyles(objParent);
 }
 
 var formatInputNumber=function(obj, decimals)
 {
    
    if(decimals==null)
        decimals=2;

    obj=getElement(obj);
    if(!obj)
        return false;
    if(!obj.tagName=='INPUT')
        return false;
    var mValue=obj.value;        
    mValue=getFloat(mValue);        
    obj.value=number_format(mValue,decimals,'.',',');
    
 }
 
 var getNumberFromId=function(obj,debug)
 {
	obj = getElement(obj);
	if(!obj)
		return false;
    if(!obj.id)
        return false;
    var nNumero;
	//var patronNumero	= /[a-zA-Z_]+\[\d+\]\[(\d+)\]|[a-zA-Z_]+\[(\d+)\]/;
    var patronNumero = /[a-zA-Z0-9_\-]+\[[0-9]+\]\[([0-9]+)\]|[a-zA-Z0-9_\-]+\[([0-9]+)\]/;
    
    var aNumero 		= patronNumero.exec(obj.id);
    if(!aNumero)
        return false;
   if(aNumero[1]=='' || typeof aNumero[1]=='undefined')
        if(aNumero[2]=='' || typeof aNumero[2]=='undefined')
            return false;
        else
            return aNumero[2];
   else       
        return aNumero[1];
        
        
 
    return false; 
}
var fadeElement=function(obj,TimeToFade)
{    
    var obj = getElement(obj);
    if(!obj)
        return false;
    if(obj.FadeState == null)
    {        
        if(obj.style.opacity == null || obj.style.opacity == '' || obj.style.opacity == '1')
           obj.FadeState = 2;
        else
           obj.FadeState = -2;       
    }
    if(obj.FadeState == 1 || obj.FadeState == -1)
    {
        obj.FadeState = obj.FadeState == 1 ? -1 : 1;
        obj.FadeTimeLeft = TimeToFade - obj.FadeTimeLeft;
    }
    else
    {        
        obj.FadeState = obj.FadeState == 2 ? -1 : 1;
        obj.FadeTimeLeft = TimeToFade;
        setTimeout(function(){ animateFade(new Date().getTime(),obj,TimeToFade)}, 33);
        
        
    }
}
var animateFade=function(lastTick, obj,TimeToFade)
{   
    var curTick = new Date().getTime();
    var elapsedTicks = curTick - lastTick;
    if(obj.FadeTimeLeft <= elapsedTicks)
    {        
        obj.style.opacity = obj.FadeState == 1 ? '1' : '0';
        obj.style.filter = 'alpha(opacity = ' + (obj.FadeState == 1 ? '100' : '0') + ')';
        obj.FadeState = obj.FadeState == 1 ? 2 : -2;
        return;
    }
     
    obj.FadeTimeLeft -= elapsedTicks;
    var newOpVal = obj.FadeTimeLeft/TimeToFade;
    if(obj.FadeState == 1)
        newOpVal = 1 - newOpVal;
    obj.style.opacity = newOpVal;
    obj.style.filter = 'alpha(opacity = ' + (newOpVal*100) + ')';
    setTimeout(function(){ animateFade(curTick,obj,TimeToFade)}, 33);
    
}
 var getDocHeight= function() 
    {        
        if(parent.window.document)
            var D=parent.window.document;
        else
            var D=window.document;              
        var scrollMax=Math.max(D.body.scrollHeight, D.documentElement.scrollHeight);
        var offsetMax=Math.max(D.body.offsetHeight, D.documentElement.offsetHeight);
        var clientMax=Math.max(D.body.clientHeight, D.documentElement.clientHeight);    
        var maxHeight=Math.max(scrollMax,offsetMax,clientMax);      
        return maxHeight;

       
    }
    var getDocWidth=function() 
    {        
        if(parent.window.document)
            var D=parent.window.document;
        else
            var D=window.document;
        var scrollMax=Math.max(D.body.scrollWidth, D.documentElement.scrollWidth);
        var offsetMax=Math.max(D.body.offsetWidth, D.documentElement.offsetWidth);
        var clientMax=Math.max(D.body.clientWidth, D.documentElement.clientWidth);    
        var maxWidth=Math.max(scrollMax,offsetMax,clientMax);         
        return maxWidth;
    
    }


var _seconds; 
var _critical=0;
var _object;
var _url;
var _id;
var countDown=function(seconds,url,id)
{
    _url=url;
    _id=id;
    setInterval(function(){ counter(seconds);},1000);    
}
var resetCounter=function(id)
{
    _seconds=null;
    _critical=0;
    if(id)
        _id=id;
    //countDown(seconds,url,id);    
}

var counter=function(secondsOrig,url)
{
    if(_seconds==null)
        _seconds=secondsOrig;    
    var minutes=(Math.floor(_seconds/60));
    var seconds=(_seconds%60);   
    
    //alert("Bienvenido");
    
    return;
       
    if(!_object)    
    {
        
        
        _object=autoCreateElement('_timer','SPAN');
        if(_id)
            insertAfter(_object,_id);
        else
        document.body.appendChild(_object);
    }
    if(minutes===0)
    {
        _object.style.color='red';
        _object.style.fontWeight='bold';
    }
    else
    {
        _object.style.color='black';
        _object.style.fontWeight='bold';        
    }
    if(minutes<1 && !_critical)
    {        
        var str="<div><input value='renovar' type='button' onclick='xajax_renew_session();_seconds="+secondsOrig+";'></div>";
        //openModal('id',str,1,'Sesión',350,200);        
        alert("Su sesión expirará en menos de un minuto.\nSe recomienda guardar sus cambios.");
        _critical=1;
    }
    else if(_seconds==0)
    {  
        _object.innerHTML='Su sesion ha expirado';
        //alert('Su sesión ha expirado!');
        //document.location.href=_url;
        return false;
    }    
    
    minutes=str_pad(minutes,2,'0','STR_PAD_LEFT');
    seconds=str_pad(seconds,2,'0','STR_PAD_LEFT');    
    _object.innerHTML='Tiempo restante de su sesion: ' + minutes + ':' + seconds;  
    _seconds--;
    return;    
} 
/*  
function windowEvent(e) {
   alert ("The window got an event of type: " + e.type);
   window.routeEvent(e);
   return true;
}
window.captureEvents(Event.CLICK);
window.onclick=windowEvent;

*/
var sendData=function(obj,eventName,func)
{
    
    var objIframe 	= getElement(obj);
    var objDocument;
    if(objIframe.contentDocument)//DOM
        objDocument = objIframe.contentDocument;
	else if(objIframe.contentWindow)//IE
        objDocument = objIframe.contentWindow.document;
    addEvent(objDocument,eventName,func);
}
var addEventIframe=function(obj,eventName,func,affectParent)
{      
    var oldQueue = window.onload ? window.onload: function() {};
    window.onload = function() {
        oldQueue();
        sendData(obj,eventName,func);   
    }         
    if(affectParent)
        addEvent(window,eventName,func);
}

var checkFlash=function(version,msg)
{
    if(!FlashDetect)
    {
        alert('Debe instalar el plugin FlashDetect!');
        return false;
    }  
    if(!FlashDetect.versionAtLeast(version))
    {	   
       if(!msg) 
            msg="Debe tener instalado el plugin Adobe Flash Player para acceder a esta función";            
       alert(msg);       
       return false;
    }
    return true;
}

var sumarCeldas=function(obj,parent)
{      
    if(!obj)
        return false;
    obj=getElement(obj);
    if(!parent)
        parent=obj.parentNode;  
    var x       =0;      
    var children=getChildren(parent,obj.tagName);
    var len     =children.length;    
    var matches =/([a-zA-Z\_0-9]+)\[(\d+)\]/.exec(obj.name);
    var text;
    var number;
    var monto=0;
    var vtotalvalue=0;
    var htotalvalue=0;
    var totalvalue=0;
    var hgroup;
    var vgroup;
    var subtext;
    var hsubgroup;
    var vsubgroup;
    var vsubtotal;
    var hsubtotal;
    var gsubtotal;   
      
    var index=false;
    if(matches)
    {
        text    =matches[1];
        index   =matches[2];        
    }
    else
        text=obj.id;
        
    //alert(obj.htotal); 
    
    hgroup=readAttribute(obj,'hgroup');
    vgroup=readAttribute(obj,'vgroup');
    vtotal=readAttribute(obj,'vtotal');
    htotal=readAttribute(obj,'htotal');
    gtotal=readAttribute(obj,'gtotal');
    
    if(!hgroup || !vgroup || !vtotal || !htotal || !gtotal)
        return false;   
    
    if(index!==false)
    {    
        hgroup=hgroup.replace('\#',index);
        vgroup=vgroup.replace('\#',index);
        vtotal=vtotal.replace('\#',index);
        htotal=htotal.replace('\#',index);
        gtotal=gtotal.replace('\#',index);
    }
    
    //alert('htotal: '+htotal);
    
    while(x<len)
    {       
        element = children[x++];
        if(element.type!==obj.type)
            continue;         
        hsubgroup=readAttribute(element,'hgroup');
        vsubgroup=readAttribute(element,'vgroup');
        vsubtotal=readAttribute(element,'vtotal');
        hsubtotal=readAttribute(element,'htotal');
        gsubtotal=readAttribute(element,'gtotal');          
        if(!hsubgroup || !vsubgroup || !vsubtotal || !hsubtotal || !gsubtotal)
            continue;
        monto   = getFloat(element.value);
        matches =/([a-zA-Z\_0-9]+)\[(\d+)\]/.exec(element.name);
        if(matches)
        {
            subtext =matches[1]; 
            number  =matches[2];            
            vsubgroup   =vsubgroup.replace('\#',number);
            hsubgroup   =hsubgroup.replace('\#',number);
            vsubtotal   =vsubtotal.replace('\#',number);
            hsubtotal   =hsubtotal.replace('\#',number);
            gsubtotal   =gsubtotal.replace('\#',number);
        }
        
        if(vsubgroup===vgroup)
             vtotalvalue+=monto;
        if(hsubgroup===hgroup)
             htotalvalue+=monto;
        totalvalue+=monto;
        monto=0;
    }

	if(htotal)
        asignaValor(htotal,htotalvalue,2);
    if(vtotal)
        asignaValor(vtotal,vtotalvalue,2);
    if(gtotal)
        asignaValor(gtotal,totalvalue,2);   
}

var asignaValor=function(obj,value,decimals)
{
    if(decimals==null)
    {
        decimals=2;
        
    }
    obj  =getElement(obj); 
    if(!obj)
        return false;
    if('value' in obj)
        obj.value=value.toFixed(decimals);
    else
        obj.innerHTML=value.toFixed(decimals);
        
}

/* ****************************************************/

function __buildURL(actualURL,elements)
{
    var values=getValues(elements);
    var url=values.join('&');
    var separator = (actualURL.indexOf('?')!==false ? '&' : '?');
    url=actualURL+ separator + url;
    return url;        
}
function __getValues(elements)
{
    if(elements.constructor!==Array)
        return [elements + '=' + getValue(elements)];
    var len=elements.length;
    var x=0,y=0;        
    var element;
    var values=[];
    var value;    
    var id;
    while(x<len)
    {           
        id=elements[x++];
        value=getValue(id);
        if(value!==false)
            values[y++]=id + "=" + value;
    }
    return values;
}
function __getValue(id)
{
    var element;
    if(element=document.getElementById(id))
        if(element.tagName=='INPUT' || element.tagName=='TEXTAREA')
            return element.value;
     return false;
}


var typewatch = function(){
    var timer = 0;
    return function(callback, ms){
        clearTimeout (timer);
        timer = setTimeout(callback, ms);
    }  
}();


var getElementValue=function(obj)
{
	var obj	= getElement(obj);
	if(!obj)
		return false;
    if(obj.type)
        mValue	= obj.value;
    else
	   mValue	= obj.innerHTML;    
    return mValue;
}
var buscar=function()
{     
    var valor;
    var obj;
    var args='';
    var cfg=arguments[0];
    var delay=cfg['delay'];
    var xajax_func=cfg['func'];
    delete cfg['func'];        
    delete cfg['delay'];    
    for(var x=1;x<arguments.length;x++)
    {        
        obj=getElement(arguments[x]);
        valor=arguments[x];
        if(!obj)       
            args+='"' + valor + '" : "' + arguments[x] + '",';  
        else
            args+='"' + valor + '" : "' + getElementValue(obj) + '",';      
    }    
    args=args.substr(0,args.length-1);
    var func=function(){ eval( xajax_func + "(cfg,{" + args + "});"); };
    typewatch(func,delay);
}


function copy_to_clipboard(text)  
  {  
      if(window.clipboardData)  
      {  
      window.clipboardData.setData('text',text);  
      }  
      else  
      {  
          var clipboarddiv=document.getElementById('divclipboardswf');  
      if(clipboarddiv==null)  
      {  
         clipboarddiv=document.createElement('div');  
             clipboarddiv.setAttribute("name", "divclipboardswf");  
         clipboarddiv.setAttribute("id", "divclipboardswf");  
         document.body.appendChild(clipboarddiv);  
      }  
          clipboarddiv.innerHTML='<embed src="clipboard.swf" FlashVars="clipboard='+  
  encodeURIComponent(text)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';  
      }  
      //alert('The text is copied to your clipboard...');  
      return false;  
  }  
var validateForm=function(obj)
{
    var error=true;
    var tmp;
    var form={};
    if(!jQuery)
        return false;
    $(obj).find('input[type!="button"],input[type!="hidden"],select,textarea').each(function()
    {                
        var el=$(this);
        var val=el.val();
        var type=el.attr('dtype');
        var name=el.attr('name');
        form[name]=val;
        tmp=true;
        if(!val)
        {
            if(el.attr('mandatory')!== undefined)
                tmp=false;
        }
        else
        {                
            switch(type)
            {
                case 'email':
                    if(!checkMail(val))
                        tmp=false;
                break;
                case 'number':
                    if(!checkInteger(val))
                        tmp=false;
                break;
                case 'document':
                    if(!checkDocument(val))
                        tmp=false;
                break;
                default:
                    if(!checkText(val))
                        tmp=false;                        
                break;                
            }
        }
        if(!tmp)
        {
            el.addClass('error');
            error=false;
        }
        else
            el.removeClass('error');
    });
    if(!error)
        return false;
    return form;
}

function getEvent()
{
    var event = e || window.event;
    var target = event.target || event.srcElement;
    return target;
}
function cleanText(texto)
  {
          texto=texto.replace(/\.+/,'');
          texto=texto.replace(/\u00e1/,'A');
          texto=texto.replace(/\u00e9/,'E');
          texto=texto.replace(/\u00ed/,'I');         
          texto=texto.replace(/\u00f3/,'O');
          texto=texto.replace(/\u00fa/,'U');
          texto=texto.replace(/\u00c1/,'A');
          texto=texto.replace(/\u00c9/,'E');
          texto=texto.replace(/\u00cd/,'I');
          texto=texto.replace(/\u00d3/,'O');
          texto=texto.replace(/\u00da/,'U');
          texto=texto.replace(/\u00f1/,'N');
          texto=texto.replace(/\u00d1/,'N');
          texto=texto.toUpperCase(); 
          return texto;
  }
var dialog=function(title,html,config){var id,dialog;if(config)id=config.id?config.id:'modal';else id='modal';if(!$[id]){var modal=$("#"+id);if(!modal.length){modal=$('<div id="'+id+'" class="modal"><div></div></div>');$('body').append(modal);}modal.dialog({autoOpen: false});$[id]=modal;}$[id].dialog("option","title",title?title:'').dialog("option","position",config.position!==undefined?config.position:'center').dialog("option","buttons",config.buttons!==undefined?config.buttons:{Cerrar:function(){$(this).dialog('close');}}).dialog("option","hide",config.hide!==undefined?config.hide:'fade').dialog("option","show",config.show!==undefined?config.show:'fade').dialog("option","draggable",config.draggable!==undefined?config.draggable:false).dialog("option","resizable",config.resizable!==undefined?config.resizable:false).dialog("option","modal",config.modal!==undefined?config.modal:true).dialog("option","height",config.height!==undefined?config.height:300).dialog("option","width",config.width!==undefined?config.width:500).dialog("open");var div=$[id].children('div');div.html(html?html:'');if(config.autosize!==undefined){$[id].dialog("option","height",div.height()+100);$[id].dialog("option","width",div.width()+50);$[id].dialog("option","position",config.position!==undefined?config.position:'center');}if(config.refobj!==undefined){var p=$(config.refobj).offset();var left=p.left,top=p.top;left=div.width()>left?left:p.left-(div.width()-50);$[id].dialog("option","position",[left,top-div.height()]);}if(config.autoclose!==undefined)setTimeout(function(){$[id].dialog('close');},config.autoclose);};  

var makeGridIcon=function(grid,alias,url,icon,dclass)
{

	var id,bt,grid=$(grid); 
    var ids = grid.jqGrid('getDataIDs');
    for(e in ids)
    {
        id=ids[e];
        if(typeof id=='function')
            continue;
        bt='<div class="'+dclass+'"><a href="'+url+'?id='+id+'"><img src="'+icon+'"/></a></div>';                  
        grid.jqGrid('setRowData',id,{alias:bt});
    }
    
 };  

//if(typeof $=='undefined'&&currentBrowser!=='Explorer')
  // var $=getElement;  

  function pausecomp(millis)
{
var date = new Date();
var curDate = null;

do { curDate = new Date(); }
while(curDate-date < millis);
} 
