/*
	FUNCIONES DEL CALENDARIO
*/

var toDateUpdate="";
auxfecha=new Date();
var hoyEs=''+auxfecha.getDate()+'/'+(auxfecha.getMonth()+1)+'/'+auxfecha.getFullYear();
var hoyEn=''+(auxfecha.getMonth()+1)+'/'+auxfecha.getDate()+'/'+auxfecha.getFullYear();

var url = window.location.host;
if (url.indexOf('www') == -1){	if (url.indexOf('.tomadepedidos.com.ar') > -1){ var empresa = url.replace(".tomadepedidos.com.ar", "");  }else{  var empresa = '' ; } }else{ empresa = ''; }

var intervalID //GLOBAL INTERVAL

//this is a global variable to have only one instance of the calendar
var calendar = null;

function showCalendar(element, input, container, source) {		
	//element   => is the <div> where the calender will be rendered by Scal.
	//input     => is the <input> where the date will be updated.
	//container => is the <div> for dragging.
	//source    => is the img/button which raises up the calender, the script will locate the calenar over this control.

	if (!calendar){
		container = $(container);
		//the Draggable handle is hard coded to "rtop" to avoid other parameter.
		new Draggable(container, {handle: "rtop", starteffect: Prototype.emptyFunction, endeffect: Prototype.emptyFunction});
		
		//The singleton calendar is created.
		calendar = new scal(element, $(input), {
			updateformat: 'dd/mm/yyyy', 
			closebutton: '&nbsp;', 
			wrapper: container
		}); 
	} else {
		calendar.updateelement = $(input);
	}

	var date = new Date($F(input));
	calendar.setCurrentDate(isNaN(date) ? new Date() : date);
	
	//Locates the calendar over the calling control  (in this example the "img").
	if (source = $(source)){
		Position.clone($(source), container, {setWidth: false, setHeight: false, offsetLeft: source.getWidth() + 2});
	}
	
	//finally show the calendar =)
	calendar.openCalendar();
};


function estilizarFechas(tdu){
	id=tdu.substr(tdu.indexOf('_'));
//	alert(id);
//	var lnks = document.getElementsByClassName('linkfechaSelected');
	var lnks = $$('a.linkfechaSelected');
	lnks.each( function (xitem){ xitem.className="linkfecha"; });
	
//	var lnks=document.getElementsByClassName('linkfecha');
	var lnks = $$('a.linkfecha');
	lnks.each( 
		function (xitem){ 
			sufix=xitem.id.substr(xitem.id.indexOf('_'));
			if (sufix==id) xitem.className="linkfechaSelected";
		}		  
	);
}

function getCanonical( date,  format_real, formato_return  ){
	if ( format_real == 'dd/mm/yyyy' ){
		switch ( formato_return ){
			case 'yyyy/mm/dd': 
				return date.split("/")[2]+'/'+date.split("/")[1]+'/'+date.split("/")[0]
				break;
			case 'yyyymmdd' : 
				return date.split("/")[2]+date.split("/")[1]+date.split("/")[0]
				break;
		}
			
	}
}

function posCalendar( id ){
	toDateUpdate=id;
	
	cal=$('divCalendario');
	cal.style.left=xMousePos+'px';
	cal.style.top=yMousePos+'px';
	ver('divCalendario', 1);
	
	// $('startDate').value = new Date( getCanonical( $(id).innerHTML, 'dd/mm/yyyy')  ).format('dd/mm/yyyy')
	$('realDate').value = new Date( getCanonical( $(id).innerHTML, 'dd/mm/yyyy', 'yyyy/mm/dd') )
	
	$('calendar-container').show().descendants().invoke('show')
	
	showCalendar('calendar','realDate','calendar-container',$('imgStartDate'));
}

function changeCalendar(ctl,ctl2,mostrar){
	//if ($('divCalendario').visible()) return;

	fe=$F(ctl);
	
	if (ctl2=='realDate'){
		//le llega una fecha al visible, ya esta validada
			validar_fecha(fe)
			$(ctl2).value=fe.substring(3,6)+fe.substring(0,3)+fe.substr(6);
	}else{
		//tengo que validar
		aux = validaFecha(fe);
		if (aux!=''){
				validar_fecha(aux)
				$(ctl2).value=aux.substr(3,2)+'/'+aux.substr(0,2)+'/'+aux.substr(6,4);
				if (mostrar) showCalendar('calendar','startDate','calendar-container',$('imgStartDate'));
		}
	}
}

function validar_fecha( date , field ){ 
	// SIRVE PARA COMPARAR LAS FECHAS DE ENTREGA Y PEDIDO,
	// NO PARA SABER SI LA FECHA ES VALIDA
	var msg = '';
	
	selectedDate = new Date( getCanonical( date, 'dd/mm/yyyy', 'yyyy/mm/dd' ) ); //
	if ( idPedNuevo =! curIdPed ){
		checkDate = new Date();
		msg = 'La fecha elegida es menor a la de hoy';
	}else{
		switch ( field ){
			case 'fechaPedido':
				//_capa = $(field + '_' + curIdPed).innerHTML.split("/")
				_capa = $('fechadehoy').value.split("/")				
				checkDate = new Date( _capa[2]+'/'+_capa[1]+'/'+_capa[0] ); // FECHA 
				if ( selectedDate < checkDate ) msg = 'La fecha del pedido es menor al d\u00eda de hoy'; 
				_capa = $('fechaEntrega' + '_' + curIdPed).innerHTML.split("/")
				checkDate = new Date( _capa[2]+'/'+_capa[1]+'/'+_capa[0] ); // FECHA 				
				if ( selectedDate > checkDate )	msg = 'La fecha de pedido es mayor a la de entrega';
				break;
			case 'fechaEntrega':
				_capa = $('fechaPedido' + '_' + curIdPed).innerHTML.split("/")
				checkDate = new Date(  _capa[2]+'/'+_capa[1]+'/'+_capa[0] ); // FECHA 
				if ( selectedDate < checkDate )	msg = 'La fecha de entrega es menor a la de pedido';
				break;
		}
	}
	
	if ( msg != '' ) { 
		alert(msg); 
		return false; 
	}else{
		return true;			
	}
}

function updateDate( ctl ){
	// genera una llamada ajax 
	// que actualiza la base de datos
	// ctl => id de elemento del calendario
	if ( toDateUpdate != null ){
		date = $F(ctl);
		campo = toDateUpdate.split("_")[0];
		dato = getCanonical( date , 'dd/mm/yyyy' , 'yyyymmdd' );
		id = toDateUpdate.split("_")[1];
		feedback = date
		
		if ( validar_fecha( date , campo ) ){
			resAjax('_sql.asp', toDateUpdate, 'ope=2&tabla=pedidos&campo='+campo+'&dato='+dato+'&key=idPedidos&id='+id+'&feedback='+feedback);
			calendar.toggleCalendar();
			ver( 'divCalendario' , 0 )
		}
	}
}

function emptyCalendar(ctl,ctl2, capa){
	if ( typeof capa != 'undefined' ) {
		anio = $(capa).innerHTML.split("/")[2]
		mes = $(capa).innerHTML.split("/")[1]
		dia= $(capa).innerHTML.split("/")[0]
	
		var _hoyEs=dia+'/'+mes+'/'+anio
		var _hoyEn=mes+'/'+dia+'/'+anio
	}else{
		_hoyEs = hoyEs;
		_hoyEn = hoyEn;
	}
	
	$(ctl2).value=_hoyEn;
	$(ctl).value=_hoyEs;

	ver('divCalendario', 0);
	toDateUpdate="";
	if (calendar) calendar.closeCalendar();
}

function acceptNum(e, bent, besc, ctl){	
	if(window.event){
		keynum = e.keyCode;
	}
	else if(e.which){
		keynum = e.which;
	}
	if (keynum == 13) {$(bent).focus(); $(bent).click();}
	else if (keynum == 27) $(besc).click();
	else{
		var cadena = "1234567890/-";
		var aux="";
		for (var contador = 0 ; contador < ctl.value.length ; contador++){
			if (cadena.indexOf(ctl.value.substr(contador, 1),0) > -1){
				aux += ctl.value.substr(contador, 1);
			}
		}
		if (ctl.value!=aux) ctl.value=aux;
	}
}

function validaFecha(valor){  
	  var aux = replaceStr(valor,'-','/');
	  if(aux.substr(1,1) == "/") aux = '0'+aux;
	  //alert(aux);
	  if(aux.substr(4,1) == "/") aux = aux.substr(0,3)+'0'+aux.substr(3);
	  //alert(aux);
	  if ((aux.substr(2,1) == "/") && (aux.substr(5,1) == "/")){      
	  //alert('entro '+aux);
		 for (i=0; i<aux.length; i++){	
			if (((aux.substr(i,1)<"0") || (aux.substr(i,1)>"9")) && (i != 2) && (i != 5)){
			   aux = '';
			   break;  
			}  
		 }
		 if (aux.length>0){ 
			//conversion del ao corto
			anio=aux.substr(6,4);
			if (anio.length<4){ 
				anio='20'+anio.substr(0,2);
				aux=aux.substr(0,2)+'/'+aux.substr(3,2)+'/'+anio;
			}
			a = parseInt(anio);
			m = aux.substr(3,2);
			d = parseInt(aux.substr(0,2));
			//alert('d: '+d+' m: '+m+' a: '+a);
			if((a < 2008) || (a > 2050) || (m < 1) || (m > 12) || (d < 1) || (d > 31))
			   aux = '';
			else{
			   if((a%4 != 0) && (m == 2) && (d > 28))	   
				  aux = ''; 
			   else{
				  if ((((m == 4) || (m == 6) || (m == 9) || (m==11)) && (d>30)) || ((m==2) && (d>29)))
					 aux = '';	      				  	 
			   }  
			} 
		 } // if (error)
	  }else
		 aux = '';
	  if (aux == '')
	     alert('Fecha erronea');
	  return aux;
}

var imgCalendar_Click = function(e, input){
	showCalendar("calendar", input, "calendar-container", Event.element(e));
};

Event.observe(window, "load", function(e){
	if ($("calendar-container")!=null) Event.observe("imgStartDate", "click", imgCalendar_Click.bindAsEventListener(this, "startDate"));
});

/*
		MOUSE EVENTS
*/

if (document.layers) { // Netscape
    document.captureEvents(Event.MOUSEUP);
    document.onmouseup = captureMousePosition;
} else if (document.all) { // Internet Explorer
    document.onmouseup = captureMousePosition;
} else if (document.getElementById) { // Netcsape 6
    document.onmouseup = captureMousePosition;
}
// Global variables
xMousePos = 0; // Horizontal position of the mouse on the screen
yMousePos = 0; // Vertical position of the mouse on the screen
xMousePosMax = 0; // Width of the page
yMousePosMax = 0; // Height of the page

function captureMousePosition(e) {
    if (document.layers) {
        xMousePos = e.pageX;
        yMousePos = e.pageY;
        xMousePosMax = window.innerWidth+window.pageXOffset;
        yMousePosMax = window.innerHeight+window.pageYOffset;
    } else if (document.all) {
        xMousePos = window.event.x+document.body.scrollLeft;
        yMousePos = window.event.y+document.body.scrollTop;
        xMousePosMax = document.body.clientWidth+document.body.scrollLeft;
        yMousePosMax = document.body.clientHeight+document.body.scrollTop;
    } else if (document.getElementById) {
        // Netscape 6 behaves the same as Netscape 4 in this regard
        xMousePos = e.pageX;
        yMousePos = e.pageY;
        xMousePosMax = window.innerWidth+window.pageXOffset;
        yMousePosMax = window.innerHeight+window.pageYOffset;
    }
}

/*
		ELEMENT - MOUSE EVENTS
*/

function posCC(idPedido){
	// posiciona el elemento 'cajaClientes' en el renglon del idPedido
	CC=$('cajaClientes');
	CC.style.left=xMousePos+'px';
	CC.style.top=yMousePos+'px';
	ver('cajaClientes', 1);
}

function abrirMenu_servicios(id){
	menu = $('menu_servicios');
	menu.setStyle({	'left' : $(id).viewportOffset()[0] + 17 +'px',
					 'top' : $(id).viewportOffset()[1] + 'px' });
	Effect.toggle( menu , 'appear' , {duration: 0.5});
	document.observe('click', function (event) { menu_servicios_handler(event, id) }  );
}

function menu_servicios_handler(event, id){
	menu = $('menu_servicios');
	
	if ( Event.element(event).up(0) != $(id) && Event.element(event) != menu ){
		menu.fade({duration: 0.5});
		document.stopObserving(	'click' );
	}
}

//COOKIES
function getThisCookie(name){
	devolver=""; //default
	var cname=name + "=";
	var dc=document.cookie;  
	if(dc.length>0){
		  begin=dc.indexOf(cname);
		  if(begin!=-1){
			begin+=cname.length;
			end=dc.indexOf(";",begin);
			if(end==-1) end=dc.length;
			devolver=dc.substring(begin,end);
		  }
	}
	return devolver;
 }

function setCookie(name,value,expires){
   document.cookie=name+ "=" +escape(value) +
   ((expires==null)?"":";expires="+expires.toGMTString());
}

/*
		BUSQUEDA
*/

var delayBuscarInt = 'BUSCAR';
var inputBuscarInt_1;
var inputBuscarInt_2;

function delayBuscar(xdatafile, xcapa, xcampo, xvalor, xtipo, evento){
	// se usa para buscar un articulo.
	// crea un intervalo ( incBuscar )
	// xdatafile	= url
	// xcapa		= elemento a actualizar
	// xcampo		= campo para buscar
	// xvalor		= valor del campo
	// xtipo		= ?
	// evento		= evento por el que fue disparado la function
	var agregar = esEnter( evento ); 
	
	inputBuscarInt_1 = xvalor;
	
	if (agregar) {
		if ( existe( 'unSoloArt' ) ){
			if ( $F('unSoloArt') != '0' ){
				addArt($F('unSoloArt'));
				clearInterval( delayBuscarInt );
				delayBuscarInt = "BUSCAR";
				return;
			}
		}
	}
	if ( xvalor.length >= 3 ){
		if ( delayBuscarInt == 'BUSCAR' ){
			var capa=$(xcapa);
			capa.innerHTML='<div style="width: 100%; height: 100%; position: relative;"><img border="0" style="position: absolute; top: 50%; left:50%" src="images/PleaseWait.gif"/></div>';
			if ( esLetraYnumero ( xvalor ) ) 
				delayBuscarInt = setInterval("incBuscar('" + xdatafile +"','"+ xcapa +"','"+ xcampo +"','"+ xtipo +"'," + agregar + "); ", 400);
			else capa.innerHTML = '';
		}
	}
}

function incBuscar(datafile, capa, campo, tipo, agregar){
	// Dispara una llamada ajax si el campo
	// tiene un valor diferente al anterior
	valor=fixAscii($F(campo));
	
	if ( inputBuscarInt_1 == inputBuscarInt_2 ){
// 		if ( campo == 'codigo' ) tipo = '=';
		resAjax(datafile, capa, '&campo=' + campo + '&tipo=' + tipo + '&valor=' + valor);
		inputBuscarInt_2 = inputBuscarInt_1 = '';
		clearInterval( delayBuscarInt );
		delayBuscarInt = "BUSCAR";
	}else{
		inputBuscarInt_2 = inputBuscarInt_1;
		inputBuscarInt_1 = '';
	}
}


function esLetraYnumero( s ){
	var re = new RegExp('[A-Za-z0-9 ]');	
	
	var esLetra = true;
	var sArray = s.toArray();

	sArray.each( function ( _s ){
		if ( _s.match( re ) ) {
			if ( esLetra != false ) esLetra = true;
		}else esLetra = false;
	});
	
	if ( esLetra ) return true; else return false;
}

/*
		PAGINADO
*/

function irA(datafile, nropag, campo, tipo, valor){
	// se usa en el paginado
	// es para cambiar la pagina
	resAjax(datafile + '?pag=' + nropag, 'artResultado', '&campo=' + campo + '&tipo=' + tipo + '&valor=' + valor);
}

/*
		AJAX
*/

//Prototype Ajax
function resAjax(datafile, xcapa, qs, after, clase, numRows, numSize, maxLength, afterfile){
	// datafile		= url del ajax
	// xcapa		= el elemento (si existe) que se va a actualizar con la rpta.
	// qs			= parametros
	// after		= bandera para hacer los inplaceeditors ( opcional )
	// clase		= clase de los elementos para hacer inplace ( opcional )
	// numRows, numSize, maxLength = tamao de los inplace ( opcional )
	// afterfile	= url para el ajax del inplace ( opcional )
	//alert(qs)
	if ( existe( xcapa ) ) {
		var capa=$(xcapa);
		capa.innerHTML='<div style="width: 100%; height: 100%; position: relative;"><img border="0" style="position: absolute; top: 50%; left:50%" src="images/PleaseWait.gif"/></div>';
	}
	
	this.salida = function(solicitud){
		//document.location.href='_login.asp';
	}
	this.respuesta = function(solicitud){
		//si vencio la session lo mando a logear y sale
		if (solicitud.responseText.indexOf('gotoLogin')>-1){ 
			alert( 'Sr. Usuario:\r\nLa sesion a finalizado.\r\nSe le redireccionara a la pantalla de login' );
			document.location.href='_login.asp';	
		}else{
			if ( existe( xcapa ) ) capa.update(solicitud.responseText);
			initflag=false;
			//initdif=setTimeout(init,delay);
			if (after!=null){
				var matriz=new Array();
				var matrizExtCtls=new Array();
				var divs=$$('div.'+clase);
				divs.each( function (item){ 
					var xdiv = item.id.split("_")[0];
					var Safter = Object.values( after ).toString();
					if ( Safter.indexOf(xdiv) > -1 ){
						matriz.push(item.id); 
					} 
				});
				
				if (matriz.length>0){ edFromArray(afterfile,matriz,numRows,numSize,maxLength); }
			}
			
			if ( exist_f("nuevoEvento") ) { nuevoEvento(); }
			if ( exist_f("getSelected") ) { makeEditable('usuariosRow_'+curIdPed,'',0); }
		}
	}
	
	//alert(datafile);
	
	var solicitud = new Ajax.Request( datafile,{
									 	encoding: 'ISO-8859-1',
										parameters: qs, 
										onComplete: this.respuesta, 
										onFailure: this.salida, 
										evalJS: 'force', 
										asynchronous:false
					});
	f_ajaxHistory(solicitud);
}

//creo una hash para tener todas los envios de ajax
var ajaxHistory = new Hash();
var ajaxContador = 0; 
var ajaxHistoryPos = 0;

function f_ajaxHistory(solicitud){	
	// solicitud	= la llamada ajax ( ver el final de resAjax )
	// si no es igual a la ltima llamada, la grabo en el history
	if ( !f_ajaxCheckLast(solicitud) && ajaxHistoryPos == ajaxContador ){
		if ( solicitud.url != '_sql.asp' ){			
			ajaxHistory.set(ajaxContador, solicitud);
			ajaxContador++;
		}
	}	
	ajaxHistoryPos = ajaxContador;
}

function f_ajaxCheckLast(solicitud){
	// solicitud	= la llamada ajax ( ver el final de resAjax )
	var ajaxLastRequest = ajaxHistory.keys().last();
	if ( typeof ajaxHistory.get(ajaxLastRequest) != "undefined" ) {
		
		var aux1 = $H( ajaxHistory.get( ajaxLastRequest ).parameters ).keys().toString();
		var aux2 = $H( solicitud.parameters ).keys().toString();

		var equalParam = ( aux1 == aux2 )
		
		var aux1 = $H(ajaxHistory.get(ajaxLastRequest).parameters).values().toString();
		var aux2 = $H(solicitud.parameters).values().toString();
			
		var equalURL = ( aux1 == aux2 )
		
		if ( equalParam && equalURL ) return true; else return false;
	}else return false; 
}

function ajaxGoBack(){
	// Genera la ultima 
	// llamada ajax que se hizo.
	var ajaxLastRequest = ajaxHistoryPos - 1 ;
	var ajaxLast = ajaxHistory.get( ajaxLastRequest - 1 );
	if ( !ajaxLast ) return false;
	var ajaxOptions = ajaxLast.options;
		
	var ajaxReq = new Ajax.Request( ajaxLast.url, ajaxOptions );	
	ajaxHistoryPos--;
}

function logByAjax(datafile, xcapa, s, qs){
	// datafile	= url para la llamada
	// xcapa 	= elemento a actualizar
	// s		= boton de submit
	// qs		= parametros
	var capa=$(xcapa); var btn=$(s);
	btn.disabled=true;
	capa.update("<center><img src='images/PleaseWait.gif' border='0'></center>");
	this.respuesta = function(solicitud){
		if (solicitud.responseText.indexOf("OK") > -1) {
			location.href='_container.asp';		
		}else if( (solicitud.responseText).indexOf("[.]") > -1 ){
			$$('.comodinOcultar2').invoke("show");
			$$('.comodinOcultar1').invoke("hide");			
			capa.update('Ingrese el nombre de su Empresa');
			btn.disabled=false;
		}else{
			capa.update(solicitud.responseText);
			btn.disabled=false;
		}
	}
	var solicitud = new Ajax.Request(datafile,{method: 'post', parameters: qs, onComplete: this.respuesta});
}

function saveByAjax(datafile, xcapa, qs, targetfile){
	var capa=$(xcapa);
	capa.innerHTML="<center><img src='images/PleaseWait.gif' border='0'></center>";
	this.salida = function(solicitud){
		document.location.href='_login.asp';
	}
	this.respuesta = function(solicitud){
		var rta = solicitud.responseText
		var re = new RegExp('^OK');		if ( rta.match(re) ) location.href=targetfile;
		else capa.innerHTML=solicitud.responseText;
		var re = new RegExp('[0-9]+');	if ( rta.match(re) ) makeEditable( 'pedidoRow_'+rta.split('|')[1] );
	}
	var solicitud = new Ajax.Request(datafile,{method: 'post', parameters: qs, onComplete: this.respuesta, onFailure: this.salida});
}

function logas(id, co, cl, em, coderp){
	// id = idusuario
	// co = codigo 	( usuario )
	// cl = clave	( contrasea )
	// em = empresa
	if (coderp == null || coderp == ''){ alert('Este vendedor no tiene asignado un codigo de Tango.'); return false;}
	if (confirm('Esta seguro que quiere loguearse como ' + co + '?')){
		LogAsAjax('_loginValidar.asp', 'codigo='+co+'&clave='+cl+'&empresa='+em+'&logas=true', 'POST');
		//window.location = '_container.asp'
	}else{
		return false;
	}
}

function LogAsAjax(url, qs, mt){
	// url 	= url
	// qs 	= parametros ( querystring o json )
	// mt	= method
	if (mt == '') mt = 'GET';
	new Ajax.Request(url, { 
			method: mt, 
			asynchronous: false,
			parameters: qs, 
			onComplete: function(rsp){ if (rsp.responseText == "OK") { window.location.reload(); } }, 
			onFailure: function(){ respuesta = 'FALLO'; }  
	});
}

function validarLogin(u,p,s,em,sb){
	// valida el login contra _loginValidar.asp
	// u	= id o elemento input del form de login ( usuario )
	// p	= id o elemento input del form de login ( pass )
	// s	= id del boton de submit
	// em	= id o elemento input del form de login ( empresa )
	// sb	= si entro por subdominio hay un hidden	
	$(s).disabled=true;
	var flag=false;
	var usuario=removeLeadingAndTrailingChar ($F(u),' ');
	var pass=removeLeadingAndTrailingChar ($F(p),' ');
	var empresa = ''; if (em == null) { em = '' }else{ if ($F(em) != null) var empresa='&empresa=' + $F(em); }
	var subdominio = ''; if (sb == null) { sb = '' }else{ if (existe(sb)) var subdominio='&subdominio=' + $F(sb); }
	if (usuario==''){ 
		$('feedback').innerHTML='Completa con tu Usuario';
		flag=true;
		$(u).focus();
	}
	if (!flag){
		if (pass==''){ 
			$('feedback').innerHTML='Completa con tu Clave';
			flag=true;
			$(p).focus();
		}	
	}
	if (!flag) logByAjax('_loginValidar.asp', 'feedback', s, u+'='+usuario+'&'+p+'='+pass+ empresa + subdominio); 
	else $(s).disabled=false;
	return false;
}

function roundNumber(num, dec) {
	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	return result;
}

function cambiaPrecios( capa ){
	// Recorre todos los divs del pedido 
	// actualizando los precios con el ultimo cambio
	// capa		= elemento
	function valRenglon( id ){
		// id	= id del pedido
		var val_1 = $("pedidosDetail|precioNuevo_" + id).innerHTML.replace(".","").replace(",",".");
		var val_2 = $("pedidosDetail|cantidad_" + id).innerHTML.replace(".","").replace(",",".");
		var bonif = $("pedidosDetail|descuento_" + id ).innerHTML.replace(".","").replace(",",".");
		bonif = 1 - ( bonif / 100 );
		var st_ren = parseFloat(val_1,10) * parseFloat(val_2,10) * parseFloat(bonif, 10);
		return (st_ren).toFixed(2).replace(".",",");
	}
	
	function valSubtotal(){
		var st = 0;
		$$('div.importe').each( function(el){ 
			var valor = el.innerHTML.replace(".", "").replace(",","."); 
			st += parseFloat(valor,10); 
		});	
		return (st).toFixed(2)
	}
	
	function valDescuento(){
		var dto = 0;
		dto = $('descuento').innerHTML.strip().replace("%", "").replace(".","").replace(",", "."); 	
		return ( 1 - dto / 100 );
	}
	
	function valDifDesc(){	
		var t = ( valSubtotal() * valDescuento() )
		var sb = ( valSubtotal() )
	
		return sb - t;
	}
		
	if ( typeof capa.id != 'undefined' ) id = capa.id; else id = capa;
	
	var xfield_1 = id.split("|")[0];
	var xfield_2 = id.split("|")[1].split("_")[0];
	var xfield_3 = id.split("|")[1].split("_")[1];
	
	if ( xfield_1 == 'pedidos' && xfield_2 == 'descuento'){
		nuevo_dto = $(capa).innerHTML.strip().replace("%", "").replace(".",",");
		$(capa).setStyle({ 'display':'inline' });
		$('descuento').update( nuevo_dto + '%' );
		$('total').update( (valSubtotal() * valDescuento()).toFixed(2) );
		$('total_descuento').update( ( valDifDesc() ).toFixed(2) );
}
	
	if ( existe( xfield_1 +"|"+ xfield_2 + "_" + xfield_3 )  && xfield_2 != 'observaciones' && xfield_1 != 'usuarios'  ){	
		if ( existe( 'pedidoDetailImporteRow_' + xfield_3 ) ){
			$('pedidoDetailImporteRow_' + xfield_3).update( valRenglon(xfield_3) );	
			$('subtotal').update( valSubtotal() );					
			$('total').update( ( valSubtotal() * valDescuento() ).toFixed(2) );
			$('total_descuento').update( ( valDifDesc() ).toFixed(2) );
		}
	}
}

/*
		MAKE ELEMENTS ( INPLACE , SCROLLABLE, DRAGGABLE, INPLACE-AUTOCOMPLETER, TABS )
*/

//inPlace editors scriptaculous
function edFromArray(datafile, matriz, numRows, numSize, maxLength){
	/*
	function que hace un inplaceeditor 
	de cada elemento de la matriz
	*/
	for(i=0;i<matriz.length;i++){
		edAjax(datafile,matriz[i],numRows, numSize, maxLength);	
	}
}
function edAjax(datafile, ctl, numRows, numSize, maxLength){
	/*
	Function para hacer inPlaceEditors 
		datafile 	= url para el ajax
		ctl 		= el elemento que se va a hacer inPlace
		numRows, numSize, maxLength, el tamao del inplace
	*/
	//alert($(ctl));
	extCtl=null;
	if ($('EC'+ctl)!=null) extCtl=$('EC'+ctl);

	if ( inplace.get(ctl) == undefined ) {
		// si el div es el de cantidad, le pongo un validador.
		
		// Un objeto con todas las opciones 
		// por default del inplaceEditor
		var inplaceOPT = {				 
		 onFailure		: this.salida,
		 okText			: 'OK',
		 cancelText		: 'Cancelar',
		 okControl		: 'link',
		 cancelControl	: 'link',
		 savingText		: 'guardando...',
		 clickToEditText: 'click para editar',
		 rows: numRows, size: numSize, highlightColor: '#bbbbbb', highlightEndColor: '#cccccc',
		 maxLength		: maxLength,
		 externalControl: extCtl,
		 onComplete		: function( ) { cambiaPrecios( ctl ); }
		}
		
		
		var _renglon  = 'numUnidadVta_' + ctl.split("_")[1];	
		var control_cantidad = 'controlCantidad_' + ctl.split("_")[1];
			
		var equivalencia = function equivalencia( r ){
				if ( !!r ){
				if ( r.responseText.indexOf('noequiv') > -1 ) {
					alert( 	'Las unidades ingresadas no son aceptadas\r\n' 	+ 
							'La Equivalencia de unidad de compra es de ' 	+ $F(_renglon) + 
							' un. o multiplo de esta.');
					$(ctl).update( $F(control_cantidad) );
				}else $(ctl).update( r.responseText );
					cambiaPrecios( ctl );
				}
			}
				 
		// Si el renglon es el de cantidad 
		// y existe un hidden de equivalencia 
		// le agrego un par de parametros mas
		if ( ctl.indexOf('pedidosDetail|cantidad') > -1 && existe( _renglon ) ){
			Object.extend( inplaceOPT, {
				 htmlResponse	: false,
				 ajaxOptions	: { method: 'POST' },
				 onComplete		: function( rta ) { equivalencia( rta ) }
			});
		}
		
		var inPlaEd = new Ajax.InPlaceEditor( ctl, datafile, inplaceOPT );
		inplace.set( ctl , inPlaEd );
	}
	
	this.salida = function(solicitud){
		//document.location.href='_login.asp';
	}
}

var inplace = new Hash(); //OBJETO DE CONTROL DE LOS INPLACEEDITORS EXISTENTES
function limpiarInPlace( tag ){
	/*
	Esta function sirve para limpiar el hash, 
	porque si en el hash ya estn
	los id de los inplaces existentes no los rehace.
	
	Busca el tag esta adentro de cada uno de los keys y si lo encuentra, lo borra	
	tag => str
	*/
	if ( $A(inplace).length > 0 ){
		inplace.each( function(pair){
			if ( pair.key.indexOf(tag) > -1 ) inplace.unset(pair.key);
		});
	}
}

function makeINPLACE( id ){
	/*
	Se usa solo para editar los parametros.
	No aparece en el inplace ( HASH )
	*/
	new Ajax.InPlaceEditor( id , '_sql.asp', {
		rows		: 1, 		size	: 20, 
		maxLength	: 100,		okText	: 'OK',
		cancelText	: 'Cancelar', okControl	: 'link',
		cancelControl	: 'link', savingText	: 'guardando...',
		clickToEditText	: 'click para editar', highlightColor: '#bbbbbb', highlightEndColor: '#cccccc',
		callback: function(form, value) { return 'parametros=edit&datos='+id+'&resultado=' + encodeURIComponent(value) }
	});
}

//scrollables
function makeScrollable(id){	
   var elements = $$('.textoScroll');
   elements.each(
       function(item) {
			item.className='textoNoScroll';
       }
   );
   var elements = $$('.textoNoScroll');
   elements.each(
       function(item) {
			if (item.id==id) item.className='textoScroll';
       }
   );
}
//Draggables scriptaculous
function makeDraggables(){
	// Busca todos los elementos
	// con clase arrastrable y los convierte en draggables
	// Si se quiere un handler ( barra para arrastrar ), 
	// esta se tiene que llamar con el id del elemento + Handler 
	// ( por ej. 'cajaHandler' )
   var elements = $$('.arrastrable');
   elements.each(
       function(item) {
			idhandler=item.id + 'Handler';
			handler=$(idhandler);
			new Draggable(item, {handle: handler});
       }
   );
}
//editabilidad de fila
function makeEditable(rowid){
	// Abre la caja de controles del pedido
	// ( editar, eliminar, log as, etc )
	if ( existe(rowid) ){
		fila=$(rowid);
		
		$$('tr.parSelected').invoke('removeClassName','parSelected')
								.invoke('addClassName','par');
					
		$$('tr.imparSelected').invoke('removeClassName','imparSelected')
								.invoke('addClassName','impar');
		
		$$('div table.sort span.opButtons').invoke("hide");
		
		fila.className +='Selected';
		sClassName = eval('"' + "#" + fila.id + " .opButtons" + '"');
		$$(sClassName).invoke("show");

		// hace los editables de nro orden
		soloid=rowid.substr(rowid.indexOf('_')+1);
		div="pedidos|NRO_O_COMP__"+soloid;
		if (existe(div)) edAjax('_sql.asp',div,1,6,14);
	}
}
function makeEdAu(mysize){
	// Busca todos los elementos
	// con la clase makeEd_au
	// y los hace inPlaceEditor y Autocompleter
	// tiene harcodeada la url autocompleter	
	$$('.makeEd_au').each(function (el){
		var id = el.id;		var idcliente;		var url = '_sql.asp';	
		
		if ( typeof inplace.get(id) == "object" ) inplace.unset(id);		
		if (mysize!=null) {
			var editor = new Ajax.InPlaceEditor(id, url, { 
				callback: function (form, value){ return 'idpedido=' + eval("id.replace('cli_', '')")+ '&idcliente=' + idcliente },
				indicator: 'cargando',
				/*para el ancho*/
				size: mysize,			
				savingText: 'guardando'				
			});
		}else{
			//default
			var editor = new Ajax.InPlaceEditor(id, url, { 
				callback: function (form, value){ return 'idpedido=' + eval("id.replace('cli_', '')")+ '&idcliente=' + idcliente },
				indicator: 'cargando',
				savingText: 'guardando'				
			});
		}
		
		inplace.set( id , editor );
		
		Object.extend(editor, { //mientras el inplaceeditor se va creando, le agrego el autocompleter
			_createEditField	: editor.createEditField,
			createEditField		: function() {
				this._createEditField();
				new Ajax.Autocompleter(
					this._controls.editor,
					'cajaClientes',
					'_sql.asp?buscaClientes=SI'	, { 
						afterUpdateElement: function(text, el){ idcliente = el.id; } ,
						minChars: 4
				}); 	
			}
		});
		
	});
}

function makeTabs( contid, dtab, urls ){
	// hace las pestanias
	// contid	= id del contenedor
	// dtab		= tab por default ( la parte despues de # en el href )
	// urls		= un objecto con la parte que viene despues de # del link y la url ( por ej: { contenedor : 'pedidosweb.com' } ) 
	if ( !!$$("a[href='#"+dtab+"']").first() ) tabSelectedHref = $$("a[href='#"+dtab+"']").first().href; else tabSelectedHref = $$('ul#tabs li a').first().href;
	tabSelected = tabSelectedHref.substr( tabSelectedHref.indexOf('#') + 1,	tabSelectedHref.length );
	if ( typeof urls == 'undefined' ) urls = {};
	var tabSet1 = new ProtoTabs( contid , { 
		defaultPanel: tabSelected,
		ajaxUrls: urls,
		ajaxLoadingText: '<center><img src="images/PleaseWait.gif" border="0"></center>'
	});
}

function makeTableKit ( id ) {
	// Hace un tablekit a una tabla
	// id	= id de la tabla
	TableKit.options.sortableSelector = ['table.sort'];
	TableKit.options.editable = false;
	TableKit.options.rowEvenClass = 'par';
	TableKit.options.rowOddClass = 'impar';
	$$('.sort').each( function(item){ TableKit.Sortable.init(item) });
	TableKit.reload()
}

function makeBal(){
	// crea las balloons de ayuda
	$$('.helpicon').each( function(item){
		new HelpBalloon({ 	
			title: 'AYUDA', 
			dataURL: 'helpBalloon.asp?help='+item.alt,
			cacheRemoteContent: false,  
			icon: $(item),
			autoHideTimeout: 0,
			altText: 'Haga click aqui para leer la ayuda'
		}); 
	});
}

/*
		NUMEROS
*/

function ponerPuntitos( entero ){
	var x; var i; var m; var ret;
	x = ""+entero;
	m = 0;
	
	ret = "";
	if ((x.length) > 3){
		for(i = x.length; i>0; i--){
			m++;
			ret = x.substr(i,1) + ret;
			if (m == 3){
				if (i>1) ret = "." + ret; 
				m = 0;
			}
		}
	}else{
		ret = x;
	}
	return ret;
}

function separarMiles( doble ){
	// recibe un doble ( por ej: 2000.30 ) y lo devuelve notacion espaol ( por ej: 2.000,30 )
	var x; var parteEntera; var parteDecimal;
	if (!isNaN(doble)){
		x = parseFloat(doble);
		parteEntera = Math.floor(x);
		parteDecimal = "" + Math.round((x - parteEntera) * 100);
		if (parteDecimal.length==0) parteDecimal="00";
		if (parteDecimal.length==1) parteDecimal += "0";
//		return ponerPuntitos(parteEntera) + "," + parteDecimal;
		return parteEntera + ',' + parteDecimal;
	}else{
		return "0,00";
	}
}

function applyChanges(ctl, valor, target, ecuacion){
	// cambia el subtotal del renglon de un pedido
	// ctl		= elemento
	// valor	= no se usa
	// target	= elemento
	// ecuacion	= se evalua el innerHTML del elemento con esto
	var subtotal = 0
	if ( $(ctl)==null ) return;
	else{
		ih=$(ctl).innerHTML;
		if ( (ih.indexOf('input')<0) && (ih.indexOf('guardando')<0) && (ih!=valor) ){
			que=eval("parseInt(" + ih + ")" + ' ' +  ecuacion );
			$(target).update(separarMiles(que));
			
			$$('div.importe').each( function(el){ valor = el.innerHTML.replace(".", "").replace(",","."); subtotal += parseFloat(valor); });
			$('subtotal').update(separarMiles(subtotal));
		}
	}
}

function getIds( xclass , search_in ){
	// devuelve un array con ids si el search_in est en el id 
	// xclass		= clase para buscar
	// search_in	= parte de id
	var arr = new Array();
	$$(xclass).each( 
		function(item) {
			if ( item.id.indexOf( search_in ) > -1 ){
				arr.push( item.id ); 
			}
	});
	return arr; 
}

var tt=0;
function tryEditarNuevo(){
	obj=$$('.clickame')[0];
	if (obj!=null){ 
		obj.click();
		clearInterval(tt);
	}
}

function addArt(id){
	// agrega el articulo al pedido
	// desde el buscador
	resAjax('_pedDetail.asp', 'pedResultado', 'idArticulos='+id); 
	//ver( 'divArtFinder', 0 );
}

//VISIBILIDAD

function abrirServicios( srv ){
	// curIdPed es una variable global que est en la pagina, no en este archivo
	// srv	= el servicio
	divS = $('divServicios');
	$('capa').setStyle({ "width": getSize()[0] + 'px', "height": getSize()[1] + 'px' });
	
	pos_x = (getSize()[0]/2) - (divS.getWidth()/2); 	if ( pos_x < 10 ) pos_x = 10;
	pos_y = (getSize()[1]/2) - (divS.getHeight()/2); 	if ( pos_y < 10 ) pos_y = 10;
				
	switch ( srv ){
		case 'genera_excel':
			//$('capa').appear();
			//divS.setStyle({ 'top' : pos_y + 'px', 'left' : pos_x + 'px' }).appear();
			//resAjax('excel/', 'servicios_contenido'); 
			window.open('excel_new/index.asp?idPedidos='+curIdPed, '_blank' );
			break;
		case 'descarga_excel':
			//console.log('excel/pedido.asp?idPedidos='+curIdPed);
			//window.open('excel/pedido.asp?idPedidos='+curIdPed,'_blank');
			window.open('excelNew/pedido.asp?idPedidos='+curIdPed+'&ce='+bd+'&v='+verTodos ,'_blank');
			break;
		case 'excel_multiple':
			//console.log('excel/pedido.asp?idPedidos='+curIdPed);
			//window.open('excel/pedido.asp?idPedidos='+curIdPed,'_blank');
			window.open('excel_New/index_multiple.asp','_blank');
			break;
	}
}

function ver(id, state){
	// id	= id del elemento
	// state= int. depende el numero cambia de visible: a visible:none
	obj=$(id);
	if (obj!=null){
		switch(state){
			case 0: obj.style.display="none";
			break;
			case 1: obj.style.display="";
			break;
			case 2: if (obj.style.display=="none") obj.style.display="";
					else obj.style.display="none";
			break;
		}
	}
}
function vaciarInputs(id){
	//busca todos los elementos hijos de un elemento
	$(id).descendants().each( 
		function (child){ // para cada uno de los elementos
			if (child.tagName == 'input' || child.tagName ==  'INPUT'){
				child.value = '';
			}
		});
}

function vaciar(id){ $(id).update(); } // limpia el inner de un elemento
function existe( id ) { return !!$(id) } // se fija si existe un elemento en el dom
function exist_f(func){ return eval("!!window."+func); } // se fija si existe una funcion

//IFRAME
function getIframe(id){
	var iframeElem = parent.document.getElementById(id);
	win = iframeElem.contentWindow.document;
	if (win==undefined) win=iframeElem.contentDocument.document;
	return win;
}

//OPACIDAD
function ocultarFondo(){
	if ($('capa').style.display == 'none'){
		window.scrollTo(0, getSize());
		$('capa').style.height = getSize() + document.viewport.getScrollOffsets().top + 'px';
		$('capa').show();
	}else{
		$('capa').style.top = 0;
		$('capa').style.left = 0;
		$('capa').style.height = 1 + 'px';
		$('capa').hide();
	}
}

function opacity(id, opacStart, opacEnd, millisec) { 
    //speed for each frame 
    var speed = Math.round(millisec / 100); 
    var timer = 0; 
    //determine the direction for the blending, if start and end are the same nothing happens 
    if(opacStart > opacEnd) { 
        for(i = opacStart; i >= opacEnd; i--) { 
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed)); 
            timer++; 
        } 
    } else if(opacStart < opacEnd) {
        for(i = opacStart; i <= opacEnd; i++) { 
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed)); 
            timer++; 
        } 
    } 
} 

function changeOpac(opacity, id) { 
    var object = document.getElementById(id).style; 
    object.opacity = (opacity / 100); 
    object.MozOpacity = (opacity / 100);  
    object.KhtmlOpacity = (opacity / 100); 
    object.filter = "alpha(opacity=" + opacity + ")"; 
}

//RESIZE Y SCROLL
function getScrollXY() {
  var scrOfX = 0, scrOfY = 0;
  var total = 2048;
  if( document.documentElement) {
        //IE6 standards compliant mode
        scrOfY = document.documentElement.scrollTop;
        scrOfX = document.documentElement.scrollLeft;
        total = document.documentElement.scrollHeight;
    }else{ 
        if(document.body) {
            //DOM compliant
            scrOfY = document.body.scrollTop;
            scrOfX = document.body.scrollLeft;
            total = document.body.scrollHeight;
        }
    }
  //return [ scrOfX, scrOfY ];
  return total;
}

function getSize() {
  // devuelve un array con
  // el alto y el ancho del viewport
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  var size = new Array(myWidth, myHeight);
  return size;
}

function getSizeWidth(){
	var myWidth = 0
	if( typeof( window.innerWidth ) == 'number' ) {
		//Non-IE
		myWidth = window.innerWidth;
	} else if( document.documentElement && ( document.documentElement.clientWidth ) ) {
		//IE 6+ in 'standards compliant mode'
		myWidth = document.documentElement.clientWidth;
	} else if( document.body && ( document.body.clientWidth ) ) {
		//IE 4 compatible
		myWidth = document.body.clientWidth;
	}
	return myWidth;
}

function ubicarDiv(id){
	// ubica un elemento ( id )
	// en el medio del monitor
	var hScreen;	var hDiv;	
	var wScreen;	var wDiv;
	
	wScreen = parseInt(document.viewport.getDimensions().width)/2;
	wDiv = parseInt($(id).getWidth()) /2
	
	hScreen = parseInt(document.viewport.getDimensions().height)/3;
	hDiv = parseInt($(id).getHeight()) /2

	posX = (hScreen + $(id).cumulativeScrollOffset().top ) - hDiv
	posY = (wScreen + $(id).cumulativeScrollOffset().left )- wDiv

	$(id).style.left = posY + 'px';
	$(id).style.top =  posX + 'px';	
}

function maximizeHeight(id){
    obj=document.getElementById(id);
	alto = ''+getScrollXY()+'px';
	obj.style.height=alto;
}


// Funciones auxiliares

function Left(str, n){
	// Lo mismo que la funcion de asp
	// str 	=> string 
	// n	=> integer
	if (n <= 0)
	    return "";
	else if (n > String(str).length)
	    return str;
	else
	    return String(str).substring(0,n);
}
function Right(str, n){
	// Lo mismo que la funcion de asp
	// str 	=> string 
	// n	=> integer
    if (n <= 0)
       return "";
    else if (n > String(str).length)
       return str;
    else {
       var iLen = String(str).length;
       return String(str).substring(iLen, iLen - n);
    }
}

function fixAscii(cad){
	cadena=replaceStr(cad, '', '[|n|]');
	cadena=replaceStr(cadena, '', '[|n|]');
	cadena=replaceStr(cadena, '', '[|a|]');
	cadena=replaceStr(cadena, '', '[|a|]');
	cadena=replaceStr(cadena, '', '[|e|]');
	cadena=replaceStr(cadena, '', '[|e|]');
	cadena=replaceStr(cadena, '', '[|i|]');
	cadena=replaceStr(cadena, '', '[|i|]');
	cadena=replaceStr(cadena, '', '[|o|]');
	cadena=replaceStr(cadena, '', '[|o|]');
	cadena=replaceStr(cadena, '', '[|u|]');
	cadena=replaceStr(cadena, '', '[|u|]');
	return cadena;
}

function replaceStr(cad, cual, xcual){
	var returnStr = '';
	cadena = cad + '||';
	var fin = cadena.indexOf('||');
	for (i=0;i<fin;i++){
		if(''+cadena.charAt(i)==cual){
			returnStr = returnStr + xcual;
		}else{
	   		returnStr = returnStr + cadena.charAt(i);
		}
	}	
	return returnStr;
}


var arrayEsp=new Array('','!','','','\\','/','|','@','"',"'",'(',')','=',',',';','.',':','?','','&','%','$','%','[',']','+','*','{','}','^','#');
function removeLeadingAndTrailingChar (inputString, removeChar){
	var returnString = inputString;
	if (removeChar.length){
	  	while(''+returnString.charAt(0)==removeChar){
		  returnString=returnString.substring(1,returnString.length);
		}
		while(''+returnString.charAt(returnString.length-1)==removeChar){
	    	returnString=returnString.substring(0,returnString.length-1);
	  	}
	}
	return returnString;
}


function vmail(texto){
    var mailres = true;
    var cadena = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890@._-";
    var arroba = texto.indexOf("@",0);
    if ((texto.lastIndexOf("@")) != arroba) arroba = -1;
    var punto = texto.lastIndexOf(".");
    for (var contador = 0 ; contador < texto.length ; contador++){
        if (cadena.indexOf(texto.substr(contador, 1),0) == -1){
            mailres = false;
            break;
     	}
    }
    if ((arroba > 1) && (arroba + 1 < punto) && (punto + 1 < (texto.length)) && (mailres == true) && (texto.indexOf("..",0) == -1)) mailres = true;
    else mailres = false;
    return mailres;
}

//EVENT

function obsEv(xclass, xevent, innerfunction){ 
	// Observa el xevent en los objetos con una clase xclass 
	// y hace una function innerfunctions
	// xclass => str 
	// xevent => str
	// innerfunction => str		
	$$(xclass).each( function(el){ Event.observe(el, xevent, function(){ eval(innerfunction) }) }); 
}

function esEnter(e){
	// Devuelve si un evento
	// de teclado fue enter. 
	var keynum;
	if(window.event){ // IE 
		keynum = e.keyCode;
	} else if(e.which) {// Netscape/Firefox/Opera
		keynum = e.which;
	}
	return (keynum==13);
}

function esAN(e){
	// Devuelve si un evento
	// fue un alfanumerico
	var keynum;
	if(window.event){ // IE 
		keynum = e.keyCode;
	} else if(e.which) {// Netscape/Firefox/Opera
		keynum = e.which;
	}
	
	if ( ( keynum > 65 && keynum < 90 ) || ( keynum > 96 && keynum < 105 ) ) return true; else return false;
}

function esEsc(e){
	// Devuelve si un evento
	// fue escape
	var keynum;
	if(window.event)	{ // IE
		keynum = e.keyCode;
	} else if(e.which)	{ // Netscape/Firefox/Opera
		keynum = e.which;
	}
	return (keynum==27);
}

function clnFlt(x) {
	// devuelve x float
	return parseFloat('0'+x);
}

function tgle(div1, div2){
	// Recibe dos ids y los cambia a visible y no visible
	div1 = $(div1); 	div2 = $(div2)
	if ( div1.visible() ) { div1.hide();	div2.show(); }else{ div2.hide();	div1.show(); }
}
