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 MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function AC_AddExtension(src, ext)
{
  if (src.indexOf('?') != -1)
    return src.replace(/\?/, ext+'?'); 
  else
    return src + ext;
}


function AC_Generateobj(objAttrs, params, embedAttrs) 
{ 
  var str = '<object ';
  for (var i in objAttrs)
    str += i + '="' + objAttrs[i] + '" ';
  str += '>';
  for (var i in params)
    str += '<param name="' + i + '" value="' + params[i] + '" /> ';
  str += '<embed ';
  for (var i in embedAttrs)
    str += i + '="' + embedAttrs[i] + '" ';
  str += ' ></embed></object>';

  document.write(str);
}

function AC_FL_RunContent(){
  var ret = 
    AC_GetArgs
    (  arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
     , "application/x-shockwave-flash"
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_SW_RunContent(){
  var ret = 
    AC_GetArgs
    (  arguments, ".dcr", "src", "clsid:166B1BCA-3F9C-11CF-8075-444553540000"
     , null
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_GetArgs(args, ext, srcParamName, classid, mimeType){
  var ret = new Object();
  ret.embedAttrs = new Object();
  ret.params = new Object();
  ret.objAttrs = new Object();
  for (var i=0; i < args.length; i=i+2){
    var currArg = args[i].toLowerCase();    

    switch (currArg){	
      case "classid":
        break;
      case "pluginspage":
        ret.embedAttrs[args[i]] = args[i+1];
        break;
      case "src":
      case "movie":	
        args[i+1] = AC_AddExtension(args[i+1], ext);
        ret.embedAttrs["src"] = args[i+1];
        ret.params[srcParamName] = args[i+1];
        break;
      case "onafterupdate":
      case "onbeforeupdate":
      case "onblur":
      case "oncellchange":
      case "onclick":
      case "ondblClick":
      case "ondrag":
      case "ondragend":
      case "ondragenter":
      case "ondragleave":
      case "ondragover":
      case "ondrop":
      case "onfinish":
      case "onfocus":
      case "onhelp":
      case "onmousedown":
      case "onmouseup":
      case "onmouseover":
      case "onmousemove":
      case "onmouseout":
      case "onkeypress":
      case "onkeydown":
      case "onkeyup":
      case "onload":
      case "onlosecapture":
      case "onpropertychange":
      case "onreadystatechange":
      case "onrowsdelete":
      case "onrowenter":
      case "onrowexit":
      case "onrowsinserted":
      case "onstart":
      case "onscroll":
      case "onbeforeeditfocus":
      case "onactivate":
      case "onbeforedeactivate":
      case "ondeactivate":
      case "type":
      case "codebase":
        ret.objAttrs[args[i]] = args[i+1];
        break;
      case "width":
      case "height":
      case "align":
      case "vspace": 
      case "hspace":
      case "class":
      case "title":
      case "accesskey":
      case "name":
      case "id":
      case "tabindex":
        ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];
        break;
      default:
        ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];
    }
  }
  ret.objAttrs["classid"] = classid;
  if (mimeType) ret.embedAttrs["type"] = mimeType;
  return ret;
}

function oNumero(numero)
{
//Propiedades
this.valor = numero || 0
this.dec = -1;
//Métodos
this.formato = numFormat;
this.ponValor = ponValor;
//Definición de los métodos
function ponValor(cad)
{
if (cad =='-' || cad=='+') return
if (cad.length ==0) return
if (cad.indexOf('.') >=0)
    this.valor = parseFloat(cad);
else
    this.valor = parseInt(cad);
}
function numFormat(dec, miles){
	var num = this.valor, signo=3, expr;
	var cad = ""+this.valor;
	var ceros = "", pos, pdec, i;
	
	for (i=0; i < dec; i++)
		ceros += '0';
		pos = cad.indexOf('.')
		if (pos < 0)
			cad = cad+"."+ceros;
		else{
			pdec = cad.length - pos -1;
			if (pdec <= dec)
				{
				for (i=0; i< (dec-pdec); i++)
					cad += '0';
				}
			else
				{
				num = num*Math.pow(10, dec);
				num = Math.round(num);
				num = num/Math.pow(10, dec);
				cad = new String(num);
				}
		 }
		pos = cad.indexOf('.')
		if (pos < 0) pos = cad.lentgh
		if (cad.substr(0,1)=='-' || cad.substr(0,1) == '+')
			   signo = 4;
		if (miles && pos > signo)
			do{
				expr = /([+-]?\d)(\d{3}[\.\,]\d*)/
				cad.match(expr)
				cad=cad.replace(expr, RegExp.$1+','+RegExp.$2)
				}
		while (cad.indexOf(',') > signo)
			if (dec<0) cad = cad.replace(/\./,'')
				return cad;
		}
}//Fin del objeto oNumero:

function agregar_carrito(producto){
		top.frames['hiddenFrame'].location='/carrito_agregar.php?ce_id='+producto;
		return true;
			
}

function actualiza(param){

			var precio_unidad;
			var precio_unidad_iva;
			var cantidad;						
			var total_sin_iva;
			var iva_total;
			
			cantidad = eval("document.getElementById('cantidad_"+param+"').value");
			precio_unidad = eval("document.getElementById('hid_precio_" +param+"').value");
			precio_unidad_iva = eval("document.getElementById('hid_iva_"+param+"').value");
			
			//Primero compruebo que lo que se introduce es número
			if (isNaN(cantidad)){
				alert('El valor introducido no es númerico');
				aux= eval("document.getElementById('cantidad_"+param+"').focus()");
				aux= eval("document.getElementById('cantidad_"+param+"').select()");
				aux= eval("document.getElementById('cantidad_"+param+"').value='1'");							
				return false;
			}
			/*
			if (cantidad==0){
				alert('El valor introducido no puede ser cero');
				aux= eval("document.getElementById('cantidad_"+param+"').focus()");
				aux= eval("document.getElementById('cantidad_"+param+"').select()");
				aux= eval("document.getElementById('cantidad_"+param+"').value='1'");							
				return false;
			
			}
			*/
			
			//actualizo el item
			var numero = new oNumero(cantidad*precio_unidad);
			
			aux = eval("document.getElementById('total_base_"+param+"').innerHTML='"+ numero.formato(2,false) +"'");
			
			numero = new oNumero(cantidad*precio_unidad_iva);
			
			aux = eval("document.getElementById('total_iva_"+param+"').innerHTML='"+ numero.formato(2,false) +"'");
			
			
			return saca_totales();	
 }
 
 function saca_descuento(b_total,devuelve_valor){
 	
	var entra;
	entra=0;
	descuento=0;
	tanto=0;
	array_minimos = new Array();
	array_maximos = new Array();
	array_tanto = new Array();
	
 	array_minimos[0] = 1500;
	array_maximos[0] = 2999.99;
	array_tanto[0] = 3;
	
	array_minimos[1] = 3000;
	array_maximos[1] = 5999.99;
	array_tanto[1] = 5;
	
	array_minimos[2] = 6000;
	array_maximos[2] = 1000000;
	array_tanto[2] = 7;

	for (j = 0; j < array_minimos.length; j++){
		if ((b_total >= array_minimos[j]) && (b_total<=array_maximos[j])){
			entra=1;
			document.getElementById('tanto_descuento').innerHTML='DESCUENTO '+ array_tanto[j] +' %';
			descuento = (b_total * array_tanto[j])/100;
			tanto = array_tanto[j];
			var numero = new oNumero(descuento);
			document.getElementById('total_descuento').innerHTML=' '+numero.formato(2,true)+' &euro;';
			
		}
	}
	
	if (entra==0){
		document.getElementById('tanto_descuento').innerHTML='DESCUENTO 0%';
		var numero = new oNumero(0);	
		document.getElementById('total_descuento').innerHTML=' '+numero.formato(2,true)+' &euro;';
		
	}
	
	if (devuelve_valor==0){
		
		return true;
	}
	
	if (devuelve_valor==1){
		return descuento;
	}
	
	if (devuelve_valor==2){
		return tanto;
	}
	
	return true;
	
 }
 
 function saca_portes(base_total){
 	var peso_total=0;
	var portes=0;	
	if (base_total>=700){
		var numero = new oNumero(0);
		document.getElementById('total_portes').innerHTML=' '+numero.formato(2,true)+' &euro;';
	}else{
			for (j = 0; j < document.forms.form_compra.elements.length; j++){
					if ((document.forms.form_compra.elements[j].name.substring(0,9)=='cantidad_') && document.forms.form_compra.elements[j].disabled==false){
						
						aux = document.forms.form_compra.elements[j].name.substring(9);
						peso = eval("document.getElementById('peso_"+aux+"').value");
						cantidad = eval("document.getElementById('cantidad_"+aux+"').value");					
						peso_total= peso_total + (peso * cantidad);
															
					}
						
			}
			
			if (peso_total <= 10){
				if (peso_total > 0){
					portes = 5.65;
				}else{
					portes = 0;
				}
			}else{
				portes = 5.65;
				fracciones = Math.ceil((peso_total - 10) / 5);
				portes = portes + (fracciones * 1.95);			
			}
			
			var numero = new oNumero(portes);	
			document.getElementById('total_portes').innerHTML=' '+numero.formato(2,true)+' &euro;';
		
			
	
	}
	
	return portes;
 }//Fin function
 
 function saca_totales(){
 	
 	var base_total=0;
	var iva_total = 0;
	var total = 0;
	var iva_lotes = 0;
 	var contrareembolso = 0;
		
	for (j = 0; j < document.forms.form_compra.elements.length; j++){
				
			if ((document.forms.form_compra.elements[j].name.substring(0,9)=='cantidad_') && document.forms.form_compra.elements[j].disabled==false){
				
				aux = document.forms.form_compra.elements[j].name.substring(9);
				cantidad = eval("document.getElementById('cantidad_"+aux+"').value");
				precio_unidad = eval("document.getElementById('hid_precio_" +aux+"').value");
				precio_unidad_iva = eval("document.getElementById('hid_iva_"+aux+"').value");
				base_total = base_total + (cantidad * precio_unidad);
				iva_total = iva_total + (cantidad * precio_unidad_iva);
				//total = base_total + iva_total;
							
			}
					
	}
	
	iva_lotes = iva_total;
	
	
	var numero = new oNumero(base_total);
	aux = eval("document.getElementById('base_total').innerHTML='"+ numero.formato(2,true) +" €'");
	
	//DESCUENTO
	x = saca_descuento(numero.formato(2,false),0);
	descuento_tanto = saca_descuento(base_total,2);
	iva_total = iva_total - (iva_total * (descuento_tanto/100));
	
	
	//PORTES
			
	portes = saca_portes(numero.formato(2,false));
	iva_total = iva_total + (portes * 0.18);
	
	//CONTRAREEMBOLSO
	if (document.getElementById('forma_de_pago').options[document.getElementById('forma_de_pago').selectedIndex].value == 0){
		contrareembolso = ( ((base_total+iva_lotes)*(100-descuento_tanto)/100) + (portes*1.16) ) * 0.05;
		if (contrareembolso > 150){
			contrareembolso=150;
		}
	}
	var numero = new oNumero(contrareembolso);
	document.getElementById('contra').innerHTML=' '+numero.formato(2,true)+' &euro;';
	
	iva_total = iva_total + (contrareembolso * 0.18);
	
	var numero = new oNumero(iva_total);
	aux = eval("document.getElementById('iva_total').innerHTML='"+ numero.formato(2,true) +" €'");
	
	
	
	total = base_total - saca_descuento(base_total,1) + portes + contrareembolso + iva_total;
	var numero = new oNumero(total);
	aux = eval("document.getElementById('total').innerHTML='"+ numero.formato(2,true) +" €'");
	
	var numero=new oNumero(base_total);
	
	
	//Pongo el total para luego la comprobación del formulario
	aux = eval("document.getElementById('hid_total').value='"+ total +"'");
	
	
	return true;
 
 
 }
 
 function elimina_item(par){
 	
	aux= eval("document.getElementById('cantidad_"+par+"').disabled=true;");
	aux= eval("document.getElementById('td1_"+par+"').style.textDecoration='line-through';");
	aux= eval("document.getElementById('td2_"+par+"').style.textDecoration='line-through';");
	aux= eval("document.getElementById('td3_"+par+"').style.textDecoration='line-through';");
	aux= eval("document.getElementById('td4_"+par+"').style.textDecoration='line-through';");
	aux= eval("document.getElementById('td5_"+par+"').style.textDecoration='line-through';");
	aux= eval("document.getElementById('enlace_"+par+"').innerHTML='<a href=\"javascript:;\" onClick=\"return recupera_item("+par+");\">Recuperar</a>'");
	return saca_totales();
	
	return true;
 }
 
 function recupera_item(par){
 	aux= eval("document.getElementById('cantidad_"+par+"').disabled=false;");
	aux= eval("document.getElementById('td1_"+par+"').style.textDecoration='none';");
	aux= eval("document.getElementById('td2_"+par+"').style.textDecoration='none';");
	aux= eval("document.getElementById('td3_"+par+"').style.textDecoration='none';");
	aux= eval("document.getElementById('td4_"+par+"').style.textDecoration='none';");
	aux= eval("document.getElementById('td5_"+par+"').style.textDecoration='none';");
	aux= eval("document.getElementById('enlace_"+par+"').innerHTML='<a href=\"javascript:;\" onClick=\"return elimina_item("+par+");\">Eliminar</a>'");
	return saca_totales();
	return true;
 }
 
 function comprueba_form(){
				
		if (document.getElementById('hid_total').value==0 || document.getElementById('hid_total').value==''){
			alert('Debe añadir algún producto');
			return false;
		}
		
		//compruebo que no haya ninguna cantidad vacía, ni decimal
		for (j = 0; j < document.forms.form_compra.elements.length; j++){
				
			if ((document.forms.form_compra.elements[j].name.substring(0,9)=='cantidad_') && document.forms.form_compra.elements[j].disabled==false){
				aux = document.forms.form_compra.elements[j].name.substring(9);
				cantidad = eval("document.getElementById('cantidad_"+aux+"').value");
				if (cantidad == ''){
					
					aux2= eval("document.getElementById('cantidad_"+aux+"').focus()");
					aux2= eval("document.getElementById('cantidad_"+aux+"').select()");
					alert ('Introduzca la cantidad');
					return false;
				}
							
			}
					
		}
		
		alert(' Se va a generar un fichero.pdf con la orden de pedido completa, descuentos disponibles y portes incluidos.\n\n Envíenoslo por email y le confirmaremos su orden de pedido. Sólo entonces procesaremos su pedido.\n\n Si en 48 horas no ha recibido la confirmación, póngase en contacto con nosotros para indicárnoslo.');
		top.frames['hiddenFrame'].location='./vacia_carrito.php';
		return true;
	}
	
	function envia_form_contacto(){
		document.getElementById('form_contacto').submit();
		
	}
	
	function reset_form_contacto(){
		document.getElementById('form_contacto').reset();	
	}
	
	function envia_form_distribuidor(){
		document.getElementById('form_distribuidor').submit();
		
	}
	
	function reset_form_distribuidor(){
		document.getElementById('form_distribuidor').reset();	
	}
	
	function actualiza_url(path){
		var index;
		index = document.getElementById('tipo').options[document.getElementById('tipo').selectedIndex].value;
		switch(index){
			case "1":{
				document.getElementById('form1').action=path+'lotes-y-estuches/';
				break;
			}
			case "2":{
				document.getElementById('form1').action=path+'cestas/';
				break;
			}
			case "8":{
				document.getElementById('form1').action=path+'baules/';
				break;
			}
			case "9":{
				document.getElementById('form1').action=path+'jamoneros/';
				break;
			}
			case "10":{
				document.getElementById('form1').action=path+'regalos/';
				break;
			}
			case "11":{
				document.getElementById('form1').action=path+'vinos-y-cavas/';
				break;
			}
	
		}
		document.getElementById('form1').submit();
	
	}
	function focusAndPrint() {
parent.imprimir.focus()
parent.print()
}
