function ShowModalSignedDialog(signedURL)
{
	var retvalue;
	retvalue = window.showModalDialog(signedURL, window, "dialogHeight: 500px; dialogWidth: 800px; edge: Raised; center: Yes; help: No; resizable: Yes; status: Yes; ");
	
	// two or more values
	if (retvalue && retvalue.length>=2)
	{
		document.forms[0].txtBrwSel.value = retvalue[1];
		document.forms[0].__EVENTTARGET.value="";
		document.forms[0].submit();
	}
	// only one value
	else if ((retvalue!=null) && (retvalue[0] != "") && (retvalue[0] != "undefined"))
	{
		document.forms[0].txtBrwSel.value = retvalue[0];
		document.forms[0].__EVENTTARGET.value="";
		document.forms[0].submit();
	}
}

function GetById(id)
{
	return document.getElementById(id);
}

function GetByName(name)
{
	return document.getElementByName(name);
}

function GetByTag(id, tag)
{
	if(IsEmpty(id)) return document.getElementsByTagName(tag);
	return GetById(id).getElementsByTagName(tag);	
}

function GetValue(id)
{
	var o = GetById(id);
	if(IsNull(o)) return null;
	return o.value;
}

function GetText(id)
{
	var o = GetById(id);
	if(IsNull(o)) return null;
	return GetById(id).innerText;
}

function GetHTML(id)
{
	var o = GetById(id);
	if(IsNull(o)) return null;
	return GetById(id).innerText;
}

function SetValue(id, value)
{
	var o = GetById(id);
	if(!IsNull(o)) GetById(id).value = value;
}

function SetImg(id, src)
{
	var oImg = GetById(id);
	if(!IsNull(oImg)) oImg.src = src;
}

function SetText(id, text)
{
	var o = GetById(id);	
	if(!IsNull(o)) GetById(id).innerText = text;
}

function SetHTML(id, html)
{
	var o = GetById(id);
	if(!IsNull(o)) GetById(id).innerHTML = html;
}

function IsNull(obj)
{
	return (typeof(obj) == "undefined") || (obj == null);
}

function IsEmpty(val)
{
	return (val == null) || (val == "");
}

function IsNotEmpty(val)
{
	return (val != null) && (val != "");
}

function Show(id)
{
	var o = GetById(id);
	if(!IsNull(o)) o.style.display = '';
}

function Hide(id)
{
	var o = GetById(id);
	if(!IsNull(o)) o.style.display = 'none';
}

function Enable(id)
{
	var o = GetById(id);
	if(!IsNull(o)) o.disabled = false;
}

function Disable(id)
{
	var o = GetById(id);
	if(!IsNull(o)) o.disabled = true;
}

function Switch(id)
{
	var o = GetById(id);
	if(IsNull(o)) return;
  if(o.style.display == 'none') o.style.display = '';
  else o.style.display = 'none';
}

function IsVisible(id)
{
	var o = GetById(id);
	return (o.style.display != "none") && (o.style.visibility != "hidden");
}

// Desactivar una alerta.
function SubmitByParam(paramId, paramValue, message)
{	
	if(!confirm(message)) return;
	var sUrl = location.href.toLowerCase();
	sUrl = sUrl.replace("#", "");
	var sParam = paramId + "=" + paramValue;
	if(sUrl.indexOf("?") < 0) sUrl += "?" + sParam;
	else
	{
		var iPos = sUrl.indexOf(paramId);
		if(iPos < 0) sUrl += "&" + sParam;
		else
		{
			var iEnd = sUrl.indexOf("&", iPos);			
			var sAux = sUrl.substring(0, iPos) + sParam;
			if(iEnd >= 0)
				sUrl = sAux + sUrl.substring(iEnd, sUrl.length);
			else sUrl = sAux;
		}
	}
	
	location.replace(sUrl);
}function getURLParam(strParamName){
	var strReturn = "";
	var strHref = window.location.href;
	if ( strHref.indexOf("?") > -1 ){
		var strQueryString = strHref.substr(strHref.indexOf("?"));
		var aQueryString = strQueryString.split("&");
		for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
			if( 
				aQueryString[iParam].indexOf(strParamName + "=") > -1 ){
				var aParam = aQueryString[iParam].split("=");
				strReturn = aParam[1];
				break;
			}
		}
	}
	return unescape(strReturn);
}

function pnlDesplegar(control)
{
  var oControl=document.getElementById(control);
  if (oControl.style.display == 'none')
     {oControl.style.display = '';}
  else   
     {oControl.style.display = 'none';}
}

//Comportamientos ( si hay mootools)
if  (typeof MooTools != 'undefined')
{

window.addEvent('load',function()
{
	// Para ejecutar los paneles contraibles.
	$$('.CollapsiblePanel').each(function(obj)
	{
		// Se obtinen los controles a traves de las clases PanelToHide y PanelManager
		var myElements = obj.getElements('.PanelToHide');
		var panel = myElements[0];
		myElements = obj.getElements('.PanelManager');
		var PanelManager = myElements[0];

        // Se declara el efecto slide a ejecutar.
        var efecto = new Fx.Slide(panel, {duration:300, wait:false })
		// Si los elementos anteriores tienen float el wrapper generado por el slide debe 'limpiar' los float. 
		panel.getParent().setStyle('clear', 'both');
		//Si en vez de Collapse tiene la clase Expanda se esconde el panel.
		if (PanelManager.hasClass('Expand')==true)
		    efecto.hide();
        
        // Para que el efecto sea accesible desde cualquier punto a traves la propiedad efecto del Panel.
        PanelManager.efecto = efecto;
        
        // Se registra el evento que dispara el 'slide' al clicar en el PanelManager
    	PanelManager.addEvent('click',function()
    	{
    	    efecto.toggle(); 
    	    if (PanelManager.hasClass('PanelManagerIcon') == true)
    	    {
	            PanelManager.toggleClass('Collapse');
	            PanelManager.toggleClass('Expand');    	
    	    }
    	});
	});
	
	// Para ejecutar las tablas con enlaces.
	$$('a[href].MasterRowLink').each(function(obj)
	{
		// Se obtine el atributo con el link
		var oHref = obj.getProperty('href');
		var oTitle = obj.getProperty('Title');
		var oAlt = obj.getProperty('Alt');
		var oTarget = obj.getProperty('target');
		
		// Se obtiene la fila o tbody(conjunto de filas) a las que hay que aplicar el link
		var oFila = obj.getParent().getParent(); // TR
		var oParentFila = oFila.getParent(); // TBODY?
		// Si se trata de un conjunto de filas se usa el tbody
		if (oParentFila.hasClass('DoubleRow')) 
		    oFila = oParentFila;
    	
    	// Si la fila no esta inactiva:
    	if (!oFila.hasClass('InActive')) 
    	{
    	    // Se atacha el evento onclick en la fila correspondiente.
            if (oTarget == '_blank')  	
            {
    	        oFila.addEvent('click',function()
    	        {
                    var newWindow = window.open(oHref, '_blank');
                    newWindow.focus();
                    return false;
    	        });
    	    }
            else
    	        oFila.addEvent('click',function()
    	        {
    	            location.href = oHref;
    	        });
    	    oFila.setProperty('Title',oTitle);
    	    oFila.setProperty('Alt',oAlt);
    	    // Se Marca como link:
    	    oFila.addClass('Selectable');
            // Se elimina el anchor (a)
		    //obj.dispose();
    	}
	});
	
	// Para ejecutar las tablas con un enlace de detalle al principio y uno especial al final (como el de seguimiento de 
	// autoliquidaciones cuando se puede pagar,o el buzón de documentos.
	$$('a[href].MasterRowLinkPartial').each(function(obj)
	{
		// Se obtine el atributo con el link
		var oHref = obj.getProperty('href');
		var oTitle = obj.getProperty('Title');
		var oAlt = obj.getProperty('Alt');
		var oTarget = obj.getProperty('target');
		
		// Para cada una de las celdas iremos comprobando 
		var oCelda = obj.getParent(); // TD
		
    	// Se obtiene la fila o tbody(conjunto de filas) a las que hay que aplicar el link
		var oFila = oCelda.getParent().getParent(); // TBody
		// Para cada una de las filas miramos los tds y ponemos el href a todos menos en el caso que el TD sea enlace		
		var oChildren = oFila.getChildren(); //Aquí tenemos los tds de la primera fila
		
		//for every row... 
        oChildren.each(function(tr,trCount)
        { 
              //for every cell... 
              var oTds = tr.getChildren();
              oTds.each(function(td,tdCount) 
              { 
                // Si la fila no esta inactiva:
    	        if (!oFila.hasClass('InActive') &&  !td.hasClass('LastRow')) 
    	        {
    	            // Se atacha el evento onclick a la celda correspondiente.
                    if (oTarget == '_blank')  	
                    {
    	                td.addEvent('click',function()
    	                {
                            var newWindow = window.open(oHref, '_blank');
                            newWindow.focus();
                            return false;
    	                });
    	            }
                    else
    	                td.addEvent('click',function()
    	                {
    	                    location.href = oHref;
    	                });
    	            td.setProperty('Title',oTitle);
    	            td.setProperty('Alt',oAlt);
    	            // Se Marca como link:
    	            td.addClass('Selectable');
    	        }                
              }); 
        });  
	});
	
	// Para ejecutar las tablas con un enlace de detalle al principio y uno especial al final (como el de seguimiento de 
	// autoliquidaciones cuando se puede pagar,o el buzón de documentos.
	$$('a[href].MasterRowLinkPartialLast').each(function(obj)
	{
		// Se obtine el atributo con el link
		var oHref = obj.getProperty('href');
		var oTitle = obj.getProperty('Title');
		var oAlt = obj.getProperty('Alt');
		var oTarget = obj.getProperty('target');
		
		// Para cada una de las celdas iremos comprobando 
		var oCelda = obj.getParent(); // TD
		
    	// Se obtiene la fila o tbody(conjunto de filas) a las que hay que aplicar el link
		var oFila = oCelda.getParent().getParent(); // TBody
		
        // Si la fila no esta inactiva:
        if (!oFila.hasClass('InActive') &&  oCelda.hasClass('LastRow')) 
        {
            // Se atacha el evento onclick a la celda correspondiente.
            if (oTarget == '_blank')  	
            {
                oCelda.addEvent('click',function()
                {
                    var newWindow = window.open(oHref, '_blank');
                    newWindow.focus();
                    return false;
                });
            }
            else
                oCelda.addEvent('click',function()
                {
                    location.href = oHref;
                });
            oCelda.setProperty('Title',oTitle);
            oCelda.setProperty('Alt',oAlt);
            // Se Marca como link:
            oCelda.addClass('Selectable');
        }                
     });          
});	


function RemoveAccentsToLowerCase(texto)
{
	texto = texto.toLowerCase()
	texto = texto.replace(/[àáâä]/gi,'a');
	texto = texto.replace(/[èéêë]/gi,'e');
	texto = texto.replace(/[ìíîï]/gi,'i');
	texto = texto.replace(/[òóôö]/gi,'o');
	texto = texto.replace(/[ùúûü]/gi,'u');
	//texto = texto.replace(/[ñ]/gi,'n');
	texto = texto.replace(/['"`]/gi,' ');
	return texto;
};


if(!window.DG){
	window.DG = {};
}

DG.Filter = new Class({
	Extends : Events,
	xPathFilterElements : false,	/** Css class for text elements to be indexed */
	html :  {
		filterField : null,	/** Reference to text field */
		filterEl : null	,	/** Reference to element to be filtered */
		filterGroups : null /** Reference to the  select element for groups filtering **/
	},
	searchIndex : null,
	groupIndex : null,
	onMatchShowChildren : false,
	idCounter : 0,
	matchedNodes : null,			/** Temporary array of matched nodes */
	txtNoMatchFound : '',			/** No matches found text */
	txtAllGroups : '',			/** Todos los grupos */

	/**
	 * Constructor
	 * @param {Object} config
	 */
	initialize : function(config) {
		this.html.filterField = $(config.filterField);
		this.html.filterEl = $(config.filterEl);
		this.html.filterGroups = $(config.filterGroups);
		this.xPathFilterElements = config.xPathFilterElements;
		this.onMatchShowChildren = config.onMatchShowChildren;
		this.txtNoMatchFound = config.txtNoMatchFound || 'No matches found';
		this.txtAllGroups = config.txtAllGroups || '< Todas las Solicitudes >';
		this.listeners = config.listeners || null;
		this.addFilterEvents();
		this.createSearchIndex();
		this._createNoMatchFoundElement();
	},

	_setNewNodeId : function(node) {
		node.setProperty('id', 'dgfilter' + this.idCounter);
		this.idCounter++;

	},
	_setParent : function(group)
	{		
		for (var i = 0; i < this.groupIndex.length; i++)
		{
			if (this.groupIndex[i].objetoDOM == group)
				return i;
		}	
	},	
	_resetGroupsVisibilityForChilds: function()
	{		
		for (var i = 0; i < this.groupIndex.length; i++)
			this.groupIndex[i].hasVisibleChilds = false;
	},		
	_SetGroupsVisibility: function()
	{		
		var matchesFound = false;
	
		for (var i = 0; i < this.groupIndex.length; i++)
			if (this.groupIndex[i].hasVisibleChilds && this.groupIndex[i].show)
			{
				matchesFound = true;			
				this.groupIndex[i].objetoDOM.setStyle('display', '');
			}
			else
				this.groupIndex[i].objetoDOM.setStyle('display', 'none');
								
		if(!matchesFound) {
			this._showNoMatchFoundElement();
		}else{
			this._hideNoMatchFoundText();
		}				
	},		
	/**
	 * Create search index - makes the search work faster
	 */
	createSearchIndex : function()
	{
		//Create Groups
		var groups = this.html.filterEl.getElements('.EntitiesGroup');	
		this.groupIndex = [];

		for(var i=0; i< groups.length; i++)
		{
			this.groupIndex.push({
				objetoDOM : groups[i],
				hasVisibleChilds : true,
				show : true
			});

			// Fill de select element with the groups
			this.html.filterGroups.options[0] = new Option(this.txtAllGroups, -1);
			this.html.filterGroups.options[0].selected  = true;
			var textElement = groups[i].getElement('.TitleBar span');
			this.html.filterGroups.options[this.html.filterGroups.length] = new Option(textElement.innerHTML, i);		
		}
		
		//Create elements
		var elements = this.html.filterEl.getElements('tr');	
		var textProperty = document.body.innerText ? 'innerText' : 'textContent';

		this.searchIndex = [];
		
		for(var i=0; i< elements.length; i++) {
			if (!elements[i].get('id'))
				this._setNewNodeId(elements[i]);
			
			var textContent = '';
			var firstParent = null;
			if (this.xPathFilterElements)
			{
				var textElements = elements[i].getElements(this.xPathFilterElements);
				for(var j=0;j<textElements.length;j++)
					textContent = textContent + textElements[j][textProperty];
			}
			this.searchIndex.push({
				itemText : RemoveAccentsToLowerCase(textContent),
				branchText : RemoveAccentsToLowerCase(elements[i][textProperty]),
				el : elements[i],
				parentEl : this._setParent(elements[i].getParent('.EntitiesGroup'))
			});
		}
	},

	addFilterEvents : function() {
	    
	    if(this.html.filterField!= null)
	    {
		    this.html.filterField.addEvent('keyup', this.filter.bind(this));
		    this.html.filterField.addEvent('paste', this.filter.bind(this));
		    this.html.filterGroups.addEvent('change', this.setGroupFilter.bind(this));
		    this.addEvents(this.listeners);
		}
	},

	_showNode : function(node) {
		node.el.setStyle('display', '');

	},
	_hideNode : function(node) {
		node.el.setStyle('display', 'none');
	},

	setGroupFilter : function()
	{
		var indexGroupSelected = this.html.filterGroups.options[this.html.filterGroups.selectedIndex].value
		for(var i=0; i< this.groupIndex.length; i++)
			this.groupIndex[i].show = (indexGroupSelected == -1 || indexGroupSelected == i);

		this._SetGroupsVisibility();
		
		// Throw event that a group has been selected
		if (indexGroupSelected != -1)
			this.fireEvent('setGroupFilter', this.groupIndex[indexGroupSelected].objetoDOM);		
	},
	
	filter : function() {
		this.fireEvent('beforefilter', this);
		
		this._resetGroupsVisibilityForChilds();
		
		this.matchedNodes = {};
		if(!this.searchIndex) {
			this.createSearchIndex();
		}
		var searchPhrase = RemoveAccentsToLowerCase(this.html.filterField.get('value'));
		this.filterTable(searchPhrase);

		this._SetGroupsVisibility();
		
		this.fireEvent('afterfilter', this);
	},

	_matchAbove : function(node) {
		return this.matchedNodes[node.el.id];
	},

	_nodeMatch : function(indexNode, searchPhrase) {
		return indexNode.branchText.indexOf(searchPhrase) >=0;
	},

	_getIdOfNoMatchFoundElement : function() {
		return this.html.filterEl.id + 'noMatchFound';
	},
	_hideNoMatchFoundText : function() {
		var el = $(this._getIdOfNoMatchFoundElement());
		if(el) {
			el.setStyle('display', 'none');
		}
	},

	_showNoMatchFoundElement : function() {
		var el = $(this._getIdOfNoMatchFoundElement());
		if(el) {
			el.setStyle('display', '');
		}
	},
	_createNoMatchFoundElement : function() {
		var el = new Element('p');
		el.id = this._getIdOfNoMatchFoundElement();
		el.inject(this.html.filterEl, 'after');
		el.set('html', this.txtNoMatchFound);
		el.setStyle('display','none')
	},

	filterTable : function(searchPhrase) {
		for (var i = 0; i < this.searchIndex.length; i++) {
			if(this._nodeMatch(this.searchIndex[i], searchPhrase)) {
				var parentGroup = this.groupIndex[this.searchIndex[i].parentEl];
				
				// Set the parent group that have visible childs
				this.groupIndex[this.searchIndex[i].parentEl].hasVisibleChilds = true;
				
				this._showNode(this.searchIndex[i]);
			}else{
				this._hideNode(this.searchIndex[i]);
			}
		}
	}
});


}
