var NavegadorUnidades = new Object();
NavegadorUnidades.numPaginas=7;
NavegadorUnidades.anchoCelda=18;

var NavegadorDecenas = new Object();
NavegadorDecenas.numPaginas=6;
NavegadorDecenas.anchoCelda=21;

var NavegadorCentenas = new Object();
NavegadorCentenas.numPaginas=4;
NavegadorCentenas.anchoCelda=31;

function crearBuscador(xmlDocInput, pais, idioma, checksumFicha){
	if (this.obj == null) {
		this.obj = 'BuscadorObj';
		eval(this.obj+"=this");
		this.idioma = idioma;
		this.pais = pais;
		
		this.reinit = b_reinit;
	
		this.makeList = b_makeList;
		this.setMenus = b_setMenus;
		this.add = b_addProducto;
		this.print = b_print;
		this.printNext = b_printNext;
		this.printPrevious = b_printPrevious;
		this.checklinks = b_checklinks;
		this.printPage = b_printPage;
		this.changeTamano = b_changeTamano;
		//Variables para anadir y restar filas
		this.addRow = b_addRow;
		this.removeRow = b_removeRow;
		this.setRows = b_setRows;
		this.checkRowlinks = b_checkRowlinks;
		//Variables del paginador
		this.printpaginador = b_printpaginador;
		this.preloadImages =  b_preloadImages;
		this.clearPreloadedPages = b_clearPreloadedPages;
		this.pagesPreLoaded = new Array();    // Guarda las páginas que ya han sido precargadas.
		this.num_rows = -1;
		this.rewrite =  b_rewrite;
		this.getState = b_getState;
		this.setState = b_setState;
		this.getItemSelected = b_getItemSelected;
		this.selectImage = b_selectImage;
		
		this.slideShow = b_slideShow;
		this.keepSlideShow = b_keepSlideShow;
		
		// Funcion para filtrar la lista de los productos segun los menus
		this.filtrar = b_filtrar;
		// Valores de los filtros:
		this.valorAllInt = '-1'; 		// 'todos' para los menus con valores numericos
		this.valorAllString = 'ALL'; 	// 'todos' para los menus con valores string
		this.filters = new Array();
		this.tamano = null;
		this.patillas = new Array();
	}
	this.reinit(xmlDocInput, checksumFicha);
	this.rewrite();
	//alert('Elementos '+this.productListlength);
	return BuscadorObj;	
}

function b_parseBool(value) {
	if (value == 'true') return true;
	return false;
}

function b_reinit(xmlDocInput, checksumFicha){

	// Guardamos el valor del checksum para las fichas, para a?adirlo en la llamada de la funcion submitProducto, que solicita
	// las fichas de productos a?adiendo el valor de este checksum en la URL, para controlar asi el akamizado de las fichas.
	this.checksumFicha = checksumFicha;

	//Lista creada a partir de los datos del xmlDoc donde tenemos toda la informacion necesaria
	var tipoBuscador = xmlDocInput.getAttribute("tipo");
	this.tipo = tipoBuscador;
	if (tipoBuscador == 'coleccion')
		this.xmlDoclist = xmlDocInput.getElementsByTagName('productos')[0].getElementsByTagName('p');
	else	
		this.xmlDoclist = xmlDocInput.getElementsByTagName('conjuntos')[0].getElementsByTagName('conjunto');
	
	idPati = xmlDocInput.getAttribute("patilla");
	if (this.patillas[idPati] == null) {
		this.patillas[idPati] = new Object();
		this.patillas[idPati].tamanos = new Array();
	}	
	
	this.xmlMenuList = xmlDocInput.getElementsByTagName('menus')[0].getElementsByTagName('menu');
	this.xmlConfig = xmlDocInput.getElementsByTagName('config')[0];
	xmlTamanos = xmlDocInput.getElementsByTagName('tamanos')[0].getElementsByTagName('tamano');
	this.tamanos = new Array();
	for (i=0; i<xmlTamanos.length; i=i+1) {
		var tamanoXml = xmlTamanos[i];
		this.tamanos[i] = new Object();
		this.tamanos[i].id = xmlTamanos[i].getAttribute("id");
		this.tamanos[i].src = tamanoXml.getAttribute("src");
		this.tamanos[i].srcActivo = tamanoXml.getAttribute("srcActivo");
		this.tamanos[i].height = tamanoXml.getAttribute("height");
		this.tamanos[i].width = tamanoXml.getAttribute("width");
		this.tamanos[i].infoHeight = tamanoXml.getAttribute("infoHeight");
		this.tamanos[i].dir = tamanoXml.getAttribute("dir");
		this.tamanos[i].ext = tamanoXml.getAttribute("ext");
		this.tamanos[i].showPrices = b_parseBool(tamanoXml.getAttribute("showPrices"));
		this.tamanos[i].showOriginalPrice = b_parseBool(tamanoXml.getAttribute("showOriginalPrice"));
		this.tamanos[i].showDivisa = b_parseBool(tamanoXml.getAttribute("showDivisa"));
		this.tamanos[i].rows = tamanoXml.getAttribute("rows");
		this.tamanos[i].cols = tamanoXml.getAttribute("cols");
		this.tamanos[i].maxRows = tamanoXml.getAttribute("maxRows");
		this.tamanos[i].srcNotfound = tamanoXml.getAttribute("srcNotfound");
		this.tamanos[i].srcLoading = tamanoXml.getAttribute("srcLoading");
		this.tamanos[i].defecto = b_parseBool(tamanoXml.getAttribute("defecto"));
		
		if ( (this.patillas[idPati].tamano == null && this.tamanos[i].defecto) ||
				(this.patillas[idPati].tamano != null && this.patillas[idPati].tamano.id == this.tamanos[i].id)) {
			this.tamano = this.tamanos[i];
			this.patillas[idPati].tamano = this.tamano;
			if (this.patillas[idPati].tamanos[this.tamano.id] == null) {
				this.patillas[idPati].tamanos[this.tamano.id] = new Object();
				this.patillas[idPati].tamanos[this.tamano.id].selectedRows = this.tamano.rows;
			}
			if (tipoBuscador == 'coleccion')
				document.getElementById('Form:SVBody:SVBusc:tamano:'+this.tamanos[i].id).src=this.tamanos[i].srcActivo;
		} else {
			if (tipoBuscador == 'coleccion')
				document.getElementById('Form:SVBody:SVBusc:tamano:'+this.tamanos[i].id).src=this.tamanos[i].src;
		}
	}
	
	//Array de productos que se visualizan en el buscador, seleccionando solo los que cumplen los criterios de
	// los menus.
	this.productList = new Array();
	this.productListlength = 0;
	
	//Array de todos los productos que nos llegan por XML. Crearemos la lista anterior a partir de esta, despues de aplicar
	// los criterios de los menus.
	this.productListAll = new Array();//Array de productos
	this.productListlengthAll = 0;//Longitud de la lista de productos

	if (this.patillas[idPati].currPage == null) this.currPage = 0;
	else this.currPage = this.patillas[idPati].currPage;
	this.currItem=0;//Item actual, ultimo item seleccionado(=0 ningun item seleccionado)
	this.pagelength=0;
	this.externalItemSelected=0;//(=0 ningun item seleccionado)
	
	//Variables del paginador
	this.navegador = NavegadorUnidades;

	// Tratamiento de los filtros.
	if (tipoBuscador == 'coleccion') {	
		this.estilo = this.valorAllString;
		this.temporada = this.valorAllString;
		this.grupoFamilia = this.valorAllInt;
		this.precioMin = this.valorAllInt;
		this.precioMax = this.valorAllInt;
		this.descuentoMin = this.valorAllInt;
		this.descuentoMax = this.valorAllInt;
		this.tipoTalla = this.valorAllInt;
		this.bloque = this.valorAllInt;
		this.cole = this.valorAllInt;
		this.promo = this.valorAllString;
	} else {
		this.catalogo = this.valorAllInt;
	}
	this.num_rows = this.patillas[idPati].tamanos[this.tamano.id].selectedRows;//numero de filas
	this.num_cols = this.tamano.cols;//numero de columnas
	
	//Creamos productList a partir del XML
	this.makeList();

	if (this.patillas[idPati].selectedItem == null) this.patillas[idPati].selectedItem = this.productList[0].id;
	else {
		changeOpacitySelectedImage('imagen_'+this.patillas[idPati].selectedItem);
		//_mng_submitFicha(this.patillas[idPati].selectedItem, false);
		_mng_submitProductoA4J_h(this.patillas[idPati].selectedItem);
	}
	// Despues de crear la lista inicial de productos, establecemos los possibles menus
	this.patillaId = idPati;	
	this.setMenus();
	
}

function b_rewrite(){
	var panel = document.getElementById('panelBuscador');

	while (panel.firstChild) {
		panel.removeChild(panel.firstChild);
	}
	
	var table = this.print();
	panel.appendChild(table);
	
	this.clearPreloadedPages();
	this.preloadImages();
	
	var panelPaginador = document.getElementById('paginadorBuscador');
	
	while (panelPaginador.firstChild) {
		panelPaginador.removeChild(panelPaginador.firstChild);
	}
	
	var tablePaginador = this.printpaginador();
	panelPaginador.appendChild(tablePaginador);
	
	//Comprobamos los links Previous y Next (arriba y abajo)
	this.checklinks(document.getElementById('Form:SVBody:SVBusc:buscadorAnteriorUp'),document.getElementById('Form:SVBody:SVBusc:buscadorSiguienteUp'));
	this.checklinks(document.getElementById('Form:SVBody:SVBusc:buscadorAnteriorDown'),document.getElementById('Form:SVBody:SVBusc:buscadorSiguienteDown'));
	
	//Comprobamos las imagenes de addRow y delRow
	this.checkRowlinks(document.getElementById('Form:SVBody:SVBusc:addRow'),document.getElementById('Form:SVBody:SVBusc:delRow'));

	//Mostramos con opacidad la imagen seleccionada	
	this.changeOpacitySelectedImage(this.lastSelectedImage);
	
	this.currItem = 0;
}

function b_addProducto(id,idImagen,nombre,estilo,grupoFamilia,grupoTalla,bloques,coles,promos,pvp,pvpND,pvpOriginal,pvpOriginalND,tiposTallas,descuento,color) {
	if(!this.productListAll[this.productListlengthAll]) 
		this.productListAll[this.productListlengthAll] = new Object();
	this.productListAll[this.productListlengthAll].id = id;//id="41000671"
	this.productListAll[this.productListlengthAll].idImagen = idImagen;//idImagen="41000671"
	this.productListAll[this.productListlengthAll].index = this.productListlengthAll;
	this.productListAll[this.productListlengthAll].nombre = nombre;//nombre="ABRIGO SVD PARTY"
	this.productListAll[this.productListlengthAll].estilo = estilo;//estilo="E"
	this.productListAll[this.productListlengthAll].grupoFamilia = grupoFamilia;//grupoFamilia="2"  
	this.productListAll[this.productListlengthAll].grupoTalla = grupoTalla;//grupoTalla="34"
	if (!this.productListAll[this.productListlengthAll].bloques) 
		this.productListAll[this.productListlengthAll].bloques = new Array();
	this.productListAll[this.productListlengthAll].bloques = bloques.split(',');
	
	if (!this.productListAll[this.productListlengthAll].coles) 
		this.productListAll[this.productListlengthAll].coles = new Array();
	this.productListAll[this.productListlengthAll].coles = coles.split(',');

	if (!this.productListAll[this.productListlengthAll].promos) 
		this.productListAll[this.productListlengthAll].promos = new Array();
	this.productListAll[this.productListlengthAll].promos = promos.split(',');
	
	this.productListAll[this.productListlengthAll].pvp = pvp;
	this.productListAll[this.productListlengthAll].pvpND = pvpND;//Precio que se debe mostrar sin DIVISA
	this.productListAll[this.productListlengthAll].pvpOriginal = pvpOriginal;
	this.productListAll[this.productListlengthAll].pvpOriginalND = pvpOriginalND;//Precio original sin DIVISA
	this.productListAll[this.productListlengthAll].tiposTalla = tiposTallas.split(',');
	this.productListAll[this.productListlengthAll].descuento = descuento;
	this.productListAll[this.productListlengthAll].color = color;

	// Inicialmente todos los productos seran visibles. Copiamos todos los items de la lista total, sobre la
	// lista de items visibles.	
	this.productList[this.productListlengthAll] = this.productListAll[this.productListlengthAll];
	this.productListlengthAll++;
	this.productListlength = this.productListlengthAll;
}

function b_addConjunto(id, imagen, nombre, catalogo, producto) {
	if(!this.productListAll[this.productListlengthAll]) 
		this.productListAll[this.productListlengthAll] = new Object();
	this.productListAll[this.productListlengthAll].id = id;
	this.productListAll[this.productListlengthAll].imagen = imagen;
	this.productListAll[this.productListlengthAll].nombre = nombre;
	this.productListAll[this.productListlengthAll].catalogo = catalogo;
	this.productListAll[this.productListlengthAll].producto = producto;
	
	this.productList[this.productListlengthAll] = this.productListAll[this.productListlengthAll];
	this.productListlengthAll++;
	this.productListlength = this.productListlengthAll;
}

function b_makeList() {
	var i=0;
	var j=0;

	//Recorremos xmlDoclist para leer todos los productos e introducirlos en this.productList
	for (i=0;i<xmlDoclist.length;i++)//filas
	{
		var prenda=xmlDoclist[i];
		
		if (this.tipo == 'coleccion') {
			/*b_addProducto(prenda.getAttribute('id'),
						  prenda.getAttribute('nombre'),
						  prenda.getAttribute('estilo'),
						  prenda.getAttribute('grupoFamilia'),
					 	  prenda.getAttribute('grupoTalla'),
						  prenda.getAttribute('bloques'),
						  prenda.getAttribute('promos'),
						  prenda.getAttribute('pvp'),
						  prenda.getAttribute('pvpND'),
						  prenda.getAttribute('pvpOriginal'),
						  prenda.getAttribute('pvpOriginalND'),
						  prenda.getAttribute('tiposTalla'));*/
			b_addProducto(prenda.getAttribute('a'),
						  prenda.getAttribute('aa'),
						  prenda.getAttribute('b'),
						  prenda.getAttribute('g'),
						  prenda.getAttribute('j'),
					 	  prenda.getAttribute('k'),
						  prenda.getAttribute('h'),
						  prenda.getAttribute('i'),
						  prenda.getAttribute('n'),
						  prenda.getAttribute('c'),
						  prenda.getAttribute('d'),
						  prenda.getAttribute('e'),
						  prenda.getAttribute('f'),
						  prenda.getAttribute('l'),
						  prenda.getAttribute('n'),
						  prenda.getAttribute('o'));
		
		   			  
		   if(prenda.getAttribute('m') == 'yes'){//Si esta seleccionado(selected =yes or =no)
		   	/*if(i!=0){//si no es el primer articulo(pq el primero siempre esta seleccionado por defecto)
		   		this.externalItemSelected=prenda.getAttribute('a');
			   	_mng_submitFicha(this.productList[i].id, this.tipo, true);
			}*/
		   	changeOpacitySelectedImage('imagen_'+prenda.getAttribute('a'));
		   }
						  
		} else {
			b_addConjunto(prenda.getAttribute('id'),
						  prenda.getAttribute('imagen'),
						  prenda.getAttribute('nombre'),
						  prenda.getAttribute('catalogo'),
						  prenda.getAttribute('producto'));
		}
	}//end del for
	this.productListlength = i;
	if (xmlDoclist.length > this.num_rows*this.num_cols)
		this.pagelength = Math.ceil(this.productListlength/(this.num_rows*this.num_cols)) - 1;//Le restamos 1 porque empieza en la p?gina 0
	else this.pagelength = 1;
	
	if (this.currPage == 0) this.currItem = 0;
	else this.currItem = (this.currPage * (this.num_rows*this.num_cols));
	if (this.currItem >= xmlDoclist.length) this.currItem = xmlDoclist.length - 1;
}

function b_setMenus() {
	// En el XML recibiremos una lista opcional con los menus que esten preseleccionados. Recorremos esta lista y llamamos
	// a la funci?n de filtrado para cada uno de estos menus.
	
	// Apliquem nomes els menus que arribin al XML a la carrega inicial de la home
	if (this.xmlMenuList != null) {
		var preselect = false;
		for (cont=0; cont<this.xmlMenuList.length;cont++) {
			var menu = this.xmlMenuList[cont];
			var name = menu.getAttribute('id');
			valor = _mng_DD_initMenus('menuPati',name);
			var aux = this.filtrar(name, valor, false, false);
			preselect = (preselect || aux);
		}

		/*if (preselect && this.tipo == 'coleccion'&& this.externalItemSelected==0) {
			setCurrItem(0);
			_mng_submitFicha(this.productList[0].id, this.tipo, true);
		   	changeOpacitySelectedImage('imagen_'+this.productList[0].id);
		}*/
	}
	
	if (this.patillas[this.patillaId].filtros != null) {
		for (key in this.patillas[this.patillaId].filtros) {
			valor = this.patillas[this.patillaId].filtros[key];
			if (valor != null) {
				_mng_DD_selection('menuPati',key, valor);
				this.filtrar(key, valor, false, false);
			}
		}
	}
	
}

function b_getState() {
	var state = '';
	for (contMenu = 0; contMenu < this.xmlMenuList.length; contMenu++) {
		key = this.xmlMenuList[contMenu].getAttribute('id');
		state = state + 'm_' + key + '_';
		if (this.patillas[this.patillaId].filtros != null && this.patillas[this.patillaId].filtros[key] != null)
			state = state + this.patillas[this.patillaId].filtros[key]
		else {
			if (key == 'familia' || key == 'tipoTalla' || key == 'bloque'
				|| key == 'coleccion' || key == 'estacion') state = state + this.valorAllInt;	
			if (key == 'estilo' || key == 'promocion') state = state + this.valorAllString;	
			if (key == 'precioVenta' || key == 'descuento') state = state + this.valorAllInt + '/';	
		}
		state = state + '.';	
	}
	state = state + 'page_' + this.currPage + '.';
	state = state + 'size_' + this.tamano.id + '.';
	state = state + 'rows_' + this.num_rows;
	return state;
}

function b_setState(state) {
	var params = state.split('.');	
	for (contParam = 0; contParam < params.length; contParam++) {
		var values = params[contParam].split('_');
		if (values.length == 3) {
			b_filtrar(values[1], values[2], true);
			_mng_DD_selection('menuPati', values[1], values[2]);
		} else {
			if (values[0] == 'page' && Number(values[1]) != Number(this.currPage) ) this.printPage(Number(values[1]));
			if (values[0] == 'size' && values[1] != this.tamano.id ) this.changeTamano(values[1]);
			if (values[0] == 'rows' && Number(values[1]) != Number(this.num_rows) ) this.setRows(values[1]);
		}
	}
}

function b_getItemSelected() {
	return this.patillas[this.patillaId].selectedItem;
}

function b_selectImage(id) {
	changeOpacitySelectedImage('imagen_'+id);
	this.patillas[this.patillaId].selectedItem = id;
}

function b_newItemCell(producto, tamano) {
	var cell = document.createElement('td');
	cell.setAttribute('valign','top');
	cell.setAttribute('align','center');
	cell.appendChild(b_newItemImage(producto, tamano));
	cell.appendChild(b_newItemData(producto, tamano));
	
	return cell;
}

function b_newEmptyCell(tamano) {
	var cell = document.createElement('td');
	
	var panel = document.createElement('div');
	panel.style.cssText = 'width:'+tamano.width+'px;height:'+(Number(tamano.height)+Number(tamano.infoHeight))+'px;overflow:hidden;';
	
	cell.appendChild(panel);
	
	return cell;
}

function b_newItemImage(prenda, tamano) {
	var panel = document.createElement('div');
	panel.style.cssText = 'cursor: pointer; background: '+this.xmlConfig.getAttribute("fondoImagenes")+' url("'+this.tamano.srcLoading+'") 50% 50% no-repeat;overflow:hidden;vertical-align:top;height:'+tamano.height+'px;width:'+tamano.width+'px;';
	
	var imagen = document.createElement('img');
	imagen.setAttribute('id','imagen_'+prenda.id)
	imagen.setAttribute('width',tamano.width);	
	imagen.setAttribute('height',tamano.height);
	// En onerror indicamos que si no se encuantra la imagen se muestre una imagen alternativa
	imagen.onerror = new Function("this.src='"+tamano.srcNotfound+"';");
	imagen.style.cssText = 'visibility: hidden;';
	imagen.onload = new Function("this.style.visibility = 'visible'; if (this.parentNode) try { this.parentNode.style.backgroundImage='none'; } catch(err) {}");
	var dirBase = tamano.dir.replace('#temporada#',prenda.id.substr(0,1));
	
	if (this.tipo == 'coleccion') {
		if (prenda.color != null && prenda.color != '00')
			src = dirBase+prenda.idImagen+"_"+prenda.color+tamano.ext;
		else src = dirBase+prenda.idImagen+tamano.ext;
	}
	else src = dirBase+prenda.imagen+tamano.ext;
	
	imagen.setAttribute('src',src);
	imagen.setAttribute('title',prenda.nombre);
	imagen.style.display = 'block';
	
	// En el onclick de la imagen, llamamos a submitProducto definido en libreriaAjax, que har? una llamada ajax get.
	//imagen.onclick = new Function("this.parentNode.style.backgroundImage = 'none'; b_selectImage('"+prenda.id+"'); _mng_submitFicha('"+prenda.id+"','"+this.tipo+"', true); scrollTop();");
	imagen.onclick = new Function("this.parentNode.style.backgroundImage = 'none'; b_selectImage('"+prenda.id+"'); _mng_submitProductoA4J('"+prenda.id+"'); scrollTop();");
		
	panel.appendChild(imagen);
		
	return panel;
}

function b_newItemData(prenda, tamano) {
	var panel = document.createElement('div');
	panel.style.cssText = 'width:100%;height:'+tamano.infoHeight+'px;overflow:hidden;background-color:'+this.xmlConfig.getAttribute("fondoPanel")+';text-align:center;';
	
	var panelPrecio = document.createElement('div');
	if (tamano.showPrices) {
		var original = Number(prenda.pvpOriginalND.replace(",","."));
		var venta = Number(prenda.pvpND.replace(",","."));
		if (tamano.showOriginalPrice && original > 0 && original != venta) {
			var spanPrecio = document.createElement('span');
			spanPrecio.style.cssText = 'color:'+this.xmlConfig.getAttribute("colorPrecioTachado")+';background-image:url("'+this.xmlConfig.getAttribute("srcPrecioTachado")+'");background-repeat:repeat-x;background-position:left center;padding-left:3px;padding-right:3px';
			spanPrecio.className = 'txt7';
			var precio = null;
			if (tamano.showDivisa) precio = document.createTextNode(prenda.pvpOriginal);
			else precio = document.createTextNode(prenda.pvpOriginalND);
			spanPrecio.appendChild(precio);
			panelPrecio.appendChild(spanPrecio);
		} else {
			//alert('pvpOriginalND:'+prenda.pvpOriginalND);
		}
		panel.appendChild(panelPrecio);
		var spanVenta = document.createElement('div');
		spanVenta.className = 'txt7';
		spanVenta.style.cssText = 'color:'+this.xmlConfig.getAttribute("colorPrecio")+';';
		panelPrecio.style.cssText = 'margin-top:2px; padding-top:1px;padding-bottom:1px; '+
			'background-color: '+this.xmlConfig.getAttribute("fondoPrecio")+
			'; border: 1px solid '+this.xmlConfig.getAttribute("bordePrecio")+'; margin-left: 1px; margin-right: 1px; ';
		var venta = null;
		if (tamano.showDivisa) venta = document.createTextNode(prenda.pvp);
		else venta = document.createTextNode(prenda.pvpND);
		spanVenta.appendChild(venta);
		panelPrecio.appendChild(spanVenta);
	}
	return panel;
}

function b_print(){
	var i=0;
	var j=0;
	var table=document.createElement('table');
	var tbody=document.createElement('tbody');
	table.style.cssText = 'border-collapse: separate; empty-cells: show;';
	table.setAttribute('border','0');
	table.setAttribute('width','100%');
	table.setAttribute('cellspacing','0');
	table.setAttribute('cellpadding','0');
	table.cellSpacing = 0;
	table.cellPadding = 0;

	if (!b_isPagePreloaded(Number(this.currPage))) this.pagesPreLoaded[this.pagesPreLoaded.length] = Number(this.currPage);

	for (i=0;(i<this.num_rows)&&(this.currItem<this.productListlength);i++)//filas
	{
		var fila= document.createElement('tr');//salto de linea
		fila.setAttribute('height',this.tamano.height);
		for (j=0;(j<this.num_cols)&&(this.currItem<this.productListlength);j++)//columnas
		{
			fila.appendChild(b_newItemCell(this.productList[this.currItem], this.tamano));
			this.currItem++;
		}//end del for
		
		//Si no se han insertado las celdas suficientes para una fila rellenamos con celdas vac?as.
		while (j < this.num_cols) {
			fila.appendChild(b_newEmptyCell(this.tamano));
			j++;	
		}
		
		tbody.appendChild(fila);
	}//end del for
	
	table.appendChild(tbody);
	
	return table;
}

function b_addNextPage(table) {
	var tbody = table.firstChild;
	var filas = tbody.childNode;
	for (i=0; i<filas.length; i++) {
		
	}
}

function b_preloadImages() {
	var indice = -1;
	if (!b_islastpage() && !b_isPagePreloaded(this.currPage+1)) {
		indice = Number(this.currPage)+1;
		setTimeout('b_preloadPageImages('+indice+')',2000);
	} if (!b_isfirstpage() && !b_isPagePreloaded(this.currPage-1)) {
		indice = Number(this.currPage)-1;
		setTimeout('b_preloadPageImages('+indice+')',2000);
	}
}

/**
* Esta funcion se encarga de precargar las imagenes de una pagina concreta.
**/
function b_preloadPageImages(page) {
	var inicio = (page * this.num_rows * this.num_cols);
	var fin = inicio + (this.num_rows * this.num_cols);
	var images = new Array();
	var cont = 0;
	for (i=inicio; i<fin && i<this.productListlength;i++) {
		images[cont] = new Image();
		var prenda = this.productList[i];
		if (this.tipo == 'coleccion') {
			if (prenda.color != null && prenda.color != '00')
				src = this.tamano.dir.replace('#temporada#',prenda.id.substr(0,1))+prenda.idImagen+'_'+prenda.color+this.tamano.ext;
			else src = this.tamano.dir.replace('#temporada#',prenda.id.substr(0,1))+prenda.idImagen+this.tamano.ext;
		} else src = this.tamano.dir+prenda.imagen+this.tamano.ext;
		images[cont].src = src;
		cont++;
	}
	this.pagesPreLoaded[this.pagesPreLoaded.length] = page;
}

function b_isPagePreloaded(page) {
	for (k=0; k<this.pagesPreLoaded.length; k++) {
		if (this.pagesPreLoaded[k] == page) return true;
	}
	return false;
}

function b_clearPreloadedPages() {
	this.pagesPreLoaded = new Array();
}

function b_isfirstpage(){
	if(this.currPage==0){
		return true;
	}else{
		 return false;
	}
}

function b_islastpage(){
	if(this.currPage==this.pagelength){
		return true;
	}else{
		return false;
	}
}

function b_checklinks(linkPrevious,linkNext){

	if(b_isfirstpage()){
		linkPrevious.style.color=this.xmlConfig.getAttribute("colorNavegaDisabled");
		linkPrevious.style.cursor='default';
	}else{
		linkPrevious.style.color=this.xmlConfig.getAttribute("colorNavega");
		linkPrevious.style.cursor='pointer';
	}
	
	if(b_islastpage()){
		linkNext.style.color=this.xmlConfig.getAttribute("colorNavegaDisabled");
		linkNext.style.cursor='default';
	}else{
		linkNext.style.color=this.xmlConfig.getAttribute("colorNavega");
		linkNext.style.cursor='pointer';
	}
}

function b_printNext(){
	if(currPage<this.pagelength){
		this.currPage++;
		this.printPage(this.currPage);
	}else{
		//alert('No hay pagina siguiente');
	}//end del if
}

function b_printPrevious(){
	if(currPage>0){
		this.currPage--;
		this.printPage(this.currPage);
	}else{
		//alert('No hay pagina anterior');
	}//end del if
}

function b_printPage(page){
	if((page>=0)&&(page<=this.pagelength)){
		this.currPage = page;
		this.patillas[patillaId].currPage = page;
		this.lastCurrItem = this.currItem;
		this.currItem = page * (this.num_rows*this.num_cols);
		rewrite();//funcion dentro de libreriaAjax.js
		this.currItem = this.lastCurrItem;
		changeOpacitySelectedImage(lastSelectedImage);
	}else{
		//alert('Esta paagina no existe!');
		showNoPrendas();
	}//end del if
}

function b_changeTamano(tipoTamano){
	// Inicializamos la lista de paginas precargadas, porque al cambiar el tamaño cambian las imagenes
	b_clearPreloadedPages();
	
	for (i=0; i<this.tamanos.length; i=i+1) {
		if (tipoTamano == this.tamanos[i].id) {
			this.tamano = this.tamanos[i];
			this.patillas[patillaId].tamano = this.tamano;
			if (this.patillas[patillaId].tamanos[this.tamano.id] == null) {
				this.patillas[patillaId].tamanos[this.tamano.id] = new Object();
				this.patillas[patillaId].tamanos[this.tamano.id].selectedRows = this.tamano.rows;
			}
			this.num_rows = this.patillas[patillaId].tamanos[this.tamano.id].selectedRows;
			this.num_cols = this.tamano.cols;
			document.getElementById('Form:SVBody:SVBusc:tamano:'+this.tamanos[i].id).src=this.tamanos[i].srcActivo;
		} else {
			document.getElementById('Form:SVBody:SVBusc:tamano:'+this.tamanos[i].id).src=this.tamanos[i].src;
		}
	}
	
	this.pagelength = Math.ceil(this.productListlength/(this.num_rows*this.num_cols)) - 1;//Le restamos 1 porque empieza en la pagina 0
	if (this.productListlength > this.num_rows*this.num_cols)
		this.pagelength = Math.ceil(this.productListlength/(this.num_rows*this.num_cols)) - 1;//Le restamos 1 porque empieza en la pagina 0
	else this.pageLength = 1;
	if( this.currItem == 0 && (this.num_rows*this.num_cols)== 0 ){
			this.currPage = 0 ;
		}else{
			this.currPage = Math.floor(this.currItem / (this.num_rows*this.num_cols) ) ;
		}
	this.printPage(this.currPage);
		
}

function b_addRow(){
	b_setRows(Number(this.num_rows)+1);
}

function b_removeRow(){
	b_setRows(Number(this.num_rows)-1);
}

function b_setRows(rows){ 
	maximo = this.tamano.maxRows;
	if (rows <= maximo && rows >= 0) {
		this.num_rows = rows;
		this.patillas[patillaId].tamanos[this.tamano.id].selectedRows = this.num_rows;
		if (this.productListlength > this.num_rows*this.num_cols)
			this.pagelength = Math.ceil(this.productListlength/(this.num_rows*this.num_cols)) - 1;//Le restamos 1 porque empieza en la p?gina 0
		else this.pageLength = 1;
		if( this.currItem == 0 && (this.num_rows*this.num_cols)== 0 ){
			this.currPage = 0 ;
		}else{
			this.currPage = Math.floor(this.currItem / (this.num_rows*this.num_cols) ) ;
		}
		this.printPage(this.currPage);
	}
}

function b_checkRowlinks(addRowImage,delRowImage){

	maximo = this.tamano.maxRows;
	
	if(this.num_rows >= maximo) {//Debemos desactivar el boton de addRow
		addRowImage.src='images/buscador/addRowDisabled.gif';
		addRowImage.onmouseout=new Function("this.src='images/buscador/addRowDisabled.gif'");
		addRowImage.onmouseover=new Function("this.src='images/buscador/addRowDisabled.gif'");
	}else{
		addRowImage.src='images/buscador/addRow.gif';
		addRowImage.onmouseout=new Function("this.src='images/buscador/addRow.gif'");
		addRowImage.onmouseover=new Function("this.src='images/buscador/addRowOver.gif'");
	}//end del if
	
	if(this.num_rows <= 1){//Debemos desactivar el boton de delRow
		delRowImage.src='images/buscador/delRowDisabled.gif';
		delRowImage.onmouseout=new Function("this.src='images/buscador/delRowDisabled.gif'");
		delRowImage.onmouseover=new Function("this.src='images/buscador/delRowDisabled.gif'");
	}else{
		delRowImage.src='images/buscador/delRow.gif';
		delRowImage.onmouseout=new Function("this.src='images/buscador/delRow.gif'");
		delRowImage.onmouseover=new Function("this.src='images/buscador/delRowOver.gif'");
	}//end del if
	
}//end de la funcion b_checkRowlinks

function b_filtrar(propiedad, valor, print, guardar) {
	if (guardar == null) guardar = true;
	switch (propiedad) {
		case 'familia':
			this.grupoFamilia = valor; 
			break;
		case 'estilo':
			this.estilo = valor; 
			break;
		case 'temporada':
			this.temporada = valor; 
			break;
		case 'precioVenta':
			var valorSplit = valor.split("/"); 
			this.precioMin = valorSplit[0]; 
			if (valorSplit.length > 1 && valorSplit[1] != "") this.precioMax = valorSplit[1]; 
			else this.precioMax = this.valorAllInt;
			break;
		case 'descuento':
			var valorSplit = valor.split("/"); 
			this.descuentoMin = valorSplit[0]; 
			if (valorSplit.length > 1 && valorSplit[1] != "") this.descuentoMax = valorSplit[1]; 
			else this.descuentoMax = this.valorAllInt;
			break;
		case 'tipoTalla': 
			this.tipoTalla = valor; 
			break;
		case 'bloque': 
			this.bloque = valor; 
			break;
		case 'coleccion'://coleccion 
			this.cole = valor; 
			break;
		case 'promocion'://coleccion 
			this.promo = valor; 
			break;
		case 'estacion': //catalogo
			this.catalogo = valor; 
			break;
		default:
	}
	
	if (this.patillas[this.patillaId].filtros == null)
		this.patillas[this.patillaId].filtros = new Array();
		
	var filtrado = false;
	if (
		( propiedad != 'precioVenta' && propiedad != 'descuento' && valor != this.valorAllString && valor != this.valorAllInt ) ||
		( (propiedad == 'precioVenta' || propiedad == 'descuento') && this.precioMin != this.valorAllString && this.precioMin != this.valorAllInt )
		) {
		filtrado = true;
		if (guardar) this.patillas[this.patillaId].filtros[propiedad] = valor;
	}
	else {
	 	if (guardar) this.patillas[this.patillaId].filtros[propiedad] = null; 	
	}
	
	this.productList = new Array();	
	var cont = 0;
	for (i=0; i<this.productListlengthAll; i++) {
		// Inicialmente cada producto entrar? en la lista.
		var inList = true;
		
		if (this.tipo == 'coleccion') {
			// Si la familia seleccionada por men? no es 'todas', y la familia del producto no se corresponde a esta familia seleccionada,
			// el producto queda fuera de la lista.
			if (this.grupoFamilia != this.valorAllInt && this.grupoFamilia != this.productListAll[i].grupoFamilia)
				inList = false;
	
			// Idem para el estilo...
			if (inList && this.estilo != this.valorAllString && this.estilo != this.productListAll[i].estilo)
				inList = false;

			// Temporada
			if (inList && this.temporada != this.valorAllString && this.temporada != this.productListAll[i].id.substring(0,1)) {
				inList = false;
			}
	
			var pvp = Number(this.productListAll[i].pvpND.replace(",","."));
			// Si el precio minimo seleccionado no es 'todos', y el precio del producto es menor al precio minimo, se descarta.		
			if (inList && this.precioMin != this.valorAllInt && Number(this.precioMin) > pvp)
				inList = false;
			// Si el precio maximo seleccionado no es 'todos', y el precio del producto es mayor al precio maximo, se descarta.		
			if (inList && this.precioMax != this.valorAllInt && Number(this.precioMax) <= pvp)
				inList = false;

			// Idem para el descuento
			var descuento = Number(this.productListAll[i].descuento);
			if (inList && this.descuentoMin != this.valorAllInt && Number(this.descuentoMin) > descuento)
				inList = false;
			if (inList && this.descuentoMax != this.valorAllInt && Number(this.descuentoMax) <= descuento)
				inList = false;
			
			// Si el bloque seleccionado por menu no es 'todos', comparamos este bloque seleccionado con todos los bloques a
			// los que pertenece el producto, y si no hay coincidencia con ninguno lo descartamos.
			if (inList && this.bloque != this.valorAllInt) {
				var found = false; 
				for (j=0; j<this.productListAll[i].bloques.length; j++) {
					if (Number(this.productListAll[i].bloques[j]) == Number(this.bloque)) found = true;
				}
				inList = found; 
			}
	
			// Idem para las colecciones...
			if (inList && this.cole != this.valorAllInt) {
				var found = false; 
				for (j=0; j<this.productListAll[i].coles.length; j++) {
					if (Number(this.productListAll[i].coles[j]) == Number(this.cole)) found = true;
				}
				inList = found; 
			}

			// Idem para las promos...
			if (inList && this.promo != this.valorAllString) {
				var found = false; 
				for (j=0; j<this.productListAll[i].promos.length; j++) {
					if (this.productListAll[i].promos[j] == this.promo) found = true;
				}
				inList = found; 
			}
			
			// Idem para llos tipos de talla
			if (inList && this.tipoTalla != this.valorAllInt) {
				var found = false; 
				for (j=0; j<this.productListAll[i].tiposTalla.length; j++) {
					if (Number(this.productListAll[i].tiposTalla[j]) == Number(this.tipoTalla)) found = true;
				}
				inList = found; 
			}
		}else{
			//Lo mismo para la pestana catalogo
			if (this.catalogo != this.valorAllInt && this.catalogo != this.productListAll[i].catalogo)
				inList = false;
		}//end del if (this.tipo == 'coleccion')
		
		if (inList) {
			this.productList[cont++] = this.productListAll[i];
		}
	}
	this.productListlength = cont;
	
	this.pagelength = Math.ceil(this.productListlength/(this.num_rows*this.num_cols)) - 1;//Le restamos 1 porque empieza en la p?gina 0
	
	if (print) this.printPage(0);
	
	return filtrado;
}

function b_printpaginador(){
	//Asignamos a la variable navegador el tipo de navegador segun el valor de CurrPage para mostrarlo de una manera u otra
	if(this.currPage<10){
		this.navegador = NavegadorUnidades;
	}else if(this.currPage<100){
			this.navegador = NavegadorDecenas;
		  }else this.navegador = NavegadorCentenas;
		
	//Ahora creamos el paginador
	var i=0;
	var color='#999999';
	var font_weight='normal';
	var table=document.createElement('table');
	var tbody=document.createElement('tbody');
	table.setAttribute('border','0');
	table.setAttribute('cellspacing','0');
	table.setAttribute('cellpadding','0');
	table.setAttribute('style','empty-cells: show;');
	
	var fila= document.createElement('tr');//salto de linea(solo habr? uno)

	//Primero creamos la celda del valor [1] porque esta siempre se mostrara
	var cell = document.createElement('td');
	cell.className = 'txt7';
	if(this.currPage=='0'){
		color=this.xmlConfig.getAttribute("colorPaginaSel");
		font_weight='bold';
	}else{
		 color=this.xmlConfig.getAttribute("colorPaginas");
		 font_weight='normal';
	}
	//cell.setAttribute('style','width:'+this.navegador.anchoCelda+'px; text-align:center;color: '+color+';cursor: pointer;');
	cell.style.cssText  = 'width:'+this.navegador.anchoCelda+'px; text-align:center;color: '+color+';font-weight: '+font_weight+';cursor: pointer;';
	cell.onclick = new Function('_mng_setPage(0)');
	cell.appendChild(document.createTextNode('1'));
	fila.appendChild(cell);
	
	if(this.pagelength!='0'){//Si entra aqui significa que hay mas p?ginas que mostrar
	
		//Imprimimos primeros [...] si 
		if(this.currPage - (Math.round(this.navegador.numPaginas)/2) > 1){
			var cell = document.createElement('td');
			cell.className = 'txt7';
			cell.style.cssText  = 'style','width:'+this.navegador.anchoCelda+'px; text-align:center;color: '+this.xmlConfig.getAttribute("colorPaginas")+';';
			cell.appendChild(document.createTextNode('...'));
			fila.appendChild(cell);
		}//end del if
		
		//Ahora imprimiremos los paginas anteriores y siguientes a currPage
		var numPaginaInicial = (this.currPage-Math.round(this.navegador.numPaginas/2));
		if(numPaginaInicial<=1) numPaginaInicial = 2;
		
		var numPaginaFinal = numPaginaInicial + this.navegador.numPaginas - 1;
		if(numPaginaFinal>=pagelength){
			 numPaginaInicial = pagelength - this.navegador.numPaginas;
			 if(numPaginaInicial<=1) numPaginaInicial = 2;
			 numPaginaFinal = pagelength;
		}
		
		for (i=numPaginaInicial;i<=numPaginaFinal;i++){
				var cell = document.createElement('td');
				cell.className = 'txt7';
				if(this.currPage==(i-1)){
					color=this.xmlConfig.getAttribute("colorPaginaSel");
					font_weight='bold';
				}else{
					 color=this.xmlConfig.getAttribute("colorPaginas");
					 font_weight='normal';
				}
				//cell.setAttribute('style','width:'+this.navegador.anchoCelda+'px; text-align:center;color: '+color+';font-weight: '+font_weight+';cursor: pointer;');
				cell.style.cssText  = 'width:'+this.navegador.anchoCelda+'px; text-align:center;color: '+color+';font-weight: '+font_weight+';cursor: pointer;';
				cell.onclick = new Function('_mng_setPage('+(i-1)+')');
				cell.appendChild(document.createTextNode(i));
				fila.appendChild(cell);
		}//end del for
		
		//Imprimimos ultimos [...] si (Math.round(navegador.numPaginas)/2) - currPage < pagelength
		if(numPaginaFinal != this.pagelength){
			var cell = document.createElement('td');
			cell.className = 'txt7';
			//cell.setAttribute('style','width:'+this.navegador.anchoCelda+'px; text-align:center;color: #999999;');
			cell.style.cssText  = 'width:'+this.navegador.anchoCelda+'px; text-align:center;color: '+this.xmlConfig.getAttribute("colorPaginas")+';';
			cell.appendChild(document.createTextNode('...'));
			fila.appendChild(cell);
		}//end del if
		
		//Por ?ltimo creamos la celda del valor [productListlength] porque esta siempre se mostrara
		var cell = document.createElement('td');
		cell.className = 'txt7';
		if(this.currPage==this.pagelength){
			color=this.xmlConfig.getAttribute("colorPaginaSel");
			font_weight='bold';
		}else{
			color=this.xmlConfig.getAttribute("colorPaginas");
			font_weight='normal';
		}
		//cell.setAttribute('style','width:'+this.navegador.anchoCelda+'px; text-align:center;color: '+color+';cursor: pointer;');
		cell.style.cssText  = 'width:'+this.navegador.anchoCelda+'px; text-align:center;color: '+color+';font-weight: '+font_weight+';cursor: pointer;';
		cell.onclick = new Function('_mng_setPage('+this.pagelength+')');
		cell.appendChild(document.createTextNode((this.pagelength+1)));
		fila.appendChild(cell);
	
	}//end del if(this.pagelength!='0')
	
	tbody.appendChild(fila);
	table.appendChild(tbody);
	
	return table;
}//end de function b_printpaginador

var lastSelectedImage = null;

function changeOpacitySelectedImage(SelectedImage) { 

	//if (SelectedImage != lastSelectedImage) { 
	if (SelectedImage != null) { 
		var img = document.getElementById(SelectedImage); 
		var img1 = document.getElementById(lastSelectedImage); 
		lastSelectedImage = SelectedImage; 

		if (img1) b_setOpacity(img1,10);//img1.style.opacity = 1; 
		if (img){
			img.parentNode.style.backgroundImage = 'none';
			b_setOpacity(img,4.5);//img.style.opacity = 0.45; 
		}
		
	}//end del if 
	
}//end de la function changeOpacitySelectedImage(SelectedImage)

function b_setOpacity(imagen,value) {//Value entre 0 y 10
	imagen.style.opacity = value/10;
	imagen.style.filter = 'alpha(opacity=' + value*10 + ')';
}


function setCurrItem(currItem) {
	this.currItem=currItem;
}

var b_slideActivo = false;
function b_slideShow() {
	this.currItem = Number(this.currItem)+1;
	_mng_submitProductoA4J_h(this.productList[this.currItem].id);	
	this.selectImage(this.productList[this.currItem].id);
	document.addEventListener('click', b_stopSlide, false);
}

var b_sliteTimeout = null;
function b_keepSlideShow() {
	if (b_slideActivo) b_sliteTimeout = setTimeout('b_slideShow()', 2400);
}

function  b_stopSlide() {
	if (b_slideActivo) {
		document.removeEventListener('click', b_stopSlide, false);
		if (b_sliteTimeout != null) clearTimeout(b_sliteTimeout);
		b_slideActivo = false;
	} else b_slideActivo = true;
}


