var checkedComboBox = { '': -1 };

var redirect = 0;

var num_radios = 5;

var num_floreros_opcionales = 3;

var precios = { '': new Array(num_radios)};
var precios_orig = { '': new Array(num_radios)};

var nombres = { '': new Array(num_radios)};

var preciosAO = { '': new Array(num_floreros_opcionales)};
var preciosAO_orig = { '': new Array(num_floreros_opcionales)};

var nombresAO = { '': new Array(num_floreros_opcionales)};

var idsProdAO = { '': new Array(num_floreros_opcionales)};

var clavesAO = { '': new Array(num_floreros_opcionales)};
//getNumProductosCarrito();

var num_recomienda_arreglo = 0;
var sufix_arreglo_opcional = "";

function init(valor,log)
{
	//setVisible('layer1',valor);
	//alert(valor);
	showLoading( 'imgPopUp', 54, 55 );
	
	showLoading( 'imgZoom', 54, 55 );
	//showLoadingNoResize( 'imgZoom' )
	//alert();
	
	dojo.xhrGet({
		url: findBasePath() + "/dojo_php_imp/get_detalles_producto.php?prod=" + valor + "&log=" + log,
		handleAs: "json",
		handle: function(data,args){
			if(typeof data == "error"){
				console.warn("error!");
				console.log(args);
				//alert(1);
			}else{
				dojo.byId("fbDiv").style.display = "none";
				checkLikes( data['id'] );
				//
				//alert(data);

				/*
				Limpiamos el arreglo global de valores y borramos lo que est� en los productos.
				*/
				for(var j=0; j<num_radios; j++)
				{
					
					dojo.byId("rad_" + j).innerHTML = '';
					dojo.byId("nom_" + j).innerHTML = '';
					dojo.byId("prec_" + j).innerHTML = '';
					//precios[j] = 0;
					
				}
				
				//dojo.byId("producto_0").innerHTML = '';
				
				/*
				Limpiamos los divs de detalles del producto.
				Seleccionamos el primer elemento del combobox.
				Desactivamos el checkbox de florero
				*/
				dojo.byId("precioTotal").innerHTML = "&nbsp;";
				dojo.byId("precioTotal").innerHTML = "0";
				
				dojo.byId("cmbCantidad").value = 1;
				dojo.byId("florerosHeader").innerHTML = "";
				
				//dojo.byId( "cmbCantidad" )[0].selected = true;
	
				for (var m=0; m < num_floreros_opcionales; m++)
				{
					closePopUp('floreroOpcional' + m );
					closePopUp('precioArregloOpcional' + m );
					dojo.byId('msgArregloOpcional' + m ).innerHTML = "";
					dojo.byId("chkFlorero" + m).checked = false;
					dojo.byId("hidIdFlorero" + m).value = "";
				}
				//setVisible( 'floreroOpcional',1 );
				
				//alert( data['arreglo_opcional'] );
				if( data['arreglo_opcional'].length > 0)
				{
					dojo.byId("florerosHeader").innerHTML = "Opcionales disponibles:";

					for ( m in data.arreglo_opcional )
					{
						preciosAO_orig[''][m] = data.arreglo_opcional[m].precio;
						
						if (data.arreglo_opcional[m].precio_desc != '')
						{
							data.arreglo_opcional[m].precio = data.arreglo_opcional[m].precio_desc;
						}
						
						setVisible( 'floreroOpcional' + m );
						setVisible( 'precioArregloOpcional' + m );
						//msgArregloOpcional
						dojo.byId('msgArregloOpcional' + m).innerHTML = "<span class=\"texto\">" + data.arreglo_opcional[m].nombre + "</span>";
						dojo.byId('precioArregloOpcional' + m).innerHTML = "<span class=\"preciosdetalleseleccion\">$ " + data.arreglo_opcional[m].precio + "</span> <span><a class=\"footerunderline\" href=\"javascript:initFlorero("+data.arreglo_opcional[m].id+", "+data.arreglo_opcional[m].clave+", 1)\">ver</a></span>";
						dojo.byId('precioArregloOpcionalOrig' + m).innerHTML = "<span class=\"detalle_preciotache\">" + ( data.arreglo_opcional[m].precio_desc != '' ? ("$ " + preciosAO_orig[''][m]) : '' ) + "</span>";
						dojo.byId('chkFlorero' + m).value = data.arreglo_opcional[m].precio;
						dojo.byId('hidIdFlorero' + m).value = data.arreglo_opcional[m].idAO;
						//chkFlorero

						preciosAO[''][m] = data.arreglo_opcional[m].precio;
						nombresAO[''][m] = data.arreglo_opcional[m].nombre;
						idsProdAO[''][m] = data.arreglo_opcional[m].id;
						clavesAO[''][m] = data.arreglo_opcional[m].clave;
					}
					
				}
				
				//closePopUp('floreroOpcional');
				//dojo.byId("chkFlorero").disabled = true;

				dojo.byId("nombreProducto").innerHTML = "";
				dojo.byId("imgDet").innerHTML = "";

				//alert(0);
				/*
				Asigmanos el nombre del producto,id y su imagen. 
				*/
				dojo.byId("nombreProducto").innerHTML = data['nombre'];
				dojo.byId("imgDet").innerHTML = "<img id=\"imgPopUp\" src=\"" + findBasePath() + "/images/productos/" + data['imagen_med'] + "\" width=\"360\" height=\"355\" border=\"0\" />";
				dojo.byId("imgNom").innerHTML = data['nombre_imagen'];
				dojo.byId("id_p").value = data['id'];
				
				dojo.byId("id_pp1").value = data['id'];
				
				
				dojo.byId("imgZoom").src = findBasePath() + "/images/productos/" + data['imagen_gde'];

				/*
				Creamos unas variables para seleccionar por default el primer producto.
				*/
				var seleccionar = 0;
				var seleccionado = "";
				//alert(1);
				
				var precio_original = 0;

				for(var i in data.datos)
				{
					precios_orig[''][i] = data.datos[i].precio;
					
					if (data.datos[i].precio_desc != '')
					{
						data.datos[i].precio = data.datos[i].precio_desc;
					}
					
					seleccionar = (data.datos[i].clave == data.tamanio_inicial ? 0 : 1 );

					seleccionado = (seleccionar == 0)?"checked":"";
					/*
					Agregamos los radio buttons con sus atributos de onClick
					*/
					dojo.byId("rad_" + i).innerHTML = "<input type=\"radio\" "+seleccionado+" onClick=\"actualizaRenglon(" + i + ")\" id=\"tamProd"+i+"\" name=\"tamProd\" value=\""+data.datos[i].clave+"\" />";
					
					//alert( data.datos[i].nombre );
					if (seleccionar == 0)
					{
						checkedComboBox[''] = i;
						dojo.byId("nom_" + i).innerHTML = "<div class=\"detalle_over_red\">" + data.datos[i].nombre + "</div>";
						
						dojo.byId("prec_" + i).innerHTML = "<div class=\"cerounoochocientos\">$ " + data.datos[i].precio + "</div>";
					}
					else
					{
						dojo.byId("nom_" + i).innerHTML = "<div class=\"texto\">" + data.datos[i].nombre + "</div>";
						
						dojo.byId("prec_" + i).innerHTML = "<div class=\"preciosdetalleseleccion\">$ " + data.datos[i].precio + "</div>";
					}
					dojo.byId("prec_orig_" + i).innerHTML = "<span class=\"detalle_preciotache\">" + ( data.datos[i].precio_desc != '' ? ("$ " + precios_orig[''][i]) : '' ) + "</span>";
					
					//alert( data.datos[i].desc );
					//dojo.byId("producto_" + i).innerHTML = "<td><input type=\"radio\" "+seleccionado+" onClick=\"actualizaPrecioPopUp(" + data.datos[i].precio + ","+i+")\" id=\"tamProd"+i+"\" name=\"tamProd\" value=\""+data.datos[i].clave+"\" /></td><td class=\"texto\">" + data.datos[i].nombre + "</td><td class=\"preciosdetalleseleccion\">$ " + data.datos[i].precio +"</td>";
					//dojo.byId("producto_" + i).innerHTML = "<td><input name=\"radio\" type=\"radio\" id=\"radio6\" value=\"radio\" /></td><td class=\"texto\">Radiant Bouquete (40 rosas)</td><td class=\"preciosdetalleseleccion\">$599</td>";
					precios[''][i] = data.datos[i].precio; //Asignamos los precios al arreglo global de precios
					nombres[''][i] = data.datos[i].nombre; //Asignamos los precios al arreglo global de precios

					if(seleccionar == 0)
					{
						
						actualizaPrecioPopUp(data.datos[i].precio,i); //Actualizamos el precio inicial del popup.

					}
					
				}

				var desde_tag = "";
				var tache_original = "";
				
				for(n=0; n<num_radios; n++  )
				{
					
					if( precios[''][n] != undefined)
					{
						if (precios[''][n+1] != undefined)
						{
							desde_tag = " desde";
						}
						
						if (precios_orig[''][n] != precios[''][n])
						{
							desde_tag = "ahora" + desde_tag;
							tache_original = "<br><span class=\"detalle_preciotache\">$" + precios_orig[''][n] + "</span>";
						}
						
						dojo.byId("apDiv2").innerHTML = "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\">" + 
														"<tr><td align=\"right\" valign=\"bottom\" class=\"footerlines\"><div style=\"position:relative;top:-4px;white-space:nowrap;\">" + desde_tag + tache_original + "</div></td><td align=\"left\" valign=\"bottom\" class=\"detalle_preciored\">$" + precios[''][n] + "</td></tr>" +
														"<tr><td align=\"right\" colspan=\"2\"><div class=\"detalle_over_red\" style=\"position:relative;top:-6px;font-weight:normal;\">envío gratis*</div></td></tr>" +
														"</table>"; 
														
						//alert(data.datos[n].desc);
						dojo.byId("descripcionProducto").innerHTML = data.datos[n].desc; 
						break;
						//alert(precios[n]);
						
					}
					
				}
				dojo.byId("fbFrame").src = data['fbSrc'];
				
				changeWidthHeightImage( "imgZoom", "650", "650" );

				setVisible('layer1',valor); //mostramos el popoup
				
			}
		}
	});
}

function checkLikes( valor, divId )
{
	if (divId == undefined) {
		divId = "fbDiv";
	}
	dojo.xhrGet({
		url: findBasePath() + "/dojo_php_imp/get_num_likes_producto.php?prod=" + valor,
		handleAs: "text",
		handle: function(data,args){
			if (data-0 > 0) {
				// Si tiene "Me gusta" o recomendaciones, lo mostramos
				dojo.byId( divId ).style.display = "";
			}
		}
	});
}

function initFlorero(valor, clave, num_div)
{
	showLoading( 'imgPopUpFlorero' + num_div, 54, 55 );
	
	dojo.xhrGet({
		url: findBasePath() + "/dojo_php_imp/get_detalles_producto.php?prod=" + valor,
		handleAs: "json",
		handle: function(data,args){
			if(typeof data == "error"){
				console.warn("error!");
				console.log(args);
				//alert(1);
			}else{
				//
				//alert(data);

				for(var i in data.datos)
				{
					if( data.datos[i].clave == clave )
					{
						dojo.byId("nombreProductoFlorero" + num_div).innerHTML = data.datos[i].nombre;
						dojo.byId("imgDetFlorero" + num_div).innerHTML = "<img id=\"imgPopUpFlorero" + num_div + "\" src=\"" + findBasePath() + "/images/productos/" + data['imagen_med'] + "\" width=\"360\" height=\"355\" border=\"0\" />";
		
						dojo.byId("descripcionProductoFlorero" + num_div).innerHTML = data.datos[i].desc; 
						//alert(precios[n]);
						
						// Mostramos el porpup
						showPopupBanner('', 'popupDetalleOpcional' + num_div, 1, 0, 0);
						//setVisible('detalle_opcional1',valor); //mostramos el popoup
					}
				}
			}
		}
	});
}

function actualizaRenglonesFlorerosBase( sufix )
{
	actualizaPrecioChkBoxBase( sufix );

	id_ver = sufix == '' ? 1 : sufix;
	
	for(var m=0; m<num_floreros_opcionales; m++)
	{
		if (dojo.byId('chkFlorero' + m + sufix) != undefined)
		{
			if (dojo.byId('chkFlorero' + m + sufix).checked)
			{
				dojo.byId('msgArregloOpcional' + m + sufix).innerHTML = "<span class=\"detalle_over_red\">" + nombresAO[sufix][m]+ "</span>";
				dojo.byId('precioArregloOpcional' + m + sufix).innerHTML = "<span class=\"cerounoochocientos\">$ " + preciosAO[sufix][m] + "</span> <span><a class=\"footerunderline\" href=\"javascript:initFlorero("+idsProdAO[sufix][m]+", "+clavesAO[sufix][m]+", '" + id_ver + "')\">ver</a></span>";
			}
			else
			{
				if (nombresAO[sufix][m] != undefined && nombresAO[sufix][m] != "")
				{
					dojo.byId('msgArregloOpcional' + m + sufix).innerHTML = "<span class=\"texto\">" + nombresAO[sufix][m]+ "</span>";
					dojo.byId('precioArregloOpcional' + m + sufix).innerHTML = "<span class=\"preciosdetalleseleccion\">$ " + preciosAO[sufix][m] + "</span> <span><a class=\"footerunderline\" href=\"javascript:initFlorero("+idsProdAO[sufix][m]+", "+clavesAO[sufix][m]+", '" + id_ver + "')\">ver</a></span>";
				}
			}
		}
	}
}

function actualizaRenglonesFloreros()
{
	actualizaRenglonesFlorerosBase('');
}

function actualizaRenglonBase(index, sufix)
{
	actualizaPrecioBase(precios[sufix][index], index, sufix);
	
	for(var j=0; j<num_radios; j++)
	{
		if (dojo.byId("rad_" + j + sufix) != undefined && dojo.byId("rad_" + j + sufix).innerHTML != '')
		{
			dojo.byId("nom_" + j + sufix).innerHTML = "<div class=\"texto\">" + nombres[sufix][j] + "</div>";
			
			dojo.byId("prec_" + j + sufix).innerHTML = "<div class=\"preciosdetalleseleccion\">$ " + precios[sufix][j] + "</div>";
		}
	}
	
	dojo.byId("nom_" + index + sufix).innerHTML = "<div class=\"detalle_over_red\">" + nombres[sufix][index] + "</div>";
	
	dojo.byId("prec_" + index + sufix).innerHTML = "<div class=\"cerounoochocientos\">$ " + precios[sufix][index] + "</div>";

}

function actualizaRenglon(index)
{
	actualizaRenglonBase(index, '');
}

function cerrarTodoPopUp()
{
	for (var m=0; m < num_floreros_opcionales; m++)
	{
		closePopUp('floreroOpcional' + m);
		closePopUp('precioArregloOpcional' + m);
	}
	closePopUp('recomienda1');
	closePopUp('zoom');
}


function aCar(data,ioArgs) {
	//alert(data);
	//alert(redirect);
	
	switch( redirect )
	{
	
		case 0:
			
		break;
			
		case 1:
			
			window.location = findBasePath() + "/pages/carrito.php";
			return;
			
		break;
		
		case 2:
			
			window.location = findBasePath() + "/busqueda.php";
			return;
			
		break;
	
	}
	
	/*if(redirect)
	{
		
		window.location = "./pages/carrito.php";
		return;
		
	}*/
		
	
	actualizaNumeroArticulosCarrito( data[1] );
	closePopUp('layer1');
	cerrarTodoPopUp();
}

 function errorFunction(data, ioArgs) {
    //alert(data[0]);
    console.log(data);
 }

function carBase( rd, frm_sufix )
{
	valid_num = dojo.byId('cmbCantidad' + frm_sufix).value/1;
	
	if( isNaN( valid_num ) )
	{
		
		alert("Verifique que la cantidad sea un numero.");
		return;
		
	}
	
	if( ( valid_num  < 1 ) )
	{
		
		alert("Verifique que la cantidad sea un mayor a 1.");
		return;
		
	}

	hidLogCar = dojo.byId('logCar' + frm_sufix);
	
	if (frm_sufix == '')
	{
		if (rd == 0)
		{
			hidLogCar.value = 2;
		}
		else if (rd == 1)
		{
			hidLogCar.value = 1;
		}
	}
	else if (frm_sufix == 'Main')
	{
		if (rd == 0)
		{
			hidLogCar.value = 4;
		}
		else if (rd == 1)
		{
			hidLogCar.value = 3;
		}
	}

	
	redirect = rd;
	dojo.xhrPost({
        url: findBasePath() + '/dojo_php_imp/agrega_carrito.php',
        handleAs: "json",
        load: aCar,
        error: errorFunction,
        form: 'frmCar' + frm_sufix
   });
}
 
function car ( rd )
{
	carBase( rd, '');
};

function getNumProductosCarrito(){
	
	url_actual = location.href.match(/[^?]+/);
	
	url_index = location.protocol + '//' + findBaseUrl() + '/';
	
	fg_log = (url_actual== url_index || url_actual == url_index + 'index.php');

	if (fg_log)
	{
		re_hostname = new RegExp(location.hostname);
		fg_entrada = !re_hostname.test(document.referrer);
		
		if (fg_entrada)
		{
			get_csrc = location.href.match(/csrc=[^&]*/);
			entrada_param = (get_csrc ? get_csrc : 'csrc=') + '';
			
			entrada_param += '&url=' + encodeURIComponent(document.referrer);
		}
	}
	
	get_param = fg_log ? 'log=1' + (fg_entrada ? '&' + entrada_param : '') : '';
	
	dojo.xhrGet({
		url: findBasePath()+ "/dojo_php_imp/get_num_productos_carrito.php?" + get_param,
		handleAs: "json",
		handle: function(data,args){
		//alert(data);
			if(typeof data == "error"){
				console.warn("error!");
				console.error(args);
				console.log(data);
				alert(data);
			}else{
				
				//alert( data[0] + data[1] );
				//alert( data[1] );
				
				actualizaNumeroArticulosCarrito( data[0] );
				dojo.byId('usrLogged').innerHTML = "<span class=\"footer\">Bienvenido </span> <span class=\"footer\" style=\"font-weight:bold;\">"+ data[1] +"</span>";
				if( data[1] != "" )
					dojo.byId('divLogout').innerHTML = "<a href=\"http://"+ findBaseUrl() +"/logout.php\"><img src=\"" + findBasePath() + "/images/btn_salirtop.gif\" width=\"35\" height=\"12\" border=\"0\" /></a>";
				else
					dojo.byId('divLogout').innerHTML = "<a href=\"http://"+ findBaseUrl() +"/pages/micuenta.php\"><img src=\"" + findBasePath() + "/images/btn_entrartop.gif\" width=\"45\" height=\"12\" border=\"0\" /></a>";

			}
		}
		
	});
	//alert(2);
}

function recomiendaArreglo(num_form){
	
	//alert(1);
	num_recomienda_arreglo = num_form;

	dojo.xhrPost({
		url: findBasePath() + "/dojo_php_imp/recommend_arreglo.php",
		handleAs: "text",
		form: 'frmRecomiendaArreglo' + num_recomienda_arreglo,
		handle: function(data,args){
		//alert(data);
		//console.log(data);
			if(typeof data == "error"){
				console.warn("error!");
				console.error(args);
				console.log(data);
				//alert(data);
				//console.log(data);
			}else{
				
				data = replaceSpecialChars( data );
				if( data != '1' )
				{
					
					alert( data );
					return;
					
				}
				
				msg = "Su recomendaciooon ha sido enviada. \nGracias.";
				msg = replaceSpecialChars( msg );
				
				alert( msg );
				
				dojo.byId('txtNombreDeRecomiendaDet'+ num_recomienda_arreglo).value = "";
				dojo.byId('txtCorreoDeRecomiendaDet'+ num_recomienda_arreglo).value = "e-mail";
				dojo.byId('txtNombreParaRecomiendaDet'+ num_recomienda_arreglo).value = "";
				dojo.byId('txtCorreoRecomiendaDet'+ num_recomienda_arreglo).value = "e-mail";
				
				closePopUp('recomienda' + num_recomienda_arreglo);
				//actualizaNumeroArticulosCarrito( data[0] );
				//dojo.byId('usrLogged').innerHTML = "<span class=\"footer\">Bienvenido :</span> <span class=\"footer\">"+ data[1] +"</span>";
				
				

			}
		}
		
	});
	//alert(2);
}

function showLoading( img_id, w,h )
{
	
	dojo.byId( img_id ).src = findBasePath() + "/images/cargando.gif";
	dojo.byId( img_id ).width = w;
	dojo.byId( img_id ).height = h;
	
}

function showLoadingNoResize( img_id2 )
{
	
	dojo.byId( img_id2 ).src = findBasePath() + "/images/cargando.gif";
	
}

function changeWidthHeightImage( img_idH, wi, he )
{
	
	dojo.byId( img_idH ).width = wi;
	dojo.byId( img_idH ).height = he;
	
}

function init_arrays_detalle( sufix )
{
	
	precios[sufix] = new Array(num_radios);
	nombres[sufix] = new Array(num_radios);
	preciosAO[sufix] = new Array(num_floreros_opcionales);
	nombresAO[sufix] = new Array(num_floreros_opcionales);
	idsProdAO[sufix] = new Array(num_floreros_opcionales);
	clavesAO[sufix] = new Array(num_floreros_opcionales);
	checkedComboBox[sufix] = dojo.byId("hidSelected" + sufix).value;

	for(var j=0; j<num_radios; j++)
	{
		if (dojo.byId("rad_" + j + sufix) != undefined && dojo.byId("rad_" + j + sufix).innerHTML != '')
		{
			nombres[sufix][j] = dojo.byId("hidNom" + j + sufix).value;
			precios[sufix][j] = dojo.byId("hidPrec" + j + sufix).value;
		}
	}
	for(var m=0; m<num_floreros_opcionales; m++)
	{
		if (dojo.byId("floreroOpcional" + m + sufix) != undefined && dojo.byId("floreroOpcional" + m + sufix).innerHTML != '')
		{
			preciosAO[sufix][m] = dojo.byId("hidPrecFlorero" + m + sufix).value;
			nombresAO[sufix][m] = dojo.byId("hidNomFlorero" + m + sufix).value;
			idsProdAO[sufix][m] = dojo.byId("hidIdProdFlorero" + m + sufix).value;
			clavesAO[sufix][m] = dojo.byId("hidClaveFlorero" + m + sufix).value;
		}
	}

}

function callLogCat ( cat, log )
{
	dojo.xhrGet({
		url: findBasePath() + "/dojo_php_imp/direct_log_paginas.php?log=" + log + "&cat=" + cat,
		handleAs: "text",
		handle: function(data,args){
			if(typeof data == "error"){
				console.warn("error!");
				console.log(args);
				//alert(1);
			}else{
				// Nada que hacer
			}
			window.location = findBasePath() + "/busqueda.php?c=" + cat;
		}
	});
}

function searchCat ( cat )
{
	callLogCat ( cat, 1 );
}

function zoomProd ( sufix )
{
	log = 0;
	
	if (sufix ==  '')
	{
		log = 2;
	}
	else if (sufix == 'Main')
	{
		log = 3;
	}
	
	if (log != 0)
	{
		prod = dojo.byId( 'id_p' + sufix ).value;
		
		dojo.xhrGet({
			url: findBasePath() + "/dojo_php_imp/direct_log_paginas.php?log=" + log + "&prod=" + prod,
			handleAs: "text",
			handle: function(data,args){
			}
		});

		setVisible( 'zoom' + sufix );

	}
	
}
