// +----------------------------------------------------------------------+
// | Autor:  Daniel Figueroa J. <daniel@comuniterra.com>                  |
// +----------------------------------------------------------------------+
// | Descripcion:                                                         
// |     Libreria de funciones JScript para funciones especificas del sistema
// +----------------------------------------------------------------------+

function agregarFilaCondicion() {  
  var num_txt=document.getElementById('contador_cajas').value;  
  var label_condiciones=document.getElementById('label_condiciones');
  var div_condiciones=document.getElementById('div_condiciones');  
  
  
             /* <input type="text" name="dias<?=$ind?>" id="dias<?=$ind?>" class="textoedit" size="5" title="Condicion de pago <?=$ind+1?>" accept="numerico">
			   <input type="text" name="porcentaje<?=$ind?>" id="porcentaje<?=$ind?>" class="textoedit" size="5" title="Porcentaje <?=$ind+1?>" accept="numerico">	*/
    
  //Crear txtbox 1 - Nombre del campo y agregar a la columna
  var cajaTxt1=document.createElement('div');
  cajaTxt1.innerHTML="D&iacute;as:  <input type='text' size='5' name='dias"+num_txt+"' id='dias"+num_txt+"' class='textoedit' title='Condicion de pago "+num_txt+"' accept='numero' onFocus='focoActivo(this.id)' onBlur='focoFuera(this.id)' /> Porcentaje: <input type='text' size='5' name='porcentaje"+num_txt+"' id='porcentaje"+num_txt+"' class='textoedit' title='Porcentaje "+num_txt+"' accept='numero' onFocus='focoActivo(this.id)' onBlur='focoFuera(this.id)' /><br>&nbsp;";
  div_condiciones.appendChild(cajaTxt1);
  
  var cajaTxt2=document.createElement('div');
  cajaTxt2.innerHTML="Condici&oacute;n "+(parseInt(num_txt)+1)+":<br>&nbsp;";
  label_condiciones.appendChild(cajaTxt2);
    
  num_txt++;
  document.getElementById('contador_cajas').value=num_txt;
	
} //funcion

function enviarArchivo() {
 if(document.getElementById('idcomp').value=="") alert('Para subir una imagen , primero debes guardar la informacion general del registro');
 else document.form2.submit();
} //funcion

function checaCaja(cajacheck,id,textbox) {
 //alert(id); alert(textbox);
 var caja=objeto(cajacheck);
 var contenedor=objeto(textbox);
 if(caja.checked==1) { //agregar usuario
  contenedor.value=contenedor.value+id+"-";
 } 
 else {
  var str=contenedor.value;  
   contenedor.value=str.replace(id,"0");
 }
} //funcion

function setIndice(indice) {
 document.getElementById('indice').value=indice;	
} //funcion
function getIndice() {
 return document.getElementById('indice').value;	
} //funcion 

function buscarPieza(e,obj,campoBuscar) {
 var url="doBuscarPieza.php?txtBuscar="+obj.value+"&campoBuscar="+campoBuscar;
 var tecla = (document.all) ? e.keyCode : e.which;
 //alert(tecla);
 if(tecla==13)
  abreSeccionEval(url);
 
} //funcion

function calcularImportePieza(indice) { 
 var costo=0;
 var precio=0;
 var cantidad=0;
 var costo_extra=0;
 var tapiz=0;
 var rodaja=0;
 var codera=0;
 var cantidad=document.getElementById('cantidad'+indice).value;
 var costo=document.getElementById('costosillas'+indice).value;  
 //alert("cantidad: "+cantidad+" - costo: "+costo);
 document.getElementById('importe'+indice).value=""; 
 precio=parseFloat(cantidad)*parseFloat(costo);
 
 //Verificar si hay costos extra
 if(document.getElementById('costotapices'+indice).value!="")
  tapiz=document.getElementById('costotapices'+indice).value;
 if(document.getElementById('costorodajas'+indice).value!="")
  rodaja=document.getElementById('costorodajas'+indice).value;
 if(document.getElementById('costocoderas'+indice).value!="")
  codera=document.getElementById('costocoderas'+indice).value;
 
 //alert("sumar: "+tapiz+" + "+rodaja+" + "+codera );
   
 costo_extra=parseFloat(tapiz*cantidad)+parseFloat(rodaja*cantidad)+parseFloat(codera*cantidad);
 
 //alert("extra: "+costo_extra);
 
 if(isNaN(precio))
  document.getElementById('importe'+indice).value=0;
 else {
  document.getElementById('importe'+indice).value=formatoMoneda(parseFloat(precio)+parseFloat(costo_extra));
 }
    
 desglosar_factura();		
} //funcion

function verTip2(ref,obj,mensaje) {  
  var ref=document.getElementById(ref);
  var obj=document.getElementById(obj);  
//posIzq=ref.offsetLeft-225;
posIzq=250;
  posTop=ref.offsetTop-100;
/*obj.className="tooltip";
obj.style.position="absolute";*/
/*obj.style.left = posIzq+'px';
obj.style.top = posTop+'px';*/
obj.innerHTML=mensaje;
obj.style.visibility='visible';
var capap=document.getElementById('spanDetallesVentana');
capap.style.position="absolute";
capap.style.left = posIzq+'px';
capap.style.top = posTop+'px';
capap.style.visibility='visible';
} //funcion

function ocultarTip(objeto) {
 var obj=document.getElementById(objeto);
 var capap=document.getElementById('spanDetallesVentana');
 obj.style.visibility = 'hidden';
 capap.style.visibility = 'hidden';
} //Funcion

function bajarValoresModelo(modelo,id,costo,descripcion,tapiz_default,rodaja_default,codera_default) {
 var tituloVentana=document.getElementById('tituloVentana').value;
 var nombre=tituloVentana+getIndice(); 
 document.getElementById(nombre).value=modelo;
 document.getElementById('id'+tituloVentana+getIndice()).value=id;
 document.getElementById('costo'+tituloVentana+getIndice()).value=costo;
 if(tituloVentana=="sillas") {
  try{document.getElementById('descripcion'+getIndice()).innerHTML=descripcion;}catch(e){}; 
  try{document.getElementById('precio'+getIndice()).value=costo;}catch(e){};
  try{document.getElementById('tapices'+getIndice()).value=tapiz_default;}catch(e){};
  try{document.getElementById('rodajas'+getIndice()).value=rodaja_default;}catch(e){};
  try{document.getElementById('coderas'+getIndice()).value=codera_default;}catch(e){};
 }
 calcularImportePieza(getIndice());
 ocultarTip('spanTip');
}  //funcion

function bajarValoresModeloRodaja(modelo,id,costo) {
 var tituloVentana=document.getElementById('tituloVentana').value;
 var nombre=tituloVentana+getIndice(); 
 document.getElementById(nombre).value=modelo;
 document.getElementById('id'+tituloVentana+getIndice()).value=id;
 document.getElementById('costo'+tituloVentana+getIndice()).value=costo; 
 if(tituloVentana=="sillas") {
  try{document.getElementById('descripcion'+getIndice()).innerHTML=descripcion;}catch(e){}; 
  try{document.getElementById('precio'+getIndice()).value=costo;}catch(e){};
  try{document.getElementById('tapices'+getIndice()).value=tapiz_default;}catch(e){};
  try{document.getElementById('rodajas'+getIndice()).value=rodaja_default;}catch(e){};
  try{document.getElementById('coderas'+getIndice()).value=codera_default;}catch(e){};
 }
 calcularImportePieza(getIndice());
 ocultarTip('spanTip');
}  //funcion




function desglosar_factura() {
  var subtotal=0;  
  var subtotal2=0;  
  var iva=0;
  var total=0;
  var importe=0;
  var porcentaje_descuento_aux="";
  var descuento_ppago=0;
  var descuento_otorgado=0;
  var cantidad_base=0;
  var cantidad=0;
  var tope=document.getElementById('filas_sillas').value;   
  for(ind=1;ind<=tope;ind++) {
   //validar que haya valor
   cantidad=document.getElementById('cantidad'+ind).value;
   //alert("fila "+ind+" = "+cantidad);
   if(cantidad=='' || cantidad<1) 
    importe=0;
   else {
    importe=parseFloat(document.getElementById('importe'+ind).value);      
	cantidad_base=document.getElementById('cantidad'+ind).value;
	document.getElementById('precio'+ind).value=formatoMoneda(importe/cantidad_base);      
   }
   
   //alert("importe: "+importe);
   subtotal=subtotal+importe;
   importe=0;

   
   //Verificar si aplicar pronto pago
   try{porcentaje_descuento_aux=document.getElementById('porcentaje_desc_ppago').value;}catch(e){porcentaje_descuento_aux="";}
   if(porcentaje_descuento_aux!="") {
    document.getElementById('porcentaje_pp').value=formatoMoneda(subtotal*porcentaje_descuento_aux);
	descuento_ppago=subtotal*porcentaje_descuento_aux;
   }
   else descuento_ppago=0;
   
   //Verificar que forma de pago esta seleccionada
   var forma_pago_aplicar=document.getElementById('forma_pago_activa').value;
   if(forma_pago_aplicar=="2") { //Contado
    //Obtener el porcentaje para descuento
	porcentaje_descuento_aux=document.getElementById('porcentaje_desc_contado').value;
	if(porcentaje_descuento_aux!="") {
	 document.getElementById('porcentaje_contado').value=formatoMoneda(subtotal*porcentaje_descuento_aux);
	 descuento_otorgado=subtotal*porcentaje_descuento_aux;
	} else descuento_otorgado=0;
   } //if forma=2
   if(forma_pago_aplicar=="3") { //Credito
    //Obtener el porcentaje para descuento
	porcentaje_descuento_aux=document.getElementById('porcentaje_desc_credito').value;
	if(porcentaje_descuento_aux!="") {
	 document.getElementById('porcentaje_credito').value=formatoMoneda(subtotal*porcentaje_descuento_aux);
	 descuento_otorgado=subtotal*porcentaje_descuento_aux;
	} else descuento_otorgado=0;
   } //if forma=3
   if(forma_pago_aplicar=="4") { //Anticipo
    //Obtener el porcentaje para descuento
	porcentaje_descuento_aux=document.getElementById('porcentaje_desc_anticipo').value;
	if(porcentaje_descuento_aux!="") {
	 document.getElementById('porcentaje_anticipo').value=formatoMoneda(subtotal*porcentaje_descuento_aux);
	 descuento_otorgado=subtotal*porcentaje_descuento_aux;
	} else descuento_otorgado=0;
   } //if forma=4
   
         
   iva=(subtotal-descuento_ppago-descuento_otorgado)*0.15;
   total=(subtotal-descuento_ppago-descuento_otorgado)+iva;
   document.getElementById('subtotal').value=formatoMoneda(subtotal);
   document.getElementById('subtotal2').value=formatoMoneda(subtotal-descuento_otorgado);
   document.getElementById('iva').value=formatoMoneda(iva);
   document.getElementById('total').value=formatoMoneda(total);   
  }      
 } //fin funcion

function formatoMoneda(cantidad) {
var val = parseFloat(cantidad);
if (isNaN(val)) { return "0.00"; }
if (val <= 0) { return "0.00"; }
val += "";
// Next two lines remove anything beyond 2 decimal places
if (val.indexOf('.') == -1) { return val+".00"; }
else { val = val.substring(0,val.indexOf('.')+3); }
val = (val == Math.floor(val)) ? val + '.00' : ((val*10 ==
Math.floor(val*10)) ? val + '0' : val);
return val;
}  //funcion

function enviaMensaje(tabla,accion,capa,tipo_notificacion,formulario) {      
 if(!formulario)
  formulario=document.form1;
 if(confirm("Deseas enviar la informacion?")) 
 {
  if(validaCampos(formulario)) 
  {
   var url="enviaMensajeContacto.php?tabla="+tabla+"&accion="+accion+"&tipo_notificacion="+tipo_notificacion+"&"+obtenerVariables(formulario); 
   //alert(url);
   FAjax(url,capa,'','POST',tipo_notificacion); 
   if(accion=="insertar") 
    //limpiaCampos(formulario);       
   limpiaCapa(capa);
  }
  
 } //if confirm
 } //termina funcion

function setImagen(img,path) {
 //alert(img); alert(path); return	
 document.getElementById('menuActivo').value=img;
 document.getElementById(img).src=path;
} //funcion

function habilitarFormaPago(numero) {
 var i; var visible="";	
 if(numero!="%") {
  for(i=2;i<=4;i++) {
   if(i==numero) {
    visible='visible';
	document.getElementById('forma_pago_activa').value=numero;
	desglosar_factura();
   }   
   else visible='collapse';
   try{document.getElementById('forma_pago_'+i).style.visibility=visible;}catch(e){alert('La opcion de pago seleccionada no esta disponible en tu cuenta');}
  } //for
 }
} //funcion

function enviaPedido(tabla,accion,capa,tipo_notificacion,formulario) {      
 if(!formulario)
  formulario=document.form1;
 if(confirm("Deseas enviar la informacion?")) 
 {
  if(validaCampos(formulario)) 
  {
   var url="enviaPedido.php?tabla="+tabla+"&accion="+accion+"&tipo_notificacion="+tipo_notificacion+"&"+obtenerVariables(formulario); 
   //alert(url);
   FAjax(url,capa,'','POST',tipo_notificacion); 
   if(accion=="insertar") 
    //limpiaCampos(formulario);       
   limpiaCapa(capa);
  }
  
 } //if confirm
 } //termina funcion

function imprimePedido(tabla,accion,capa,tipo_notificacion,formulario) {      
 if(!formulario)
  formulario=document.form1;
 if(confirm("Deseas imprimir la hoja?")) 
 {
  if(validaCampos(formulario)) 
  {
   var url="imprimePedido.php?tabla="+tabla+"&accion="+accion+"&tipo_notificacion="+tipo_notificacion+"&"+obtenerVariables(formulario); 
   //alert(url);
   document.location.href=url;
  }
  
 } //if confirm
 } //termina funcion
 
function llenaDireccionEnvio(contacto,telefono,direccion,cp,colonia,ciudad,estado) {
 objeto('contacto_envio').value=contacto		
 objeto('telefono_envio').value=telefono		
 objeto('direccion_envio').value=direccion		
 objeto('cp_envio').value=cp		
 objeto('colonia_envio').value=colonia		
 objeto('ciudad_envio').value=ciudad
 objeto('estado_envio').value=estado   
} //funcion

function buscarCompatibilidadesVentana(idtipocomp,tituloVentana,idsilla) { 
  //var url="ventanaListaModelos.php?idtipocomp="+idtipocomp+"&tituloVentana="+tituloVentana+"&idsilla="+idsilla	
  
  var url="ventanaListaModelosTapices.php?idtipocomp="+idtipocomp+"&tituloVentana="+tituloVentana+"&idsilla="+idsilla	
  abreSeccion(url,'spanDetallesVentana');	
} //funcion

function validaEnvioMensaje() {
   var empresa=document.getElementById('empresa').value; 
   var email=document.getElementById('email').value;
   var telefonos=document.getElementById('telefonos').value;   
   var errores="";
  if(empresa=="") errores=errores+"Debes llenar el campo: Empresa\n";
  if(email=="") errores=errores+"Debes llenar el campo: Email\n";
  if(telefonos=="") errores=errores+"Debes llenar el campo: Telefono\n";
  
  //Si no hay vacios, enviar form
  if(errores=="")
   enviaMensaje('','','msgSistema','alert');
  else alert(errores);
} //funcion

function validaEnvioPedido() {
   var contacto_envio=document.getElementById('contacto_envio').value; 
   var telefono_envio=document.getElementById('telefono_envio').value;   
   var direccion_envio=document.getElementById('direccion_envio').value;   
   var cp_envio=document.getElementById('cp_envio').value;   
   var colonia_envio=document.getElementById('colonia_envio').value;   
   var ciudad_envio=document.getElementById('ciudad_envio').value;   
   var estado_envio=document.getElementById('estado_envio').value;   
   var errores="";
  if(contacto_envio=="") errores=errores+"Debes llenar el campo: Contacto envio\n";
  if(telefono_envio=="") errores=errores+"Debes llenar el campo: Telefono envio\n";  
  if(direccion_envio=="") errores=errores+"Debes llenar el campo: Direccion envio\n";
  if(cp_envio=="") errores=errores+"Debes llenar el campo: CP\n";
  if(colonia_envio=="") errores=errores+"Debes llenar el campo: Colonia envio\n";
  if(ciudad_envio=="") errores=errores+"Debes llenar el campo: Ciudad envio\n";
  if(estado_envio=="") errores=errores+"Debes llenar el campo: Estado envio\n";
  
  //Si no hay vacios, enviar form
  if(errores=="")
   enviaPedido('','','spanPrincipal','capa');
  else alert(errores);
} //funcion

function validaEnvioSolicitudGarantia() {
   var fecha=document.getElementById('fecha').value; 
   var solicitante=document.getElementById('solicitante').value; 
   var modelo=document.getElementById('modelo').value; 
   var of=document.getElementById('of').value;
   var sc1=document.getElementById('sc1').value;   
   var sc2=document.getElementById('sc2').value;   
   /*var refaccion=document.getElementById('refaccion').value;   
   var descripcion=document.getElementById('descripcion').value;   */
   var errores="";
  //if(modelo=="") errores=errores+"Debes llenar el campo: Modelo\n";
  if(solicitante=="") errores=errores+"Debes llenar el campo: Quien solicita\n";
  if(of=="") errores=errores+"Debes llenar el campo: OF\n";
  if(sc1=="") errores=errores+"Debes llenar el campo: SC\n";
  if(sc2=="") errores=errores+"Debes llenar el campo: SC\n";
  /*if(refaccion=="") errores=errores+"Debes llenar el campo: Refaccion\n";
  if(descripcion=="") errores=errores+"Debes llenar el campo: Descripcion\n";        */
  //Si no hay vacios, enviar form
  if(errores=="") {
   //var url="doAccionesGenerales.php?task=solicitud_garantia&modelo="+modelo+"&of="+of+"&sc1="+sc1+"&sc2="+sc2+"&refaccion="+refaccion+"&descripcion="+descripcion+"&fecha="+fecha;
   //abreSeccion(url,'spanPrincipal');   
   document.form1.submit();
  }
  else alert(errores);
} //funcion

function muestraFila() {
 //Verificar proxima fila
 var fila=document.getElementById('fila_next').value;
 if(fila<=10) {
  document.getElementById('fila_silla_'+fila).style.visibility='visible';
  document.getElementById('fila_next').value=parseInt(fila)+1;
 }
} //funcion

function switchFoto() {
 //Verificar la foto actual
 var foto_actual=document.getElementById('foto_prod').src;
 var foto_nueva=document.getElementById('foto_activa').value;
 document.getElementById('foto_prod').src=foto_nueva;
 document.getElementById('foto_activa').value=foto_actual;  
} //funcion

function bajarValoresModeloTapiz(costo,tapiz) { 
 //alert(costo); 
 try{
	 document.getElementById('costosillas'+getIndice()).value=costo;
	 document.getElementById('tapices'+getIndice()).value=tapiz;
	 }catch(e){};  
 calcularImportePieza(getIndice());
 ocultarTip('spanTip');
}  //funcion

function limpiaFilaProducto(indice) {
 document.getElementById('cantidad'+indice).value="";
 document.getElementById('sillas'+indice).value="";
 document.getElementById('idsillas'+indice).value="";
 document.getElementById('tapices'+indice).value="";
 document.getElementById('rodajas'+indice).value="";
 document.getElementById('idtapices'+indice).value="";
 document.getElementById('idrodajas'+indice).value="";
 document.getElementById('coderas'+indice).value="";
 document.getElementById('idcoderas'+indice).value="";
 document.getElementById('costocoderas'+indice).value="";
 document.getElementById('costorodajas'+indice).value="";
 document.getElementById('costotapices'+indice).value="";
 document.getElementById('costosillas'+indice).value="";
 document.getElementById('descripcion'+indice).innerHTML="";
 document.getElementById('precio'+indice).value="";
 document.getElementById('importe'+indice).value="";
} //funcion

function eliminarFotoProducto(idcomp,campo) {
  var url="doAccionesGenerales.php?task=eliminar_imagen_producto&idcomp="+idcomp+"&campo="+campo;
  abreSeccionEval(url);	 	
} //funcion

function recargaIframeFotos() {
 document.location.reload();
}
