 //Funcion para bloquear la pantalla.

   var id_thread_animacion = null;
   var puntos_carga = 3;
   var div_cargando = null;
   var contador = 1;

   function bloquear_pantalla(){
       div_cargando = document.createElement('div');
       div_cargando.style.backgroundColor = 'red';
       div_cargando.style.color = 'white';
       div_cargando.style.position = 'absolute';
       var left = 0;
       var top  = document.body.scrollTop ;
       div_cargando.style.left = '0px';
       div_cargando.style.top  = top + 'px';
       div_cargando.style.fontSize = '20px';
       div_cargando.innerHTML = '<strong>Cargando...</strong>';
       div_cargando.id = 'div_cargando';
       document.getElementsByTagName('body')[0].appendChild(div_cargando);
       init_animacion_carga();
   }

   function desbloquear_pantalla(){
   	   var div_carga = document.getElementById('div_cargando');
       detener_animacion_carga();
       div_carga.parentNode.removeChild(div_carga);
   }

   function init_animacion_carga(){
       id_thread_animacion = setInterval(function(){
       	 var spuntos = '';
       	 if(puntos_carga == 0){
              spuntos = '&nbsp;&nbsp;&nbsp;';
              puntos_carga++;
       	 }else if(puntos_carga == 1){
         	spuntos = '.&nbsp;&nbsp;';
         	puntos_carga++;
         }else if(puntos_carga == 2){
         	spuntos = '..&nbsp;';
         	puntos_carga++;
         }else if(puntos_carga == 3){
         	spuntos='...';
         	puntos_carga= 0;
         }
         div_cargando.innerHTML = '<strong>Cargando' + spuntos + '</strong>';
       }, 500);
    }

    function detener_animacion_carga(){
      clearInterval(id_thread_animacion);
    }

   function viewPic(img){
    picfile = new Image();
    picfile.src =(img);
    fileCheck(img);
   }

function fileCheck(img){
	    if( (picfile.width!=0) && (picfile.height!=0) ){
	        makeWindow(img);
	    }else{
	        funzione="fileCheck('"+img+"')";
	        intervallo=setTimeout(funzione,50);
  	    }
}

function makeWindow(img){
    ht = picfile.height;
	wd = picfile.width;
    var popwin = null;
    var args= "height=" + ht + ",innerHeight=" + ht;
    args += ",width=" + wd + ",innerWidth=" + wd;
    if (window.screen){
        var avht = screen.availHeight;
        var avwd = screen.availWidth;
        var xcen = (avwd - wd) / 2;
        var ycen = (avht - ht) / 2;
        args += ",left=" + xcen + ",screenX=" + xcen;
        args += ",top=" + ycen + ",screenY=" + ycen + ",resizable=yes";
    }
    popwin=window.open("","_blank",args)
	popwin.document.open()
	popwin.document.write('<html><head><title>'+img+'</title></head><body bgcolor=white scroll=no topmargin=0 leftmargin=0 rightmargin=0 bottomargin=0 marginheight=0 marginwidth=0><div style="position: absolute; top:0px;left:0px"><a href="javascript:window.close()"><img src="'+img+'" width="'+wd+'" height="'+ht+'" border="0"></a></div></body></html>')
	popwin.document.close()
}

function addEvent(elm, evType, fn, useCapture){
		if(elm.addEventListener){
			elm.addEventListener(evType, fn, useCapture);
			return true;
		}else if(elm.attachEvent){
			var r = elm.attachEvent('on' + evType, fn);
		}else{
			elm['on' + evType] = fn;
		}
}

function $(ids){
   	 if(typeof ids == 'string'){
   	 	return document.getElementById(ids);
   	 }else if(ids.length){
   	 	var objetos = new Array();
   	 	for(var i=0; i < ids.length; i++){
   	 		objetos.push(document.getElementById(ids[i]));
   	 	}
   	 	return objetos;
   	 }
   	 return null;
}

function getTags(tags){
	try {
	  return document.getElementsByTagName(tags);
	}catch(exception){
	   alert(exception);
	   alert(arguments.callee.toString().split('(')[0]);
	   return null;
	}
}

function getDataServer(url, vars){
	  	var xml = null;
	  	try{
	  		 xml = new ActiveXObject('Microsoft.XMLHTTP');
	  	}catch(exception){
	  		xml = new XMLHttpRequest();
	  	}

	  	xml.open('GET',url + '?param=1&' + vars, false);
	  	xml.send(null);
	  	if(xml.status == 404) alert('Url no valida');
	  	return xml.responseText;
}

function postDataServer(url, vars){
  	var xml = null;
  	try {
  		xml = new ActiveXObject('Microsoft.XMLHTTP');
  	}catch(exception){
  		xml = new XMLHttpRequest();
  	}
  	xml.open('POST',url,false);
  	xml.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
  	xml.send (vars);
  	if(xml.status == 404) alert('Url no valida');
  	return xml.responseText;
}

var con_contenido = false;

function view_cargar_producto(id_productos,id_vista,precio){
   	 try{
   	   
   	   var id_contenido = 'contenido_' + id_vista;
   	   var url = self;
   	   var params = 'act=get_prod_con_contenido&id_productos=' + id_productos + '&id_vista=' + id_vista;
   	   var response = getDataServer(url, params);
   	   //obtengo el contenido
   	   var contenido = $( id_contenido );
   	   //pongo el nuevo contenido

   	   contenido.innerHTML = response;

   	   //recorro el modelo y actualizo el id_current_producto
   	   for(var i in modelo){
   	   	 if(modelo[i].id_vista == id_vista){
   	   	 	 modelo[i].id_current_producto = id_productos;
   	   	 	 modelo[i].precio = precio;
   	   	 	 break;
   	   	 }
   	   }
   	   set_up_listener_cantidades();	 
       calcular_total();
   	 }catch(exception){
   	 	alert(exception);
   	 	alert(arguments.callee.toString().split('{')[0]);
   	 }
}

function view_descargar_producto(id_vista){
   	try {
   	
   	  if(total_oferta){	 	
   	     alert('No puede realizar modificaciones en el cotizador por tratarse de una oferta !!!');
   	     return;
   	  }
   		
      //se muestra sin contenido el cuadro
      var contenido = $('contenido_' + id_vista);
      //obtengo el tipo de producto asociado a la vista
      var id_tproductos = 0;
      for(var i in modelo){
      	  if(modelo[i].id_vista == id_vista){
      	  	 id_tproductos = modelo[i].id_tproductos;
      	  	 modelo[i].id_current_producto = 0;
      	  	 break;
      	  }
      }
      var url = self;
  	  var params = 'act=get_prod_sin_contenido&id_tproductos=' + id_tproductos + '&id_vista=' + id_vista;
  	  var response = getDataServer(url, params);
  	  contenido.innerHTML = response;
  	  calcular_total();
   	}catch(exception){
   		alert(exception);
   		alert('Error on : view_descargar_producto');
   	}
}

function cambiar(){
      var contenido = $('contenido_1');
      var url = self;
      if(! con_contenido){
          view_cargar_producto(36, 5);
          con_contenido = ! con_contenido;
      }else{
      	  //se muestra sin contenido el cuadro
      	  view_descargar_producto(5);
      	  con_contenido = ! con_contenido;
      }
}

function descargar_producto(id_vista){
   	  view_descargar_producto(id_vista);
}

function seleccionar_producto(id_vista){
	   if(total_oferta){
	   	  alert('No puede seleccionarse el tipo de producto por tratarse de una oferta !!!!');
	   	  return;
	   }
   	   // Recorro la lista del modelo para obtener los productos que se encuentran seleccionados
   	   var url = 'new_cotizador_pop.php?id_vista=' + id_vista ;
   	   var productos_seleccionados = '';
   	   var id_tproductos = 0;
   	   for(var i in modelo){
   	   	  if(modelo[i].id_current_producto){
   	   	  	  productos_seleccionados += '&p_seleccionados[]=' + modelo[i].id_current_producto ;
   	   	  }
   	   	  if(modelo[i].id_vista == id_vista){
   	   	  	  id_tproductos = modelo[i].id_tproductos ;
   	   	  }
   	   }
   	   url += productos_seleccionados + '&idtp=' + id_tproductos + '&id_marcas=' + id_marcas_procesadores ;
   	   open_popup(url,700,560);
}

function number_format( number, decimals, dec_point, thousands_sep ){
    number = Math.round( number * Math.pow(10, decimals) ) / Math.pow(10, decimals);

    var str_number = number + '';
    var arr_int = str_number.split(".");
    var str_int = '';
    var str_decimals = '';
    var str_ext = '';

    if ( !arr_int[0] ) arr_int[0] = '0';
    if ( !arr_int[1] ) arr_int[1] = '';

    if ( arr_int[1].length < decimals )
    {
        str_decimals = arr_int[1];

        for ( var i = arr_int[1].length + 1; i <= decimals; i++ )
        {
            str_decimals += '0';
        }

        arr_int[1] = str_decimals;
    }

    if ( thousands_sep != '' && arr_int[0].length > 3 )
    {
        str_int = arr_int[0];
        arr_int[0] = '';

        for ( var j = 3; j < str_int.length; j += 3 )
        {
            str_ext = str_int.slice( str_int.length - j, str_int.length - j + 3 );
            arr_int[0] = thousands_sep + str_ext +  arr_int[0] + '';
        }

        str_first = str_int.substr( 0, ( str_int.length % 3 == 0 ) ? 3 : ( str_int.length % 3 ) );
        arr_int[0] = str_first + arr_int[0];
    }

    return arr_int[0] + dec_point + arr_int[1];
}

var ID_THREAD_CALCULAR_TOTAL = null;
var CALCULAR_TOTAL_DELAY     = 400;

function onkeypress_calcular_total(){
    if( ID_THREAD_CALCULAR_TOTAL != null ){
	clearTimeout(ID_THREAD_CALCULAR_TOTAL);
    }

    ID_THREAD_CALCULAR_TOTAL = setTimeout("calcular_total()", CALCULAR_TOTAL_DELAY );
}

function calcular_total(){
  try{	
    var total = 0 ;
    var cantidad = 0;
    var id_vista = 0;
    var input_cantidad =  0;
    var precio_total_item = 0;
    if(! total_oferta){   
       //recorro el modelo para obtener los precios.
       for(var i in modelo){
       	  id_vista = parseInt(i) + 1;
       	  if(modelo[i].id_current_producto){
       	  	  // Obtengo la cantidad del producto.
       	  	  input_cantidad = $('cantidad_' + id_vista);
       	  	  cantidad = input_cantidad.value;
       	  	  if(cantidad == '')
       	  	      cantidad = 1;
       	  	  if(isNaN(cantidad)) {
		      //alert('Las cantidades deben ser valores numericos!!!');
                      
		      //input_cantidad.focus();
		      //input_cantidad.select();
		      
		      //return;
		      
		      cantidad =1;
		      input_cantidad.value = 1;
       	  	  }
       	  	  cantidad = parseInt(cantidad);
       	  	  total += modelo[i].precio * cantidad;
       	  	  // Actualizo el total del producto en si.
       	  	  precio_total_item = number_format(modelo[i].precio * cantidad,2,'.',',');
       	  	  $('precio_' + id_vista).innerHTML = precio_total_item + ' &euro;';
       	  }
       }
       
       if(esta_armada)
           total += 20 ;
       
        total = number_format( total, 2, '.', ',' );
    }else {
    	total = total_oferta;
    }
    if($('total')){
        $('total').innerHTML =   total + ' &euro; ';
    }
  }catch(exception){
  	  alert(exception);
  	  alert(arguments.callee.toString().split('{')[0]);
  }
}



// Se agregan los productos seleccionados por el cotizador al carrito.
function agregar_al_carrito(){
   
 try {  
   
   var vars =  'act=agregar_cotiz_carrito';
   var hay_productos_cargados = false;
   var id_vista = 0;
   var input_cantidad = 0;
   var cantidad = 0;
   
   for(var  i in modelo){
   	  //Obtengo el id de la vista.
   	  id_vista = parseInt(i) + 1;
   	     
      if(modelo[i].id_current_producto){
      	 input_cantidad =$('cantidad_' + id_vista);
      	 cantidad = input_cantidad.value;
      	 if(cantidad == '' ) // Si el usuario no selecciona ninguna cantidad por defecto es 1.
      	     cantidad = 1;
      	     
      	 if(isNaN(cantidad) || cantidad <= 0 || cantidad == ''){
      	 	alert('Las cantidades deben ser valores numericos!!!');
      	 	return;
      	 }
      	 // Convierto la cantidad en un valor entero.
      	 cantidad = parseInt(cantidad);
         //agrego todos los datos de la seleccion de productos.
         vars += '&id_productos[]='  + modelo[i].id_current_producto +
                '&id_tproductos[]=' + modelo[i].id_tproductos + '&cantidades[]=' + cantidad;
                hay_productos_cargados = true;
      }
   }
//   return;
   if(! hay_productos_cargados){
      alert('Debe seleccionar por lo menos un producto!!');
   }else{
   	  if(esta_armada)
   	      vars += '&armada=y';
   	      
   	  if(total_oferta)
   	  	vars += '&total_oferta=' + total_oferta;
   	  	
      var response = postDataServer(self,vars);
//      alert(response);
      if(response != 'save_ok'){
          alert('Error: no se pudo guardar la configuracion!!!');
      }else{
//         alert('El cotizador fue enviado correctamente al carrito!!!');
         location.href ='carrito.php';
      }
   }
 }catch(exception){
 	 alert(exception);
 	 //imprimo el nombre de la funcion.
     alert(arguments.callee.toString().split('{')[0]);
 }
}

var esta_armada = false;
function calcular_armado(armado){
	if(armado){
		// Agrego 20 euros que corresponden al armado de la pc.
		esta_armada = true;
	}else{
		if(esta_armada){
			// Se calcula el total sin agregados.
			esta_armada = false ;
		}
	}
	calcular_total();
}


function set_up_listener_cantidades(){
   try {
     var inputs = getTags('input');
     for(var i= 0; i < inputs.length; i++){
     	 if(inputs[i].id && inputs[i].id.indexOf('cantidad_') != -1 ){
     	 	 // Cuando cambia el foco entonces se calcula nuevamente el total. 
     	 	 addEvent(inputs[i],'blur', function(){calcular_total()}, false);
     	 }
     }
   }catch(exception){
      alert(exception);
      alert(arguments.callee.toString().split('(')[0]);
   }
}

//   document.body.innerHTML += '<a href="javaScript: cambiar()">[cambiar]</a>';
//   addEvent(window,'load',view_cargar_producto,false);