// 
$(document).ready(function() {
		   
	// cambia style a position absolute solo si javascript esta activado
	if(validado){
		clase_midoce = "jactive";
	}else{
		clase_midoce = "unactive";	
	}

	$("#midoce").addClass(clase_midoce);
	// esconder ULs inactivos
	$("#midoce ul ul ul:not(:first)").hide();
	// marcar categoria activa
	$("#midoce ul li ul li:first").addClass("unactive");
	// on click
	$("#midoce ul li ul li.subcat").click(function() {
				if(!$(this).hasClass("unactive")) {
					$(this).parent().find(".unactive").removeClass("unactive");
					$(this).addClass("unactive");
	// abrir/cerrar
					$(this).parent().find("ul:visible").slideUp(300);
					$(this).find("ul").slideDown(300,calc_midoce_height);
			//setTimeout('calc_midoce_height()', 400);
				}
	return false;
	});
	
	// Abrir primera categoria del segundo tab, marcar 2ndo tab como activo
	$("#midoce #mdm ul ul:first").show();
	$("#midoce #mdm ul li:first").addClass("unactive");
	$("#midoce ul li.tabs:first .tab").addClass("activo");
	// Creacion de tabs
	$("#midoce ul ul.bmenu:not(:first)").hide();
	// cambiar de tab on click
	$("#midoce ul li.tabs").click(function() {
		$("#midoce ul ul.bmenu:visible").hide();
		$(this).find("ul.bmenu").show();
		$("#midoce ul li.tabs span.tab").removeClass("activo");
		$(this).find("span.tab").addClass("activo");

		setTimeout('calc_midoce_height()', 400);
		return false;
	});
	
	if(!validado){
		$('#mdm').hide();
	}

	
	setTimeout('calc_midoce_height()', 400);

	// Initialize history plugin.
	// The callback is called at once by present location.hash. 
	$.historyInit(pageload);
	inicializa_history();


	});


function loading(capa){
	document.getElementById(capa).innerHTML = '<img class="loadimg" src="imgs/rotate.gif" alt="loading &hellip;" />';
}
function loading_login(capa){
	document.getElementById(capa).innerHTML = '<img class="loadimg" src="imgs/rotate_black.gif" alt="loading &hellip;" />';
}

// carrega les dades obtingudes a la capa indicada
function cargaDadesCapa(dades,capa){
	//$('#'+capa).hide();
	document.getElementById(capa).innerHTML = dades;
	//$('#'+capa).fadeIn('slow');

}




// carrega les dades obtingudes a la capa indicada
function cargaMutipleDadesCapaInicio(dades,capa){
	//$('#'+capa).hide();
	var codigo_origen = document.getElementById(capa).innerHTML;
	document.getElementById(capa).innerHTML = dades + codigo_origen;
	// $(obj2).fadeIn('fast',function(){$(obj2).remove();});
	//$('#'+capa).fadeIn('slow');

}

// carrega les dades obtingudes a la capa indicada
function cargaMutipleDadesCapa(dades,capa){
	//$('#'+capa).hide();
	document.getElementById(capa).innerHTML += dades;
	//$('#'+capa).fadeIn('slow');

}
function compruebaLoginado(){
	$.ajax({
	   type: "POST",
	   url: "secciones/comunes/loginado.php",
	   data: "ajax=1",
	   success: function(msg){
		  if(msg=="ok"){
			usuario_validado = true;
			
		 	 //$("#midoce").addClass('jactive');
			 	getHome();
			recargaMenuMy12();
		


		  }else{
			  usuario_validado = false;  
			  $("#midoce").removeClass();
		 	  $("#midoce").addClass('unactive');
		  }
	   }
	 });
}


//Controla el fluxe de dades del login entre client i servidor
function login_proces_estats(estat_desti, op2, op3){
	//alert("ajax=1&OP_1="+estat_desti+"&OP_2="+op2+"&OP_3="+op3);
	
	loading_login('content_login');
	$.ajax({
	   type: "POST",
	   url: "secciones/comunes/login.php",
	   data: "ajax=1&OP_1="+estat_desti+"&OP_2="+op2+"&OP_3="+op3,
	   success: function(msg){
	
		  cargaDadesCapa(msg,'content_login');
		  actualizaCestaCabecera();
		  compruebaLoginado();
		  if(estat_desti==7){
			 document.location = path_absoluto;
			}
		 
	   }
	 });	
}



// HOME ........................................................................................................................................................

// obté el topten per obrir la home
function getHome() {
	activaSeccionMenu(0);
	loading('container_general');
	$.ajax({
	   type: "POST",
	   url: "secciones/comunes_contenido/topten.php",
	   data: "ajax=1&OP_1=-1",
	   success: function(msg){
		cargaDadesCapa(msg,'container_general');
		inicializa_history()
	   }
	 });
}

// MODIFICACIO DE PASSWORD ........................................................................................................................................................
function modificarPass() {
	activaSeccionMenu(99);
	loading('container_general');
	$.ajax({
	   type: "POST",
	   url: "secciones/modifica/password.php",
	   data: "ajax=1&OP_1=view",
	   success: function(msg){
		  cargaDadesCapa(msg,'container_general');
	   }
	 });
}
// VALIDACIÓN DE FORMULARIOS
function oculta_valida_password(){

		 $("#no_pass").fadeOut("slow");
		 $("#no_conf_pass").fadeOut("slow");

 }
 

function valida_password(){
	
		oculta_valida_password();
		
		pass = document.getElementById("pass").value;
		conf_pass = document.getElementById("conf_pass").value;
		
		validado = true;
		if(pass==''){
				validado=false;
				$('#no_pass').fadeIn('slow');
		}
		if(pass!=conf_pass){
				validado=false;
				$('#no_conf_pass').fadeIn('slow');
		}
		
		if(validado){
				loading('container_general');	
				$.ajax({
				   type: "POST",
				   url: "secciones/modifica/password.php",
				   data: "ajax=1&OP_1=submit&OP_2="+pass,
				   success: function(msg){
					  cargaDadesCapa(msg,'container_general');
				   }
				 });		
		}

}

// MODIFICACIO DE DADES PERSONALS (MI CUENTA) ........................................................................................................................................................

// obté el formulari de modificació de dades
function getModify() {
	activaSeccionMenu(99);
	loading('container_general');
	$.ajax({
	   type: "POST",
	   url: "secciones/modifica/modifica.php",
	   data: "ajax=1&OP_1=view",
	   success: function(msg){
		  cargaDadesCapa(msg,'container_general');
	   }
	 });
}

//VALIDACIÓN I ENVIAMENT DE FORMULARI DE MODIFICACIO DE DADES
function oculta_valida_modifica(){
		 $("#no_nombre").fadeOut("slow");
		 $("#no_mail").fadeOut("slow");
		 $("#no_pass").fadeOut("slow");
		 $("#no_pais").fadeOut("slow");
		 $("#no_conf_pass").fadeOut("slow");
		 $("#no_acepto").fadeOut("slow");
 }
 
function envia_datos_modificar(nombre,mail,pais,apellidos,direccion,cp,poblacion,provincia,telefono,newsletter,comentario){
	
		var nombre		=		nombre.htmlEntities();
		var apellidos	=		apellidos.htmlEntities();
		var direccion	=		direccion.htmlEntities();
		var cp			=		cp.htmlEntities();
		var poblacion	=		poblacion.htmlEntities();
		var telefono	=		telefono.htmlEntities();
		var comentario	=		comentario.htmlEntities();
		
		loading('container_general');
		$.ajax({
		   type: "POST",
		   url: "secciones/modifica/modifica.php",
		   data: "ajax=1&OP_1=submit&"+
		   "OP_2="+nombre+
		   "&OP_3="+mail+
		   "&OP_5="+pais+
		   "&OP_6="+apellidos+
		   "&OP_7="+direccion+
		   "&OP_8="+cp+
		   "&OP_9="+poblacion+
		   "&OP_10="+provincia+
		   "&OP_11="+telefono+
		   "&OP_12="+newsletter+
		   "&OP_13="+comentario,
		   success: function(msg){
			  cargaDadesCapa(msg,'container_general');
		   }
		 });

} 
 
function validaModifica(do_upload){
	
		oculta_valida_modifica();
		comentario 	= "";
		
		nombre 		= document.getElementById("nombre").value;
		mail 		= document.getElementById("mail").value;
		pais 		= document.getElementById("pais").options[document.getElementById("pais").selectedIndex].value;
		apellidos 	= document.getElementById("apellidos").value;
		direccion 	= document.getElementById("direccion").value;
		cp 			= document.getElementById("cp").value;
		poblacion 	= document.getElementById("poblacion").value;
		provincia 	= document.getElementById("provincia").value;
		telefono 	= document.getElementById("telefono").value;
		//typeUser 	= document.getElementById("typeUser").value;
		
		//	Los usuarios tipo Chart tiene un campo de texto "comentario" que el resto de usuarios no tiene.
		comentario 	= document.getElementById("comentario").value;
		
		if(document.getElementById("newsletter").checked==true){
			newsletter= '1';	
		}else{
			newsletter= '0';	
		}
		
		if(do_upload){
			hay_imagen = (document.getElementById("fileToUpload").value!='');
		}else{
			hay_imagen = false;
		}
		
		validado = true;
		if(nombre==''){
				validado=false;
				$('#no_nombre').fadeIn('slow');
		}
		if(!isValidEmail(mail)){
				validado=false;
				$('#no_mail').fadeIn('slow');
		}
		if(pais==''){
				validado=false;
				$('#no_pais').fadeIn('slow');
		}

		
		if(validado){
			
				if((do_upload)&&(hay_imagen)){			
			
						//aqui es donde enviaremos la imagen y 
						//si ha ido bien enviaremos despues todos los datos
								
							$.ajaxFileUpload
							(
								{
									url:'secciones/modifica/doajaxfileupload.php',
									secureuri:false,
									fileElementId:'fileToUpload',
									dataType: 'json',
									success: function (data, status)
									{
										if(typeof(data.error) != 'undefined')
										{
											if(data.error != '')
											{
												alert(data.error);
											}else
											{
												//alert(data.msg);
												envia_datos_modificar(nombre,mail,pais,apellidos,direccion,cp,poblacion,provincia,telefono,newsletter, comentario);
											}
										}
									},
									error: function (data, status, e)
									{
										alert(e);
									}
								}
							)					
							return false;	
					
				}else{
					
						//no hay que hacer upload, por lo que solo enviamos datos
							envia_datos_modificar(nombre,mail,pais,apellidos,direccion,cp,poblacion,provincia,telefono,newsletter,comentario);
				
				}

				
		}
		
	
	
	
}


function isValidEmail(str) {
   return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
}


	
	

// REGISTRE ........................................................................................................................................................

// obté el formulari de registre ó força el seu procés
function getRegistre() {
	activaSeccionMenu(99);
	loading('container_general');
	$.ajax({
	   type: "POST",
	   url: "secciones/registro/registro.php",
	   data: "ajax=1&OP_1=-1",
	   success: function(msg){
		  cargaDadesCapa(msg,'container_general');
	   }
	 });
}


// VALIDACIÓN DE FORMULARIOS
function oculta_valida_registro(){
		 $("#no_nombre").fadeOut("slow");
		 $("#no_mail").fadeOut("slow");
		 $("#no_pass").fadeOut("slow");
		 $("#no_pais").fadeOut("slow");
		 $("#no_conf_pass").fadeOut("slow");
		 $("#no_acepto").fadeOut("slow");
 }
 

function valida_registro(){
	
		oculta_valida_registro();
	
		nombre 		= document.getElementById("nombre").value;
		mail 		= document.getElementById("mail").value;
		pass 		= document.getElementById("pass1").value;
		conf_pass 	= document.getElementById("conf_pass").value;
		pais 		= document.getElementById("pais").options[document.getElementById("pais").selectedIndex].value;
		apellidos 	= document.getElementById("apellidos").value;
		direccion 	= document.getElementById("direccion").value;
		cp 			= document.getElementById("cp").value;
		poblacion 	= document.getElementById("poblacion").value;
		provincia 	= document.getElementById("provincia").value;
		telefono 	= document.getElementById("telefono").value;
		
		if(document.getElementById("newsletter").checked==true){
			newsletter= '1';	
		}else{
			newsletter= '0';	
		}
		
		validado = true;
		if(nombre==''){
				validado=false;
				$('#no_nombre').fadeIn('slow');
		}
		if(!isValidEmail(mail)){
				validado=false;
				$('#no_mail').fadeIn('slow');
		}
		if(pass==''){
				validado=false;
				$('#no_pass').fadeIn('slow');
		}
		if(pais==''){
				validado=false;
				$('#no_pais').fadeIn('slow');
		}
		if(pass!=conf_pass){
				validado=false;
				$('#no_conf_pass').fadeIn('slow');
		}
		if(document.getElementById("acepto").checked==false){
				validado=false;
				$('#no_acepto').fadeIn('slow');
		}
		nombre 		= 	nombre.htmlEntities();
		apellidos 	=	apellidos.htmlEntities();
		direccion 	=	direccion.htmlEntities();
		cp			=	cp.htmlEntities();
		poblacion	=	poblacion.htmlEntities();
		telefono	=	telefono.htmlEntities();
		
		if(validado){
				loading('container_general');	
				$.ajax({
				   type: "POST",
				   url: "secciones/registro/registro.php",
				   data: "ajax=1&OP_1=submit"+
				   "&OP_2="+nombre+
				   "&OP_3="+mail+
				   "&OP_4="+pass+
				   "&OP_5="+pais+
				   "&OP_6="+apellidos+
				   "&OP_7="+direccion+
				   "&OP_8="+cp+
				   "&OP_9="+poblacion+
				   "&OP_10="+provincia+
				   "&OP_11="+telefono+
				   "&OP_12="+newsletter,
				   success: function(msg){
					  //alert(msg);
					  
					  cargaDadesCapa(msg,'container_general');
				   }
				 });		
		}

}

function activaSeccionMenu(seccio, id){
	
	//	Lógica para mostrar los banners superiores
	//	Aparecen en las secciones: home, géneros.
	switch(seccio){
		
		case -1:
			//	inicialización. Carga la home
			$('#recomendaciones').show();
			$('#embedBanner').show();
			
			recargaBanner(seccio);
		break;		
		case 0:
			$('#recomendaciones').show();
			$('#embedBanner').show();
			
			recargaBanner(seccio);
		break;
		case 3:
			//	Solo se muestran en el caso de ser un género concreto
			if(id!=null){
				compruebaNumeroBanners(seccio, id);
			}else{
				$('#recomendaciones').hide();
				$('#embedBanner').hide();
			}
		break;
		default:
			$('#recomendaciones').hide();
			$('#embedBanner').hide();
		break;
		
	}
	
	for(i=0;i<10;i++){
		if(i!=4){
			$('#link_'+i).removeClass();
		}
	}	
		//	El valor 99 es el de las secciones que no aparecen en el menú principal y por tanto no las marcamos en el. Ej. FAQ, Mis compras
		if(seccio!=-1 && seccio!=99){
			$('#link_'+seccio).addClass('selec');	
		}

//document.title = seccio;
}



// ARTISTES + SEGELLS + CHARTS ........................................................................................................................................................

// obté la llista d'artistes / segells
function getLlista_Artista_Segell_Chart(seccio) {
	
	//seccio=1: artistes
	//seccio=2: segells
	//seccio=6: charts
	document.getElementById('cerca').value ="";
	switch(seccio){
		case 1:
			activaSeccionMenu(1);
		break;
		case 2:
			activaSeccionMenu(2);
		break;
		case 6:
			activaSeccionMenu(5);
		break;
		
	}
	
	loading('container_general');
	
	$.ajax({
	   type: "POST",
	   url: "secciones/comunes_contenido/destacados.php",
	   data: "ajax=1&OP_1="+seccio+"&OP_2=-1",
	   success: function(msg){
		   //cargaDadesCapa(msg,'container_general');
		
			$.ajax({
			   type: "POST",
			   url: "secciones/comunes_contenido/paginacion.php",
			   data: "ajax=1&OP_1="+seccio,
			   success: function(msg2){
				   cargaDadesCapa(msg + msg2,'container_general');
					inicializa_history();
			   }
			 });
	   }
	 });
}


// obté el detall d'un artista / segell
function getDetall_Artista_Segell_Chart(seccio, id) {

	switch(seccio){
		case 1:
			activaSeccionMenu(1);
		break;
		case 2:
			activaSeccionMenu(2);
		break;
		case 6:
			activaSeccionMenu(5);
		break;
		
	}
	//seccio=1: artistes
	//seccio=2: segells
	//seccio=6: charts
	loading('container_general');
	//anadeHistory(obj);
	//artistes + segells
	if(seccio != 6){	
		$.ajax({
		   type: "POST",
		   url: "secciones/comunes_contenido/ficha.php",
		   data: "ajax=1&OP_1="+seccio+"&OP_3="+id,
		   success: function(msg){
			   //cargaDadesCapa(msg,'container_general');
				$.ajax({
				   type: "POST",
				   url: "secciones/comunes_contenido/referencias_tracks.php",
				   data: "ajax=1&OP_1="+seccio+"&OP_3="+id,
				   success: function(msg2){
					   //cargaMutipleDadesCapa(msg2,'container_general');

						$.ajax({
						   type: "POST",
						   url: "secciones/comunes_contenido/topten.php",
						   data: "ajax=1&OP_1="+seccio+"&OP_3="+id,
						   success: function(msg3){
							   //cargaMutipleDadesCapa(msg3,'container_general');
							 cargaDadesCapa(msg + msg2 + msg3,'container_general');
							 inicializa_history();
						   		
						   }
						 });
				   }
				 });
		   }
		 });
	}
			
	//charts
	else{
		$.ajax({
		   type: "POST",
		   url: "secciones/comunes_contenido/destacados.php",
		   data: "ajax=1&OP_1="+seccio+"&OP_2=1&OP_3="+id,
		   success: function(msg){
			   
			  		$.ajax({
						   type: "POST",
						   url: "secciones/comunes_contenido/topten.php",
						   data: "ajax=1&OP_1="+seccio+"&OP_3="+id,
						   success: function(msg2){
							   cargaDadesCapa(msg + msg2,'container_general');
							   inicializa_history();
									$.ajax({
									   type: "POST",
									   url: "secciones/chart/chart_utilitats.php",
									   data: "ajax=1&accion=ids_chart&idUsuario="+id,
									   success: function(msg3){
										    
											//var idTracks = new Array(msg3);
											var idTracks = msg3.split(",");
											dragTopten("sortable", id, idTracks);
										   
									   }
									 });
							   
						   }
						 });
		   }
		 });
	}
}
// obté el detall d'un artista / segell
function getDetall_Artista_Segell_Chart_Paginat(seccio, id, num_pagina, num_items,tipo,vista) {

	switch(seccio){
		case 1:
			activaSeccionMenu(1);
		break;
		case 2:
			activaSeccionMenu(2);
		break;
		case 6:
			activaSeccionMenu(5);
		break;
		
	}
	//seccio=1: artistes
	//seccio=2: segells
	//seccio=6: charts
	//seccio=3: generes
	loading('container_general');
	//anadeHistory(obj);
	//artistes + segells
	if((seccio != 6)&&(seccio!=3)){	
		$.ajax({
		   type: "POST",
		   url: "secciones/comunes_contenido/ficha.php",
		   data: "ajax=1&OP_1="+seccio+"&OP_3="+id,
		   success: function(msg){
			   //cargaDadesCapa(msg,'container_general');
				$.ajax({
				type: "POST",
				   url: "secciones/comunes_contenido/referencias_tracks.php",
				   data: "ajax=1&OP_1="+seccio+"&OP_3="+id+"&num_pagina="+num_pagina+"&num_items="+num_items+"&tipo="+tipo+"&vista="+vista,
				   success: function(msg2){
					   //cargaMutipleDadesCapa(msg2,'container_general');

						$.ajax({
							type: "POST",
						   url: "secciones/comunes_contenido/topten.php",
						   data: "ajax=1&OP_1="+seccio+"&OP_3="+id,
						   success: function(msg3){
							   //cargaMutipleDadesCapa(msg3,'container_general');
							    cargaDadesCapa(msg + msg2 + msg3,'container_general');
						   		inicializa_history();
						   }
						 });
				   }
				 });
		   }
		 });
	}
			
	//charts
	else{
		if(seccio==6){
			$.ajax({
			   type: "POST",
			   url: "secciones/comunes_contenido/destacados.php",
			   data: "ajax=1&OP_1="+seccio+"&OP_2=1&OP_3="+id,
			   success: function(msg){
				   
						$.ajax({
								type: "POST",
							   url: "secciones/comunes_contenido/topten.php",
							   data: "ajax=1&OP_1="+seccio+"&OP_3="+id,
							   success: function(msg2){
								   cargaDadesCapa(msg + msg2,'container_general');
								   inicializa_history();
										$.ajax({
										   type: "POST",
										   url: "secciones/chart/chart_utilitats.php",
										   data: "ajax=1&accion=ids_chart&idUsuario="+id,
										   success: function(msg3){
												
												//var idTracks = new Array(msg3);
												var idTracks = msg3.split(",");
												dragTopten("sortable", id, idTracks);
											   
										   }
										 });
								   
							   }
							 });
			   }
			 });
		}
		if(seccio==3){
			$.ajax({
			   type: "POST",
			   url: "secciones/generos/detalle_genero.php",
			   data: "ajax=1&OP_3="+id,
			   success: function(msg){
				 //cargaDadesCapa(msg,'container_general');
					$.ajax({
						type: "POST",
					   url: "secciones/comunes_contenido/referencias_tracks.php",
					   data: "ajax=1&OP_1=3&OP_3="+id+"&num_pagina="+num_pagina+"&num_items="+num_items+"&tipo="+tipo+"&vista="+vista,					   success: function(msg2){
						   //cargaMutipleDadesCapa(msg2,'container_general');
						
							$.ajax({
								type: "POST",
							   url: "secciones/comunes_contenido/topten.php",
							   data: "ajax=1&OP_1=3&OP_3="+id,
							   success: function(msg3){
								   //cargaMutipleDadesCapa(msg3,'container_general');
									cargaDadesCapa(msg + msg2 + msg3,'container_general');
									inicializa_history();
							   }
							 });
					   }
					 });
			   }
			 });
		}
	}
}



// obté la llista de referències-pistes d'un artista o segell 
function get_refTracks(seccio, id, cerca_tipus, cerca_seleccio) {
	
	loading('container_refTracks');
	$.ajax({
	   type: "POST",
	   url: "secciones/comunes_contenido/referencias_tracks.php",
	   data: "ajax=1&OP_1="+seccio+"&OP_3="+id+"&OP_4="+cerca_tipus+"&OP_5="+cerca_seleccio,
	   success: function(msg){
		 cargaDadesCapa(msg,'container_refTracks');
		 inicializa_history();
	   }
	 });
}
// obté la llista de referències-pistes d'un artista o segell 
function get_refTracks_Paginacio(seccio, id, cerca_tipus, cerca_seleccio,num_pagina,num_items) {
	
	loading('container_refTracks');
	$.ajax({
	   type: "POST",
	   url: "secciones/comunes_contenido/referencias_tracks.php",
	   data: "ajax=1&OP_1="+seccio+"&OP_3="+id+"&OP_4="+cerca_tipus+"&OP_5="+cerca_seleccio+"&num_pagina="+num_pagina+"&num_items="+num_items+"&tipo="+cerca_tipus+"&vista="+cerca_seleccio,
	   success: function(msg){
		 cargaDadesCapa(msg,'container_refTracks');
		 inicializa_history();
	   }
	 });
}

// GÈNERES ........................................................................................................................................................

// obté la llista de gèneres
function getLlista_Generes() {
	activaSeccionMenu(3);
	loading('container_general');
	$.ajax({
	   type: "POST",
	   url: "secciones/generos/generos.php",
	   data: "ajax=1",
	   success: function(msg){
		cargaDadesCapa(msg,'container_general');
		inicializa_history();
	
	   }
	 });
}



// obté el detall d'un gènere
function getDetall_Genere(id) {
	activaSeccionMenu(3, id);
	loading('container_general');
	$.ajax({
	   type: "POST",
	   url: "secciones/generos/detalle_genero.php",
	   data: "ajax=1&OP_3="+id,
	   success: function(msg){

			$.ajax({
				type: "POST",
			   url: "secciones/comunes_contenido/referencias_tracks.php",
			   data: "ajax=1&OP_1=3&OP_3="+id,
			   success: function(msg2){
				
					$.ajax({
						type: "POST",
					   url: "secciones/comunes_contenido/topten.php",
					   data: "ajax=1&OP_1=3&OP_3="+id,
					   success: function(msg3){
						    cargaDadesCapa(msg + msg2 + msg3,'container_general');
							inicializa_history();
					   }
					 });
			   }
			 });
			
	   }
	 });
}



// ACCESSORIS ........................................................................................................................................................

// obté la llista d'accessoris 
function getLlista_Accessoris(tipus_cerca, id_marca) {

	loading('container_general');
	$.ajax({
	   type: "POST",
	   url: "secciones/accesorios/accesorios.php",
	   data: "ajax=1&OP_2="+tipus_cerca+"&OP_3="+id_marca,
	   success: function(msg){
		 cargaDadesCapa(msg,'container_general');
	
	   }
	 });
}


// OFERTES ........................................................................................................................................................

// obté la llista d'ofertes
function getLlista_Ofertes() {
	
	//alert('Ofertes');
}


// NOTÍCIES ........................................................................................................................................................

// obté la llista de notícies
function getLlista_Noticies(categoria,num_pagina,num_items) {
	activaSeccionMenu(6);
	loading('container_general');
	$.ajax({
	   type: "POST",
	   url: "secciones/noticias/noticias.php",
	   data: "ajax=1&categoria="+categoria+"&num_pagina="+num_pagina +"&num_items="+num_items,
	   success: function(msg){
		 cargaDadesCapa(msg,'container_general');
		 inicializa_history();
	   }
	 });
}
function cargaMasTextoNoticia(id){
	 if ($('#more_'+id).is(":hidden")) {
		$('#more_'+id).fadeIn("slow");
	 }else{
		$('#more_'+id).fadeOut("slow");
	}

}

// CLUBS ........................................................................................................................................................

// obté la llista de clubs
function getLlista_Clubs() {
	activaSeccionMenu(7);
	loading('container_general');
	$.ajax({
	   type: "POST",
	   url: "secciones/club/club.php",
	   data: "ajax=1",
	   success: function(msg){
		 cargaDadesCapa(msg,'container_general');
		 inicializa_history();
	
	   }
	 });
}

// FAQS ........................................................................................................................................................

// obté la llista de faqs
function getLlista_Faqs() {
	activaSeccionMenu(99);
	loading('container_general');
	$.ajax({
	   type: "POST",
	   url: "secciones/faq/faq.php",
	   data: "ajax=1",
	   success: function(msg){
		   //alert(msg);
		 cargaDadesCapa(msg,'container_general');
		 inicializa_history();
	   }
	 });
}

// LINKS ........................................................................................................................................................

// obté la llista de links
function getLlista_Links() {
	activaSeccionMenu(8);
	loading('container_general');
	$.ajax({
	   type: "POST",
	   url: "secciones/enlaces/enlaces.php",
	   data: "ajax=1",
	   success: function(msg){
		cargaDadesCapa(msg,'container_general');
		inicializa_history();
	   }
	 });
}



// DISCS ........................................................................................................................................................

// obté el detall d'un disc
// objecte determina si l'id que passem és d'un disc o una pista
function getDetall_Disc(objecte,id,origen) {

	loading('container_general');
	$.ajax({
	   type: "POST",
	   url: "secciones/disco/disco.php",
	   data: "ajax=1&OP_2="+objecte+"&OP_3="+id+"&origen="+origen,
	   success: function(msg){
		cargaDadesCapa(msg,'container_general');
		inicializa_history();
	   }
	 });
}



// PAGINACIO ........................................................................................................................................................
cerca_global = "";
// recarrega la paginació d'artistes/segells/charts
function getPaginacio_Artista_Segell_Chart(seccio, lletra, num_pagina, num_items) {
	
	//seccio=1: artistes
	//seccio=2: segells
	//seccio=6: charts
	cerca = document.getElementById('cerca').value;
	cerca = cerca.htmlEntities();

	if((cerca!="Buscar")&&(cerca!="Search")){
		
		cerca_global = cerca;
		seccio = document.getElementById('seccion_combo').options[document.getElementById('seccion_combo').selectedIndex].value;
		
			loading('container_general');
				$.ajax({
				   type: "POST",
				   url: "secciones/comunes_contenido/busqueda.php",
				   data: "ajax=1&OP_1="+seccio+"&OP_4="+num_pagina+"&OP_5="+num_items+"&OP_6="+lletra+"&cerca="+cerca,
				   success: function(msg){

						cargaDadesCapa(msg,'container_general');
						inicializa_history();
				   }
				 });

	}else{

		loading('container_paginacion');
		alert(OP_1);
		$.ajax({
		   type: "POST",
		   url: "secciones/comunes_contenido/paginacion.php",
		   data: "ajax=1&OP_1="+seccio+"&OP_4="+num_pagina+"&OP_5="+num_items+"&OP_6="+lletra,
		   success: function(msg){
				cargaDadesCapa(msg,'container_paginacion');
				inicializa_history();
		   }
		 });
	}
}
// recarrega la paginació d'artistes/segells/charts
function getPaginacio_Artista_Segell_Tracks( lletra, num_pagina, num_items) {

	//seccio=1: artistes
	//seccio=2: segells
	//seccio=3: generes
	cerca = document.getElementById('cerca').value;
	seccio = document.getElementById('seccion_combo').options[document.getElementById('seccion_combo').selectedIndex].value;

	if(cerca!="Buscar"){
		loading('container_general');
		 if(seccio!=3){
		
		
		$.ajax({
		   type: "POST",
		   url: "secciones/comunes_contenido/paginacion.php",
		   data: "ajax=1&OP_1="+seccio+"&OP_4="+num_pagina+"&OP_5="+num_items+"&OP_6="+lletra+"&cerca="+cerca,
		   success: function(msg){
				cargaDadesCapa(msg,'container_general');
				inicializa_history();
		   }
		 });
		 }else{
			 
		}
	}
}

// FOOTER ........................................................................................................................................................

// obté la pàgina d'RSS
function getRSS() {
	activaSeccionMenu(99);
	loading('container_general');
	$.ajax({
	   type: "POST",
	   url: "secciones/footer/rss.php",
	   data: "ajax=1",
	   success: function(msg){
		 cargaDadesCapa(msg,'container_general');
	
	   }
	 });
}


// obté la pàgina de Nosotros
function getNosotros() {
	activaSeccionMenu(99);
	loading('container_general');
	$.ajax({
	   type: "POST",
	   url: "secciones/footer/nosotros.php",
	   data: "ajax=1",
	   success: function(msg){
		 cargaDadesCapa(msg,'container_general');
	
	   }
	 });
}
		
// obté la pàgina de Contacto
function getContacto() {
	activaSeccionMenu(99);
	loading('container_general');
	$.ajax({
	   type: "POST",
	   url: "secciones/footer/contacto.php",
	   data: "ajax=1",
	   success: function(msg){
		 cargaDadesCapa(msg,'container_general');
	
	   }
	 });
}
		
// obté la pàgina de FAQ
function getFAQ() {
	activaSeccionMenu(99);
	loading('container_general');
	$.ajax({
	   type: "POST",
	   url: "secciones/faqs/faq.php",
	   data: "ajax=1",
	   success: function(msg){
		   //alert(msg);
		 cargaDadesCapa(msg,'container_general');
	
	   }
	 });
}
		
// obté la pàgina de Gastos de Envío
function getGastosEnvio() {
	activaSeccionMenu(99);
	loading('container_general');
	$.ajax({
	   type: "POST",
	   url: "secciones/footer/gastos_envio.php",
	   data: "ajax=1",
	   success: function(msg){
		 cargaDadesCapa(msg,'container_general');
	
	   }
	 });
}
		
// obté la pàgina d'Aviso Legal
function getAvisoLegal() {
	activaSeccionMenu(99);
	loading('container_general');
	$.ajax({
	   type: "POST",
	   url: "secciones/footer/aviso_legal.php",
	   data: "ajax=1",
	   success: function(msg){
		 cargaDadesCapa(msg,'container_general');
	
	   }
	 });
}
// obté la pàgina de condicions d'us
function getCondiciones() {
	activaSeccionMenu(99);
	loading('container_general');
	$.ajax({
	   type: "POST",
	   url: "secciones/footer/condiciones.php",
	   data: "ajax=1",
	   success: function(msg){
		 cargaDadesCapa(msg,'container_general');
	
	   }
	 });
}

// DISTRIBUIDORS ........................................................................................................................................................

// Obté la info de vendes de les tracks d'un disc a partir de la info de any, mes i identificador del disc
function getPistesDiscDistribuidors(mes,any,disc) {
	loading('disco_'+disc+'_ul');
	$.ajax({
	   type: "POST",
	   url: "secciones/reports/reportrack.php",
	   data: "ajax=1&OP_1="+mes+"&OP_2="+any+"&OP_3="+disc,
	   success: function(msg){
		 cargaDadesCapa(msg,'disco_'+disc+'_ul');
	
	   }
	 });
}

// HISTORY



// MENSAGES ........................................................................................................................................................
//	estado 	-> SI/NO (Si/No). Define si el mensaje es positivo o negativo. Y condiciona el estilo css de la capa
//	tipo	-> Existen n tipos. Definen el texto de salida
//	texto	-> Variable de entrada que acompaña al texto de salida. Ej. El nombre de la pista añadida al carrito

// Petición de nuevo mensaje
function getMsg(estado, tipo, texto) {

	//loading('cont_mensajes');
	$.ajax({
	   type: "POST",
	   url: "secciones/comunes/msns.php",
	   data: "ajax=1&OP_1="+estado+"&OP_2="+tipo+"&OP_3="+texto,
	   success: function(msg){
		 //alert(msg);
		  

		cargaMutipleDadesCapaInicio(msg,'cont_mensajes');
		
		defineCerrarMensage();
			$(document).ready(function() {
			 var todos_msg = $("a[@rel='close_msg']");
			 if(todos_msg.length>0){
				 //alert(todos_msg);
		   for(i=0;i<2;i++){
			    var obj3 = todos_msg[i].parentNode;
			  $(obj3).fadeIn('slow');
		   }
		  for(i=2;i<todos_msg.length;i++){
			  var obj2 = todos_msg[i].parentNode;
			  $(obj2).remove();

			  /*
			  if(i==2){
			  $(obj2).fadeOut('fast',function(){
					$(obj2).remove();
			  });
			  }else{
				  $(obj2).remove();
				 }
				 */
		  }
			 }
		});
	   }
	 });
}

function defineCerrarMensage(){
	// set onlick event for buttons
	$("a[@rel='close_msg']").click(function(){
		var obj = this.parentNode;
		$(this).attr("disabled","disabled");
		$(obj).fadeOut('slow',function(){
			$(obj).removeAttr("disabled");
			$(obj).remove();
			
		});
		return false;
	});

}
function deleteMsg(){
	document.getElementById('cont_mensajes').innerHTML = "";
}

// LA CESTA ........................................................................................................................................................

// obté la pàgina genèrica de Cesta de la compra
function getCesta() {
	activaSeccionMenu(99);
	loading('container_general');
	$.ajax({
	   type: "POST",
	   url: "secciones/cesta/cesta.php",
	   data: "ajax=1",
	   success: function(msg){
		   deleteMsg();
		 cargaDadesCapa(msg,'container_general');
		
	   }
	 });
}

function getCesta2() {
	
	loading('container_general');
	$.ajax({
	   type: "POST",
	   url: "secciones/cesta/cesta_2.php",
	   data: "ajax=1",
	   success: function(msg){
		   deleteMsg();
		 cargaDadesCapa(msg,'container_general');
	
	   }
	 });
}
function getCesta3() {
	loading('container_general');
	$.ajax({
	   type: "POST",
	   url: "secciones/cesta/cesta_3.php",
	   data: "ajax=1",
	   success: function(msg){
		  deleteMsg();
		 cargaDadesCapa(msg,'container_general');
		 actualizaCestaCabecera();
		recargaMenuMy12();
	
	   }
	 });
}


function lanza_tpv() { 
	//vent=window.open('','tpv','width=725,height=600,scrollbars=no,resizable=yes,status=yes,menubar=no,location=no');
	//document.forms[0].submit();
	document.getElementById('tpv_form').submit();
}

//Añadr un char al carrito
function addCestaChart(id_chart){
	
	$.ajax({
	   type: "POST",
	   url: "secciones/cesta/cesta_utilitats.php",
	   data: "ajax=1&accion=addchart&id_chart="+id_chart,
	   success: function(msg){
		   //alert(msg);
			   if(msg == 'not_logged'){
					getMsg('NO', 'CESTA_NOT_LOGGED', '');
				}else{
					getMsg('SI', 'CESTA_ANADIR_CHART', '');
					actualizaCestaCabecera();
				}
						
	
	   }
	 });	
	
}

//Añadr un accesorio al carrito
function addCestaAccesorio(id_accesorio){
	
	$.ajax({
	   type: "POST",
	   url: "secciones/cesta/cesta_utilitats.php",
	   data: "ajax=1&accion=addaccesorio&id_accesorio="+id_accesorio,
	   success: function(msg){
		   //alert(msg);
		   	
			if(msg == 'ok'){	
				getMsg('SI', 'CESTA_ANADIR_ACCESORIO', '');
				actualizaCestaCabecera();
			}else if(msg == 'not_logged'){
				getMsg('NO', 'CESTA_NOT_LOGGED', '');
			}else if(msg == 'ya_existe'){
				getMsg('NO', 'CESTA_YA_EXISTE_ACCESORIO', '');
			}else if(msg == 'no_stock'){
				getMsg('NO', 'CESTA_NO_STOCK_ACCESORIO', '');
			}else{
				getMsg('NO', 'CESTA_ANADIR_ACCESORIO', '');
			}
						
	
	   }
	 });	
	
}


//añadir un disco entero al carrito
//puede ser en formato MP3 ó FISICO
function addCestaDisco(id_disco){
	//alert(document.getElementById("comprar_referencia"+id_disco+"_mp3").checked);
	if(document.getElementById("comprar_referencia"+id_disco+"_mp3").checked){

		//añadiremos al carrito todo el disco en mp3
		addCestaDisco_subrutina_MP3_Completo(id_disco);

	}else{	
			addCestaDisco_subrutina_VINILO(id_disco);
	}

}
function addCestaDiscoCompleto(id_disco){
	addCestaDisco_subrutina_MP3_Completo(id_disco);
}
function addCestaDisco_subrutina_MP3(id_disco){
		$.ajax({
		   type: "POST",
		   url: "secciones/cesta/cesta_utilitats.php",
		   data: "ajax=1&accion=adddiscomp3&id_disco="+id_disco,
		   success: function(msg){
			   //alert(msg);
			   if(msg == 'not_logged'){
					getMsg('NO', 'CESTA_NOT_LOGGED', '');
				}else{
					getMsg('SI', 'CESTA_ANADIR_DISCO', '');
					actualizaCestaCabecera();
					addCestaDisco_subrutina_VINILO(id_disco);
				}
				
							
		   }
		 });	
}
function addCestaDisco_subrutina_MP3_Completo(id_disco){
		$.ajax({
		   type: "POST",
		   url: "secciones/cesta/cesta_utilitats.php",
		   data: "ajax=1&accion=adddiscomp3completo&id_disco="+id_disco,
		   success: function(msg){
			   //alert(msg);
			   if(msg == 'not_logged'){
					getMsg('NO', 'CESTA_NOT_LOGGED', '');
			   }else if(msg == 'ya_existe'){
					getMsg('NO', 'CESTA_YA_EXISTE_DISCO', '');
				}else{
					getMsg('SI', 'CESTA_ANADIR_DISCO', '');
					actualizaCestaCabecera();
				}
		   }
		 });	
}

function addCestaDisco_subrutina_VINILO(id_disco){
		if(document.getElementById("comprar_referencia"+id_disco+"_vinilo")!=null){
			if(document.getElementById("comprar_referencia"+id_disco+"_vinilo").checked){
					$.ajax({
				   type: "POST",
				   url: "secciones/cesta/cesta_utilitats.php",
				   data: "ajax=1&accion=adddiscovinilo&id_disco="+id_disco,
				   success: function(msg){
		
						if(msg == 'ok'){	
							getMsg('SI', 'CESTA_ANADIR_VINILO', '');
							actualizaCestaCabecera();
						}else if(msg == 'not_logged'){
							getMsg('NO', 'CESTA_NOT_LOGGED', '');
						}else if(msg == 'ya_existe'){
							getMsg('NO', 'CESTA_YA_EXISTE_VINILO', '');
						}else if(msg == 'no_stock'){
							getMsg('NO', 'CESTA_NO_STOCK_VINILO', '');
						}else{
							getMsg('NO', 'CESTA_ANADIR_VINILO', '');
						}
										
					   }
					 });
			}
		}
}
function desplegaDisco(id){
	if($('#desplega_track_'+id).is(":hidden")){
		$('#desplega_track_'+id).slideDown(300);	
	}else{
		$('#desplega_track_'+id).slideUp(300);
	}
}
//añadir una cancion al carrito
//si no pasan tipo producto forzaremos a que sea MP3 (tipo 1).
function addCestaTrack(id_producto) {
	addCestaTrackConTipo(id_producto,'1');
}

//funcion que añade un producto a la cesta y devuelve un mensaje por pantalla
function addCestaTrackConTipo(id_producto,tipo_producto) {
	//alert(id_producto);
	$.ajax({
	   type: "POST",
	   url: "secciones/cesta/cesta_utilitats.php",
	   data: "ajax=1&accion=addtrack&id_producto="+id_producto+"&tipo_producto="+tipo_producto,
	   success: function(msg){
		   //alert(msg);
		   	
		   	
			if(msg == 'ok'){	
				getMsg('SI', 'CESTA_ANADIR', "P_"+id_producto);
				actualizaCestaCabecera();
			}else if(msg == 'not_logged'){
				getMsg('NO', 'CESTA_NOT_LOGGED', '');
			}else if(msg == 'ya_existe'){
				getMsg('NO', 'CESTA_YA_EXISTE', '');
			}else if(msg == 'ya_existe_comprado'){
				getMsg('NO', 'CESTA_YA_EXISTE_COMPRADO', '');
			}else{
				getMsg('NO', 'CESTA_ANADIR', '');
			}
			
	
	   }
	 });	
	
}

function actualizaCestaCabecera(){
	$.ajax({
	   type: "POST",
	   url: "secciones/cesta/cesta_utilitats.php",
	   data: "ajax=1&accion=calcul_total",
	   success: function(msg){

		   mi_valor = msg;
		   tmp = mi_valor.split("_");
		   document.getElementById('valor_cesta_cabecera').innerHTML =  tmp[0] +" &iacute;tems <br /> "+ tmp[1] +" &euro;";
	   }
	 });	
}
function deleteMy12(){
	$.ajax({
	   type: "POST",
	   url: "secciones/cesta/cesta_utilitats.php",
	   data: "ajax=1&accion=calcul_total",
	   success: function(msg){

		   mi_valor = msg;
		   tmp = mi_valor.split("_");
		   document.getElementById('valor_cesta_cabecera').innerHTML =  tmp[0] +" &iacute;tems <br /> "+ tmp[1] +" &euro;";
	   }
	 });	
}
function actualizaCestaCantidad(tipo, id_producto){
	
	cantidad = document.getElementById('cantidad_'+id_producto).value;
	
		$.ajax({
		   type: "POST",
		   url: "secciones/cesta/cesta_utilitats.php",
		   data: "ajax=1&accion=update"+tipo+"&id_producto="+id_producto+"&cantidad="+cantidad,
		   success: function(msg){
			   //alert(msg);
			   
			   if(msg == 'not_logged'){
					getMsg('NO', 'CESTA_NOT_LOGGED', '');
				}else if(msg == 'non_available'){
					getMsg('NO', 'CESTA_UPDATE_NA', '');
				}else if(msg == 'ok'){
					getMsg('SI', 'CESTA_UPDATE', '');
					getCesta();
					actualizaCestaCabecera();
				}else{
					getMsg('NO', 'CESTA_UPDATE', '');
				}
				
							
		   }
		 });	
}

function eliminaProductoCesta(id_producto){
	
		$.ajax({
		   type: "POST",
		   url: "secciones/cesta/cesta_utilitats.php",
		   data: "ajax=1&accion=delete&id_producto="+id_producto,
		   success: function(msg){
			   //alert(msg);
			   
			   if(msg == 'not_logged'){
					getMsg('NO', 'CESTA_NOT_LOGGED', '');
				}else if(msg == 'ok'){
					getMsg('SI', 'CESTA_DELETE', id_producto);
					getCesta();
					actualizaCestaCabecera();
				}else{
					getMsg('NO', 'CESTA_DELETE', '');
				}
				
							
		   }
		 });


}

// CHART UTILITATS ............................................................................................................................................................
function dragTopten(idTopten, idUsuari, idTracks){
	
	$('#topten_sortable').Sortable(
		{
			accept : 		'sortableitem',
			opacity: 		0.9,
			axis:				'vertically',
			revert:			true,
			onStop : function(){
				serial = $.SortSerialize('topten_sortable');
				$.ajax({
					type: "POST",
					url: "secciones/chart/chart_utilitats.php",
					data: serial.hash+"&accion=ordenar&id="+idUsuari+"&idTracks="+idTracks,
					success:function(msg){
						//alert(msg);
						if(msg == 'ok'){	
							getMsg('SI', 'CHART_ORDEN', '');
						}else{
							getMsg('NO', 'CHART_ORDEN', '');
						}
						
					}
				});
			}
		}
	);

}

function addChartTrack(idTrack, idUsuario){

	$.ajax({
	   type: "POST",
	   url: "secciones/chart/chart_utilitats.php",
	   data: "ajax=1&accion=add&idUsuario="+idUsuario+"&idTrack="+idTrack,
	   success: function(msg){
		   //alert(msg);
			if(msg == 'ok'){	
	
				getMsg('SI', 'CHART_ANADIR', 'P_'+idTrack);
			}else{
				getMsg('NO', 'CHART_ANADIR', 'P_'+idTrack);
			}
						
	
	   }
	 });
}

function removeChartTrack(idTrack, idUsuario, idTopten){

	$('#'+idTopten).remove();
	$.ajax({
	   type: "POST",
	   url: "secciones/chart/chart_utilitats.php",
	   data: "ajax=1&accion=remove&idUsuario="+idUsuario+"&idTrack="+idTrack,
	   success: function(msg){
		   //alert(msg);
			if(msg == 'ok'){	
				getMsg('SI', 'CHART_ELIMINAR', '');
			}else{
				getMsg('NO', 'CHART_ELIMINAR', '');
			}
						
	
	   }
	 });
}
function addMy12(tipo,idElement, idUsuario){
	//alert('addChartTrack'+idTrack);

	$.ajax({
	   type: "POST",
	   url: "secciones/my12/my12_utilitats.php",
	   data: "ajax=1&accion="+tipo+"&idElement="+idElement+"&idUsuario="+idUsuario,
	   success: function(msg){
		   //alert(msg);
			if(msg == 'ok'){	
				getMsg('SI', 'ANADIR_MY12', tipo+"_"+idElement);
				recargaMenuMy12();
			}else{
				getMsg('NO', 'ANADIR_MY12', '');
			}
						
	
	   }
	 });
}
function deleteMy12(tipo,idElement, idUsuario){
	//alert('addChartTrack'+idTrack);
	$.ajax({
	   type: "POST",
	   url: "secciones/my12/my12_utilitats.php",
	   data: "ajax=1&accion="+tipo+"&idElement="+idElement+"&idUsuario="+idUsuario,
	   success: function(msg){
		   //alert(msg);
			if(msg == 'ok'){	
				getMsg('SI', 'MY12_BORRADO', tipo+'_'+idElement);
				recargaMenuMy12();
			}else{
				getMsg('NO', 'MY12_NO_BORRADO', '');
			}
						
	
	   }
	 });
}
function recargaMenuMy12(){
	loading('midoce');
	$.ajax({
	   type: "POST",
	   url: "secciones/my12/my12.php",
	   data: "ajax=1",
	   success: function(msg){
		 cargaDadesCapa(msg,'midoce');
		 	// cambia style a position absolute solo si javascript esta activado
		reprogramaComportamiento();
		activaMi12();
	   }
	 });	
}

function reprogramaComportamiento(){
	validado = true;

	$("#midoce").addClass('jactive');

	// esconder ULs inactivos
	$("#midoce ul ul ul:not(:first)").hide();

	// marcar categoria activa
	$("#midoce ul li ul li:first").addClass("unactive");
	// on click
	$("#midoce ul li ul li.subcat").click(function() {
				if(!$(this).hasClass("unactive")) {
					$(this).parent().find(".unactive").removeClass("unactive");
					$(this).addClass("unactive");
	// abrir/cerrar
					$(this).parent().find("ul:visible").slideUp(300);
					$(this).find("ul").slideDown(300,calc_midoce_height);
			//setTimeout('calc_midoce_height()', 400);
				}
	return false;
	});
	
	// Abrir primera categoria del segundo tab, marcar 2ndo tab como activo
	$("#midoce #mdm ul ul:first").show();
	$("#midoce #dst ul li:first").addClass("unactive");
	$("#midoce ul li.tabs:second .tab").addClass("activo");
	// Creacion de tabs
	$("#midoce ul ul.bmenu:not(:first)").hide();
	// cambiar de tab on click
	$("#midoce ul li.tabs").click(function() {
									   
		$("#midoce ul ul.bmenu:visible").hide();
		$(this).find("ul.bmenu").show();
		$("#midoce ul li.tabs span.tab").removeClass("activo");
		$(this).find("span.tab").addClass("activo");

		setTimeout('calc_midoce_height()', 400);
		return false;
	});
	validado = true;
	//calc_midoce_height_reprogramado();
	setTimeout('calc_midoce_height_reprogramado()', 400);
	// Initialize history plugin.
	// The callback is called at once by present location.hash. 
}

function activaMi12(){

			//setTimeout('calc_midoce_height()', 400);
	
		$("#midoce ul ul.bmenu").hide();
		$("#midoce ul ul.bmenu:not(:first)").show();
		$("#midoce ul li.tabs span.tab").removeClass("activo");
		$("#midoce ul li.tabs:not(:first) span.tab").addClass("activo");
		// Creacion de tabs
		$("#midoce #mdm ul li:first").addClass("unactive");
		$("#midoce ul li.tabs:not(:first) .tab").addClass("activo");

		setTimeout('calc_midoce_height()', 400);
		//document.getElementById("midoce").style.height = mtop+"px";
	}

// COMUNICACION CON PLAYER

function thisMovie(movieName) {
         if (navigator.appName.indexOf("Microsoft") != -1) {
             return window[movieName];
         } else {
             return document[movieName];
         }
}

// AÑADIDAS POR JORDI TEMA CESTA

function controlaSpain(pais,n_accesorios, n_vinilos){
	if (pais!=73){
			
			document.getElementById('provincia').disabled = true;
			$('#provincia').hide();
			$('#label_provincia').hide();
			if(datos_envio_diferentes){
				document.getElementById('provincia_e').disabled = true;
				$('#provincia_e').hide();
				$('#label_provincia_e').hide();
			}
			document.getElementById('provincia').selectedIndex = 0;
			document.getElementById('provincia_e').selectedIndex = 0;
			
			
			
	}else{

			document.getElementById('provincia').disabled = false;
			$('#provincia').show();
			$('#label_provincia').show();
			if(datos_envio_diferentes){
				document.getElementById('provincia_e').disabled = false;
				$('#provincia_e').show();
				$('#label_provincia_e').show();
			}
			
	
			if((n_accesorios>0) || (n_vinilos>0)){
				calculaGastosEnvio(pais,0,n_accesorios, n_vinilos);
			}
			
	}
}
function controlaProvincia(provincia,n_accesorios, n_vinilos){
	if(datos_envio_diferentes){
		provincia = document.getElementById('provincia_e').options[document.getElementById('provincia_e').selectedIndex].value;	
	}
	if((n_accesorios>0) || (n_vinilos>0)){
		calculaGastosEnvio(73,provincia,n_accesorios, n_vinilos);
	}
}
function redondear(cantidad, decimales) {

var cantidad = parseFloat(cantidad);
var decimales = parseFloat(decimales);

return cantidad.toFixed(decimales);
} 
function calculaGastosEnvio(pais,provincia,n_accesorios, n_vinilos){
	total = document.getElementById('hidden_total').value;
	$.ajax({
	   type: "POST",
	   url: "secciones/cesta/cesta_utilitats.php",
	   data: "ajax=1&accion=calcul_gastos&pais="+pais+"&provincia="+provincia+"&n_accesorios="+n_accesorios+"&n_vinilos="+n_vinilos,
	   success: function(msg){
		   document.getElementById('gastos_envios_valor').innerHTML =  msg;
		 
		   msg = msg.replace(",",".");
		  
		   suma =  parseFloat(parseFloat(total) + parseFloat(msg));
		   suma = redondear(suma, 2);
		   document.getElementById('hidden_ge').value = suma;
		   suma_txt = suma.replace(".",",");
		   document.getElementById('gastos_total_valor').innerHTML = suma_txt;
		   
		   
	   }
	 });	
}
function activaDatosEnvio(){
	$.ajax({
	   type: "POST",
	   url: "secciones/cesta/cesta_utilitats.php",
	   data: "ajax=1&accion=datos_envio_diferentes",
	   success: function(msg){
	   }
	 });
	
	if(!datos_envio_diferentes){
		
		$('#dt_envio').fadeIn('slow');
			document.getElementById('igual').checked = true;
			datos_envio_diferentes = true;
	}else{
		
		$('#dt_envio').fadeOut('slow');
		document.getElementById('igual').checked = false;
		datos_envio_diferentes = false;
		}

}

function enviaCesta(){
		nombre_f = document.getElementById('nombre').value;
		nombre_f = nombre_f.htmlEntities();
		apellidos_f = document.getElementById('apellidos').value;
		apellidos_f = apellidos_f.htmlEntities();
		direccion_f = document.getElementById('direccion').value;
		direccion_f = direccion_f.htmlEntities();
		cp_f = document.getElementById('cp').value;
		cp_f = cp_f.htmlEntities();
		pais_user_f = document.getElementById('pais').options[document.getElementById('pais').selectedIndex].value;
		provincia_f = document.getElementById('provincia').options[document.getElementById('provincia').selectedIndex].value;
		poblacion_f = document.getElementById('poblacion').value;
		poblacion_f = poblacion_f.htmlEntities();
		telefono_f = document.getElementById('telefono').value;
		telefono_f = telefono_f.htmlEntities();
		mail_f = document.getElementById('mail').value;
		mail_f = mail_f.htmlEntities();
		if(datos_envio_diferentes){
			nombre_e = document.getElementById('nombre_e').value;
			nombre_e = nombre_e.htmlEntities();
			apellidos_e = document.getElementById('apellidos_e').value;
			apellidos_e = apellidos_e.htmlEntities();
			direccion_e = document.getElementById('direccion_e').value;
			direccion_e = direccion_e.htmlEntities();
			cp_e = document.getElementById('cp_e').value;
			cp_e = cp_e.htmlEntities();
			pais_user_e = document.getElementById('pais_e').options[document.getElementById('pais_e').selectedIndex].value;
			provincia_e = document.getElementById('provincia_e').options[document.getElementById('provincia_e').selectedIndex].value;
			poblacion_e = document.getElementById('poblacion_e').value;
			poblacion_e = poblacion_e.htmlEntities();
			telefono_e = document.getElementById('telefono_e').value;
			telefono_e = telefono_e.htmlEntities();
			mail_e = document.getElementById('mail_e').value;
			mail_e = mail_e.htmlEntities();
		}else{
			nombre_e = nombre_f;
			apellidos_e = apellidos_f;
			direccion_e = direccion_f;
			cp_e = cp_f;
			pais_user_e = pais_user_f;
			provincia_e = provincia_f;
			poblacion_e = poblacion_f;
			telefono_e = telefono_f;
			mail_e = mail_f;
		}
		valor_descuento = document.getElementById('hidden_descuento').value;
		valor_gastos_envio = document.getElementById('hidden_ge').value;
		valor_total = document.getElementById('hidden_total').value;
		perfil = document.getElementById('perfil').checked;
		aceptotodo = document.getElementById('aceptotodo').checked;
		if((nombre_f!="")&&(apellidos_f!="")&&(direccion_f!="")&&(cp_f!="")&&(pais_user_f!="")&&(poblacion_f!="")&&(mail_f!="")&&(aceptotodo)){
		
			if(((pais_user_f==73)&&(provincia_f!=""))||(pais_user_f!=73)){

				if(datos_envio_diferentes){
					if((nombre_e!="")&&(apellidos_e!="")&&(direccion_e!="")&&(cp_e!="")&&(pais_user_e!="")&&(poblacion_e!="")&&(mail_e!="")){
						if(((pais_user_e==73)&&(provincia_e!=""))||(pais_user_e!=73)){
							$.ajax({
							   type: "POST",
							   url: "secciones/cesta/cesta_utilitats.php",
							   data: "ajax=1&accion=envia_datos_formulario&nombre_f="+nombre_f+"&apellidos_f="+apellidos_f+"&direccion_f="+direccion_f+"&cp_f="+cp_f+"&pais_user_f="+pais_user_f+"&provincia_f="+provincia_f+"&poblacion_f="+poblacion_f+"&telefono_f="+telefono_f+"&mail_f="+mail_f+"&nombre_e="+nombre_e+"&apellidos_e="+apellidos_e+"&direccion_e="+direccion_e+"&cp_e="+cp_e+"&pais_user_e="+pais_user_e+"&provincia_e="+provincia_e+"&poblacion_e="+poblacion_e+"&telefono_e="+telefono_e+"&mail_e="+mail_e+"&valor_descuento="+valor_descuento+"&valor_gastos_envio="+valor_gastos_envio+"&valor_total="+valor_total+"&perfil="+perfil+"&aceptotodo="+aceptotodo,
							   success: function(msg){

								   getCesta2();
							   }
							 });	
						}else{
							$('#datos_obligatorios').fadeIn('slow');
						}
					}else{
						$('#datos_obligatorios').fadeIn('slow');
					}
				}else{
					$.ajax({
					   type: "POST",
					   url: "secciones/cesta/cesta_utilitats.php",
					   data: "ajax=1&accion=envia_datos_formulario&nombre_f="+nombre_f+"&apellidos_f="+apellidos_f+"&direccion_f="+direccion_f+"&cp_f="+cp_f+"&pais_user_f="+pais_user_f+"&provincia_f="+provincia_f+"&poblacion_f="+poblacion_f+"&telefono_f="+telefono_f+"&mail_f="+mail_f+"&nombre_e="+nombre_e+"&apellidos_e="+apellidos_e+"&direccion_e="+direccion_e+"&cp_e="+cp_e+"&pais_user_e="+pais_user_e+"&provincia_e="+provincia_e+"&poblacion_e="+poblacion_e+"&telefono_e="+telefono_e+"&mail_e="+mail_e+"&valor_descuento="+valor_descuento+"&valor_gastos_envio="+valor_gastos_envio+"&valor_total="+valor_total+"&perfil="+perfil+"&aceptotodo="+aceptotodo,
					   success: function(msg){

						  getCesta2();
					   }
					 });	
				}
			}else{
				$('#datos_obligatorios').fadeIn('slow');
			}	
		}else{
			$('#datos_obligatorios').fadeIn('slow');	
		}
	}

function cargaMisCompras(letra,pag,maxim){
	activaSeccionMenu(99);
	loading('container_general');
	setTimeout('calc_midoce_height()', 400);
	$.ajax({
	   type: "POST",
	   url: "secciones/my12/my12_compras.php",
	   data: "ajax=1&letra="+letra+"&pag="+pag+"&max="+maxim,
	   success: function(msg){
		 cargaDadesCapa(msg,'container_general');
		
	   }
	 });
	}
function cargaMisComprasDiscos(letra,pag,maxim){
	activaSeccionMenu(99);
	loading('container_general');
	setTimeout('calc_midoce_height()', 400);
	$.ajax({
	   type: "POST",
	   url: "secciones/my12/my12_compras_discos.php",
	   data: "ajax=1&letra="+letra+"&pag="+pag+"&max="+maxim,
	   success: function(msg){
		 cargaDadesCapa(msg,'container_general');
		
	   }
	 });
	}
function cargaComoCrearChart(){
	loading('container_general');
	$.ajax({
	   type: "POST",
	   url: "secciones/chart/chart_help.php",
	   data: "ajax=1",
	   success: function(msg){
		 cargaDadesCapa(msg,'container_general');
	
	   }
	 });
}

	
//
//	prototipo htmlentity en javascript
String.prototype.htmlEntities = function () {
   return this.replace(/&/g,'_AMP_').replace('>','_GRAN_').replace('<','_PETIT_').replace(/[+]/g,'_PLUS_').replace(/#/g,'_ALMO_');
};


//
//	BANNERS	//////////////////////////////////////////////////////////////////////////////////////////////////////
//


//	Recarga los banners superiores dependiendo del contenido de la sección que la llame.
function recargaBanner(seccion, id){
	//alert(seccion+" cacas id="+id);
	//delete embedBanner;
	var params = {
	  menu: "false",
	  allowScriptAccess: "always"
	};
	
	var flashvars = { _seccion:seccion, _id:id};
	//flashvars._seccion 	=	seccion;
	//flashvars._id 		= 	id;
	
	var attributes = {
		//id:"embedBanner"
	};
	
	swfobject.embedSWF("flash/navegador_banners.swf", "recomendaciones", "661", "130", "8.0.0","flash/expressInstall.swf", flashvars, params, attributes);
}

function compruebaNumeroBanners(seccion, id){
	//loading('recomendaciones');
	$.ajax({
	   type: "POST",
	   url: "secciones/banner/compruebaNumeroBanners.php",
	   data: "ajax=1&seccion="+seccion+"&genero="+id,
	   success: function(msg){
		if(msg=="OK"){
			$('#recomendaciones').show();
			$('#embedBanner').show();
			recargaBanner(seccion, id);
			
			
		}else{
			$('#recomendaciones').hide();
			$('#embedBanner').hide();
		}
	
	   }
	 });
}

//
//	funciones de conversión	///////////////////////////////////////////////////////////////////////////////////////
//


function DecodeHtmlEntities(str){
		str =  str.replace(/_AMP_/g, '&').replace(/_GRAN_/g, '>').replace(/_PETIT_/g, '<').replace(/_PLUS_/g,'+').replace(/_ALMO_/g,'#').replace(/%20/g,' ');
		try{
			var txt = document.createElement('textarea');
			txt.innerHTML = str;
			return txt.value;
		}catch(e){
			return str;
		}
}


//
//	History	//////////////////////////////////////////////////////////////////////////////////////////////////////
//

// PageLoad function
// This function is called when:
// 1. after calling $.historyInit();
// 2. after calling $.historyLoad();
// 3. after pushing "Go Back" button of a browser
function pageload(hash) {
		// hash doesn't contain the first # character.
		if(hash) {
			// restore ajax loaded state
//alert("Pageload="+hash);
			seccion	= 	hash.split("/");
			hash	=	seccion[0];

 			temp_title = hash;

			switch(hash){
				case -1:
				case "home":
				case "":
					getHome();
				break;
				case "artists":
					if(seccion.length>1){
						//	Carga el detalle de un artista
						getDetall_Artista_Segell_Chart(1,seccion[2]);
						temp_title+= " » "+seccion[1];
					}else{
						getLlista_Artista_Segell_Chart(1);
					}
				break;
				case "labels":
					if(seccion.length>1){
						//	Carga el detalle de un sello
						getDetall_Artista_Segell_Chart(2,seccion[2]);
						temp_title+= " » "+seccion[1];
					}else{
						getLlista_Artista_Segell_Chart(2);
					}
				break;
				case "genres":
					if(seccion.length>1){
						//	Carga el detalle de un genero
						getDetall_Genere(seccion[2]);
						temp_title+= " » "+seccion[1];
					}else{
						getLlista_Generes();
					}
					
				break;
				case "charts":
					if(seccion.length>1){
						//	Carga el detalle de un chart
						getDetall_Artista_Segell_Chart(6,seccion[2]);
						temp_title+= " » "+seccion[1];
					}else{
						getLlista_Artista_Segell_Chart(6);
					}
				break;
				case "discs":
					if(seccion.length>1){
						//	Carga el detalle de un disco
						if(seccion.length == 3){ids = seccion[2].split("-");getDetall_Disc('disc',ids[0],ids[1]);}
						if(seccion.length == 4){ids = seccion[3].split("-");getDetall_Disc('track',ids[0],ids[1]);}
						
						temp_title+= " » "+seccion[1];
					}
				break;
	
				case "news":
					getLlista_Noticies('',1,10); 
				break;
				case "clubs":
					getLlista_Clubs();
				break;
				case "links":
					getLlista_Links();
				break;
				case "rss":
					getRSS();
				break;
				case "us":
					getNosotros();
				break;
				case "contact":
					getContacto();
				break;
				case "faq":
					getLlista_Faqs();
				break;
				case "shipment":
					getGastosEnvio();
				break;
				case "legal":
					getAvisoLegal();
				break;

				case "basket":
					getCesta();
				break;
				case "new_user":
					getRegistre();
				break;
				case "my_acount":
					getModify();
				break;



			}
		//	Asignamos un TITLE HTML de la página nuevo
		asigna_title(temp_title);


		} else {
			// start page
			$("#load").empty();
		}
	}


function inicializa_history(){
	// set onlick event for buttons
	$("a[@rel='history']").click(function(){
		// 
		var hash = this.href;
		//	quitamos la url básica, no interesa
		//hash = hash.replace('http://192.168.1.2/236.WEB.DM/', '');
		hash = hash.replace('http://www.docemusic.com/', '');
		hash = hash.replace('http://docemusic.com/', '');
		//hash = hash.replace('http://www.docemusic.com/beta_/', '');
		//Le quitamos la almoadilla #, por si tiene alguna al final
		hash = hash.replace(/^.*#/, '');
		// moves to a new page. 
		// pageload is called at once. 
		//	incorporamos en el history lo que hay en hash
		$.historyLoad(hash);

		asigna_title(hash);


		return false;
	});

}



// Cambiamos el title de la página.
function asigna_title(hash){
		//title_tmp = title.toUpperCase();
		temp_title = "";
		path_title = hash.split("/");
		if(path_title.length>1){
			for(i=0;i<(path_title.length-1);i++){
				//alert(path_title[i]);
				temp_title += path_title[i]+" » ";
			}
		}else{
			temp_title = path_title[0] +" » ";
		}

		document.title = DecodeHtmlEntities(temp_title)+"12\"MUSIC  ";	
}




