var nv=navigator.userAgent.toLowerCase();
var is_ie = ((nv.indexOf("msie") != -1) && (nv.indexOf("opera") == -1));



function MM_showHideLayers() { //v6.0
            var i,p,v,obj,args=MM_showHideLayers.arguments;
            for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) { v=args[i+2];
            if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v=='hide')?'hidden':v; }
            obj.visibility=v; }
          }
          function MM_findObj(n, d) { //v4.01
 			var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    		d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  			if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  			for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  			if(!x && d.getElementById) x=d.getElementById(n); return x;
}
function mostrar_cargando(form){
	 MM_showHideLayers('cargando1','','show'); 
	 }


function ventana(url,nombre,prop){window.open(url,nombre,prop);}

//Funcion para capturar eventos de teclado
function tecla(e){
 var tecla;
 if(document.all){ //IE 4
  tecla = event.keyCode; 
 }else if(document.layers){ //NS 4
  tecla = e.which; 
 }else if(document.getElementById){ //NS 6
  tecla = e.which; 
 } 
}
document.onkeydown = tecla
if (document.layers) document.captureEvents(Event.KEYUP)

function trim(cadena){
 cadena=cadena.replace(/^[\s]+/g,"");
 cadena=cadena.replace(/[\s]+$/g, ""); 
   return cadena;
}

function isValid(string,allowed){
	if (allowed == ""){
		allowed = 'áéíóúabcdefghijklmnñopqrstuvwxyzÁÉÍÓÚABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890._- ';
	}
	
    for (var i=0; i< string.length; i++){
        if (allowed.indexOf(string.charAt(i)) == -1) return false;
    }
    return true;
}

function buscar(form,trg){
 valid = 'áéíóúabcdefghijklmnñopqrstuvwxyzÁÉÍÓÚABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890._- ';
 form.srch.value=trim(form.srch.value);
 document.location = trg + "?srch=" + form.srch.value;  
}

//Funciones para el buscador
var txUlt = "";
function text1(field){
	txUlt = field.name;
    field.select();
    field.focus();    
}

function text0(field){
  field.blur();
  txUlt="";
}

function page0(page,acc,cart,params,prefix){
	txCantidad = document.getElementById(prefix + cart);
	cantidad="0";
	if (txCantidad != null){
		cantidad = txCantidad.value;
	}	
	
	strLista = "";
	listaActual = document.getElementById("ddlListasHabituales");
	if (listaActual != null){strLista = "&clista="+listaActual.value;}	
	document.location = page + "?accionc=" + acc + "&cant=" + cantidad + "&cartcar=" + cart + params + strLista;
}

function page1(page,acc,cart,params){
	document.location = page + "?accion=" + acc + "&cart=" + cart + params;
}

function numeralsOnly(evt)
{
	Evt = (evt) ? evt : event;
	var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ?
	Evt.keyCode : ((evt.which) ? evt.which : 0));
	if (charCode > 31 && (charCode < 48 || charCode > 57))
	{
		alert("Introduzca un número");
		return false;
	}
	return true;
}
 
function onEnterKeyDown(frm,trg,fnc){
  var key;
  if (is_ie) key = window.event.keyCode;//IE 4
  else key = e.which;// FireFox, etc.

  if (key == 13) {//Enter
  	eval(fnc);
    if (!document.all) return false; 
    else {
		window.event.returnValue = false;
		window.event.cancelBubble = true;
		window.event.keyCode = 0;              
    }   
  }    
  if (!document.all) return true;
}

function onEnterKeyDownNoEnter(){
  	  var key;
	  if (is_ie) key = window.event.keyCode;//IE 4
	  else key = e.which;// FireFox, etc.
  	  if (key == 13) {//Enter
  	    return false;
  	  }else{
  	    return true;
  	  }		  
  }

function login(frm,trg){
	frm.usr.value = trim(frm.usr.value);
	frm.pwd.value = trim(frm.pwd.value);
	document.location = trg + "?accion=lg&usr=" + frm.usr.value+"&pwd="+frm.pwd.value;
}

function reloadParent(trg,closeChild){
	var pWin
	pWin = top.window.opener
   	pWin.location.replace(trg);
   	if (closeChild){
   		window.close();
   	}
}

loadsubTopMenu = function() 
{	
if (document.all&&document.getElementById) 
 {	
	
  menunavParent2 = document.getElementById("nav2");	
	
   for (x=0; x < menunavParent2.childNodes.length; x++) 
     {		
        menunode2 = menunavParent2.childNodes[x];
			
           if (menunode2.nodeName=="LI") 
             {			
              menunode2.onmouseover=function() 
                {				
                this.className+=" over";			
                }			
                menunode2.onmouseout=function() 
                {				
                  this.className=this.className.replace(" over", "");
	  }
           }
        }
     }
}

//window.onload=loadsubTopMenu;

loadTopMenu = function() 
{	
if (document.all&&document.getElementById) 
 {		
  menunavParent = document.getElementById("nav");	
	
   for (x=0; x < menunavParent.childNodes.length; x++) 
     {		
        menunode = menunavParent.childNodes[x];
			
           if (menunode.nodeName=="LI") 
             {			
              menunode.onmouseover=function() 
                {				
                this.className+=" over";			
                }			
                menunode.onmouseout=function() 
                {				
                  this.className=this.className.replace(" over", "");
	  }
           }
        }
     }
}

//window.onload=loadTopMenu;

function getSelected(opt) {
  	var selected = new Array();
  	if (opt.checked == true || opt.checked == false){//1 elemento	  		
  		if (opt.checked){	  			
  		  selected[0] = opt;
  		}	  		
  	}else{	  		
	    var index = 0;
	    for (var intLoop = 0; intLoop < opt.length; intLoop++) {
	       if ((opt[intLoop].selected) ||
	           (opt[intLoop].checked)) {
	          index = selected.length;
	          selected[index] = new Object;
	          selected[index].value = opt[intLoop].value;
	          selected[index].index = intLoop;
	       }
	    }		    
	}
	return selected;
 }	
 function outputSelected(opt) {
	var sel = getSelected(opt);		
	var strSel = "";
	for (var item in sel){
		strSel += sel[item].value + ";";
	}
	return strSel;
}
function openWindow(destino,nombre,istoolbar,isscrollbars,poslocation,isstatusbar,isstatus,ismenubar,isresizable,ancho,alto,posleft,postop){
  window.open(destino,nombre,"toolbar="+istoolbar+",scrollbars="+isscrollbars+",location="+poslocation+",statusbar="+isstatusbar+",status="+isstatus+",menubar="+ismenubar+",resizable="+isresizable+",width="+ancho+",height="+alto+",left="+posleft+",top="+postop+"");
}
function get_cookie(name) {
  var search = Name + "=";
  var returnvalue = "";
  if (document.cookie.length > 0) {
    offset = document.cookie.indexOf(search);
    if (offset != -1) { // if cookie exists
      offset += search.length;
      // set index of beginning of value
      end = document.cookie.indexOf(";", offset);
      // set index of end of cookie value
      if (end == -1)
        end = document.cookie.length;
        returnvalue=unescape(document.cookie.substring(offset, end))
    }
  }
  return returnvalue;
}

function createXMLHttpRequest() {
   try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}
   try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}
   try { return new XMLHttpRequest(); } catch(e) {}   
   return null;
 }
 
function createXmlParser(cadena){
	//load xml file
	// code for IE
	var xmlDoc;
	if (window.ActiveXObject)
  	{
  	  xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
  	  xmlDoc.async=false;
  	  xmlDoc.loadXML(cadena);  	  
  	}else if (document.implementation && document.implementation.createDocument){  	  
  	  //xmlDoc= document.implementation.createDocument("","",null);  	  
  	  //xmlDoc.loadXML(cadena);
  	  var parser = new DOMParser();
	  xmlDoc = parser.parseFromString(cadena, "text/xml");
  	}else{
  	  alert('Error al crear el parser xml.');
  	}
  	return xmlDoc;    
}

//Devuelve un Array con los elementos del tag
function getElements(pTag,pTagName){
	resultado = new Array();
	for (i = 0; i < pTag.getElementsByTagName(pTagName).length; i++){  
	  var item = pTag.getElementsByTagName(pTagName)[i];  
 	  resultado[i] = item;
 	}	
	return resultado;
}
//Devuelve un elemento unico
function getElement(pTag,pTagName){
	items = getElements(pTag,pTagName);
	return items[0];
}
//Devuelve el texto de un nodo
function getText(pTag){
	if (pTag != null){
	  return pTag.firstChild.data;
	}else{
	  return "";
	}
}
function cargaCarritoDesdeXml(capa,datos,pagina,params){
    	if (datos != null && datos != ""){
  		if (datos != "SESSION_CADUCADA"){
	  		var strCarrito = "";
			var parser = createXmlParser(datos);
			var rootElement = parser.getElementsByTagName("items").item(0);
			var imp = rootElement.getAttribute("imp");  
			var cred = rootElement.getAttribute("cred");
			var tpcl = rootElement.getAttribute("tpcl");			
			var items = getElements(rootElement,"item");
		  
			strCarrito += "<ul>";
			if (cred != "N/A"){
			  strCarrito += "<li id='producto2";
			  if (parseInt(cred) < 0){strCarrito += "_rojo";}
			    strCarrito +="'>Cr&eacute;dito disponible:<br>"+cred+"&euro;</li>"
			    if (tpcl == "1" && parseInt(cred) < 0){strCarrito += "<li  id='producto2'>Solicitar + cr&eacute;dito <a href=\"javascript:ventana('solicitarCreditoC.aspx','CREDITO','width=450,height=400,left=50,top=50,scrollbars=yes,resizable=yes')\" class='blanco'>aqu&iacute;</a></li>";}
			}
			  
			if (items != null && items.length > 0){
			    
			strCarrito += "<li id='producto2'><table border='0' cellpadding='0' cellspacing='0'><tr><td width='75' class='blanco'>Total ped.:</td><td height='25' align='right' class='blanco'>"+imp+"&euro;</td></tr></table></li>";        
			    
			for ( var i = 0; i < items.length; i++ ){  	  	
			  var item = items[i];  	
			    tag_id = getElement(item,"id");
			    tag_cant = getElement(item,"cant");
			    tag_imp = getElement(item,"imp");
			    tag_img = getElement(item,"imglist");
			    tag_idbundle = getElement(item,"idbundle");
			    val_id = getText(tag_id);
			    val_cant = getText(tag_cant);
			    val_imp = getText(tag_imp);
			    val_img = getText(tag_img);
			    val_idbundle = getText(tag_idbundle);			    
			    strCarrito += "<li id='producto'>"+
			  	          "<table width='100%' border='0' cellspacing='0' cellpadding='0'><tr><td width='50' rowspan='4'>"+val_id+
			  		  "<img src='/Documentos/Articulos/Fotos/listado/"+val_img+"' vspace='-5' border='0' align='left'/>";
			    if (val_idbundle != "-1" && val_idbundle != "0"){strCarrito += "<img src='/images/bundle.jpg' alt='articulo incluido en un bundle' class='imgRight'>";}
			    strCarrito += "</td>"+
			  		  "<td colspan='2' align='right'></td></tr>"+
			  		  "<tr><td colspan='2' align='right' valign='middle'><font class='unidades'> "+val_cant+" ud/s</font></td></tr>"+
			              	  "<tr><td colspan='2'  align='right' ><font class='precio'>"+val_imp+" &euro;</font></td></tr>"+
			  		  "<tr><td width='788'  align='right'>&nbsp;</td>";
			    if (val_idbundle == "-1"){
			    	strCarrito += "<td width='60' align='right' class='bot_peque'><a href=\"javascript:actCar('b','"+val_id+"','1','','','')\" onmouseout=\"window.status=''\" onmouseover=\"window.status='';return true\">Borrar</a></td>";
			    }else{
			        strCarrito += "<td width='60' align='right' class='bot_peque'><a href=\"javascript:actCar('b1','"+val_id+"','1','','','"+val_idbundle+"')\" onmouseout=\"window.status=''\" onmouseover=\"window.status='';return true\">Borrar</a></td>";
			    }
			              	  
			    strCarrito += "</tr>"+
			            	  "</table>"+
			          	  "</li>";
			    }
			    strCarrito += "<li class='bot' id='producto'><a href='/datosPedidoC.aspx'>Ver Compra</a><a href=\"javascript:ventana('/html/ayuda_compra.html','ayuda','width=400,height=300,left=50,top=50,scrollbars=no,resizable=no')\" class='nada' title='Acceda a su carrito de la compra'><img src='/images/info.gif' alt='Acceda a su carrito de la compra' border='0'/></a></li>"+
				  	  "<li class='bot' id='producto'><a href=\"javascript:page0('"+pagina+"','w0','','"+params+"','')\" title='Pinche aquí para guardar su carrito en pedidos en diseño'>Guardar Carrito</a><a href=\"javascript:ventana('/html/ayuda_guardar.html','ayuda','width=400,height=200,left=50,top=50,scrollbars=no,resizable=no')\" class='nada' title='Guarde su carrito para realizar la compra en otro momento'><img src='/images/info.gif' alt='Guarde su carrito para realizar la compra en otro momento' border='0'/></a></li>"+
				  	  "</ul>";
				  	
  			}else{
  	  			strCarrito="<ul><li id='producto2'>Su carrito est&aacute; vac&iacute;o</li></ul>";
			}  
		}else{
		  alert("La sesión ha caducado. Vuelva a logearse en el sistema.");
    		  capa.innerHTML = "";
		}
	}else{
	  strCarrito="<ul><li id='producto2'>Su carrito est&aacute; vac&iacute;o</li></ul>";
	}	
	capa.innerHTML = strCarrito;
}

function removeChildrenFromNode(node){
   if(node != undefined && node != null){return;}
   
   var len = node.childNodes.length;
   
   while (node.hasChildNodes())	{
     node.removeChild(node.firstChild);
   }
}

function queryArt(txart,prefijo){
    dojo.io.bind({
	method : 'POST',
	content : {
		cart : txart		
	},
	url: '/compraExpressQueryC.aspx',
	load: function(type, data, evt) {		
		  cargaCapasCompraExpress(data,prefijo);		
	},
	mimetype: "text/plain"
    });
}

function cargaCapasCompraExpress(datos,prefijo){
  inputVl = document.getElementById('ce_rf' + prefijo);
  capaSt = document.getElementById('ce_dv_st_' + prefijo);
  capaCj = document.getElementById('ce_dv_cj_' + prefijo);
  if (inputVl != null && capaSt != null && capaCj != null){  	
  	if (inputVl.value != ""){
  	  var parser = createXmlParser(datos);
  	  var rootElement = parser.getElementsByTagName("articulo").item(0);
  	  tag_id = getElement(rootElement,"id");
	  tag_udagrupacion = getElement(rootElement,"udagrupacion");
  	  val_id = getText(tag_id);
	  val_udagrupacion = getText(tag_udagrupacion);
	
	  if (val_id == "ERROR"){
		capaSt.innerHTML = "<img src='/images/no_ok.jpg' alt='Articulo no encontrado'/>";
		capaCj.innerHTML = "<img src='/images/pixel.gif'/>";
	  }else{
		capaSt.innerHTML = "<img src='/images/ok.jpg'/>";
		if (val_udagrupacion != "1"){
			capaCj.innerHTML = val_udagrupacion + "x<img src='/images/caja.jpg' alt='Venta en cajas de "+val_udagrupacion+" unidades'/>";
		}
	  }
	}else{
		capaSt.innerHTML = "<img src='/images/pixel.gif'/>";
		capaCj.innerHTML = "<img src='/images/pixel.gif'/>";
	}
	
	
  }else{
  	alert("Error al recuperar estructuras.");
  }
}

function irPagina(tForm,tPagina){
	document.location = tPagina;
}

function irPagina2(tForm,tPagina){
	if (tPagina == "/descargaTarifasC.aspx"){
	  ventana('/descargaTarifasC.aspx','TARIFAS','width=450,height=450,left=50,top=50,scrollbars=yes,resizable=yes')	  
	}else if (tPagina == "/listArticulosHabitualesC.aspx"){
	  ventana('/listArticulosHabitualesC.aspx','ART_HAB','width=650,height=500,left=50,top=50,scrollbars=yes,resizable=yes')	  
	}else{
	  document.location = tPagina;
	}
}

function reloadListNapp(urlBase,selectNapp){
	document.location = urlBase + "&napp=" + selectNapp.value;
}