var attr1;
var attr2;
var attr3;
// define variable so that eval an empty option does not crash the javascript
var arr_attrib_id___ = false;
var arr_attrib_id____ = false;


function init_attr() {
	attr1 = document.getElementById("attrib1");
	attr2 = document.getElementById("attrib2");
	attr3 = document.getElementById("attrib3");
	//if (attr1.options) select_add_data(attr1, arr_attrib1, '');
	// CVilladangos. 2007-09-03. El combo se construye poniendo la disponibilidad.
	if (attr1.options) select_add_data_value(attr1, arr_attrib1, '');
	chAttrib1();
	chAttrib2();
}

// Params:
//		product_id is hopefully self-explanatory
// 		productsArray contains the list of product_ids shown in the scroller
//		picWidth is the width of each pic
//		picSeparation is the space between pics
//		position is the position that the current article should be
function getScrollPosition(product_id, productsArray, picWidth, picSeparation, position) {
	for ( i=0; i<productsArray.length ; i++ ) {
		if(productsArray[i] == product_id) {
			productPosition = i;
		}
	}
	//productPosition = 3;
	firstPosition = productPosition - position;
	if(firstPosition < 0) {
		firstPosition = 0;
	}
	scrollPosition = firstPosition * (picWidth + picSeparation);

	return scrollPosition;
}

function current_product_id() {
	if (attr1.options && attr1.options.length!=0) sel1 = attr1.options[attr1.selectedIndex].value;
	else sel1 = "unico";
	if (attr2.options && attr2.options.length!=0) sel2 = attr2.options[attr2.selectedIndex].value;
	else sel2 = "";
	if (attr3.options && attr3.options.length!=0) sel3 = attr3.options[attr3.selectedIndex].value;
	else sel3 = "";

	try	{
		eval ("idp = arr_attrib_id_"+sel1+"_"+sel2+"_"+sel3);
	}
	catch(e){}

	if(typeof(idp) == 'string') {
		document.getElementById("product_id").value = idp;
	}

	return idp;
}

function chAttrib1() {

	/*var newOptions = new Array();
	if(attr1.options) {
		newOptions[0] = new Option('Seleccionar '+attr1_label, '');
		for($i = 0; $i < attr1.options.length; $i++) {
			newOptions[$i + 1] = new Option(attr1.options[$i].value, attr1.options[$i].value)
		}
	}*/

	if (attr2.options){
		if (attr2.options.length!=0) sel_ant = attr2.options[attr2.selectedIndex].value;
		else sel_ant = "";
		select_remove_all(attr2);
		if (attr1.options)
			sel = attr1.options[attr1.selectedIndex].value;
		else
			sel = "unico";

		//eval ("select_add_data(attr2, arr_attrib2_"+sel+", sel_ant);");
		// CVilladangos. 2007-09-03. El combo se construye poniendo la disponibilidad.
		eval ("select_add_data_value(attr2, arr_attrib2_"+sel+", sel_ant);");
		chAttrib2();
	}
	id=current_product_id();
	select_qty(id);
}

function chAttrib2() {
	if (attr3.options){
		if (attr3.options.length!=0) sel_ant = attr3.options[attr3.selectedIndex].value;
		else sel_ant = "";
		select_remove_all(attr3);
		if (attr3.options)
			sel1 = attr1.options[attr1.selectedIndex].value;
		else
			sel1 = "unico";
		sel2 = attr2.options[attr2.selectedIndex].value;

		//eval ("select_add_data(attr3, arr_attrib3_"+sel1+"_"+sel2+", sel_ant);");
		// CVilladangos. 2007-09-03. El combo se construye poniendo la disponibilidad.
		eval ("select_add_data_value(attr3, arr_attrib3_"+sel1+"_"+sel2+", sel_ant);");
	}
	id=current_product_id();
	select_qty(id);
}

function chAttrib3() {
  id=current_product_id();
  select_qty(id);
}

isIE=document.all;
isNN=!document.all&&document.getElementById;
isN4=document.layers;

function hideMe(d){
  if (isIE||isNN) {
  	d.style.visibility="hidden";
  	d.style.display="none";

  } else if (isN4) {
  	document.d.visibility="hide";
  }
}

function showMe(d){
  if (isIE||isNN) {
  	d.style.visibility="visible";
  	d.style.display="block";
  } else if (isN4) {
  	document.d.visibility="show";
  }
}

function select_qty( id )
{
	sq = document.getElementById('quantity');
	select_remove_all(sq);
	dades = new Array();

	d=document.getElementById('disponible');
	db=document.getElementById('disponible_boton');
	// nd=document.getElementById('no_disponible');

	// CVilladangos. Hay dos capas mas con disponibilidad.
	//* Monica (05/10/2007) Las capas de disponiblidad disponible_1 y no_disponible_1 han sido eliminadas para las nuevas campanas
	try {
		d1=document.getElementById('disponible_1');
		nd1=document.getElementById('no_disponible_1');
	}catch (e) {}

	//* Monica (04/10/2007) Si la cantidad es negativa tambien se oculta el boton de "añadir a mi cesta"
	if ( quantities[id] <= 0 )
	{
		hideMe(d);hideMe(db);
		//showMe(nd);
		//* Monica (05/10/2007) Las capas de disponiblidad disponible_1 y no_disponible_1 han sido eliminadas para las nuevas campanas
		try {
			hideMe(d1);showMe(nd1);
		}
		catch (e) {}
	}
	else
	{
		showMe(d);
		//showMe(db);
		//hideMe(nd);
		//* Monica (05/10/2007) Las capas de disponiblidad disponible_1 y no_disponible_1 han sido eliminadas para las nuevas campanas
		try {
			showMe(d1);hideMe(nd1);
		}
		catch (e) {}
	}

	for ( i=1; (i<=quantities[id] && i<=5) ; i++ )
	{
		dades[i-1]=i;
	}
	
	// mnoguera 18/03/09: hide 'cantidad' combo and 'add button' if 'talla' is not selected
	if (dades == '') {
		hideMe(d);
	}
	// mnoguera: hide button always, check it when change select qty
	hideMe(db);
	
	// mnoguera 18/03/09: add 'seleccionar' option
	select_add_data(sq, Array('Selecionar').concat(dades), "");
}


/*
 * hide o_element if s_word is selected on o_select, else show it
 * 
 * @author mnoguera
 * @params o_select, o_element, s_word
 * 
 */
function showButtonIfSelect(o_select, o_element, s_word){

	if (o_select.options[o_select.selectedIndex].value != s_word){
		showMe(o_element);
	}
	else{
		hideMe(o_element);
	}
		
}

/**
* Selecciona item 'select-one'
*/
function selecciona_select(_v, _it) {
	var SI = _v.options.length;
	for(var i=0;i<SI;i++)
	{
		if (_v.options[i].value == _it) {
			_v.options[i].selected = true;
			return;
		}
	}
}

/**
* Borra tots els ítems d'un select
*/
function select_remove_all(sel) {
	var SI = sel.options.length;
	while (sel.options.length!=0) sel.remove(sel.options.length-1);
}

/**
* Posa dades a un select
*
* @param sel object item select
* @param dades array of data
* @param valor_actual string valor a seleccionar
*/
function select_add_data(sel, dades, valor_actual) {
	var SI = dades.length;
	var ds;
	for(var i=0;i<SI;i++) {
		ds = ''+dades[i];
		re = /[^a-zA-Z0-9\/\-]+/;
		nt = ds.replace( re , '_' );
		sel.options[sel.length] = new Option(dades[i], nt.toLowerCase() );
	}
}


/**
* Crea un combo de seleccion html. Diferencia el valor que aparece en el option y el que se
* muestra. Utiliza el array global quantities que es el que almacena la disponibilidad.
*
* @param objet o_select. Objeto en el que se añaden los elementos.
* @param mixed st_option_value. Array con los datos
* @param valor_actual string valor a seleccionar
*/
function select_add_data_value(sel, dades, valor_actual) {

	var SI = dades.length;
	var ds;
	var s_cantidad;
	var s_id_product;
	var i_cantidad;
	var s_option;

	// DGarcia: prepend empty option
	// CVilladangos. Por compatibilidad con anteriores microsites ya generados en los que no
	// existe la variable se pregunta por la existencia de la misma. Si no existe no se muestra el
	// Seleccionar en la primera posición.
	if(typeof(attr1_label) !='undefined')
		sel.options[0] = new Option('Selecionar '+attr1_label, '');

	for(var i=0;i<SI;i++) {
		s_cantidad = "";
		ds = ''+dades[i];
		nt = ds;
		nt = decode_html_string(nt);

		//re = /[^a-zA-Z0-9\/\-]+/;
		// Las variables solo pueden tener caracteres alfanumericos, el resto se substituyen por _
		re = /[^a-zA-Z0-9]+/g;
		nt = nt.replace( re , '_' );
		//Reemplazamos tambien signos de puntuacion por _
		re = /[,'¿!¡;:()\.\?\/]/;
		nt = nt.replace( re , '_' );

		s_option = ds.replace(/_/g, ' '); // lo que mostramos: quitamos el _ y se substituye por espacio.
		eval('s_id_product = arr_attrib_id_' + nt.toLowerCase()+'__');
		i_cantidad = quantities[s_id_product];

		//* Monica (04/10/2007) Aseguramos que si no hay stock (auque éste sea negativo) salga el literal 'agotado':
		//* El stock disponible se calcula restando a la cantidad inicial ventas realizadas. Si por algun motivo
		//*	se modifica la cantidad inicial por un valor inferior al de las ventas, el stock calculado seria negativo.
		if(i_cantidad <= 0){
			s_cantidad = " -- esgotado";
		}
		else if(i_cantidad==1){
			s_cantidad = " -- resta 1";
		}
		else if(i_cantidad==2){
			s_cantidad = " -- restam 2";
		}
		//sel.options[sel.length] = new Option(dades[i]+s_cantidad, nt.toLowerCase());
		// Se pone la descripcion del producto tal y como esta en la base de datos.
		//sel.options[sel.length] = new Option(dades[i]+s_cantidad, nt.toLowerCase());
		sel.options[sel.length] = new Option(s_option+s_cantidad, nt.toLowerCase());

	}//end for

}


/* @nmelgarejo
 * Funcion que permite decodificar todos los caracteres raros posibles que nos puedan llegar en el atributo de producto final
 */
function decode_html_string(str)
{

	//@nmelgarejo: En caso se use Internet Explorer como navegador, creamos esta propiedad ya que no la soporta (Opera tampoco)
	if(!Array.indexOf){
	   	Array.prototype.indexOf = function(obj){
	        for(var j=0; j<this.length; j++){
	            if(this[j]==obj){return j;}
	        }
	  		}
	}

	html_codes = new Array(
		" ","¡","¢","£","¤","¥","¦","§","¨","©","ª","«","¬","­",
		"®","¯","°", "±","²","³","´","µ","¶","·","¸","¹","º",
		"»","¼","½","¾", "¿","À","Á","Â","Ã","Ä","Å","Æ","Ç","È",
		"É","Ê","Ë","Ì","Í","Î","Ï","Ð","Ñ","Ò","Ó","Ô","Õ","Ö",
		"×","Ø","Ù","Ú","Û","Ü","Ý","Þ","ß","à","á","â","ã","ä",
		"å","æ","ç","è","é","ê","ë","ì","í","î","ï","ð","ñ","ò",
		"ó","ô","õ","ö","÷","ø","ù","ú","û","ü","ý","þ","ÿ","\"",
		"\'","<",">","⅓","⅔","⅕","⅖","⅗","⅘","⅙","⅚","⅛","⅜","⅝","⅞"
	);

	html_decodes = new Array(
		"&nbsp;","&iexcl;","&cent;","&pound;","&curren;","&yen;","&brvbar;","&sect;",
		"&uml;","&copy;","&ordf;","&laquo;","&not;","&shy;","&reg;","&macr;","&deg;",
		"&plusmn;","&sup2;","&sup3;","&acute;","&micro;","&para;","&middot;","&cedil;",
		"&sup1;","&ordm;","&raquo;","frac14","frac12","frac34","&iquest;","&Agrave;",
		"&Aacute;","&Acirc;","&Atilde;","&Auml;","&Aring;","&AElig;","&Ccedil;","&Egrave;",
		"&Eacute;","&Ecirc;","&Euml;","&Igrave;","&Iacute;","&Icirc;","&Iuml;","&ETH;",
		"&Ntilde;","&Ograve;","&Oacute;","&Ocirc;","&Otilde;","&Ouml;","&times;","&Oslash;",
		"&Ugrave;","&Uacute;","&Ucirc;","&Uuml;","&Yacute;","&THORN;","&szlig;","&agrave;",
		"&aacute;","&acirc;","&atilde;","&auml;","&aring;","&aelig;","&ccedil;","&egrave;",
		"&eacute;","&ecirc;","&euml;","&igrave;","&iacute;","&icirc;","&iuml;","&eth;",
		"&ntilde;","&ograve;","&oacute;","&ocirc;","&otilde;","&ouml;","&divide;","&oslash;",
		"&ugrave;","&uacute;","&ucirc;","&uuml;","&yacute;","&thorn;","&yuml;","&quot;","&#39;",
		"&lt;","&gt;","frac13","frac23","frac15","frac25","frac35","frac45","frac16",
		"frac56","frac18","frac38","frac58","frac78"
	);

	for(var k=0; k < html_codes.length; k++)
	{
		var pos = (str).indexOf( html_codes[k] );
		if (pos > 0 || str == html_codes[k]) {
			str = str.replace( html_codes[k] , html_decodes[k] );
		}
	}

	return str;
}


