//Declaremos variables globales!

var intentos 	= 10; 		//Con esto validamos si el usuario le ha dado mas de n veces al intentar ingresar un valor no numerico
var clicked 	= false;	// Sabemos si esta selccionado algo para copiar la categoria
var lastclick 	= null;		// Obtenemos el ultimo click de la celda seleccionada!
var enviando 	= false;
var pulsado 	= false;
var jsvalidation= true;
var checkerror 	= false;
var debugjs	= false;

var apos=0;
var adir=2;
var alen=0;

//--------------------------------------------------------->
// Esta funcion valida si se presionó una tecla especial
// evento :: evento realizado en el window
// blocked :: se recibe un 0 ó 1 para saber si bloqueamos o no las teclas
//--------------------------------------------------------->
function teclas_especiales( evento , blocked )
{
	var iKeyCode;
	iKeyCode = (evento.which) ? evento.which : evento.keyCode

	if ( blocked == 0 ){
		bloquear = false;
	}
	
	if ( bloquear ){
		if ( iKeyCode == 27 || iKeyCode == 116 ){
			//alert('Tecla no válida')
			return false;
		}
	}
	
	/*
	if ( iKeyCode == 112 )	// presionamos F1 mostramos la ayuda
	{
		window.open('http://www.vacorp.net' , 'ayuda');
		return false;
	}
	*/
}

//--------------------------------------------------------->
// Creamos el objeto reloj para controlar la sesion
// obj :: objeto que se desplaza como ticks
// itsSteps :: cantidad de pasos qeu debe dar el reloj para el fin de sesion
// itsMovement :: si se debe desplazar o no
//--------------------------------------------------------->
function tiempo_sesion( obj , itsSteps , itsMovement )
{
	if(IE)
	{
		presentPosition = parseInt(eval('document.all.'+obj+'.style.left'))
		eval('document.all.'+obj+'.style.left=presentPosition + itsMovement')
	}
	else
	{
		presentPosition = parseInt(document.getElementById(obj).style.left)
		document.getElementById(obj).style.left = presentPosition + itsMovement
	}

	thisDiv=obj
	thisMovement=itsMovement
	itsSteps--

	if(itsSteps>0)
	{
		if ( itsSteps == aviso ) // si es igual al momento qeu se debe avisar
		{
			//alert(sesmsg);
			document.getElementById("sesion").className = 'sesfin';
		}
		setTimeout('tiempo_sesion(thisDiv,'+itsSteps+',thisMovement)', timing)
	}
}
//--------------------------------------------------------->
// valida la entrada de datos de un campo tipo fecha
// si la letra presionada es la "c" mostramos el calendario
//--------------------------------------------------------->
function calendario(evento)
{
	var iKeyCode;
	iKeyCode = (evento.which) ? evento.which : evento.keyCode
	
	if (iKeyCode > 31 && (iKeyCode < 46 || iKeyCode > 57 ) 
		&& iKeyCode != 44 && iKeyCode != 37 
		&& iKeyCode != 39 )
	{
		
		return false;
	}
		
	return true;	
}

//--------------------------------------------------------->
// validamos si un campo tiene solo datos numéricos
//--------------------------------------------------------->
function is_numeric(n)
{
	var PNum = new String(n);
	var regex = /[^0-9]/;
	return !regex.test(PNum);
}
//--------------------------------------------------------->
// seleccionamos todos los checkboxes de la pantalla
// recibimos como primer parametro el formulario
// el segundo parametro es un arreglo de javascript, con el cual validamos lo que no queremos marcar
//--------------------------------------------------------->
function selcheckbox( frm , cArray )
{
	var michecked = 0;
	var tform = eval('window.document.' + frm );
	
	for (i=0;i<tform.length;i++)
	{
		if ( tform.elements[i].type == 'checkbox'  )
		{
			if ( in_array ( tform.elements[i].name , cArray ) ){
				continue;
			}

			if ( tform.elements[i].checked == true )
			{
				tform.elements[i].checked = false ;
			}else{
			
				tform.elements[i].checked = true ;
			}
		}
	}
}

//--------------------------------------------------------->
// seleccionamos todos los checkboxes de la pantalla que estan como arreglo
// recibimos como primer parametro el formulario
// el segundo parametro es un arreglo de javascript, con el cual validamos lo que no queremos marcar
//--------------------------------------------------------->
function selcheckboxArray( frm , cArray ){
	var michecked = 0;
	var tform = eval('window.document.' + frm );

	for (i=0;i<tform.length;i++){
		if ( tform.elements[i].type == 'checkbox'  ){

			if ( in_array ( tform.elements[i].name , cArray ) ){
				continue;
			}
						
			if ( tform.elements[i].checked == true ){
				tform.elements[i].checked = false ;
			}else{			
				tform.elements[i].checked = true ;
			}
		}
	}
}

function in_array( aguja , pajar )
{
	for (var i = 0; i < pajar.length; i++)
	{
		if ( pajar[i] == aguja )
		{
			return true;
		}
	}
	
	return false;
}
//==========================================
// Esconder el DIV
//==========================================
function esconder_tabla( fid, add )
{
	saved = new Array();
	clean = new Array();

	//-----------------------------------
	// Add?
	//-----------------------------------
	
	if ( add )
	{
		my_show_div( my_getbyid( 'fc_'+fid  ) );
		my_hide_div( my_getbyid( 'fo_'+fid  ) );
		my_hide_div( my_getbyid( 'foc_'+fid  ) );
	}
	else
	{
		my_show_div( my_getbyid( 'fo_'+fid  ) );
		my_hide_div( my_getbyid( 'fc_'+fid  ) );
		my_show_div( my_getbyid( 'foc_'+fid  ) );
	}
	
}

function my_hide_div(itm)
{
	if ( ! itm ) return;
	
	itm.style.display = "none";
}

//==========================================
// Mostramos el DIV
//==========================================

function my_show_div(itm)
{
	if ( ! itm ) return;
	
	itm.style.display = "";
}
//==========================================
// Buscamos el elelmento!
//==========================================

function my_getbyid(id)
{
	itm = null;
	
	if (document.getElementById)
	{
		itm = document.getElementById(id);
	}
	else if (document.all)
	{
		itm = document.all[id];
	}
	else if (document.layers)
	{
		itm = document.layers[id];
	}
	
	return itm;
}
//--------------------------------------------------------->
// buscamos cual es el primer elemento para seleccionar
//--------------------------------------------------------->
function gfe()
{
	var consigio = 0 ;

	if (document.forms.length > 0)
	{
		var TForm = document.forms[0];

		if ( consigio == 0 )
		{
			for (i=0;i<TForm.length;i++)
			{
				if ( TForm.elements[i].type == 'text' )
				{
					document.forms[0].elements[i].focus();
					break;
				}
			}      
		}

	}
}
//==========================================
// Mostramos la ventana de ayuda
//==========================================
function mostrarayuda(seccion)
{
	var w = 310, h = 270;

	if (document.all || document.layers)
	{
	   w = screen.availWidth;
	   h = screen.availHeight;
	}

	var popW = w, popH = h;
	var leftPos = (w-popW)/2, topPos = (h-popH)/2;

	var car = 'width=310,height=300,left='+leftPos+',top=' + topPos;
	window.open('./ayuda/index.php?seccion=' + seccion , 'Ayuda' , car);
}
function numerico(evento)
{
	var iKeyCode;
	iKeyCode = (evento.which) ? evento.which : evento.keyCode

	if (iKeyCode > 31 && (iKeyCode < 44 || iKeyCode > 57 ) && iKeyCode != 44)
	{
		intentos -= 1;
		if ( intentos == 0 )
		{
			alert('Debes Ingresar un valor númerico');
			intentos = 10;
		}
		return false;
	}
	intentos = 10;
	return true;	
}
function o_numerico(evento)
{
	var iKeyCode;
	iKeyCode = (evento.which) ? evento.which : evento.keyCode

	if (iKeyCode > 31 && (iKeyCode < 48 || iKeyCode > 57 ) )
	{
		intentos -= 1;
		if ( intentos == 0 )
		{
			alert('Debes Ingresar un valor númerico');
			intentos = 10;
		}
		return false;
	}
	intentos = 10;
	return true;	
}
				
function txt2chk( obj ,  chk , clean)
{
	chk.checked = true;
	clean = 0;
	
	if ( clean )
	{		
		if ( obj.value == '' )
		{
			chk.checked = false;
		}
	}
	
	return true;
}

function copycat(cell,nclass,oclass,columns,id)
{	
	
	// Solo hacemos un pase de variables
	if ( window.document.extras.copiarprod.checked == true )
	{
		window.document.frmcategorias.copiar.value = 1;
	}
	else
	{
		window.document.frmcategorias.copiar.value = 0;
	}
	
	// Preguntamos si es distinto al anterior para guardar!
	if ( lastclick != cell && lastclick != null )
	{
		if (!confirm("¿Seguro que desea copiar de una categoría a otra?"))
		{
			return false;
		}
		window.document.frmcategorias.qh.value = 'copycat';
		window.document.frmcategorias.copyto.value = id;
		window.document.frmcategorias.submit();
		return false;
	}
	
	lastclick = cell;
	
	window.document.frmcategorias.copyfrom.value = id;
	i = 1;
	//for ( i=1 ; i<=columns ;i++ )
	//{
		itm = null;
		
		var a = cell+i;
		
		if (document.getElementById)
		{
			itm = document.getElementById(a);
		}
		else if (document.all)
		{
			itm = document.all[a];
		}
		else if (document.layers)
		{
			itm = document.layers[a];
		}
		
		if ( clicked == true )
		{
			itm.className=oclass;
		}
		else
		{
			itm.className=nclass;
		}
	//}
	
	if ( clicked == true )
	{
		clicked = false;
		lastclick = null;
	}
	else
	{
		clicked = true;
	}

}

function seltext2(obj,n)
{
	var eltext = eval('window.document.myform.cantidad_' + n );
	
	if ( obj.checked == true )
	{
		eltext.focus();
	}
	else
	{
		eltext.value = '';
	}
}

function seltext(obj,n)
{
	var eltext = eval('window.document.myform["cantidad[]"][' + n + ']');
	
	if ( obj.checked == true )
	{
		eltext.focus();
	}
	else
	{
		eltext.value = '';
	}
}

function cpedido(url , p , t)
{
	
	if ( enviando == true )
	{
		return false;
	}
	
	if (!confirm("¿Seguro que deseas cancelar este pedido?"))
	{
		return false;
	}
	
	enviando = true;
	
	turl = url + '&id=' + p + '&idtienda=' + t;
	
	document.location.href = turl
	
	return false;	
}

function cdespacho(url , p , t , l)
{
	
	if ( enviando == true )
	{
		return false;
	}
	
	if (!confirm("¿Seguro que deseas cancelar este pedido?"))
	{
		return false;
	}
	
	enviando = true;
	
	turl = url + '&id=' + p + '&idtienda=' + t + '&idlogistica=' + l;
	
	document.location.href = turl
	
	return false;	
}

function cpago( url , p  , m )
{	
	if ( enviando == true )
	{
		alert('El formulario se está enviado, por favor espere')
		return false;
	}
	
	if (!confirm(m))
	{
		return false;
	}
	
	enviando = true;
	
	mival = eval('window.document.dummy.f'+p+'.value');
	mivalc = eval('window.document.dummy.c'+p+'.value');
	
	turl = url + '&id=' + p + '&f' + p + '=' + mival+ '&c' + p + '=' + mivalc ;
	
	document.location.href = turl
	
	return false;	
}

//--------------------------------------------------------->
// validamos los datos obligatorios de una pagina en particular
// frm :: formulario que queremos validar
//--------------------------------------------------------->
function validar_datos(frm)
{
	if ( enviando )
	{
		alert('Se está enviando el formulario, por favor espere');
		return false;
	}
	
	var tform  = eval('window.document.' + frm);

	if ( jsvalidation == true )	// queremos validar por javascript?
	{
		 // regular expression to match required date format  
		 
		 re = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
					
		for (x=0 ; x<campos.length ; x++)
		{
			var c = campos[x];	//campo actual
			var t = tipo[x];	//tipo de campo actual
			var n = nombrecampo[x];	//nombre de campo actual

			c = eval('tform.' + c);
			
			if ( c.value == '' )
			{
				alert('El campo ' + n + ' debe tener información');
				c.focus();
				return false;
			}
			
			if ( t == 'numeric' )
			{
				var temp = is_numeric(c.value);
								
				if ( temp == false )
				{
					alert('El campo ' + n + ' debe ser numérico');
					c.focus();
					return false;
				}
				
				if( c.value == 0 )
				{
					alert('Debe seleccionar una opción en el campo ' + n + '');
					c.focus();
					return false;
				}
			}
			else if( t == 'date' )
			{
				if( c.value != '' && !c.value.match( re ) )
				{ 
					alert('El formato de fecha es inválido.');
					c.focus();
					return false;
				}
			}
		}
	}
	
	enviando = true;
	tform.submit();
			
	return false;
}
/*
* Eliminar factura?
*/
function afacturaimg( url,tienda,fecha ){
		
	if (!confirm('¿Seguro que desea marcar este día sin facturas?'))
	{
		return false;
	}
	
	var turl = url + '&qh=sinfactura' + '&idtienda=' + tienda + '&fecha=' + fecha;	
	
	document.location.href = turl;
	
	return false;	
}

function afactura( url , frm , tienda , fecha )
{
	var tform  = eval('window.document.' + frm);
	
	if ( tform.sinfactura.checked )
	{
		if (!confirm('¿Seguro que desea marcar este día sin facturas?'))
		{
			return false;
		}
		turl = url + '&qh=sinfactura' + '&idtienda=' + tienda + '&fecha=' + fecha;	
	}
	else
	{
		turl = url + '&qh=main' + '&idtienda=' + tienda + '&fecha=' + fecha;
	}
	
	document.location.href = turl
	
	return false;	
}

function cfactura( url , idfactura , idtienda ,dia ){

	if ( enviando == true ){
		return false;
	}
	
	if (!confirm("¿Seguro que deseas eliminar esta factura, se eliminaran todas las posteriores a esta?\n Se mostraran las facturas a eliminar en la siguiente pantalla")){
		return false;
	}
	
	enviando = true;
	
	turl = url + '&id=' + idfactura + '&idtienda=' + idtienda + '&dia=' + dia;
	
	document.location.href = turl
	
	return false;	
}

function cpedidol(url , p , t)
{
	
	if ( enviando == true )
	{
		return false;
	}
	
	if (!confirm("¿Seguro que deseas cancelar este pedido?"))
	{
		return false;
	}
	
	enviando = true;
	
	turl = url + '&id=' + p + '&idlogistica=' + t;
	
	document.location.href = turl
	
	return false;	
}

function cdespachol(url , p , t , l)
{
	
	if ( enviando == true )
	{
		return false;
	}
	
	if (!confirm("¿Seguro que deseas cancelar este pedido?"))
	{
		return false;
	}
	
	enviando = true;
	
	turl = url + '&id=' + p + '&idtienda=' + t + '&idlogistica=' + l;
	
	document.location.href = turl
	
	return false;	
}


function animate(){
	var elem = document.getElementById('progress');
	if(elem != null) {
		if (apos==0) alen += adir;
		if (alen>32 || apos>79) apos += adir;
		if (apos>79) alen -= adir;
		if (apos>79 && alen==0) apos=0;
		elem.style.left = apos;
		elem.style.width = alen;
	}
}
function remove_loading(t_id) {
	this.clearInterval(t_id);
	var targelem = document.getElementById('loader_container');
	targelem.style.display='none';
	targelem.style.visibility='hidden';
}


function eliminar( p , a , id , msg ){
	var error = 0;
	
	if ( typeof p == 'undefined' || p == '' ) { alert('Parametro 1 incorrecto'); error=1;}
	if ( typeof a == 'undefined' || a == '' ) { alert('Parametro 2 incorrecto'); error=1;}
	if ( typeof id == 'undefined' || id == '' ) { alert('Parametro 3 incorrecto'); error=1;}
	
	if ( error ){return false;}
	
	//----------------------
		
	if (confirm( msg ) )
	{
		return cargar_pagina_eliminar( p , a , id );
		return false;
	}
	else
	{
		return false;
	}
}

function cargar_pagina_eliminar( p , a , id )
{
	location.href = './admin.php?mis=' + sesion +'&do=' + p + '&qh=' + a + '&id=' + id;
	return false;
}

function validar_datos_2(f,b)
{
	
	if ( enviando )
	{
		alert('Se está enviando el formulario, por favor espere');
		return false;
	}
	
	var tform  = eval('window.document.' + f);
		
	if ( jsvalidation == true ){
		for (x=0 ; x<campos.length ; x++)
		{
			var c = campos[x];

			c = eval('tform.' + c);

			if ( c.value == '' ){
				alert('El campo debe tener información');
				c.focus();
				return false;
			}
		}
	}
	
	enviando = true;
	b.disabled = true;
	b.className = 'buttond';
	tform.submit();

	return false;
}

function handleError(msg, url, ln){
	if (debugjs){
		alert(msg)
		alert(url)
		alert(ln)
	}
   return true;
}

window.onerror = handleError;