var MaxAlerts = 1;
var CurrentAlerts = 1;



function HideAllSelects() {
	var sel = document.getElementsByTagName("SELECT");
	
	
	for ( var n = 0; n < sel.length; n++ ) {
		sel[n].style.visibility = "hidden";
	}
}

function ShowAllSelects() {
	var sel = document.getElementsByTagName("SELECT");
	
	if ( CurrentAlerts == 0 ) {
		for ( var n = 0; n < sel.length; n++ ) {
			sel[n].style.visibility = "visible";
		}
	}
}


function SuperAlert( mes ) {

	setError( "<h1>Error</h1>" + mes );
}

/* 
	This function puts values on selects
*/


function PutValuesInSelects() {
	var sels = document.getElementsByTagName("select");
	
	for ( var n = 0 ; n < sels.length; n++ ) 
	{
		var sel = sels[n];
		
		if ( sel.getAttribute("selected_value") != null ) 
		{ 
			sel.value = sel.getAttribute("selected_value");
		}
	}
}

window.OldAlert = window.alert;
window.alertHandle = null;

function AlertHack()
{
	
    window.alert = function ( str, type, call_back, field  ) 
	{
		$('error-content').innerHTML = str;
		$('error-content').setStyle('display', 'block' );
		$('error-content').setStyle('border','1px solid red');
		$('error-content').setStyle('padding','15px');
		$('error-content').setStyle('position','absolute');
		
		$('error-content').setStyle('margin-top','100px');
		$('error-content').setStyle('margin-left','50px');
		$('error-content').setStyle('width','400px');
		$('error-content').setStyle('backgroundColor','white');
 		
		window.alertHandle = setTimeout("clearAlerts()","5000");
    }

}


function clearAlerts()
{
	$('error-content').setStyle('display','none');
}

/* Overloading of the window.alert function */

AlertHack();
    

function fieldValidate( field ) {

    if ( field.getAttribute("required") == "true" ) {
    
        if ( field.value.length == 0 ) {
             addFormMessage( field.form, field.getAttribute("label") + " es un campo requerido!", field );
            return false;
        }
    }
	
	if ( (field.getAttribute("field_type") == "currency") || (field.getAttribute("field_type") == "numeric")) {

		var n = parseFloat( field.value );
		
		if ( !isNaN( n ) ) {
			field.value = n;
		}
		
		if ( isNaN(field.value) ) {
			addFormMessage( field.form, field.getAttribute("label") + " no es un valor numerico!" );
			return false;
		}
	}
    
	
    return true;
}
/*
var assistantTimeout = null;

var modalAssistant = null;



function setHelp( message ) {

	if ( window.modalAssistant == null ) {
	
		clearTimeout( window.assistantTimeout );
		
		document.getElementById("help_container").innerHTML = message;
		document.getElementById("help_panel1").style.marginTop = document.documentElement.scrollTop + "px";
		document.getElementById("help_panel1").style.display = 'block';
		document.getElementById("help_panel1").className = 'ImageInformation';
	}
	
}


function setError( message ) {
	clearTimeout( window.assistantTimeout );
	
	document.getElementById("help_container").innerHTML = message;
	document.getElementById("help_panel1").style.marginTop = document.documentElement.scrollTop + "px";
	document.getElementById("help_panel1").style.display = 'block';
	document.getElementById("help_panel1").className = 'ImageError';
}


var lockedRow = null;

function setConfirm( element, message ) {
	clearTimeout( window.assistantTimeout );
	
	var yes = "<input type='button' value='"+ window.CentrixMessages.yes +"' onclick=\"window.location = '"+ element.href +"'\">";
	var no = "<input type='button' value='"+ window.CentrixMessages.no +"' onclick=\"fadeAssistant();\">";
	
	lockedRow = element.parentNode.parentNode.parentNode;
	lockedRow.setAttribute("locked","true");
	lockedRow.className = "tr-locked";

	document.getElementById("help_container").innerHTML = "<center>" + message + "<br><br>" + yes + "&nbsp;" + no + "</center>";
	document.getElementById("help_panel1").style.marginTop = document.documentElement.scrollTop + "px";
	document.getElementById("help_panel1").style.display = 'block';
	document.getElementById("help_panel1").className = 'ImageConfirm';
	
	window.modalAssistant = 1;
	
	return false;
}



function clearLockedRows() {
	if ( window.lockedRow != null ) {
		lockedRow.setAttribute("locked","false");
		lockedRow.className = "";
		lockedRow = null;
	}
}



function fadeAssistant () {
	document.getElementById("help_panel1").style.display = 'none';
	
	if ( window.modalAssistant != null ) {
		window.modalAssistant = null;
		
		clearLockedRows();
	}
}

function clearHelp() {
	clearTimeout( window.assistantTimeout );
	//window.assistantTimeout = setTimeout("fadeAssistant()", 2000 );
	//document.getElementById("help_panel1").style.display = 'none';
}
*/

function addFormMessage( form, message, field) {

    if ( form.ValidatorMessage == null ) {
        form.ValidatorMessage = new Array();
    }
    
    form.ValidatorMessage[ form.ValidatorMessage.length ] = { message : message, field : field };
}



function FormValidationHack() {

    var forms = document.getElementsByTagName("FORM");
    
    
    for ( var n = 0; n < forms.length; n++ ) {
			
		  if( forms[n].onsubmit != null ){
		  	forms[n].old_onsubmit = forms[n].onsubmit;
		  }
		  
        forms[n].onsubmit = function () {
        
            this.ValidatorMessage = new Array();
            
			if ( this.save_action == 1 ) {
			
				this.save_action = 0;
				for ( var n = 0; n < this.elements.length; n++ ) {
					if ( fieldValidate( this.elements[n] ) == false ) {
					
						alert( this.ValidatorMessage[0].message, null, null,  this.ValidatorMessage[0].field );
						return false;
					} 
				}
			} else {
				this.save_action = 0;
			}

							
			if ( this._validation_row_required == 1 ) {
			
				this._validation_row_required = 0;
				
				var sel = false;
				
				// si hay records verificar si hay alguno seleccionado
				if ( this.row ) {
				
					var n = 0;
					
					if ( this.row.length ) {
						len = this.row.length;
						for ( n = 0; n < len;  n++) {
							if ( this.row.item(n).checked ) 
								sel = true;
						}
						
					} else {
						sel = this.row.checked;
					}		
				}
				
				if ( sel == false ) {
					alert("Debe seleccionar una linea primero");
					return false;
				}
				

			} else {
				this._validation_row_required = 0;
			}
			

			if ( this.getAttribute("retain_scroll") == "true" ) {
			
				// X Offset				
				
				if ( this.scrollx == null ) {
					var ref = document.createElement("INPUT");
					
					ref.setAttribute("type","hidden");
					ref.setAttribute("name","scrollx");
					
					this.appendChild( ref );
				} 
	
				
				if (window.pageXOffset) {
					ref.value = window.pageXOffset
				} else if (document.documentElement && document.documentElement.scrollLeft ) {
					ref.value = document.documentElement.scrollLeft;
				} else if (document.body) {
					ref.value = document.body.scrollLeft;
				}

				
				setCookie( "scrollx" , ref.value, new Date('01/01/2099')); 	
				
				
				// Y Offset				
				
				if ( this.scrolly == null ) {
					var ref = document.createElement("INPUT");
					
					ref.setAttribute("type","hidden");
					ref.setAttribute("name","scrolly");
					
					this.appendChild( ref );
				} 
				
				if (window.pageYOffset) {
					ref.value = window.pageYOffset
				} else if (document.documentElement && document.documentElement.scrollTop ) {
					ref.value = document.documentElement.scrollTop;
				} else if (document.body) {
					ref.value = document.body.scrollTop;
				}
				
				setCookie( "scrolly" , ref.value, new Date('01/01/2099')); 	
				
		
				
			}
				var ret = true;
				try {
					ret = this.old_onsubmit() ;
				}
				catch(ex){
					
				}
            return ret;
        }
    }
}

	
	/*
	var requiredColor = "#FBEF6C";
	var unfilledColor = "#FBEF6C";
	
	requiredColor = "#FFEB86";
	unfilledColor = "#FFEB86";
	*/

	
	function FormFieldRequiredHack() 
	{
	
	//     var inputs = document.getElementsByTagName("INPUT");
		
		var inputs = $$('input');
		
		setRequired = function ( bool ) 
		{
			if ( bool == true ) {
/*				this.style.backgroundColor = requiredColor;*/
				this.setAttribute( "required", "true" );
			} else {
/*				this.style.backgroundColor = "";*/
				this.setAttribute( "required", "false" );			
			}
		}
		
		// cycle through all the fields on the form
		
		for ( var n = 0; n < inputs.length; n++ ) 
		{
			var el = $(inputs[n]);
			
// 			if ( el.getProperty('type') == 'text' || el.getProperty('type') == 'password' )
// 			{
// 				el.setStyle('border','1px solid #AAB9CE' );
// 				el.setStyle('padding','3px' );
// 				el.setStyle('backgroundColor', '#FFFFFF' );
// 				
// 				if ( el.readOnly == true )
// 				{
// 					el.setStyle('background-color', '#EDEDED' );
// 				}
// 			}
			
			
			el.setRequired = setRequired;
			
// 			if ( el.getAttribute("required") == "true" ) 
// 			{
// 				el.setStyle('background-color', requiredColor );
// 			}
			
	
					
			// Append Calendar to date fields
			if ( inputs[n].getAttribute("field_type") == "date" ) {
				
	
				var but = document.createElement("img");
	
				but.setAttribute("src","templates/colegiocpa.com/sodalis/nice_theme/icons/PNG/16x16/Calendar.png");
				but.style.verticalAlign = "top";
				
				but.style.margin = "0px";
				but.style.padding = "0px";
				but.style.paddingLeft = "5px";
				but.style.cursor = "pointer";
				
				
				
	// 			but.setAttribute("value","...");
				
				but.setAttribute("id", "date_trigger_" + inputs[n].getAttribute("name") );
	
				var par = inputs[n].parentNode;
				var nextObj = inputs[n].nextSibling;
							
				if ( nextObj ) 
				{
					par.insertBefore(  but, nextObj );
				}
				else
				{
					par.appendChild( but );
				}
				
				// requires jscalendar
				try 
				{
					Calendar.setup({ inputField : inputs[n], button : "date_trigger_" + inputs[n].getAttribute("name"), ifFormat : "%Y-%m-%d", showsTime : false , singleClick : true, step : 1 });
				} catch (ex) {
				}
			}
			
	
		}
		
		
	}
	

	
	function startLoading( calling_element )
	{
 		$(document.body).setStyle('cursor','wait' );
		$('loading-img').setStyle('display','block');
		try { calling_element.setStyle('cursor','wait') } catch (shtf) {}
	}
	
	function stopLoading( calling_element )
	{
		$(document.body).setStyle('cursor','default' );
		$('loading-img').setStyle('display','none');
		try { calling_element.setStyle('cursor','pointer') } catch (shtf) {}
	}
	
	



	
	function leaving_site()
	{
		return confirm("Usted se esta dirigiendo hacia un sitio web externo. Desea proseguir?");
	}

	
	
	function refreshDomExtensions( DomParentElement )
	{
	

		$ES('.CheckRadioButton', DomParentElement).each( function(el)
		{ 
			if ( el.checked == true )
			{
				$ES('.CheckRadioButton').each( function ( checkEl )
				{
					if ( el != checkEl && el.getProperty('c:group') == checkEl.getProperty('c:group') )
					{
						checkEl.checked = false;
					}
				});
			}
			
			
			el.addEvent('click', function ( ev )
			{ 
				
				var event = new Event(ev);
				
				var currentElement = this;
				var group = this.getProperty('c:group');
				  
// 				if ( this.checked == false ) { this.checked = true; event.stop(); } 
 				$ES('.CheckRadioButton').each( function ( el2 )
				{
					if ( currentElement != el2 && el2.getProperty('c:group') == group )
					{
						if ( el2.checked == true )
						{
							el2.fireEvent('change');
							el2.checked = false;   
						}
					}
				}); 
 			});
		});	
	
		$ES('.Focused', DomParentElement).each( function ( element )
		{
			element.focus();
		});
			
		$ES('.AjaxFormButton', DomParentElement).each( function(el)
		{
		});
	
		$ES('.AjaxMultiSelectAdd', DomParentElement).each( function (el) 
		{
			el.removeEvents();
			el.addEvent('click', function( ev )
			{
				list = $(el.getProperty('list_id'));
				list.removeClass('NonEditing');
				list.addClass('Editing');
			});
		});
		
		$ES('.AjaxMultiSelectSave', DomParentElement).each( function (el) 
		{
			el.removeEvents();
			el.addEvent('click', function( ev )
			{
				list = $(el.getProperty('list_id'));
				list.removeClass('Editing');
				list.addClass('NonEditing');
			});
		});
		
		$ES('.AjaxMultiSelectListItem', DomParentElement).each( function (el) 
		{
			el.removeEvents();
			el.addEvent('click', function( ev )
			{
				if ( this.getParent().hasClass('Editing') )
				{
					if ( this.getProperty('c:check') == 'on' )
					{
						this.removeClass('On');
						this.addClass('Off');
						this.setProperty('c:check','off');				
					}
					else
					{
						this.removeClass('Off');
						this.addClass('On');
						this.setProperty('c:check','on');				
					}
					
					this.getParent().syncList();
				}
			});
		});
		
		$ES('.AjaxMultiSelect', DomParentElement).each( function (el) 
		{
			el.syncList = function ( )
			{
				var internal = $(this.getProperty('internal_id'));
				
				internal.innerHTML = '';
				
				el.getChildren().each( function (op) 
				{
					if ( op.getProperty('c:check') == 'on' )
					{
						var option = new Element('option');
						
						option.value = op.innerHTML;
						option.selected = true;
						internal.adopt( option );
					}
				});
				

			}
		});
			
		$ES('input', DomParentElement).each( function(element)
		{
			if ( element.getProperty("field_type") == "date" && element.getProperty('calendar_setup') != 'done' ) 
			{
				var but = document.createElement("img");
				
				$(but).setProperty("src","templates/colegiocpa.com/sodalis/nice_theme/icons/PNG/16x16/Calendar.png");
				but.style.verticalAlign = "top";
				
				but.style.margin = "0px";
				but.style.padding = "0px";
				but.style.paddingLeft = "5px";
				but.style.cursor = "pointer";
				
	// 			but.setAttribute("value","...");
				
				but.setProperty("id", "date_trigger_" + element.getProperty("name") );
	
				var par = element.parentNode;
				var nextObj = element.nextSibling;
							
				if ( nextObj ) 
				{
					par.insertBefore(  but, nextObj );
				}
				else
				{
					par.appendChild( but );
				}
				
				// requires jscalendar
				try 
				{
					Calendar.setup({ inputField : element, button : "date_trigger_" + element.getProperty("name"), ifFormat : "%Y-%m-%d", showsTime : false , singleClick : true, step : 1 });
					element.setProperty('calendar_setup','done');
				} catch (ex) {
				}
			}
		});
		
		
		$ES('.EditableColumn', DomParentElement).each( function ( element )
		{
			element.setCellValue = function( valor )
			{
				$(element.getParent()).getElements('span.data').each( function(datatag)
				{
					var field = element.getProperty('data:field');
					
					var oldvalue = datatag.getProperty( field );
					
					if ( oldvalue != valor )
					{
						datatag.setProperty( field, valor );
						datatag.getFirst().checked = true;
						element.setStyle('color','white' );
						element.setStyle('background-color','#A00000' );
						
						window.sodalisNeedsSave = true;
						window.sodalisNeedsSaveMessage = "Tiene cambios en la tabla que no ha procesado";
					}
				});
			}
		});


		$ES('.EditableColumn', DomParentElement).each( function(cell) 
		{	
			cell.removeEvents();
			cell.addEvent('click', function (e) 
			{
				var ev = new Event(e);
				
				var size = cell.getSize().size;
				var pos  = cell.getPosition();
				
				var editcomponent = $('Table_EditTextArea');
				
				editcomponent.setStyle('position','absolute');
				
				editcomponent.setStyle('top', pos.y + 1 +'px' );
				editcomponent.setStyle('left', pos.x + 1 + 'px' );
				
				editcomponent.setStyle('width', (size.x - 8 ) + 'px' );
				editcomponent.setStyle('height', (size.y - 8 )+ 'px' );
				
				editcomponent.setStyle('padding', '3px' );
				editcomponent.setStyle('margin', '0px' );
				
				editcomponent.setStyle('font-size', cell.getStyle('font-size') );
				
				editcomponent.setStyle('border', '0px inset #efefef' );
				
				editcomponent.setStyle('vertical-align', 'middle' );
				
				editcomponent.setStyle('display', 'inline' );
				editcomponent.setStyle('background-color', '#FCFFBE' );
				
				
				editcomponent.value = cell.innerHTML;
// 				$('edit1').value = cell.innerHTML;
				
				editcomponent.editing_cell = cell;
				
				editcomponent.focus();
				
								
				ev.stop();
			});			
		});	

		$ES('#Table_EditTextArea', DomParentElement).each( function(element) 
		{
		
			element.syncSize = function ( cell )
			{
				var size = cell.getSize().size;
			
				element.setStyle('width', (size.x - 8 ) + 'px' );
				element.setStyle('height', (size.y - 8 )+ 'px' );
			}
			
			element.removeEvents();
			element.addEvent('blur', function (e) 
			{
				var ev = new Event(e);
				var cell = element.editing_cell;
					
				cell.innerHTML = element.value;
				cell.setCellValue( element.value );
/*				cell.setProperty('c:value', element.value );*/
				
				element.setStyle('display','none');
				
 				ev.stop();
			});			
			
// 			element.addEvent('keyup', function (e) 
// 			{
// 				var ev = new Event(e);
				
// 				var cell = element.editing_cell;
					
// 				cell.innerHTML = element.value;
// 				cell.setCellValue( element.value );
				
// 				element.syncSize( cell );
				
// 				ev.stop();
// 			});	
		});	
		
		
		
		

		
		
		
		$ES('.TableGlobalCheckBox', DomParentElement).each( function ( element )
		{
			element.removeEvents();
			element.addEvent('click', function(e)
			{
				var component = element.getProperty('c:component_id');
				
				$$('#' + component + ' .TableRowCheckBox ' ).each( function(cb)
				{
					cb.checked = element.checked;
				});
			});
		});
		
		
		$ES('.TableGlobalSubmit', DomParentElement).each( function ( button ) 
		{
			button.removeEvents();
			button.addEvent('click', function (e)
			{
// 				$('loading-img').setStyle('display','inline');
				
				startLoading();
				
				var ev = new Event(e);
				
				var table_id = button.getProperty('c:component_id');
				var controller = button.getProperty('c:controller');
				var action_select = $(button.getProperty('c:action_select_id'));
				var action_method = $(action_select).getValue();
				
				if ( action_method == '' )
				{
					alert('Seleccione una acción primero');
// 					$('loading-img').setStyle('display','none');
					stopLoading();
					
					return;
				}
				else
				{
				
					var nrows = 0;
					var ncells = 0;
					var submit_string = '';
					var data_array = new Array();
					
					
					$$('#' + table_id+' .TableRowCheckBox').each( function( checkbox )
					{
						if ( checkbox.checked == true )
						{
							nrows++;
																				
							row_array = new Array();	
																	
							for (var n = 0; n < checkbox.getParent().attributes.length; n++ )
							{
								row_array[ checkbox.getParent().attributes[n].nodeName ] = checkbox.getParent().attributes[n].nodeValue;
							}
							
 							data_array.push( row_array );

// 							data_array.push( new Array( 'asdasd','asdasd') );
						}
					});		
						
						
					var php = new PHP_Serializer(true);
					var submit_string =  php.serialize( data_array );
// 					
					var url = "index.php?"+gup('node')+"_c="+controller+"&_a=" + action_method;
					
// 					alert( submit_string );
					
					var myAjax = new Ajax(url, { method: 'post', evalScripts:false, onComplete: processAjaxActions}).send(url, submit_string );
//  				
	 				myAjax.content_update = $(table_id).getParent();
 								
				}
					
			});
		});
		
		
		$ES('#context-popup-close', DomParentElement).each( function(element)
		{
			element.removeEvents();
			element.addEvent('click', function(event) 
			{
				$('context-popup').setStyle('display','none');
			});			
		});
		
		
		$ES('.AjaxPopup', document).each( function(element)
		{
			element.removeEvents();
			element.addEvent('click', function(event) 
			{
				var e = new Event(event);

				var url = this.getProperty('href');
				
				var ajax = new Ajax( url , 
						{
							onComplete: processAjaxActions,
							onFailure: processAjaxFailure
						}).request();	
				
				ajax.content_update = $('context-popup-content');
				
				ajax.content_update.getParent().setStyle('top', e.page.y - 5 + 'px' );
				ajax.content_update.getParent().setStyle('left', e.page.x - 5 + 'px');
				ajax.content_update.getParent().setStyle('display', 'block' );
				
// 				ajax.contentUpdateStyle = 'preserveParent';		
						
				e.stop();
			});			
		});
		
		
		
		$ES('.AjaxAction', DomParentElement).each( function(element) 
		{
			element.fireAjaxAction = function()
			{
				var run = false;
				
				if ( this.getProperty('confirm') != null )
				{
					if ( confirm( this.getProperty('confirm') ) )
					{
						run = true;
					}
					else
					{
						run = false;
					}
				}
				else
				{
					run = true;
				}
				
				if ( run == false ) return;
				
// 				$('loading-img').setStyle('display','inline');
				startLoading();
				
 				var url 		= this.getProperty( 'href' );
// 				window.location.hash = url;
				
				var ajax = new Ajax( url , 
						{
							method: 'get',
							onComplete: processAjaxActions,
							onFailure: processAjaxFailure
						}).request();	
						
						
				var content	= this.getProperty('content_id');						
				if ( content == null )
				{
					content = 'content';
				}
				
				ajax.content_update = $(content);
				ajax.contentUpdateStyle = 'preserveParent';
			
			}
			
			
			element.removeEvents();
			element.addEvent('click', function(event) 
			{
				this.fireAjaxAction();
				
				var e = new Event(event);
				e.stop();
			});
			
			if ( element.hasClass('FireOnShow') )
			{
				element.fireAjaxAction();
			}
		});
		
		
		
		$ES('a.TableExpandAction', DomParentElement).each( function(element) 
		{
			element.removeEvents();
			
			element.doExpand = function ()
			{
								
				var url 			= this.getProperty( 'href' );
				var row_id 			= this.getProperty( 'expand_row_id');
				var expanded_row	= this.getParent().getParent();
				var component_id	= this.getProperty('component_id');
				
				
				var table = $(component_id);
				var container 		= $( row_id );
				
				var myAjax = new Ajax( url , 
						{
							method: 'get',
							onComplete: processAjaxActions
						}).request();	
						
				myAjax.content_update = container.getFirst().getFirst();
						
				container.removeClass('TableHiddenRow');
// 				$(expanded_row).addClass('TableExpandSelectedRow');		
			}
			
			element.addEvent('click', function(event) 
			{
// 				$('loading-img').setStyle('display','inline');
				startLoading();
				
				this.doExpand();
				var e = new Event(event);
				e.stop();

			});
			
			if ( element.hasClass('FireOnShow') )
			{
				element.doExpand();
			}
						
		});
		
		
		$ES('a.TableNavigateFirst', DomParentElement).each( function(element) 
		{
			element.removeEvents();
			element.addEvent('click', function (e) 
			{
// 				$('loading-img').setStyle('display','inline');
				startLoading();
				
				var clase 		= this.getProperty('table_class');
				var component 	= this.getProperty('component_id');
				var offset		= this.getProperty('offset');
				var limit		= this.getProperty('limit');
				var sortby		= this.getProperty('sortby');
				var ascdesc		= this.getProperty('ascdesc');
				
				var url = 'index.php?node='+gup('node')+'&_c=TableNavigate&_a=ext&class='+clase+'&offset='+offset+'&limit='+limit+'&sortby='+sortby+'&ascdesc='+ascdesc;
				var myAjax = new Ajax(url, {method: 'get',evalScripts:false, onComplete: processAjaxActions}).request();
				myAjax.content_update = $(component).getParent();
				var ev = new Event(e);
				ev.stop();
			});
		});

		
		$ES('a.TableNavigatePrev', DomParentElement).each( function(element) 
		{
			element.removeEvents();
			element.addEvent('click', function (e) 
			{
// 				$('loading-img').setStyle('display','inline');
				startLoading();
				
				var clase 		= this.getProperty('table_class');
				var component 	= this.getProperty('component_id');
				var offset		= this.getProperty('offset');
				var limit		= this.getProperty('limit');
				var sortby		= this.getProperty('sortby');
				var ascdesc		= this.getProperty('ascdesc');
				
				var url = 'index.php?node='+gup('node')+'&_c=TableNavigate&_a=ext&class='+clase+'&offset='+offset+'&limit='+limit+'&sortby='+sortby+'&ascdesc='+ascdesc;
				var myAjax = new Ajax(url, {method: 'get',evalScripts:false, onComplete: processAjaxActions}).request();
				myAjax.content_update = $(component).getParent();
				var ev = new Event(e);
				ev.stop();
			});
		});
		
		$ES('a.TableNavigateNext', DomParentElement).each( function(element) 
		{
			element.removeEvents();
			element.addEvent('click', function (e) 
			{
// 				$('loading-img').setStyle('display','inline');
				startLoading();
				
				var clase 		= this.getProperty('table_class');
				var component 	= this.getProperty('component_id');
				var offset		= this.getProperty('offset');
				var limit		= this.getProperty('limit');
				var sortby		= this.getProperty('sortby');
				var ascdesc		= this.getProperty('ascdesc');
				
				var url = 'index.php?node='+gup('node')+'&_c=TableNavigate&_a=ext&class='+clase+'&offset='+offset+'&limit='+limit+'&sortby='+sortby+'&ascdesc='+ascdesc;
				var myAjax = new Ajax(url, {method: 'get',evalScripts:false, onComplete: processAjaxActions}).request();
				myAjax.content_update = $(component).getParent();
	
				var ev = new Event(e);
				ev.stop();
			});			
		});	
		
		
		$ES('a.TableNavigateRefresh', DomParentElement).each( function(element) 
		{
			element.removeEvents();
			element.addEvent('click', function (e) 
			{
// 				$('loading-img').setStyle('display','inline');
				startLoading();
				
				var clase 		= this.getProperty('table_class');
				var component 	= this.getProperty('component_id');
				var offset		= this.getProperty('offset');
				var limit		= this.getProperty('limit');
				var sortby		= this.getProperty('sortby');
				var ascdesc		= this.getProperty('ascdesc');
				
				var url = 'index.php?node='+gup('node')+'&_c=TableNavigate&_a=ext&class='+clase+'&offset='+offset+'&limit='+limit+'&sortby='+sortby+'&ascdesc='+ascdesc;
				var myAjax = new Ajax(url, {method: 'get',evalScripts:false, onComplete: processAjaxActions}).request();
				myAjax.content_update = $(component).getParent();
	
				var ev = new Event(e);
				ev.stop();
			});			
		});	

		
		$ES('a.AjaxFormRefresh', DomParentElement).each( function(element) 
		{
			element.removeEvents();
			element.addEvent('click', function (e) 
			{
// 				$('loading-img').setStyle('display','inline');
				startLoading();
				
				var component 	= this.getProperty('component_id');
				
				processAjaxForm( component, 'refresh-nosubmit' );
				
				var ev = new Event(e);
				ev.stop();
			});			
		});	

		$ES('.RefreshPanel', DomParentElement).each ( function (element) 
		{
			element.panelRefresh = function ()
			{				
				var url 		= this.getProperty('url');
				
				var myAjax = new Ajax(url, {method: 'get',evalScripts:false, onComplete: processAjaxActions}).request();
				myAjax.content_update = element.getParent();
				myAjax.calling_element = element;

				try {
					var ev = new Event(e);
				 	ev.stop(); 
				 } catch ( shtf ) { }
			}
		});
		
		
		
		$ES('.AsyncPanel', DomParentElement).each ( function (element) 
		{			
			var url 		= element.getProperty('url');
			
			var myAjax = new Ajax(url, {method: 'get', evalScripts:false, onComplete: processAjaxActions}).request();
			myAjax.content_update = element;
			myAjax.contentUpdateStyle = 'preserveParent';
			myAjax.calling_element = element;

			try {
				var ev = new Event(e);
				ev.stop(); 
			} catch ( shtf ) { }

		});		
		
		
		

		window.sodalisNeedsSave = false;
		window.sodalisNeedsSaveMessage = '';


		window.onbeforeunload = function(e)
		{
			if ( window.sodalisNeedsSave == true )
				return window.sodalisNeedsSaveMessage;
		};




		window.refreshTable = function ( el )
		{
 			try { 
			
				var ref = $($(el).getProperty('refresh_id'));
				
				ref.setProperty('limit', el.getValue() );
				ref.fireEvent('click');
				
				
 			} catch (e) {}
			
		}

		window.refreshTables = function ( tag )
		{
			$$('a.TableNavigateRefresh').each( function(element)
			{
				if  (element.getProperty('tag') == tag )
				{
					try { element.fireEvent('click'); } catch(e) {}
				}
			});
			
			$$('.RefreshPanel').each( function ( element )
			{
				try
				{
					element.panelRefresh();
				}
				catch ( e ) {}
			});			
		}
		
		window.refreshForms = function ( tag )
		{
			$$('a.AjaxFormRefresh').each( function(element)
			{	
				if  (element.getProperty('tag') == tag )
				{
					try { element.fireEvent('click'); } catch(e) {}
				}
			});
		}
		
		window.hideContentPopup = function () 
		{
			try 
			{
				$('content-popup').setHTML('');
			} catch( e ) {}
		}
		window.showContentPopup = function () 
		{
// 			$('content-popup').setStyle('display','block');
		}
		
									
		$$('input.TypeAhead').each ( function( element )
		{
			extendTypeAheadField( element.getProperty('id') );
		});
		
		var Tips2 = new Tips($ES('.tooltip', DomParentElement), 
		{

			initialize:function()
			{
				this.fx = new Fx.Style(this.toolTip, 'opacity', {duration: 500, wait: false}).set(0);
			},
			onShow: function(toolTip) 
			{
				this.fx.start(1);
			},
			onHide: function(toolTip) 
			{
				this.fx.start(0);
			}
		});

		
		
	}
	
	
	function processAjaxFailure ( httprequest )
	{
		window.pepe = httprequest;
// 	  	$('loading-img').setStyle('display','none');
		stopLoading();
		alert( '<span style="font-size: 10pt;"><b>There was a server error. Please try again later.</b></span>');
	}
	
	
	/**
	* Processes Ajax/JSON responses from Sodalis
	*/
	function processAjaxActions( jsonString )
	{		
		
		if ( this.getHeader( 'X-AjaxAction' ) != 'content' )
		{
			var response = Json.evaluate( jsonString );
			
			switch ( response.response_type )
			{
				case 'exception':
					$$('.AjaxFormButton').each( function (button) {
						button.disabled = false;
					});
					if ( response.exception == 'AjaxFormException' )
					{
						if ( this.message_div != null )
						{
							$(this.message_div).setHTML( response.error );
							$(this.message_div).setStyle('display', 'block');
							$(this.message_div).addClass('Error');
							
							var f = $( '_form_object_' + response.field );
							
							if ( f != null )
							{
								var pulseEffect = new Fx.Styles( f , { duration: 100, transition: Fx.Transitions.linear});
								
								pulseEffect.start({'opacity': [1,0]}
								).chain ( function() {this.start({'opacity': [0,1]})} 
								).chain ( function() {this.start({'opacity': [1,0]})} 
								).chain ( function() {this.start({'opacity': [0,1]})} 
								).chain ( function() {this.start({'opacity': [1,0]})} 
								).chain ( function() {this.start({'opacity': [0,1]})} 
								).chain ( function() {this.start({'opacity': [1,0]})} 
								).chain ( function() {this.start({'opacity': [0,1]})}
								);
								
								if ( f != null )
									(function () { this.focus(); }).delay(1500, $(f) );
							}
						}
						else
						{
							var obj = $( '_form_object_' + response.field );
							alert( response.error, null, null, obj );
						}
					}
					else if ( response.exception != '' )
					{
						alert( response.error, null, null, null );
					}
					break;
					
				case 'fieldok':
					var obj = $('_form_object_' + response.field + '_extra');
					obj.setHTML('');
					var field = $('_form_object_' + response.field );
					field.removeClass('FieldError');
					break;
					
				case 'fieldmessage':
					var obj = $('_form_object_' + response.field + '_extra');
					obj.setHTML( response.message );
					var field = $('_form_object_' + response.field );
					field.addClass('FieldError');
					break;
					
				case 'redirection':
					window.location = response.redirect;
					break;
				case 'message':
					if ( this.message_div != null )
					{
						$(this.message_div).setHTML( response.message );
						$(this.message_div).setStyle('display', 'block');
						$(this.message_div).addClass('Message');
					}
					else
					{
  						alert( response.message );
 					}
 					window.refreshTables('A');
					break;
				case 'refresh':
					$('error-content').innerHTML = '';
					$$('.AjaxFormButton').each( function (button) {
						button.disabled = false;
					});
// 					window.refreshForms('A');
					window.refreshTables('A');
					window.hideContentPopup();
					break;
					
				default:
					alert('Server did not respond!');
					break;
			}
		}
		else
		{
// 			$('error-content').innerHTML = '';
// 			
// 			$$('.AjaxFormButton').each( function (button) {
// 				button.disabled = false;
// 			});
// 			if ( this.getHeader('X-Content') )
// 			{
// 				this.content_update = $( this.getHeader('X-Content') );
// 			}
// 			else
// 			if ( this.content_update == $('content-popup') )
// 			{
// 			}
// 						
// 			
// 			var cont = new Element('div');
// 			$(cont).setHTML(  this.response.text );
// 			var rep = cont.getFirst();
// 
// 			$(this.content_update).setHTML( this.response.text );
			
			
			
			if ( this.getHeader('X-Content') )
			{
				this.content_update = $( this.getHeader('X-Content') );
			}
			else
			if ( this.content_update == $('content-popup') )
			{
// 				window.hideContentPopup();
			}
			
			var cont = new Element('div');
			$(cont).setHTML(  this.response.text );
			var rep = cont.getFirst();

			$(this.content_update).setHTML( this.response.text );
			if ( this.response.text  != '<div></div>' )
			{
// 				$(this.content_update).setStyle('display','block');
				showContent( $( this.content_update ) );
			}
			else
			{
				hideContent( $(this.content_update).getParent().getParent() );
// 				$(this.content_update).getParent().getParent().setStyle('display','none');
			}		
			

		}
		
		

			
				if ( this.content_update == $('content-popup')  )
				{ 
					el = $('content-popup');
					
					var w = parseInt( el.getStyle('width') );
					var ww = window.getWidth();
					
					var h = parseInt( el.getStyle('height') );
					var wh = window.getHeight();
					
					var st = window.getScrollTop();
					
					var ml = 0;
					var mt = 0;
					
					if ( w < ww )
					{
						ml = parseInt((ww - w) / 2 );
					}
					
					if ( h < wh )
					{
						mt = parseInt( (wh - h ) / 2.5 );
					}
					else
					{
						el.setStyle('height', wh + 'px !important');
						el.setStyle('overflow','auto');
					}
					
						
					el.setStyle('position', 'absolute');
					
					el.setStyle('top', mt + st + 'px');
					el.setStyle('left', ml + 'px');
					
				}				
			
			
			
					
		
			
 		refreshDomExtensions( this.content_update );
			
		if ( this.getHeader('X-Refresh') == 'yes' )
		{
// 			window.refreshForms('A');
			window.refreshTables('A');
		}
 		
 		stopLoading();
//   		$('loading-img').setStyle('display','none');
		
	}
	
	
	
	function showContent( id )
	{
		id.setStyle('display','block');
		
		var list_dim = id.getCoordinates();
		var win_width = $(window).getWidth();
		var win_height = $(window).getHeight();
						
		if ( list_dim.left + list_dim.width > win_width )
		{
 			id.setStyle('right', 10 );
		}
		
		
	}
	
	function hideContent( id )
	{
		id.setStyle('display','none');
	}	
	
	
	
	
	
	
	
	
	
	$(window).unload = function(e) 
	{
// 		$('loading-img').setStyle('display','inline');
	}
	
	$(window).addEvent('domready', function( e )
	{
 		$('loading-img').setStyle('display','inline');
		refreshDomExtensions( document );
 		$('loading-img').setStyle('display','none');
	});
	
	
	
	/**
	* Given a DOM ID extends that field to be a type ahead field
	* Must use the structure returned by the PHP Class 
	*/
	function extendTypeAheadField( search_field_id )
	{
	
		$( $( search_field_id ).getProperty( 'clear_button_id') ).removeEvents('click');
		$( $( search_field_id ).getProperty( 'clear_button_id') ).addEvent( 'click', function(e)
		{
			var event = new Event(e);		
			key_holder 		= $( event.target.getProperty('key_holder_id') );
			display_field 	= $( event.target.getProperty('display_field_id') );
			
				key_holder.value = '';
				try {
					key_holder.onchange();
				} catch( ex ) {}
				
				$($( search_field_id ).getProperty('list_values_id')).setHTML('');
				$($( search_field_id ).getProperty('list_values_id')).setStyle('display','none');
				display_field.readOnly = false;
				display_field.removeClass( 'ro' );
				display_field.value = '';
		
		});
		

		
		$( search_field_id ).addEvent('keydown', function(e) 
		{
			var event = new Event(e);
			
			if ( event.key == 'enter' )
			{
				var el = $('type_ahead_current');
				
				if ( el == null )
				{
					el = $( event.target.getProperty('list_values_id') ).getFirst();
				}
				
				e.forced_target  = el;
				el.fireEvent('click', e);
				
				event.stop();	
				
			}
			else if ( event.key == 'down' || event.key == 'up' )
			{
				var el = $('type_ahead_current');
				
				if ( el == null )
				{
					el = $(event.target.getProperty('list_values_id')).getFirst();
				}
				else
				{
					el.removeClass( 'selected' );
					el.setProperty('id','');
					if ( event.key == 'up' )
					{
						el = el.getPrevious();
					}
					else
					{
						el = el.getNext();
					}
				}
				
				el.addClass('selected');
				el.setProperty('id','type_ahead_current');
				
				event.stop();
			}
		});
		
		
		
		$( search_field_id ).selectItem = function ( event )
		{	
			var ev = new Event( event );
			var tg = (event.forced_target) ? event.forced_target : ev.target;
			
				while ( $(tg).getProperty('key') == null ) { tg = $(tg).getParent(); }
				
				if ( tg.getProperty('key') != '' )
				{
					$( search_field_id ).value = tg.getProperty('valor'); 
						
					$( $(search_field_id).getProperty('key_holder_id') ).value = tg.getProperty('key');
					
					
					// Llamar al onchange del hidden field del type ahead 
					// Probar esto en explorer
					try {
						$( $(search_field_id).getProperty('key_holder_id') ).onchange();
					} catch( ex ) {}
					
					$( $(search_field_id).getProperty('list_values_id')).setStyle('display','none'); 
					
					$( search_field_id ).readOnly = true;
					$( search_field_id ).addClass( 'ro' );	
					ev.stop();
				}
		}
		
		
		
		
		
		$( search_field_id ).onComplete = function ( jsonObj )
		{
			var list_div = $(this.getProperty('list_values_id'));
			
 			list_div.setHTML('');
			
			for ( var x = 0; x < jsonObj.list.length; x++ )
			{
				var record = jsonObj.list[x];
				
				var line = new Element('div',{'class':'opcion'});
				
				$(line).setHTML(   record.html   );
				
				$(line).setProperty('key', record.key);
				$(line).setProperty('valor', record.label );
				
				
				$(this.getProperty('list_values_id')).adopt( line );
				$(this.getProperty('list_values_id')).setStyle('display','block');
				
				$(line).addEvent('click', this.selectItem );		
			}
			
			if ( x == 0 )
			{
				var line = new Element('div', {'class':'opcion'} );
				
				$(line).setHTML('<b>Not found</b>');
				$(line).addEvent('click', function (e) 
				{
					this.getParent().setStyle('display','none');
					$( search_field_id ).value = '';
				});
				$(this.getProperty('list_values_id')).adopt( line );
				$(this.getProperty('list_values_id')).setStyle('display','block');
			}
			
			
			var list_dim = list_div.getCoordinates();
			var win_width = $(window).getWidth();
							
			if ( list_dim.left + list_dim.width > win_width )
			{
				list_div.setStyle('left', win_width - list_dim.width - 10 );
			}			

		}
		
		
		$(search_field_id).fetch = function ( key )
		{
			var model 	= $(search_field_id).getProperty('c:model_class');
			var ds 		= $(search_field_id).getProperty('c:model_datasource');
			var sf 		= $(search_field_id).getProperty('c:show_field');
			var controller = $(search_field_id).getProperty('c:controller');
							
			var url = 'index.php?node='+gup('node')+'&_c='+controller+'&_a=getTypeAhead&model='+model+'&ds='+ds+'&show_field='+sf+'&q=' + $(search_field_id).getValue();
			
			// stop if its a tab
			if ( key == 'enter' ||  key == 'down' ||  key == 'up' )
			{
				return;
			}
	
			if ( key != null )
			{
				var func = this.onComplete.bind( this );
				
				try
				{
					if ( $(search_field_id).request != null )
					{
						$(search_field_id).request.cancel();
					}
				} catch( ex ) {}
				$( search_field_id ).request = new Json.Remote(url, { onComplete: func }).send();
			}
		}		
			
		$( search_field_id ).removeEvents('keyup');
		$( search_field_id ).addEvent('keyup', function(event) 
		{
			
			window.delayedTypeAhead = function ()
			{
				$(search_field_id).fetch( window.type_ahead_key );
			}
			
			if ( window.type_ahead_timeout != null )
			{
				clearTimeout( window.type_ahead_timeout );
			}
			
			var ev = new Event(event);
			window.type_ahead_key = ev.key;
			window.type_ahead_timeout  = setTimeout('delayedTypeAhead()', 400);
		});
		
		$( $( search_field_id ).getProperty( 'showall_button_id') ).removeEvents('click');
		$( $( search_field_id ).getProperty( 'showall_button_id') ).addEvent( 'click', function(e)
		{
			window.delayedTypeAhead = function ()
			{
				$(search_field_id).fetch( 'weee' );
			}
			
			if ( window.type_ahead_timeout != null )
			{
				clearTimeout( window.type_ahead_timeout );
			}
			
			window.type_ahead_timeout  = setTimeout('delayedTypeAhead()', 2);
		});
		
		
			
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	/**
	* Process an Ajax Form and submit values with a specific form_action
	* valid values for form_action:
	* 'refresh' -> the form refreshes itself
	*/
	function processAjaxForm( component_id, form_action, button_action, trigger_field  )
	{
// 		this.disabled = true;
// 		alert('Waka');
  		submitAjaxForm( component_id , form_action, button_action, trigger_field  );
	}
	
	function gup( name )
	{
		name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
		var regexS = "[\\?&]"+name+"=([^&#]*)";
		var regex = new RegExp( regexS );
		var results = regex.exec( window.location.href );
		if( results == null )
			return "";
		else
			return results[1];
	}
	
	
	function submitAjaxForm( component_id , form_action, button_action, trigger_field )
	{
	
		try
		{
			tinyMCE.triggerSave();
		} 
		catch ( ex ) {}
		
// 		$('loading-img').setStyle('display','inline');
		startLoading();
		
		var node = $( component_id ).getProperty('node');
		
		var separator 	= '';
		var submit_str 	= '_form_action=' + form_action + '&' + '_form_button_action=' + button_action + '&_trigger_field=' + trigger_field + '&' + 'node=' + node + '&';
		var post_object = {};
		
		
		var inputs 		= $$('input[component_id='+component_id+']');
		inputs.each( function (element) 
		{
			if ( ( element.getProperty('type') == 'radio' && element.checked == true ) || element.getProperty('type') != 'radio' )
			{
				submit_str += separator + element.getProperty('name') + '=' + encodeURIComponent(element.getValue());
				post_object[ element.getProperty('name') ] = element.getValue();
				separator = '&';
			}
		});
		
		
		var inputs 		= $$('select[component_id='+component_id+']');
		
		inputs.each( function (element) 
		{
			submit_str += separator + element.getProperty('name') + '=' + encodeURIComponent(element.getValue());
			post_object[ element.getProperty('name') ] = element.getValue();				
			separator = '&';
		});		
		
		var inputs 		= $$('textarea[component_id='+component_id+']');
		
		inputs.each( function (element) 
		{
			submit_str += separator + element.getProperty('name') + '=' + encodeURIComponent(element.getValue());
			post_object[ element.getProperty('name') ] = encodeURIComponent( element.getValue() );				
			separator = '&';
		});	
	
		var url = 'index.php';
		var AjaxRequest = new Ajax( url , 
		{ 
			method: 'post',
			bubu: $( component_id ).getParent().getParent(),
			onComplete: processAjaxActions,
			onFailure: processAjaxFailure
		}).send( url, submit_str );

		AjaxRequest.content_update = $(component_id).getParent().getParent();
		
		
		AjaxRequest.message_div = $$('DIV[component_id=' + component_id + ']')[0];
		
		if ( form_action != 'refresh' && form_action != 'refresh-nosubmit')
		{
		}
	}
	
	




function processSmartForm( form_id , button_action )
{
	var form_def;
	var field_obj;
	var field_id_node;
	
	form_def = document.getElementById( form_id );
	clearFormErrors(form_def);
	
	for(var i = 0 ; i < form_def.childNodes.length; i++ )
	{
		field_id_node = null;
		
		field_id_node = form_def.childNodes[i].getAttribute('form_field_id') ;
		
		if( field_id_node != null )
		{
		
			field_obj = document.getElementById( form_def.childNodes[i].getAttribute('form_field_id') ) ;
			
			if( field_obj !='undefined' && field_obj !=null )
			{	
			
				if( field_obj.tagName =='INPUT' || field_obj.tagName =='SELECT'  )
				{	
					if( SFfieldValidate( form_def , field_obj ) == false )
					{
						
						return; 
					}
				}
			}		
		}
		
	}
	
	
	
	submitSmartFormData( form_def.getAttribute('processor') , form_id , button_action );
	
	
}


function SFfieldValidate( form_obj , field ) {

    if ( field.getAttribute("required") == "true" ) {
    
        if ( (field.value.length) == 0 || (field.value=="") ) {
            alert( field.getAttribute("label") + " es un campo requerido!", null, null, field );
            return false;
        }
    }
	
	if ( (field.getAttribute("field_type") == "currency") || (field.getAttribute("field_type") == "numeric")) {

		var n = parseFloat( field.value );
		
		if ( !isNaN( n ) ) {
			field.value = n;
		}
		
		if ( isNaN(field.value) ) {
			alert( form_obj, field.getAttribute("label") + " no es un valor numerico!" );
			return false;
		}
	}

    return true;
}





function getSmartFormData( form_id ) {
	var form_def = document.getElementById( form_id );
	var field_obj;
	var data ='';
	var temp;
	var i = 0;
	var amp='';
	
	var inputs = document.getElementsByTagName("INPUT");
	var input_selects = document.getElementsByTagName("SELECT");
	var text_areas = document.getElementsByTagName("TEXTAREA");
	
	try 
	{
			//////PROCESS REGULAR INPUTS
			for( i = 0 ; i < inputs.length; i++ )
// 			for( i = 0 ; i < form_def.childNodes.length; i++ )
			{
				
				val = inputs[i].getAttributeNode('form_id');
				
				if( val != null )
				{
					
// 					return;
					if( 'form_id_'+val.value == form_id )
// 					if( 'form_id_'+inputs[i].getAttribute('form_id') == form_id )
					{


						if( (typeof(inputs[i].type) != 'undefined') && inputs[i].name !='_form_status' ){
							
							data+=amp+getSmartFieldData( inputs[i] );
							amp = '&';
						}
					}
				}
			}
			//////PROCESS TEXTAREAS
			for( i = 0 ; i < text_areas.length; i++ )
// 			for( i = 0 ; i < form_def.childNodes.length; i++ )
			{
				
				val = text_areas[i].getAttributeNode('form_id');
				
				if( val != null )
				{
					
// 					return;
					if( 'form_id_'+val.value == form_id )
// 					if( 'form_id_'+inputs[i].getAttribute('form_id') == form_id )
					{


						if( (typeof(text_areas[i].type) != 'undefined') && text_areas[i].name !='_form_status' ){
							
							data+=amp+getSmartFieldData( text_areas[i] );
							amp = '&';
						}
					}
				}
			}
			
			for( i = 0 ; i < input_selects.length; i++ )
			{
				
// 				if( input_selects[i].hasAttribute('form_id') == true )
				val = null;
				val = input_selects[i].getAttributeNode('form_id');
				
				if( val != null )
				{
				
					if( 'form_id_'+val.value == form_id )
					{


						if( (typeof(input_selects[i].type) != 'undefined') && input_selects[i].name !='_form_status' ){
							
							data+=amp+getSmartFieldData( input_selects[i] );
							amp = '&';
						}
					}
				}
			}
		
	}catch ( a )
	{
		alert(a);
	}
		return data;
	}



	function submitSmartFormData( url , form_id  , button_action ){
// 		alert(form_id);
		var xmlhttp_obj = getXmlHttpObj();
		var form;
		var xmit_data;
		data = '';
		form = document.getElementById( form_id );
// 		alert(form_id);
// 		return;
		if(  form != null ){
			
			xmit_data = getSmartFormData( form_id );

		}
// 		return;
// 		if( data != null ){
			xmit_data += data+'&'+button_action+'.y=32&'+button_action+'.x=45';
// 		}


// 		alert (xmit_data);
// 		alert(xmlhttp_obj);

		xmlhttp_obj.open( 'POST' , url , true );

		xmlhttp_obj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

		if( xmit_data == null ){
			xmit_data = 'null';
		}

// 		alert(xmit_data);

		xmlhttp_obj.send( xmit_data );

		xmlhttp_obj.onreadystatechange=function() {

			if ( xmlhttp_obj.readyState==4 ) {

				a = xmlhttp_obj;
				var err;
				

				rcvd_error        = xmlhttp_obj.responseXML.getElementsByTagName('error_list');
				rcvd_field_error  = xmlhttp_obj.responseXML.getElementsByTagName('field_error_list');
				rcvd_messages     = xmlhttp_obj.responseXML.getElementsByTagName('message_list');
				rcvd_action_list  = xmlhttp_obj.responseXML.getElementsByTagName('action_list');
				cont = xmlhttp_obj.responseXML.getElementsByTagName('contenido');
				msg = xmlhttp_obj.responseXML.getElementsByTagName('mensaje');


				if( (rcvd_field_error[0].childNodes.length != 0) && (rcvd_field_error[0].childNodes.length != null) )
				{
					
					error_qty = rcvd_field_error[0].childNodes.length;
					ret='';
					err ='';
					var counter;
					counter=0;
					for(counter=0; counter<error_qty;counter++)
					{
						
						err=err+setFieldError( rcvd_field_error[0].childNodes[counter] );	
						
					}
					
					alert(err);
					return;

				}
//  				alert(rcvd_error[0].childNodes.length);
				if( (rcvd_error[0].childNodes.length != 0) && (rcvd_error[0].childNodes.length != null) ){
					
					
					error_qty = rcvd_error[0].childNodes.length;
					ret='';
					err ='';
					var counter;
					counter=0;
					for(counter=0; counter<error_qty;counter++)
					{
						
						err=err+setResponseError( rcvd_error[0].childNodes[counter] );	
						
					}
					
					alert(err);
					return;

				}
				if( (rcvd_messages[0].childNodes.length != 0 )&& (rcvd_messages[0].childNodes.length != null))
				{
					error_qty = rcvd_messages[0].childNodes.length;
					ret='';
					err ='';
					var counter;
					counter=0;
					for(counter=0; counter<error_qty;counter++)
					{
						
						err=err+setResponseMessage( rcvd_messages[0].childNodes[counter] );	
						
					}
					
					alert(err);
					
				}
				if( ( rcvd_action_list[0].childNodes.length != 0 ) && ( rcvd_action_list[0].childNodes.length != null))
				{
					error_qty = rcvd_action_list[0].childNodes.length;
					ret = '';
					err = '';
					var counter;
					counter = 0;
					for( counter = 0; counter < error_qty; counter++ )
					{
						processAction( rcvd_action_list[0].childNodes[counter] );
					}
				}
			}
		}
	}
	
	function setFieldError( error_obj ){

		var field_id = error_obj.getAttribute('field_id');
// 		alert(field_id+'_header');
		field_header = document.getElementById( field_id+'_header' );	
		field_header.style.cssText='color:red;font-weight:bold;';
		field_header.setAttribute("field_state","error");
		
		return '<div>'+error_obj.getAttribute('message')+'</div>';

	}
	function setResponseError( error_obj ){
		
		return '<div>'+error_obj.getAttribute('message')+'</div>';

	}
	
	
	function setResponseMessage( msg_obj ){
	
		return '<div>'+msg_obj.getAttribute('message')+'</div>';

	}
	
	
	
	function clearFormErrors( form_def )
	{
		var field_obj;
		var field_id_node ; 
		var form_id_node;
		
		for(var i = 0 ; i < form_def.childNodes.length; i++ )
		{
			
			field_id_node = form_def.childNodes[i].getAttribute('form_field_id');
			form_id_node = form_def.childNodes[i].getAttribute('form_id');
			
			
			if( field_id_node == null )
			{ return; }
				
			if( form_id_node == null )
			{ return; }
			
			field_obj = document.getElementById( field_id_node.value ) ;
		
			if( field_obj !='undefined' && field_obj !=null )
				
			if( field_obj.tagName =='INPUT' || field_obj.tagName =='SELECT' )
		
				if( (typeof(field_obj.type) != 'undefined') && field_obj.name !='_form_status' ){
					
					field_header = document.getElementById( field_id_node.value+'_header');
					
					unsetFieldError(field_header);
				}
				else{
	// 				document.write('Error');
				}
					
			
		}
	}
	
	function unsetFieldError( field )
	{
		field.style.cssText='';
		field.setAttribute("field_state","normal");
		return ;
	}
	
	function handleAction(){
	}


	function refreshContent(){

	}
	
	function refreshPage()
	{
	}
	
	function XMLredirect( action_obj )
	{
		if( action_obj.getAttributeNode("target") != null )
		{
			window.location = action_obj.getAttribute("target") ;
			return;
		}
	}
	
	
	function processAction( action_obj )
	{
		var action_type = action_obj.getAttribute("type");
		switch( action_type )
		{
			case "redirect":
				XMLredirect( action_obj );
				break; 
		}
		
		return;
	}
	
	

	function getSmartFieldData(formElement)
	{
		
// 		alert(formElement.getAttribute('id') );
		var formElement;
		
		if(formElement.length != null )
			var type = formElement.type;
			
		if( (typeof(type) == 'undefined') || ( type == 0)  )
			var type = formElement.type;
		
// 		alert(formElement.id);
		
		switch( type )
		{
			case 'undefined': return '';

			case 'radio':

				for( var x=0; x < formElement.length ; x++ )
					if(formElement[x].checked == true)
				return formElement.name+'='+formElement[x].value;

			case 'select-multiple':

				var str = Array();
				var y =0;
				for( var x=0; x < formElement.length; x++ ){
					if( y != 0 ) str+='&';

					str+=formElement.name;
						if( formElement[x].selected == true ){
							y++;
							str +=  '=' + formElement[x].value;
						}
				}
				return str;

			case 'checkbox':
				return formElement.name+'='+formElement.checked;
			
			case 'select':			
				return formElement.name+'='+formElement.value;
			
			case 'textarea':			
				return formElement.name+'='+formElement.value;
			
			default: return formElement.name+'='+formElement.value;
		}
		
	}
	
	

	function getXmlHttpObj(){
		var xmlhttp=false;
		/*@cc_on @*/
		/*@if (@_jscript_version >= 5)
		// JScript gives us Conditional compilation, we can cope with old IE versions.
		// and security blocked creation of the objects.
		try {
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
		try {
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (E) {
		xmlhttp = false;
		}
		}
		@end @*/
		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;
			}
		}
		return xmlhttp;
	}
	
	
	
		
// 	function URLEncode (clearString) 
// 	{
// 		var output = '';
// 		var x = 0;
// 		if ( clearString == null ) return '';
// 		clearString = clearString.toString();
// 		var regex = /(^[a-zA-Z0-9_.]*)/;
// 		while (x < clearString.length) {
// 			var match = regex.exec(clearString.substr(x));
// 			if (match != null && match.length > 1 && match[1] != '') {
// 				output += match[1];
// 			x += match[1].length;
// 			} else {
// 			if (clearString[x] == ' ')
// 				output += '+';
// 			else {
// 				var charCode = clearString.charCodeAt(x);
// 				var hexVal = charCode.toString(16);
// 				output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
// 			}
// 			x++;
// 			}
// 		}
// 		return output;
// 	}
	
	
	
	
	
	/**
*
*  Base64 encode / decode
*  http://www.webtoolkit.info/
*
**/

var Base64 = {

    // private property
    _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

    // public method for encoding
    encode : function (input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;

        input = Base64._utf8_encode(input);

        while (i < input.length) {

            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);

            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;

            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }

            output = output +
            this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
            this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

        }

        return output;
    },

    // public method for decoding
    decode : function (input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;

        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

        while (i < input.length) {

            enc1 = this._keyStr.indexOf(input.charAt(i++));
            enc2 = this._keyStr.indexOf(input.charAt(i++));
            enc3 = this._keyStr.indexOf(input.charAt(i++));
            enc4 = this._keyStr.indexOf(input.charAt(i++));

            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;

            output = output + String.fromCharCode(chr1);

            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }

        }

        output = Base64._utf8_decode(output);

        return output;

    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}
	
	
/**
 * Object PHP_Serializer
 * 	JavaScript to PHP serialize / unserialize class.
 * This class converts php variables to javascript and vice versa.
 *
 * PARSABLE JAVASCRIPT < === > PHP VARIABLES:
 *	[ JAVASCRIPT TYPE ]		[ PHP TYPE ]
 *	Array		< === > 	array
 *	Object		< === > 	class (*)
 *	String		< === > 	string
 *	Boolean		< === > 	boolean
 *	null		< === > 	null
 *	Number		< === > 	int or double
 *	Date		< === > 	class
 *	Error		< === > 	class
 *	Function	< === > 	class (*)
 *
 * (*) NOTE:
 * Any PHP serialized class requires the native PHP class to be used, then it's not a
 * PHP => JavaScript converter, it's just a usefull serilizer class for each
 * compatible JS and PHP variable types.
 * Lambda, Resources or other dedicated PHP variables are not usefull for JavaScript.
 * There are same restrictions for javascript functions*** too then these will not be sent.
 *
 * *** function test(); alert(php.serialize(test)); will be empty string but
 * *** mytest = new test(); will be sent as test class to php
 * _____________________________________________
 *
 * EXAMPLE:
 *	var php = new PHP_Serializer(); // use new PHP_Serializer(true); to enable UTF8 compatibility
 *	alert(php.unserialize(php.serialize(somevar)));
 *	// should alert the original value of somevar
 * ---------------------------------------------
 * @author              Andrea Giammarchi
 * @site		www.devpro.it
 * @date                2005/11/26
 * @lastmod             2006/05/15 19:00 [modified stringBytes method and removed replace for UTF8 and \r\n]
 * 			[add UTF8 var again, PHP strings if are not encoded with utf8_encode aren't compatible with this object]
 *			[Partially rewrote for a better stability and compatibility with Safari or KDE based browsers]
 *			[UTF-8 now has a native support, strings are converted automatically with ISO or UTF-8 charset]
 *
 * @specialthanks	Fabio Sutto, Kentaromiura, Kroc Camen, Cecile Maigrot, John C.Scott, Matteo Galli
 *
 * @version             2.2, tested on FF 1.0, 1.5, IE 5, 5.5, 6, 7 beta 2, Opera 8.5, Konqueror 3.5, Safari 2.0.3
 */
function PHP_Serializer(UTF8) {
	
	/** public methods */
	function serialize(v) {
		// returns serialized var
		var	s;
		switch(v) {
			case null:
				s = "N;";
				break;
			default:
				s = this[this.__sc2s(v)] ? this[this.__sc2s(v)](v) : this[this.__sc2s(__o)](v);
				break;
		};
		return s;
	};
	
	function unserialize(s) {
		// returns unserialized var from a php serialized string
		__c = 0;
		__s = s;
		return this[__s.substr(__c, 1)]();
	};
	
	function stringBytes(s) {
		// returns the php lenght of a string (chars, not bytes)
		return s.length;
	};
	
	function stringBytesUTF8(s) {
		// returns the php lenght of a string (bytes, not chars)
		var 	c, b = 0,
			l = s.length;
		while(l) {
			c = s.charCodeAt(--l);
			b += (c < 128) ? 1 : ((c < 2048) ? 2 : ((c < 65536) ? 3 : 4));
		};
		return b;
	};
	
	/** private methods */
	function __sc2s(v) {
		return v.constructor.toString();
	};
	
	function __sc2sKonqueror(v) {
		var	f;
		switch(typeof(v)) {
			case ("string" || v instanceof String):
				f = "__sString";
				break;
			case ("number" || v instanceof Number):
				f = "__sNumber";
				break;
			case ("boolean" || v instanceof Boolean):
				f = "__sBoolean";
				break;
			case ("function" || v instanceof Function):
				f = "__sFunction";
				break;
			default:
				f = (v instanceof Array) ? "__sArray" : "__sObject";
				break;
		};
		return f;
	};
	
	function __sNConstructor(c) {
		return (c === "[function]" || c === "(Internal Function)");
	};
	
	function __sCommonAO(v) {
		var	b, n,
			a = 0,
			s = [];
		for(b in v) {
			n = v[b] == null;
			if(n || v[b].constructor != Function) {
				s[a] = [
					(!isNaN(b) && parseInt(b).toString() === b ? this.__sNumber(b) : this.__sString(b)),
					(n ? "N;" : this[this.__sc2s(v[b])] ? this[this.__sc2s(v[b])](v[b]) : this[this.__sc2s(__o)](v[b]))
				].join("");
				++a;
			};
		};
		return [a, s.join("")];
	};
	
	function __sBoolean(v) {
		return ["b:", (v ? "1" : "0"), ";"].join("");
	};
	
	function __sNumber(v) {
		var 	s = v.toString();
		return (s.indexOf(".") < 0 ? ["i:", s, ";"] : ["d:", s, ";"]).join("");
	};
	
	function __sString(v) {
		return ["s:", v.length, ":\"", v, "\";"].join("");
	};
	
	function __sStringUTF8(v) {
		return ["s:", this.stringBytes(v), ":\"", v, "\";"].join("");
	};
	
	function __sArray(v) {
		var 	s = this.__sCommonAO(v);
		return ["a:", s[0], ":{", s[1], "}"].join("");
	};
	
	function __sObject(v) {
		var 	o = this.__sc2s(v),
			n = o.substr(__n, (o.indexOf("(") - __n)),
			s = this.__sCommonAO(v);
		return ["O:", this.stringBytes(n), ":\"", n, "\":", s[0], ":{", s[1], "}"].join("");
	};
	
	function __sObjectIE7(v) {
		var 	o = this.__sc2s(v),
			n = o.substr(__n, (o.indexOf("(") - __n)),
			s = this.__sCommonAO(v);
		if(n.charAt(0) === " ")
			n = n.substring(1);
		return ["O:", this.stringBytes(n), ":\"", n, "\":", s[0], ":{", s[1], "}"].join("");
	};
	
	function __sObjectKonqueror(v) {
		var	o = v.constructor.toString(),
			n = this.__sNConstructor(o) ? "Object" : o.substr(__n, (o.indexOf("(") - __n)),
			s = this.__sCommonAO(v);
		return ["O:", this.stringBytes(n), ":\"", n, "\":", s[0], ":{", s[1], "}"].join("");
	};
	
	function __sFunction(v) {
		return "";
	};
	
	function __uCommonAO(tmp) {
		var	a, k;
		++__c;
		a = __s.indexOf(":", ++__c);
		k = parseInt(__s.substr(__c, (a - __c))) + 1;
		__c = a + 2;
		while(--k)
			tmp[this[__s.substr(__c, 1)]()] = this[__s.substr(__c, 1)]();
		return tmp;
	};

	function __uBoolean() {
		var	b = __s.substr((__c + 2), 1) === "1" ? true : false;
		__c += 4;
		return b;
	};
	
	function __uNumber() {
		var	sli = __s.indexOf(";", (__c + 1)) - 2,
			n = Number(__s.substr((__c + 2), (sli - __c)));
		__c = sli + 3;
		return n;
	};
	
	function __uStringUTF8() {
		var 	c, sls, sli, vls,
			pos = 0;
		__c += 2;
		sls = __s.substr(__c, (__s.indexOf(":", __c) - __c));
		sli = parseInt(sls);
		vls = sls = __c + sls.length + 2;
		while(sli) {
			c = __s.charCodeAt(vls);
			pos += (c < 128) ? 1 : ((c < 2048) ? 2 : ((c < 65536) ? 3 : 4));
			++vls;
			if(pos === sli)
				sli = 0;
		};
		pos = (vls - sls);
		__c = sls + pos + 2;
		return __s.substr(sls, pos);
	};
	
	function __uString() {
		var 	sls, sli;
		__c += 2;
		sls = __s.substr(__c, (__s.indexOf(":", __c) - __c));
		sli = parseInt(sls);
		sls = __c + sls.length + 2;
		__c = sls + sli + 2;
		return __s.substr(sls, sli);
	};
	
	function __uArray() {
		var	a = this.__uCommonAO([]);
		++__c;
		return a;
	};
	
	function __uObject() {
		var 	tmp = ["s", __s.substr(++__c, (__s.indexOf(":", (__c + 3)) - __c))].join(""),
			a = tmp.indexOf("\""),
			l = tmp.length - 2,
			o = tmp.substr((a + 1), (l - a));
		if(eval(["typeof(", o, ") === 'undefined'"].join("")))
			eval(["function ", o, "(){};"].join(""));
		__c += l;
		eval(["tmp = this.__uCommonAO(new ", o, "());"].join(""));
		++__c;
		return tmp;
	};
	
	function __uNull() {
		__c += 2;
		return null;
	};
	
	function __constructorCutLength() {
		function ie7bugCheck(){};
		var	o1 = new ie7bugCheck(),
			o2 = new Object(),
			c1 = __sc2s(o1),
			c2 = __sc2s(o2);
		if(c1.charAt(0) !== c2.charAt(0))
			__ie7 = true;
		return (__ie7 || c2.indexOf("(") !== 16) ? 9 : 10;
	};
	
	/** private variables */
	var 	__c = 0,
		__ie7 = false,
		__b = __sNConstructor(__c.constructor.toString()),
		__n = __b ? 9 : __constructorCutLength(),
		__s = "",
		__a = [],
		__o = {},
		__f = function(){};
	
	/** public prototypes */
	PHP_Serializer.prototype.serialize = serialize;
	PHP_Serializer.prototype.unserialize = unserialize;
	PHP_Serializer.prototype.stringBytes = UTF8 ? stringBytesUTF8 : stringBytes;
	
	/** serialize: private prototypes */
	if(__b) { // Konqueror / Safari prototypes
		PHP_Serializer.prototype.__sc2s = __sc2sKonqueror;
		PHP_Serializer.prototype.__sNConstructor = __sNConstructor;
		PHP_Serializer.prototype.__sCommonAO = __sCommonAO;
		PHP_Serializer.prototype[__sc2sKonqueror(__b)] = __sBoolean;
		PHP_Serializer.prototype.__sNumber = 
		PHP_Serializer.prototype[__sc2sKonqueror(__n)] = __sNumber;
		PHP_Serializer.prototype.__sString = PHP_Serializer.prototype[__sc2sKonqueror(__s)] = UTF8 ? __sStringUTF8 : __sString;
		PHP_Serializer.prototype[__sc2sKonqueror(__a)] = __sArray;
		PHP_Serializer.prototype[__sc2sKonqueror(__o)] = __sObjectKonqueror;
		PHP_Serializer.prototype[__sc2sKonqueror(__f)] = __sFunction;
	}
	else { // FireFox, IE, Opera prototypes
		PHP_Serializer.prototype.__sc2s = __sc2s;
		PHP_Serializer.prototype.__sCommonAO = __sCommonAO;
		PHP_Serializer.prototype[__sc2s(__b)] = __sBoolean;
		PHP_Serializer.prototype.__sNumber = 
		PHP_Serializer.prototype[__sc2s(__n)] = __sNumber;
		PHP_Serializer.prototype.__sString = PHP_Serializer.prototype[__sc2s(__s)] = UTF8 ? __sStringUTF8 : __sString;
		PHP_Serializer.prototype[__sc2s(__a)] = __sArray;
		PHP_Serializer.prototype[__sc2s(__o)] = __ie7 ? __sObjectIE7 : __sObject;
		PHP_Serializer.prototype[__sc2s(__f)] = __sFunction;
	};
	
	/** unserialize: private prototypes */
	PHP_Serializer.prototype.__uCommonAO = __uCommonAO;
	PHP_Serializer.prototype.b = __uBoolean;
	PHP_Serializer.prototype.i =
	PHP_Serializer.prototype.d = __uNumber;
	PHP_Serializer.prototype.s = UTF8 ? __uStringUTF8 : __uString;
	PHP_Serializer.prototype.a = __uArray;
	PHP_Serializer.prototype.O = __uObject;
	PHP_Serializer.prototype.N = __uNull;
};
	
	
	

