var tries = 0;
var int_id;
var isPopEnews=0;
var addth=0;
function popup(url,alto,ancho,vscroll,allowresize){ // POP UP (General)
	topV=(screen.availHeight/2) - alto/2;
	leftV=(screen.availWidth/2) - ancho/2;
	win="fullscreen=0,directories=0,resizable="+allowresize+",location=0,status=0,scrollbars="+vscroll+",toolbar=0,menubar=0,width="+ancho+",height="+alto+",screenX="+topV+",screenY="+leftV+",top="+topV+",left="+leftV
	variable=window.ven
	if(variable) window.ven.close();
	ven=window.open(url,'ven',win);
	window.ven.focus();
}
function detectaNavegador() { // Detecta el navegador
	var browser = navigator.appName;
	if (browser == "Microsoft Internet Explorer"){
		var ieVer=/*@cc_on function(){ switch(@_jscript_version){ case 1.0:return 3; case 3.0:return 4; case 5.0:return 5; case 5.1:return 5; case 5.5:return 5.5; case 5.6:return 6; case 5.7:return 7; }}()||@*/0;
		navegador="ie"+ieVer;
	}else if(browser == "Opera"){
		navegador="opera";
	}else{
		navegador="standard";
	}
	return navegador;
}
function chngAtt(ID,att,val){ // CHANGE ATTRIBUTE (General)
	if(document.getElementById(ID))	eval("document.getElementById('"+ID+"').style."+att+"='"+val+"';");
}
function chngDisplay(ID){ // CHANGE DISPLAY (General)
	if(document.getElementById(ID)){
		if(document.getElementById(ID).style.display=='none')	{showDiv(ID);}
		else													{hideDiv(ID);}
	}
}
function showDiv(ID){
	if(document.getElementById(ID))document.getElementById(ID).style.display="block";
}
function hideDiv(ID) {
	if(document.getElementById(ID)) document.getElementById(ID).style.display="none";
}
function addSearchIE() { // MOTOR DE BUSQUEDA IE 7 (General)
	window.external.AddSearchProvider("http://www.acuista.com/frontend/home/live-search.xml");
}
function addSearchFirefox() { // MOTOR DE BUSQUEDA Firefox 1*-1.5 (General)
  if((typeof window.sidebar=="object")&&(typeof window.sidebar.addSearchEngine=="function"))
    window.sidebar.addSearchEngine("http://www.acuista.com/frontend/home/acuista.src","http://www.acuista.com/frontend/home/acuista.jpg","Acuista.com. Tienda de informatica online","");
  else
  	alert("Error al añadir el buscador");
}
function chngPic(picName,imgName){ // CHANGE PICTURE (Product Detail)
	if(document.images) document.getElementById('pic2change').innerHTML = '<img src="'+imgName+'" alt="'+picName+'" title="'+picName+'" />';
}
var fue = null;
function checkURL(obj, url, name) { // Comprobar si es una pagina de informacion (General)
	if ( obj.href == url+'?section='+name ) obj.href = 'javascript:void(0)';
}
function goTo(url, name, divname, params) { // Ir a pagina de informacion (General)
	divname = divname || 'col_center2'; if( params == undefined ) params = ''; else params = '&'+params || '';
	ajaxSubmit(url+'a/'+name+params, divname, 'loading_disp'); //window.scrollTo(0,0);
}
function getAndChange(idGet,idChange,attGet,attChange,capaPadre){ // Visualizacion del menu (General)
	if(!document.getElementById(idGet)) return true;
	valor=eval("document.getElementById('"+idGet+"').offset"+attGet+";");
	/*if(capaPadre=="col_left" && attGet=="Top") valor=valor-1;*/
	if(capaPadre=="col_left" && attGet=="Top") valor += document.getElementById('col_left').offsetTop-1;// - (130*muycomputer);
	chngAtt(idChange,attChange,valor+'px');
}
function quitarB(t) { // Sugerencias de busqueda NICE (General)
	var patron = /(<b>)([^<]+)(<\/b>)/g;
	return t.replace(patron,'$2');
}
function isNull(val){return(val==null);} // Helper (General)
function boxMiLista(e,id,page){ // Anadir a Mi Lista (General)
	var clickX = 0;	var clickY = 0;	var obj = document.getElementById(id); var borde = false;
	var popup = document.getElementById('popupMilista');
	if (document.layers) {		// netscape
		xMousePos = e.pageX; yMousePos = e.pageY;
		clickX = xMousePos-100; clickY = yMousePos-80;
		popup.style.left=clickX+'px'; popup.style.top=clickY+'px'; popup.style.display="block";
		setTimeout("document.getElementById('popupMilista').style.display='none';",3000);
	} else if (document.all) { var ieVer=alert('Este producto ha sido agregado a Mi Lista.'); // IE
	} else if (document.getElementById) {	// mozilla
		xMousePos = e.pageX; yMousePos = e.pageY;
		clickX = xMousePos-100; clickY = yMousePos-80;
		popup.style.left=clickX+'px'; popup.style.top=clickY+'px';	popup.style.display="block";
		setTimeout("document.getElementById('popupMilista').style.display='none';",3000);
	}
}
var idCat;
function ajaxLinks() {
	if( document.getElementById && document.getElementsByTagName ) {
		var links = document.getElementsByTagName('a');
		for( var i=0; i < links.length; i++ ){
			if( links[i].className.indexOf('alink')!='-1' ) {
				links[i].onclick = function(){goTo(url, this.name);};
				//eval("links["+i+"].onmouseover = function(){"+links[i].href+" = 'javascript:void(0)';};");
				links[i].onmouseover = function(){this.href = 'javascript:void(0)';};
			}
			else if( links[i].className.indexOf('menu')!='-1' ) {
				if(dispositive=='computer'){ // lee la variable javascript asignada en el head
					eval("links["+i+"].onmouseover = function(){contador=setTimeout(\"if(typeof chngAtt == 'function'){ getDivInfo('popupSubcats','"+links[i].id+"','head_subcategories&category="+links[i].id+"&query="+links[i].id+"'); chngAtt('popupSubcats','display','block'); actualizaPestanyaMenu('"+links[i].id+"','_sel');}\",300)}");
					eval("links["+i+"].onmouseout = function(){if(typeof contador!='undefined' && typeof chngAtt == 'function') clearTimeout(contador); contadorfade=setTimeout(\"chngAtt('popupSubcats','display','none'); actualizaPestanyaMenu('-1','_sel');\",300);}");
				}else{
					eval("links["+i+"].onclick = function(){if(idCat!=\""+links[i].id+"\"){if(typeof chngAtt == 'function'){ contador=setTimeout(\"getDivInfo('popupSubcats','"+links[i].id+"','head_subcategories&category="+links[i].id+"&query="+links[i].id+"'); chngAtt('popupSubcats','display','block'); idCat='"+links[i].id+"';\",0)}else{chngAtt('popupSubcats','display','none'); idCat='';}}}");
				}
			}
			else if( links[i].className.indexOf('buscador')!='-1' ) {
				links[i].onclick=function(){document.getElementById('selectBoxMain').innerHTML = this.innerHTML; document.searchform.url2search.value = this.href; document.getElementById('selectBuscador').style.display='none'; return false;};				
			}
		}
	}
}
function actualizaPestanyaMenu(id,nuevoEstilo){
	if( document.getElementById && document.getElementsByTagName ) {
		var links = document.getElementsByTagName('a');
		for( var i=0; i < links.length; i++ ){
			if( links[i].className.indexOf('menu')!='-1' && links[i].className.indexOf(nuevoEstilo)!='-1' && links[i].id!=id ) links[i].className = links[i].className.replace(nuevoEstilo,'');
			if( links[i].id==id && dispositive=='computer') document.getElementById(id).className = links[i].className+nuevoEstilo;
		}
	}
}
function linkTracker( url )
{
	if( ! document.getElementById || ! document.getElementsByTagName ) return false;
	var links = document.getElementsByTagName('a');
	for( var i=0; i < links.length; i++ ){
		if( links[i].className.indexOf('tracking')!='-1' ) {
			links[i].onclick = function(){var pid=this.className.split('_',1); ajaxSubmit(url+'&t='+tracking[pid], 'footer', 'loading_cats' );};
		}
	}
}
function capaTextoBotones(abre,capaOculta,boton,anchoCapa){	// Capa info popup botones en ficha de producto
	var obj = document.getElementById(capaOculta);
	var obj2 = document.getElementById(boton);
	if(abre=="si"){obj.style.display="block";}
	else{obj.style.display="none";}
	var top = parseInt(obj2.offsetTop) + parseInt(obj2.offsetHeight) + 2;
	obj.style.top = top+'px';
	obj.style.left = parseInt(obj2.offsetLeft)+'px';
	if(!parseInt(anchoCapa) || parseInt(anchoCapa)<=0){obj.style.width = parseInt(obj2.offsetWidth)+'px';}
	else{obj.style.width = anchoCapa+'px';}
}
function validaTerminosNewsletter(formulario,texto,error){ // Valida el formulario de suscripcion al newsletter
	if(formulario.email.value == "" || formulario.email.value == texto){
		alert(error);
		return false;
	}
	if(formulario.popup.value == "si"){
		var n = ( formulario.nombre ) ? formulario.nombre.value : '';
		var a = ( formulario.apellidos ) ? formulario.apellidos.value : '';
		var t = ( formulario.form ) ? formulario.form.value : '';
		popup(formulario.tienda.value+'&f=enews&Enviar=true&name='+n+'&apellidos='+a+'&email='+formulario.email.value+'&tipo='+t+'&allpage=1','520','590','1');
		if (isPopEnews && hidebox) hidebox();
		return false;
	}
}
function enviarFormulario(url, formid, divresp){
    var Formulario = document.getElementById(formid);
    var cadenaFormulario = "";
    var sepCampos;
    sepCampos = "";
    for (var i=0; i <= Formulario.elements.length-1;i++) {
        cadenaFormulario += sepCampos+Formulario.elements[i].name+'='+encodeURI(Formulario.elements[i].value);
        sepCampos="&"; }
    ajaxSubmit(url+cadenaFormulario,divresp,'loading_disp');
}
function divLinksLeft(){ // Define los links de los divs de col_left
	if( document.getElementById && document.getElementsByTagName ){
		if( document.getElementById( 'div_links_left' ) ){
			var d = document.getElementById( 'div_links_left' );
			var a = ['div','li'];
			var r = new RegExp("^http");
			for(var i=0; i<a.length; ++i){
				var e = d.getElementsByTagName(a[i]);
				for(var j=0; j<e.length; ++j){
					if(r.test(e[j].id)){
						e[j].onclick = function(){window.location=this.id; return false;};
						e[j].onmouseover = function(){this.style.color = '#C00'; return false;};
						e[j].onmouseout = function(){this.style.color = '#333'; return false;};
					}
				}
			}
		}
	}
}
function getDivInfo(id,clave,params,imagen)
{
	imagen = imagen || 'sin_imagen';
	clave  = clave || '';
	if( document.getElementById(id+'_'+clave+'_cache') && document.getElementById(id+'_'+clave+'_cache').innerHTML != '' )
		document.getElementById(id).innerHTML = document.getElementById(id+'_'+clave+'_cache').innerHTML;
	else {
		var newdiv = document.createElement('div'); newdiv.id = id+'_'+clave+'_cache'; newdiv.style.display = 'none'; document.body.appendChild(newdiv);
		ajaxSubmit(url_arbol+params,id+'_'+clave+'_cache',imagen);
}
}
var tree_loaded = false;
//#####################################################################################################
// FUNCTION PARA CAPAS FLOTANTES
var qTipTag = "a,div"; var qTipX = 0; var qTipY = 15;
tooltip = {
  name : "qTip",
  offsetX : qTipX,
  offsetY : qTipY,
  tip : null
}
tooltip.init = function () {
	var tipNameSpaceURI = "http://www.w3.org/1999/xhtml";
	if(!tipContainerID){ var tipContainerID = "qTip";}
	var tipContainer = document.getElementById(tipContainerID);
	if(!tipContainer) {
	  tipContainer = document.createElementNS ? document.createElementNS(tipNameSpaceURI, "div") : document.createElement("div");
		tipContainer.setAttribute("id", tipContainerID);
	  document.getElementsByTagName("body").item(0).appendChild(tipContainer);
	}
	if (!document.getElementById) return;
	this.tip = document.getElementById (this.name);
	if (this.tip) document.onmousemove = function (evt) {tooltip.move (evt)};
	var a, sTitle, elements;
	var elementList = qTipTag.split(",");
	for(var j = 0; j < elementList.length; j++)
	{
		elements = document.getElementsByTagName(elementList[j]);
		if(elements)
		{
			for (var i = 0; i < elements.length; i ++)
			{
				a = elements[i];
				if( a.className == 'qTip' ) {
				sTitle = a.getAttribute("title");
					if(sTitle)
					{
						a.setAttribute("tiptitle", sTitle);
						a.removeAttribute("title");
						a.removeAttribute("alt");
						a.onmouseover = function() {tooltip.show(this.getAttribute('tiptitle'))};
						a.onmouseout = function() {tooltip.hide()};
					}
				}
			}
		}
	}
}
tooltip.move = function (evt) {
	var x=0, y=0;
	if (document.all) {//IE
		x = (document.documentElement && document.documentElement.scrollLeft) ? document.documentElement.scrollLeft : document.body.scrollLeft;
		y = (document.documentElement && document.documentElement.scrollTop) ? document.documentElement.scrollTop : document.body.scrollTop;
		x += window.event.clientX;
		y += window.event.clientY;
	} else {//Good Browsers
		x = evt.pageX;
		y = evt.pageY;
	}
	porcentajeCapaCont = (document.getElementById('contenedor').offsetWidth*70)/100;
	this.tip.style.left = (x + this.offsetX) + "px";
	this.tip.style.top = (y + this.offsetY) + "px";

	if((x + this.offsetX)>porcentajeCapaCont) this.tip.style.left = (x + this.offsetX - 212) + "px";
}
tooltip.show = function (text) {
	if (!this.tip) return;
	this.tip.innerHTML = text;
	this.tip.style.display = "block";
}
tooltip.hide = function () {
	if (!this.tip) return;
	this.tip.innerHTML = "";
	this.tip.style.display = "none";
}
//#####################################################################################################
function vInt(obj) {
 aux = new String(obj.value); reg = new RegExp("[^0-9]"); obj.value = aux.replace(reg,'');
}
// Fix indexOf en internet explorer
function indexForm(item, list){
	var index = -1;
	if(Array.indexOf) index = list.indexOf(item);
	else{
		for(var j=0; j<list.length && index==-1; j++){
        	if( list[j]==item )	index =  j;
    	}
	}
	return index;
}
// Centrar Popin
function centraPopin(id,atributo){
	if(atributo=='top')		return ( ( TamVentana('height') / 2 ) - ( parseInt(document.getElementById(id).offsetHeight) / 2 ) ) + posScroll();
	else					return ( TamVentana('width') / 2 ) - ( parseInt(document.getElementById(id).offsetWidth) / 2 );
}
// Devuelve el tamanyo de la ventana del navegador
function TamVentana(dimension){
	var Tamanyo = [0, 0];
	if(typeof window.innerWidth != 'undefined'){
		Tamanyo = [window.innerWidth, window.innerHeight];
	}else if(typeof document.documentElement!='undefined' && typeof document.documentElement.clientWidth!='undefined' && document.documentElement.clientWidth != 0){
		Tamanyo = [document.documentElement.clientWidth, document.documentElement.clientHeight];
	}else{
		Tamanyo = [screen.availWidth, screen.availHeight];
	}
	if(dimension=='width')			{return Tamanyo[0];}
	else if(dimension=='height')	{return Tamanyo[1];}
	else							{return Tamanyo;}
}
// Devuelve la posicion Y del scroll de la pagina
function posScroll(){
	if(document.all)	return document.documentElement.scrollTop;
	else				return window.pageYOffset;
}
// Bloquea el scroll de la pagina
function lockScroll(lock){
	var top = posScroll();
	if(dispositive=='tablet' && lock)			{ document.ontouchmove=function(event){if(!event.elementIsEnabled){event.preventDefault(); window.focus();}}; }
	else if(dispositive=='tablet' && !lock)		{ document.ontouchmove=function(event){event.elementIsEnabled=true;}; }
	else if(dispositive=='computer' && lock)	{ document.documentElement.style.overflow='hidden'; }
	else if(dispositive=='computer' && !lock)	{ document.documentElement.style.overflow='scroll'; }
	if(dispositive!='movil')					document.documentElement.scrollTop=top;
}
function unlockScrollId(id){
	document.getElementById(id).ontouchmove=function(event){event.elementIsEnabled=true;};
}
/* CRITEO Widgets Loader Version 1.1e */
var CRITEO=function(){var G={I:[],M:function(){if(arguments.callee.bo){return;}arguments.callee.bo=true;for(var i=0;i<G.I.length;i++){G.I[i]();}},N:function(aR){this.I[this.I.length]=aR;if(document.addEventListener){document.addEventListener("DOMContentLoaded",G.M,null);}if(/KHTML|WebKit/i.test(navigator.userAgent)){var bi=setInterval(function(){if(/loaded|complete/.test(document.readyState)){clearInterval(bi);delete bi;G.M();}},10);}/*@cc_on@if(@_win32||@bz)var bV="src='javascript:void(0)'";if(location.protocol=="https:")bV="src=//:";document.write("<scr"+"ipt id=__cto_ie_onload defer "+bV+"><\/scr"+"ipt>");var s=document.getElementById("__cto_ie_onload");s.onreadystatechange=function(){if(this.readyState=="complete"){G.M();}};@end@*/;if(typeof window.onload!='function'){window.onload=G.M;}else{var aI=window.onload;window.onload=function(){G.M();if(aI){aI();}};}}};function ab(s){if(document.getElementsByTagName){var F=document.getElementsByTagName('head')[0];if(!F){F=document.createElement('HEAD');document.documentElement.appendChild(F);}if(F&&F.appendChild){F.appendChild(s);}}};function aj(){if(typeof(window.encodeURIComponent)==='undefined'){var R={bk:function(K){K=""+K;var c,s,C="",i=0;while(i<K.length){c=K.charCodeAt(i++);if(c>=0xDC00&&c<0xE000){continue;}if(c>=0xD800&&c<0xDC00){if(i>=K.length){continue;}s=K.charCodeAt(i++);if(s<0xDC00||c>=0xDE00){continue;}c=((c-0xD800)<<10)+(s-0xDC00)+0x10000;}if(c<0x80){C+=String.fromCharCode(c);}else if(c<0x800){C+=String.fromCharCode(0xC0+(c>>6),0x80+(c&0x3F));}else if(c<0x10000){C+=String.fromCharCode(0xE0+(c>>12),0x80+(c>>6&0x3F),0x80+(c&0x3F));}else{C+=String.fromCharCode(0xF0+(c>>18),0x80+(c>>12&0x3F),0x80+(c>>6&0x3F),0x80+(c&0x3F));}}return C;},aU:"0123456789ABCDEF",ak:function(n){return R.aU.charAt(n>>4)+R.aU.charAt(n&0xF);},aV:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-"};window.encodeURIComponent=function(s){s=R.bk(s);var C="";for(var i=0;i<s.length;i++){if(R.aV.indexOf(s.charAt(i))== -1){C+="%"+R.ak(s.charCodeAt(i));}else{C+=s.charAt(i);}}return C;};}};function bD(){if(document.getElementsByTagName){var n=1;var t=[];var l=[];var V,L,T,bp,aQ,as,J;var a=document.getElementsByTagName('div');var an=false;for(var i=0;i<a.length;i++){if(a[i].id&&a[i].id.substring(0,3).toLowerCase()=="cto"&&a[i].childNodes){V=L=T=bp=as=J=null;aQ=2;for(var j=0;j<a[i].childNodes.length;j++){var c=a[i].childNodes[j];if(c&&c.tagName&&c.tagName.toLowerCase()=="div"&&c.className&&c.className.substring(0,3).toLowerCase()=="cto"){var O=(c.textContent?c.textContent:(c.innerText?c.innerText:null));switch(c.className.toLowerCase()){case 'ctowidgetserver':V=O;break;case 'ctodatatype':L=O;break;case 'ctowidgettype':T=O;break;case 'ctoparams':bp=O;break;case 'ctoversion':aQ=O;break;case 'ctodata':as=c.innerHTML;break;case 'ctokeyword':J=O;break;}}}if(V&&((!L&&T)||(L&& !T))){var u="v="+aQ;if(bp){u+="&"+bp;}u="p"+n+"="+encodeURIComponent(u);if(as){u+="&d"+n+"="+encodeURIComponent(as);}if(T){u+="&w"+n+"="+T;}else{u+="&t"+n+"="+L;}if(J){u+="&kw="+encodeURIComponent(J);}if(an==false){try{u+='&ref='+encodeURIComponent(document.referrer);}catch(e){}try{u+='&sc_r='+encodeURIComponent(screen.width+'x'+screen.height);}catch(e){}try{u+='&sc_d='+encodeURIComponent(screen.colorDepth);}catch(e){}an=true;}var s;for(s=0;s<t.length;s++){if(t[s]==V){break;}}if(s!=t.length&&l[s]&&(l[s].length+u.length)>2000){CRITEO.au(l[s]);l[s]=null;}if(s==t.length|| !l[s]){t[s]=V;l[s]=V+"display.js?";}else{l[s]+="&";}l[s]+=u;n++;}}}for(var H=0;H<l.length;H++){if(l[H]){CRITEO.au(l[H]);}}}};function ad(){aj();bD();};return{N:function(){if(typeof(CRITEO_Loaded)!="undefined"){return;}CRITEO_Loaded=1;G.N(function(){ad();});},bG:function(def){if(document.createElement){var s=document.createElement('style');if(s){s.setAttribute('type','text/css');ab(s);if(s.styleSheet){try{s.styleSheet.cssText=def;}catch(e){}}else{var c=document.createTextNode(def);s.appendChild(c);}}}},au:function(u){if(document.createElement){var s=document.createElement('script');if(s){s.type='text/javascript';s.src=u.substring(0,2000);ab(s);}}},aG:function(a,u){if(document.createElement){var bj=document.createElement('IMG');if(bj){if(a){var d=document.getElementById(a);if(d===null){d=document.createElement('DIV');d.id=a;d.style.display="none";document.body.appendChild(d);}if(d!==null&&d.appendChild){d.appendChild(bj);}}bj.src=u;}}},ac:function(m){var g="";for(var i=0;i<m;i++){g+=Math.floor(Math.random()*0xF).toString(0xF);}return g+"";}};}();var CRITEO_Loaded;CRITEO.N();

// Funciones duplicadas en la home.js y el cart.js (no son exactamente iguales) @TODO unificar
function gotoGoogleRuta(ruta, idMailBox,message){
	var dir = document.getElementById('Facturacion Direccion').value;
	var cp = document.getElementById('MBE_cp').value;
	var pobl = document.getElementById('Facturacion Poblacion').value;
	var pais = document.getElementById('Facturacion Pais');
	var prov = document.getElementById('Facturacion ProvinciaS');

	if(dir == "" || dir == null || pobl == "" || pobl == null || pobl == "" ){ alert(message); }
	else{
		dir = dir +", "+pobl;
		if (prov.selectedIndex != undefined) dir += ", "+ prov.options[prov.selectedIndex].value;
		if (cp != null) dir += ", "+ cp;
		if (pais.selectedIndex != undefined) dir +=", "+ pais.options[pais.selectedIndex].value; 
		
		var left = (screen.width-630)/2;
    	var top  = (screen.height-502)/2;
		window.open(ruta+'&id='+idMailBox+'&cp='+escape(cp)+'&from='+escape(dir), 'windowname1', 'width=630, height=502, top='+top+', left='+left+', scrollbars=yes');
	}
}
function goToMbe(url,name,divname)
{	
	template	= url;
	div 		= divname;
	cargado		= false;
	imgt		= 1;
	met			= 'GET';
	params		= null;
	var req		= null;
	
	// Obtener la instancia del objeto XMLHttpRequest
 	if(window.XMLHttpRequest) {
    	req = new XMLHttpRequest();
  	}
  	else if(window.ActiveXObject) {
	    req = new ActiveXObject("Microsoft.XMLHTTP");
  	}

	req.onreadystatechange=function(){if(req.readyState == 4) {
      	if(req.status == 200) {
        	document.getElementById(div).innerHTML=req.responseText;
      		}
    	}
	}
	
	req.open( met, template, true );
	req.setRequestHeader( "Content-Type","application/x-www-form-urlencoded" );
	
	req.send( params);
	
	submt=false;

}
function cantidad(target,direccion)
{
	var cantidad = document.getElementById(target).value;
	if(cantidad =="") cantidad = 0;
	if(direccion == "MENOS" && cantidad!="0")	cantidad--;
	else if(direccion == "MAS")	cantidad++;
	document.getElementById(target).value = cantidad;
}
function wordcount(string){
	var r = 0;
	string=string.replace(/\s+/g,' ');
	string=string.split(' ');
	for (var z=0; z<string.length; z++) {if (string[z].length > 0) r++;}
	return r;
}
function DetectaEnter(e,form)
{
	var key;
	if(window.event || !e.which){ // IE
		key = e.keyCode;
	}else if(e){ // netscape
		key = e.which;
	}
	if(key==13){ //Enter
		form.submit();
	}
}
var submt=false;
var cargado=false;
var newslet_tmp = '';
function ajaxDisplay (req, div, callback) {
	if (req.readyState == 4) {
		if (req.status == 200) {
			if (callback && typeof(callback) === "function") return callback( req.responseText );
			
			if ( div == 'mailformstat' ) { eval(req.responseText); return; }

			if ( div == 'capctha_response') { checkCaptchaResponse( req.responseText ); return; }
			// PROMOCION_IPLUS_START
			if ( div == 'iplus_response') { checkIPlusResponse( req.responseText ); return; }
			// PROMOCION_IPLUS_END

			if (document.getElementById(div)) {
				document.getElementById(div).innerHTML = req.responseText;
				cargado = true;
				if ( div == 'category_tree') {
					if ( fue != null ) document.getElementById('subcat').innerHTML = document.getElementById(fue).innerHTML;
				}
				if ( div.indexOf('cache') != -1 ) { // Cache de divs
					var div = div.replace(div.substring(div.indexOf('_')),'');
					if( document.getElementById(div) ) document.getElementById(div).innerHTML = req.responseText;
			}
		}
		}
		else{ // Error message
			if (callback && typeof(callback) === "function") return callback( req.statusText );
			
			document.getElementById(div).innerHTML = "Lo sentimos, ha ocurrido un error.<br>" + req.status + " " + req.statusText;
		}
	}
}

function ajaxSubmit (template, div, imgt, met, params, callback) {
	cargado=false;
	imgt = imgt || 1;
	met = met || 'GET';
	params = params || null;
	var req = null;

	if ( imgt == 1){
		if (document.getElementById(div))
			document.getElementById(div).innerHTML = '<div align="center" style="padding:5px;"><img src="'+image_base+'ajax-loader.gif" title="Consultando..." alt="Consultando..."></div>';
	}
	else if( imgt.indexOf('sin_imagen') != -1  ) {

	}
	else {
		if( imgt.substr(0,4) == 'sel_' ) document.getElementById(div).innerHTML = '<select class="'+imgt+'"><option value="">---- Consultando ----</option></select>';
		else document.getElementById(div).innerHTML = '<div align="center"><img src="'+image_base+imgt+'.gif" title="Consultando..." alt="Consultando..."></div>';
	}

	// Safari, Firefox, etc
	if (window.XMLHttpRequest) {
 		req = new XMLHttpRequest();
		if (req.overrideMimeType) {
			//req.overrideMimeType('text/xml');
			req.overrideMimeType('text/html');
		}
	}
	// Internet Explorer
	else if (window.ActiveXObject) {
		try { req = new ActiveXObject("Msxml2.XMLHTTP"); }
		catch (e) { try { req = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {} }
	}
	// When ready calls the function that displays the loaded code
	req.onreadystatechange = function() { ajaxDisplay(req, div, callback); }
	req.open (met, template, true);
	req.setRequestHeader ("Content-Type", "application/x-www-form-urlencoded");
	req.send (params);
	submt = false;
}

function ajaxClose (div) {
	document.getElementById(div).style.display = 'none';
}

//####### POST-IT #######
function deleteProducts(url)
{
	x = document.postitform.elements;
	aux = url+'&';
	if ( x.length != undefined ) {
		aux = aux + 'postit_prod=';
		for ( i=0; i<x.length; i++) {
			if( (x[i].type == 'checkbox' && x[i].checked)){
				aux = aux + x[i].value;
				if( (i+1) != (x.length) ){	aux = aux+'_'; }
			}
		}
	}
	document.location = aux;
}


//####### COMPARATIVE PAGE #######
function dropProduct(p,page) {
	if (document.similarcomparison.prod.length==2) {
		ok=confirm('Si elimina este producto regresar\u00e1 a la p\u00e1gina del producto'); if(!ok) return false;
	}
	var aux = page+'&';
	for (i=0;i<document.similarcomparison.prod.length;i++){
		if (p != i)aux = aux+'postit_prod['+i+']='+document.similarcomparison.prod[i].value+'&';
	}
	document.location = aux;
}

function ajaxSubmitT (template, div, timeout) {
	if(!submt){
		setTimeout('ajaxSubmit(\''+template+'\', \''+div+'\', 2)', timeout ); submt = true;	}
}



		function _loadScroll()
		{
			window.onscroll = '';
			if(typeof url!='undefined' && document.getElementById('promo_facebook'))
				goTo(url, 'tools/facebook', 'promo_facebook');
			
			//if(typeof url!='undefined' && document.getElementById('boton_ciao'))
			//	goTo(url, 'tools/ciao', 'boton_ciao');
			// Solo se carga el facebook de la ficha del producto cuando se ha terminado de cargar la pagina
			if(typeof url!='undefined' && document.getElementById('promo_facebookDetail'))
				goTo(url, 'tools/facebook', 'promo_facebookDetail','d=1');
		}
		function startPage() { // Inicializar JS
			if(typeof urlsegura!='undefined' && urlsegura) ajaxLinks(); // Links x Ajax
			addth=1;
			if(typeof vista_actual!='undefined' && vista_actual == 'search') { linkTracker(url_tracking); }
			if(typeof vista_actual!='undefined' && vista_actual == 'home' && url_actual.match('myaccount')) tooltip.init();
			loadChat(); // Chat iadvize
			window.onscroll = _loadScroll;
		}function FFSuggest() {
	
	var pRequest;
	var pLayer;
	var pDebug					= false;
	var pInstanceName			= '';
	var pSearchURL				= '';
	var pQueryParamName			= '';
	var pFormname 				= '';
	var pLayerName				= '';
	var pQueryInput;
	var pSuggest				= new Array();
	var pLastQuery;
	var pCurrentSelection		= 0;
	var submitted				= false;
	var pShowImages				= false;
	var	pSearchDelay			= 400; // timer for request-delay between keypresses in milliseconds
	var pTimer					= 0;

	var pSuggestImageClass 		= 'suggestImage';
	var pSuggestQueryClass 		= 'suggestTextQuery';
	var pSuggestTypeClass 		= 'suggestTextType';
	var pSuggestAmountClass     = 'suggestTextAmount';
	var pSuggestQueryTypedClass = 'suggestTextQueryTyped';
	var pSuggestFooterClass     = 'suggestFooter';
	var pSuggestHeaderClass     = 'suggestHeader';
	var pSuggestRowClass	    = 'suggestRow';
	var pSuggestHighlightClass  = 'suggestHighlight';

	this.init = function(searchURL, formname, queryParamName, divLayername, instanceName, debugMode, channelParamName, channel, showImages) {
		pSearchURL			= searchURL;
		pFormname			= formname;
		pQueryParamName		= queryParamName;
		pChannelParamName	= channelParamName;
		pChannel			= channel;
		pLayerName			= divLayername;
		pInstanceName		= instanceName;
 		pDebug				= debugMode;
 		pShowImages			= showImages;
		if (pSearchURL == '') {		
			if (pDebug) alert('no searchurl defined');
			return null;
		} else if (pInstanceName == '') {
			if (pDebug) alert('no instancename defined');
			return null;
		} else if (pFormname == '') {
			if (pDebug) alert('no formname defined');
			return null;
		} else if (pQueryParamName == '') {
			if (pDebug) alert('no queryparamname defined');
			return null;
		} else if (pLayerName == '') {
			if (pDebug) alert('need a layer for output');
		}
		pQueryInput = document[pFormname][pQueryParamName];
		pQueryInput.onkeyup	= handleKeyPress;
		pQueryInput.onfocus	= showLayer;
		pQueryInput.onblur	= hideLayer;
		document[pFormname].onsubmit = handleSubmit;
	}
	
	function handleSubmit() {
		submitted = true;
		if (pSuggest[pCurrentSelection] != undefined) {
			addInputToForm('userInput', document[pFormname][pQueryParamName].value);
			document[pFormname][pQueryParamName].value = pSuggest[pCurrentSelection].split('###')[0];
			addInputToForm('queryFromSuggest', 'true');
		}
		var destino = encodeURI(document.searchform.url2search.value.replace('busqueda',document.searchform.search.value));
		window.location = destino;
		return false;
	}
	
	this.handleClick = function() {
		if (pSuggest[pCurrentSelection] != undefined) {
		
			addInputToForm('<%=Params.CUSTOM_PARAM_NAME_SUGGEST_USER_INPUT %>', document[pFormname][pQueryParamName].value);
			document[pFormname][pQueryParamName].value = pSuggest[pCurrentSelection].split('###')[0];
			addInputToForm('queryFromSuggest', 'true');
			document[pFormname].submit();
		}
	}
	
	this.handleMouseOver = function(pos) {
		var tblCell = getTableCell(pos);
		unmarkAll();
		if (tblCell != null) {
			highlightSuggest(tblCell);
			pCurrentSelection = pos;
		}
	}
	
	this.handleMouseOut = function(pos) {
		var tblCell = getTableCell(pos);
		if (tblCell != null) {
			unmarkSuggest(tblCell);
			pCurrentSelection = -1
		}
	}
	
	function handleKeyPress(evt) {
		evt = (evt) ? evt : ((event) ? event : null);
		var keyCode = evt.keyCode;
		if (keyCode == 38) {
			moveSelection('up')
		} else if (keyCode == 27) {	
			hideLayer();
		} else if (keyCode == 40) {
			moveSelection('down');
		} else {
			if (pLastQuery != pQueryInput.value) {
				clearTimeout(pTimer);

				if (pQueryInput.value == '') {
					hideLayer();
					if (pLayer != null){ pLayer.innerHTML = ''; }
					pLastQuery = '';
					return null;
				}
	
				// start delay timer
				pTimer = setTimeout(startAjax, pSearchDelay);

				pLastQuery = pQueryInput.value;
			}
		}
	}
	
	function moveSelection(direction) {
		var pos = pCurrentSelection;
		if (direction == 'up'){	pos--; }
		else{ 					pos += 1; }
		
		if (pos < 0) {
			unmarkAll();
			pQueryInput.focus();
			pCurrentSelection	= -1;
		} else {
			var tblCell = getTableCell(pos);
			if (tblCell != null) {
				unmarkAll();
				highlightSuggest(tblCell);
				pCurrentSelection = pos;
			}
		}
		
		var query = pQueryInput.value;
		pQueryInput.value = '';
		pQueryInput.focus();
		pQueryInput.value = query; 
	}
	
	function startAjax() {
		var query = pQueryInput.value.replace( '/', ' ' ); //Eliminar / para evitar problemas
		if(query.length > 50 ){ return; }

		var requestURL = pSearchURL +'&'+ pQueryParamName +'='+ encodeURIComponent(query) +'&'+ pChannelParamName +'='+ pChannel;

		try {
			if( window.XMLHttpRequest ) {
				pRequest = new XMLHttpRequest();
			} else if( window.ActiveXObject ) {
				pRequest = new ActiveXObject( "Microsoft.XMLHTTP" );
			} else {
				if (pDebug) alert( 'no ajax connection' );
			}
			
			pLayer = document.getElementById(pLayerName);
			if (pLayer != null) {
				if (query != '') {

					pRequest.open( "GET", requestURL, true );
					pRequest.onreadystatechange = callbackAjax;
					pRequest.send( null );
				} else {
					hideLayer();
				}
			} else {
				if (pDebug) alert( 'no layer for output found' );
			}
		} catch( ex ) {
			hideLayer();
			if (ex == undefined) {
				if (pDebug) alert( 'Error: ' + ex.getmessage );
			} else {
				if (pDebug) alert( 'Error: ' + ex );
			}
		}
	}
	
	function hideLayer() {
		if (pLayer != null) {
			pLayer.style.display = 'none';
			fireSuggestLayerHidden();
		}
	}
	
	this.hideLayerOutsideCall = function() {
		if (pLayer != null) {
			pLayer.style.display = 'none';
			fireSuggestLayerHidden();
		}
	}
	
	function showLayer() {
		if (pLayer != null && pSuggest != null && pSuggest.length >= 1) {
			pLayer.style.display = 'block';
		}
	}
	
	function callbackAjax() {
		if (submitted == false) {
			if (pRequest.readyState == 4) {
				if (pRequest.status != 200) {
					hideLayer();
					if (pDebug) alert( 'Error (' + pRequest.status + '): ' + pRequest.statusText );
				} else {
					handleResponse(pRequest.responseText);
				}
			}
		}
  }

	// calls the callback for "outside" listeners if the callback is implemented
	function fireSuggestCompleted(suggestLayerIsVisible) {
		if (typeof(onSuggestCompleted) == 'function') {
			onSuggestCompleted(suggestLayerIsVisible);
		}
	}
	
	// calls the callback for "outside" listeners if the callback is implemented
	function fireSuggestLayerHidden() {
		if (typeof(onSuggestLayerHidden) == 'function') {
			onSuggestLayerHidden();
		}
	}

	function handleResponse(text) {
		var colSpan = 3;
		if(pShowImages){colSpan++;}
		
		pCurrentSelection = -1;
		pSuggest = new Array();
		pSuggest = text.split('\n');
		var outputText = '<table cellpadding="0" cellspacing="0" class="' + pLayerName + '" width="100%" border="0" onMouseDown="' + pInstanceName + '.handleClick();">';
		outputText += '<tr class="'+pSuggestHeaderClass+'" ><td nowrap="nowrap" colspan="'+colSpan+'">Sugerencias de b&uacute;squeda...</td></tr>';
		
		var pNewSuggest = new Array();
		for (var i = 0; i < pSuggest.length; i++) {
			var firstChar = pSuggest[i].charCodeAt(0);
			
			if (firstChar != 13 && firstChar != 10 && pSuggest[i].length >= 1) {
				pNewSuggest.push(pSuggest[i]);
			}
		}
		pSuggest = pNewSuggest;
		var query = pQueryInput.value;
		
		for (var i = 0; i < pSuggest.length; i++) {
			pSuggestParts = new Array();
			pSuggestParts = pSuggest[i].split("###");
			
			outputText += '<tr id="' + pLayerName + '_' + i + '" class="'+pSuggestRowClass+'" onMouseOver="' + pInstanceName + '.handleMouseOver(' + i + ');" onMouseOut="' + pInstanceName + '.handleMouseOut(' + i + ');">';
			if(pShowImages){
				outputText +=	'<td nowrap="nowrap" class="'+ pSuggestImageClass +'"><img src="' + pSuggestParts[3] + '" alt=""/></td>';
			}
			outputText +=		'<td class="'+ pSuggestQueryClass +'">' + pSuggestParts[0].replace(new RegExp("("+query+")","ig"),'<span class="'+pSuggestQueryTypedClass+'">$1</span>') + '</td>'
								+'<td nowrap="nowrap" class="'+ pSuggestTypeClass +'">' + pSuggestParts[2] + '</td>'
								+'<td nowrap="nowrap" class="'+ pSuggestAmountClass +'">' + pSuggestParts[1] + '</td>'
						+'</tr>';
		}
		outputText += '<tr><td class="'+pSuggestFooterClass+'" colspan="'+colSpan+'">&nbsp;</td></tr></table>';
		if (pSuggest.length >= 1) {
			showLayer();
			pLayer.innerHTML = outputText;

			// calback for "outside" listeners
			fireSuggestCompleted(true);
		} else {
			hideLayer();
			pLayer.innerHTML = '';
			
			// calback for "outside" listeners
			fireSuggestCompleted(false);
		}
		
	}
	
	function highlightSuggest(tblCell) {
		tblCell.className = pSuggestHighlightClass; 
	}
	
	function unmarkSuggest(tblCell) {
		tblCell.className = pSuggestRowClass; 
	}
	
	function unmarkAll() {
		var tblCell;
		for (var i = 0; i < pSuggest.length; i++) {
			tblCell = getTableCell(i);
			if (tblCell != null) {
				unmarkSuggest(tblCell);
			}
		}
	}
	
	function getTableCell(pos) {
		var tblCell;
		tblCell = document.getElementById(pLayerName + '_' + pos);
		return tblCell;
	}
	
	function addInputToForm(name, value) {
		var element = document.createElement('input');
		element.name = name;
		element.type = 'hidden';
		element.value = value;
		document[pFormname].appendChild(element);
	}
}

	function addLoadEvent(func) { // Ejecutar funcion al cargar la pagina (General)
		var oldonload = window.onload;
		if(typeof window.onload != 'function'){ window.onload = func;}
		else { window.onload = function(){ if(oldonload){ oldonload(); } func();} }
	}
	
	addLoadEvent(startPage);
