



evalAlias = function(id)
{
 this.addScript(id, 'blur');
 
 $("#"+id).bind("blur", function(e) {
 $(this).val( $.trim( $(this).val() ) );

 var filtro =/^[a-zA-Z]+[_a-zA-Z0-9]+[a-zA-Z0-9]{1,18}$/;

 if (!filtro.test( $(this).val() ))
 {
 mensaje(this, 'Debe ingresar al menos 3 caracteres, no puede comenzar con un n&uacute;mero y/o contener caracteres especiales.');
 }
 else
 {
 mensaje(this, '', false);
 }

 });
}

evalCorreo = function(id, obligatorio)
{
 this.addScript(id, 'blur');
 this.objetos[id] = new Array;
 this.objetos[id]['obligatorio'] = obligatorio;

 $("#"+id).bind("blur", function(e) {
 var obligatorio = forms[ $(this).parent().parent().attr('id') ].objetos[$(this).attr('id')]['obligatorio'];
 
 $(this).val( $.trim( $(this).val() ) );
 
 
 if (obligatorio == false && $(this).val() == '')
 {
 mensaje(this, '', false);
 return;
 }
 
 
 var filtro =/^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@+([_a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]{2,200}\.[a-zA-Z]{2,6}$/;
 if (!filtro.test( $(this).val() ))
 {
 mensaje(this, 'El correo no es v&aacute;lido.');
 }
 else
 {
 mensaje(this, '', false);
 }
 });
}

evalLen = function(id, min_len, max_len)
{
 this.addScript(id, 'blur');
 this.objetos[id] = new Array;
 this.objetos[id]['min_len'] = min_len;
 this.objetos[id]['max_len'] = max_len;

 $("#"+id).bind("blur", function(e) {
 var min_len = forms[ $(this).parent().parent().attr('id') ].objetos[$(this).attr('id')]['min_len'];
 var max_len = forms[ $(this).parent().parent().attr('id') ].objetos[$(this).attr('id')]['max_len'];

 var texto = $.trim( $(this).val() );
 texto.replace(' ', ' ');

 if( texto.length < min_len)
 {
 mensaje(this, 'Al menos tiene que escribir '+min_len+' caracteres.');
 }
 else if (max_len != null && texto.length > max_len)
 {
 mensaje(this, 'Sólo puede escribir '+max_len+' caracteres.');
 }
 else
 {
 mensaje(this, '', false);
 }
 });

 if (max_len != null)
 {
 $("#"+id).bind("keyup", function(e) {
 funcion_len(this);
 });
 $("#"+id).bind("focus", function(e) {
 funcion_len(this);
 });
 var funcion_len = function(objeto) {
 var min_len = forms[ $(objeto).parent().parent().attr('id') ].objetos[$(objeto).attr('id')]['min_len'];
 var max_len = forms[ $(objeto).parent().parent().attr('id') ].objetos[$(objeto).attr('id')]['max_len'];

 var texto = $.trim( $(objeto).val() );
 

 var mens = '';
 mens = 'Ha escrito <strong>'+(texto.length)+'</strong> caracter(es). Minimo: '+min_len+' - Maximo: '+max_len+'.';
 if (texto.length > max_len)
 mensaje(objeto, mens, true);
 else
 mensaje(objeto, mens, false);
 };
 }
}

evalContra = function(id, id_contra2)
{
 var contra = 0;
 this.addScript(id_contra2, 'blur');
 this.contra1 = id;
 this.contra2 = id_contra2;

 $("#"+id).bind("blur", function(e) {
 var contra2 = $( '#' + forms[ $(this).parent().parent().attr('id') ].contra2 );
 if ( $(contra2).val() != '' )
 $(contra2).blur();
 });

 $("#"+id_contra2).bind("blur", function(e) {

 var contra = $( '#' + forms[ $(this).parent().parent().attr('id') ].contra1 );

 if ( $(contra).val().length < 6 )
 {
 mensaje(contra, 'La contrase?a debe tener al menos 6 caracteres.');
 }
 else if ( $(this).val() != $(contra).val() )
 {
 mensaje(contra, 'Ambas contraseñas deben ser iguales, intente escribirlas nuevamente.');
 }
 else
 {
 mensaje(contra, '', false);
 }
 });

}

evalSelect = function(id, option_value_null)
{
 this.addScript(id, 'blur');
 this.objetos[id] = new Array;
 this.objetos[id]['option_value_null'] = option_value_null;

 $("#"+id).bind("blur", function(e) {
 var option_value_null = forms[ $(this).parent().parent().attr('id') ].objetos[$(this).attr('id')]['option_value_null'];

 if ($(this).val() == option_value_null)
 {
 mensaje(this, 'Selecciona una opción por favor.');
 }
 else
 {
 mensaje(this, '', false);
 }

 });
}

evalEntero = function(id, minimo, maximo)
{
 this.addScript(id, 'blur');
 this.objetos[id] = new Array;
 this.objetos[id]['minimo'] = minimo;
 this.objetos[id]['maximo'] = maximo;

 $("#"+id).bind("blur", function(e) {
 var filtro =/^[-]?[0-9]+$/;

 if (!filtro.test( $(this).val() ))
 {
 mensaje(this, 'Escriba un número por favor.');
 }
 else
 {
 var minimo = forms[ $(this).parent().parent().attr('id') ].objetos[$(this).attr('id')]['minimo'];
 var maximo = forms[ $(this).parent().parent().attr('id') ].objetos[$(this).attr('id')]['maximo'];
 if ($(this).val() < minimo)
 {
 mensaje(this, 'El valor es demasiado peque?o. '); 
 }
 else if ($(this).val() > maximo)
 {
 mensaje(this, 'El valor es demasiado grande.');
 }
 else
 {
 mensaje(this, '', false);
 }
 }
 });
}


evalDecimal = function(id, decimales, minimo, maximo)
{
 this.addScript(id, 'blur');
 this.objetos[id] = new Array;
 this.objetos[id]['decimales'] = decimales;
 this.objetos[id]['minimo'] = minimo;
 this.objetos[id]['maximo'] = maximo;

 $("#"+id).bind("blur", function(e) {

 if (isNaN( parseFloat($(this).val()) ))
 {
 mensaje(this, 'Escriba un n?mero por favor.');
 }
 else
 {
 var minimo = forms[ $(this).parent().parent().attr('id') ].objetos[$(this).attr('id')]['minimo'];
 var maximo = forms[ $(this).parent().parent().attr('id') ].objetos[$(this).attr('id')]['maximo'];
 if ($(this).val() < minimo)
 {
 mensaje(this, 'El valor es demasiado peque?o. ');
 }
 else if (maximo != null && $(this).val() > maximo)
 {
 mensaje(this, 'El valor es demasiado grande.');
 }
 else
 {
 var decimales = forms[ $(this).parent().parent().attr('id') ].objetos[$(this).attr('id')]['decimales'];
 var numero = $(this).val();
 $(this).val( Math.round(numero * Math.pow(10, decimales)) / Math.pow(10, decimales) );

 mensaje(this, '', false);
 }
 }
 });
}

evalFecha = function(id, minimo, maximo)
{
 this.addScript(id, 'blur');
 this.objetos[id] = new Array;
 this.objetos[id]['minimo'] = minimo;
 this.objetos[id]['maximo'] = maximo;

 $("#"+id).bind("blur", function(e) { 
 
 var filtro = /^\d{1,2}\/\d{1,2}\/\d{2,4}$/;

 var texto = $.trim( $(this).val() );
 texto = texto.replace(/-/g, '/');
 
 if (!filtro.test( texto ))
 {
 mensaje(this, 'Escriba una fecha por favor.');
 }
 else
 {
 mensaje(this, '', false);
 }
 $(this).val(texto);
 });
}

evalFile = function(id)
{
 this.addScript(id, 'blur');

 $("#"+id).bind("blur", function(e) {
 if ($(this).val() == '')
 {
 mensaje(this, 'Seleccione un archivo por favor.');
 }
 else
 {
 mensaje(this, '', false);
 }
 });
}

selectInclude = function(id, depende_de_id, depende_de_file)
{
 if (this.objetos[depende_de_id] == undefined)
 this.objetos[depende_de_id] = new Array;
 this.objetos[depende_de_id]['objetivo_id'] = id;
 this.objetos[depende_de_id]['objetivo_file'] = depende_de_file;

 
 this.objetos[depende_de_id]['value_antes'] = $('#'+depende_de_id).val();

 $("#"+depende_de_id).bind("focus", function(e) {
 
 var frm = $(this).parent().parent().attr('id');
 var id = $(this).attr('id');
 forms[frm].objetos[id]['value_antes'] = $(this).val();
 });
 $("#"+depende_de_id).bind("blur", function(e) {
 var frm = $(this).parent().parent().attr('id');
 var id = $(this).attr('id');

 
 if (forms[frm].objetos[id]['value_antes'] == $(this).val()) return;
 forms[frm].objetos[id]['value_antes'] = $(this).val();

 var depende_value = $(this).val();
 var objetivo_id = forms[frm].objetos[id]['objetivo_id'];
 var objetivo_file = forms[frm].objetos[id]['objetivo_file'];

 
 $("#"+objetivo_id).text('');
 $("#"+objetivo_id).append('<option>Cargando...</option>');
 $("#"+objetivo_id).attr('disabled', 'disabled');

 var retorna = $.ajax({
 type: "GET",
 url: objetivo_file+"?id="+objetivo_id+"&depende="+depende_value,
 async: false
 }).responseText;

 $("#"+objetivo_id).text('');
 if (retorna != '')
 {
 $("#"+objetivo_id).attr('disabled', '');
 $("#"+objetivo_id).append(retorna);
 document.getElementById(objetivo_id).selectedIndex=0;
 }
 else
 {
 $("#"+objetivo_id).append('<option value="-1">No hay opciones...</option>');
 }
 mensaje("#"+objetivo_id, '', false);
 $("#"+objetivo_id).blur();
 });
}

Form = function(id_form)
{
 this.id = id_form;
 this.error = false;
 this.script = ''; 
 this.objetos = new Array();
 this.addScript = addScript;
 this.evalAlias = evalAlias;
 this.evalCorreo = evalCorreo;
 this.evalLen = evalLen;
 this.evalContra = evalContra;
 this.evalSelect = evalSelect;
 this.evalEntero = evalEntero;
 this.evalDecimal = evalDecimal;
 this.evalFecha = evalFecha;
 this.evalFile = evalFile;
 this.selectInclude = selectInclude;
 
 $('#'+this.id).bind('submit', function(event)
 {
 
 
 if (event.isPropagationStopped())
 return false;
 
 var thiis = forms[ $(this).attr('id') ];
 thiis.error = '';
 
 eval( thiis.script );
 
 
 if (thiis.error != ''&& $('#'+thiis.error).parent().is(':visible'))
 {
 $('#'+thiis.error)
 .focus()
 .prev()
 .fadeTo(10, 0.1)
 .fadeTo('slow', 1);
 return false;
 }
 
 $('.submit').attr('disabled', 'disabled');
 });
 
 
}


mensaje = function (objeto, mensaje, error)
{
 if (error == undefined) error = true;

 var claseadd = '';
 var claserem = '';
 if (error)
 {
 claseadd='error';
 claserem='info';
 } else {
 claseadd='info';
 claserem='error';
 }
 
 
 label = $(objeto).prev();
 if ( $(objeto).next('div').length == 0)
 $(objeto).after('<div></div>');
 destino = $(objeto).next('');

 $(label)
 .addClass(claseadd)
 .removeClass(claserem);
 
 if (mensaje == '')
 {
 $(destino).slideUp("slow", function (){
 $(this)
 .removeClass('error')
 .html('');
 });
 } else {
 $(destino)
 .addClass(claseadd)
 .removeClass(claserem);
 
 
 if ($(destino).html() == '') 
 {
 $(destino).hide();
 $(destino).html(mensaje);
 $(destino).slideDown("slow");
 }

 
 if ($(destino).html() != '')
 {
 $(destino).html(mensaje);
 }
 
 thiis = forms[ $(objeto).parent().parent().attr('id') ];
 thiis.error = $(objeto).attr('id');
 }
}

addScript = function (id, evento)
{
 this.script = '$("#'+id+'").'+evento+'(); ' + this.script;
}




$(document).ready( function()
{
 $('div.table table').bind('click', function(e) {
 var $object = $(e.target);

 if ($object.get(0).tagName == 'A')
 {
 if ($object.hasClass('eliminar'))
 return a_eliminar($object);
 }
 else
 {
 
 return td_click($object);
 }
 return true;
 });

 function td_click($td)
 {
 if ($td.get(0).tagName != 'TD')
 $td = $td.parents('TD');
 
 if ($td.attr('class') != 'no_edit' && $td.attr('class') != 'sort')
 {
 var fila;
 fila = $td.parents('tr'); 
 
 var url = $('a.editar', fila).attr("href");
 if (url === undefined || url == null) return false;

 location.href = url;
 return false;
 }
 
 return true;
 }

 function a_eliminar($elemento)
 {
 if ($elemento.attr('rel') != '1') 
 {
 var clase = $elemento.parents('table').attr('class');
 
 
 if (clase.indexOf('confirm') != -1)
 {
 if (!confirm('¿Está seguro que desea eliminar el elemento?'))
 return false;
 }

 if (clase.indexOf('ajax') == -1)
 return true;

 $elemento.attr('rel', '1')
 .fadeTo("slow", 0.5);

 $.get($elemento.attr('href'), function(data) {

 var $destino = $elemento.parent().parent();
 
 if (data !== '1' && data !== '0')
 {
 alert('Error. Respuesta: "'+data+'"');
 $elemento.attr('rel', '').fadeTo("slow", 1);
 } else {
 if (data == 0) data = 0.5;

 $destino.fadeTo("slow", data);

 $elemento.attr('rel', '')
 .fadeTo("slow", 1);
 }
 });
 }
 return false;
 }
 
});




$(document).ready( function()
{
 $('table.sort').tableDnD({
 dragHandle: 'sort',
 onDragClass: 'draggin',
 onDragStart: function(table, row) {
 var $table = $(table);
 
 $table.find('div.guardar').fadeTo('fast', 0, function(){ $(this).remove(); });
 },
 onDrop: function(table, row) {
 var $table = $(table);
 var $td = $(row).find('td:last');

 
 

 
 var $guardar = $('<div class="guardar"><div><a href="#">Guardar</a></div></div>');
 if ($.support.opacity) 
 $guardar.fadeTo(1, 0);
 $td.append($guardar);
 if ($.support.opacity) 
 $guardar.fadeTo('slow', 1);

 
 $guardar.find('a')
 .bind('mousedown', function(e) { return false; } ) 
 .bind('click', function(e) {
 var $this = $(this);

 
 var $table = $this.parents('div.table').children();
 var ids = '';
 $table.find('tr[rel]').each(function() {
 ids = ids + $(this).attr('rel')+',';
 });
 var xml_url = $table.attr('rel');

 $.post(xml_url, {table_sort : ids }, function(data) {
 if (data == 1)
 $this.parent().html('Guardado').fadeTo('slow', 0, function(){ $(this).remove(); });
 else
 alert('No se pudo guardar el nuevo orden');
 });
 return false;
 });
 }
 }
 );
});

jQuery.tableDnD = {
 
 currentTable : null,
 
 dragObject: null,
 
 mouseOffset: null,
 
 oldY: 0,

 
 build: function(options) {
 

 this.each(function() {
 
 this.tableDnDConfig = jQuery.extend({
 onDragStyle: null,
 onDropStyle: null,
 
 onDragClass: "tDnD_whileDrag",
 onDrop: null,
 onDragStart: null,
 scrollAmount: 5,
 serializeRegexp: /[^\-]*$/, 
 serializeParamName: null, 
 dragHandle: null 
 }, options || {});
 
 jQuery.tableDnD.makeDraggable(this);
 });

 
 
 jQuery(document)
 .bind('mousemove', jQuery.tableDnD.mousemove)
 .bind('mouseup', jQuery.tableDnD.mouseup);

 
 return this;
 },

 
 makeDraggable: function(table) {
 var config = table.tableDnDConfig;
 if (table.tableDnDConfig.dragHandle) {
 
 var cells = jQuery("td."+table.tableDnDConfig.dragHandle, table);
 cells.each(function() {
 
 jQuery(this).mousedown(function(ev) {
 jQuery.tableDnD.dragObject = this.parentNode;
 jQuery.tableDnD.currentTable = table;
 jQuery.tableDnD.mouseOffset = jQuery.tableDnD.getMouseOffset(this, ev);
 if (config.onDragStart) {
 
 config.onDragStart(table, this);
 }
 return false;
 });
 })
 } else {
 
 var rows = jQuery("tr", table); 
 rows.each(function() {
 
 var row = jQuery(this);
 if (! row.hasClass("nodrag")) {
 row.mousedown(function(ev) {
 if (ev.target.tagName == "TD") {
 jQuery.tableDnD.dragObject = this;
 jQuery.tableDnD.currentTable = table;
 jQuery.tableDnD.mouseOffset = jQuery.tableDnD.getMouseOffset(this, ev);
 if (config.onDragStart) {
 
 config.onDragStart(table, this);
 }
 return false;
 }
 }).css("cursor", "move"); 
 }
 });
 }
 },

 updateTables: function() {
 this.each(function() {
 
 if (this.tableDnDConfig) {
 jQuery.tableDnD.makeDraggable(this);
 }
 })
 },

 
 mouseCoords: function(ev){
 if(ev.pageX || ev.pageY){
 return {x:ev.pageX, y:ev.pageY};
 }
 return {
 x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
 y:ev.clientY + document.body.scrollTop - document.body.clientTop
 };
 },

 
 getMouseOffset: function(target, ev) {
 ev = ev || window.event;

 var docPos = this.getPosition(target);
 var mousePos = this.mouseCoords(ev);
 return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y};
 },

 
 getPosition: function(e){
 var left = 0;
 var top = 0;
 
 if (e.offsetHeight == 0) {
 
 e = e.firstChild; 
 }

 while (e.offsetParent){
 left += e.offsetLeft;
 top += e.offsetTop;
 e = e.offsetParent;
 }

 left += e.offsetLeft;
 top += e.offsetTop;

 return {x:left, y:top};
 },

 mousemove: function(ev) {
 if (jQuery.tableDnD.dragObject == null) {
 return;
 }

 var dragObj = jQuery(jQuery.tableDnD.dragObject);
 var config = jQuery.tableDnD.currentTable.tableDnDConfig;
 var mousePos = jQuery.tableDnD.mouseCoords(ev);
 var y = mousePos.y - jQuery.tableDnD.mouseOffset.y;
 
 var yOffset = window.pageYOffset;
 if (document.all) {
 
 
 if (typeof document.compatMode != 'undefined' &&
 document.compatMode != 'BackCompat') {
 yOffset = document.documentElement.scrollTop;
 }
 else if (typeof document.body != 'undefined') {
 yOffset=document.body.scrollTop;
 }

 }
 
 if (mousePos.y-yOffset < config.scrollAmount) {
 window.scrollBy(0, -config.scrollAmount);
 } else {
 var windowHeight = window.innerHeight ? window.innerHeight
 : document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight;
 if (windowHeight-(mousePos.y-yOffset) < config.scrollAmount) {
 window.scrollBy(0, config.scrollAmount);
 }
 }


 if (y != jQuery.tableDnD.oldY) {
 
 var movingDown = y > jQuery.tableDnD.oldY;
 
 jQuery.tableDnD.oldY = y;
 
 if (config.onDragClass) {
 dragObj.addClass(config.onDragClass);
 } else {
 dragObj.css(config.onDragStyle);
 }
 
 
 var currentRow = jQuery.tableDnD.findDropTargetRow(dragObj, y);
 if (currentRow) {
 
 if (movingDown && jQuery.tableDnD.dragObject != currentRow) {
 jQuery.tableDnD.dragObject.parentNode.insertBefore(jQuery.tableDnD.dragObject, currentRow.nextSibling);
 } else if (! movingDown && jQuery.tableDnD.dragObject != currentRow) {
 jQuery.tableDnD.dragObject.parentNode.insertBefore(jQuery.tableDnD.dragObject, currentRow);
 }
 }
 }

 return false;
 },

 
 findDropTargetRow: function(draggedRow, y) {
 var rows = jQuery.tableDnD.currentTable.rows;
 for (var i=0; i<rows.length; i++) {
 var row = rows[i];
 var rowY = this.getPosition(row).y;
 var rowHeight = parseInt(row.offsetHeight)/2;
 if (row.offsetHeight == 0) {
 rowY = this.getPosition(row.firstChild).y;
 rowHeight = parseInt(row.firstChild.offsetHeight)/2;
 }
 
 if ((y > rowY - rowHeight) && (y < (rowY + rowHeight))) {
 
 
 if (row == draggedRow) {return null;}
 var config = jQuery.tableDnD.currentTable.tableDnDConfig;
 if (config.onAllowDrop) {
 if (config.onAllowDrop(draggedRow, row)) {
 return row;
 } else {
 return null;
 }
 } else {
 
 
 var nodrop = jQuery(row).hasClass("nodrop");
 if (! nodrop && jQuery(row).children(0).get(0).tagName != 'TH') {
 return row;
 } else {
 return null;
 }
 }
 return row;
 }
 }
 return null;
 },

 mouseup: function(e) {
 if (jQuery.tableDnD.currentTable && jQuery.tableDnD.dragObject) {
 var droppedRow = jQuery.tableDnD.dragObject;
 var config = jQuery.tableDnD.currentTable.tableDnDConfig;
 
 
 if (config.onDragClass) {
 jQuery(droppedRow).removeClass(config.onDragClass);
 } else {
 jQuery(droppedRow).css(config.onDropStyle);
 }
 jQuery.tableDnD.dragObject = null;
 if (config.onDrop) {
 
 config.onDrop(jQuery.tableDnD.currentTable, droppedRow);
 }
 jQuery.tableDnD.currentTable = null; 
 }
 },

 serialize: function() {
 if (jQuery.tableDnD.currentTable) {
 return jQuery.tableDnD.serializeTable(jQuery.tableDnD.currentTable);
 } else {
 return "Error: No Table id set, you need to set an id on your table and every row";
 }
 },

 serializeTable: function(table) {
 var result = "";
 var tableId = table.id;
 var rows = table.rows;
 for (var i=0; i<rows.length; i++) {
 if (result.length > 0) result += "&";
 var rowId = rows[i].id;
 if (rowId && rowId && table.tableDnDConfig && table.tableDnDConfig.serializeRegexp) {
 rowId = rowId.match(table.tableDnDConfig.serializeRegexp)[0];
 }

 result += tableId + '[]=' + rowId;
 }
 return result;
 },

 serializeTables: function() {
 var result = "";
 this.each(function() {
 
 result += jQuery.tableDnD.serializeTable(this);
 });
 return result;
 }

}

jQuery.fn.extend(
 {
 tableDnD : jQuery.tableDnD.build,
 tableDnDUpdate : jQuery.tableDnD.updateTables,
 tableDnDSerialize: jQuery.tableDnD.serializeTables
 }
);
