function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}


//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
var xmlHttp = createXmlHttpRequestObject();
// Mostrar error (true) o comportamiento AJAX (false)
var showErrors = true;
// Muestra el estado de Place Order, falso en otro caso
var placingOrder = false;
// Link de la accion del usuario
var actionObject = '';
// Crear un XMLHttpRequest instancia
function createXmlHttpRequestObject(){
    // Objeto XMLHttpRequest
    var xmlHttp;
    // Crear el objecto XMLHttpRequest
    try {
        // Create native XMLHttpRequest object
        xmlHttp = new XMLHttpRequest();
    } catch(e) {
        // Asumir Explorer 6 o menor
        var XmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0", "MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0","MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP");
        // Buscar la version
        for (i = 0; i < XmlHttpVersions.length && !xmlHttp; i++){
            try{
                // Intentamos crear el objeto
                xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
            }
            catch (e) {} // Ignorar el error potencial
        }
    }

    // Devuelvo el objeto XMLHttpRequest creado satisfactoriamente
    if (xmlHttp){
        return xmlHttp;
    }
    // Si un error aparece lo paso a la funcion
    else{
        handleError("Error creando el objeto XMLHttpRequest.");
    }
}

// Muestro un mensaje de error o un comportamiento non-AJAX
function handleError($message){
    // Ignoro el error si es false
    if (showErrors){
        //alert("Error encontrado: \n" + $message);
        return false;
    }
    // Comportamiento non-AJAX
    else if (!actionObject.tagName){
        return true;
    }
    // Comportamiento non-AJAX
    else if (actionObject.tagName == 'A'){
        window.location = actionObject.href;
    }
    // Comportamiento non-AJAX
    else if (actionObject.tagName == 'FORM'){
        actionObject.submit();
    }
}
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
function eliminaEspacios(cadena)
{
	// Funcion para eliminar espacios delante y detras de cada cadena
	while(cadena.charAt(cadena.length-1)==" ") cadena=cadena.substr(0, cadena.length-1);
	while(cadena.charAt(0)==" ") cadena=cadena.substr(1, cadena.length-1);
	return cadena;
}

function muestraMensaje(mensaje,nombre)
{
	divMensaje=document.getElementById(nombre);
	divMensaje.innerHTML=mensaje;
}
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
// FUNCIONES para mostrar regalo

advanced_search=false;
var datos = "";
function habilitar(palabra) {
	
	if(palabra == "normal"){
	   document.getElementById('chk_regalo').checked='';
	   document.getElementById('regalo').style.display='none';		
	   advanced_search=false;
	
	}else{
		document.getElementById('chk_normal').checked='';
		
		if(advanced_search!=true){		
			document.getElementById('regalo').style.display='';	
			advanced_search=true;
		}else{
			document.getElementById('regalo').style.display='none';		
			advanced_search=false;
		}
	}
		
}

/******************************************************/
//FUNCIONES CARRITO DE COMPRAS 
// Agregar un producto al Shopping cart
function addProductToCart(formEntra){
    form = document.getElementById(formEntra);
	// Vuelvo al form clasico si no existe el objeto XMLHttpRequest
	if (!xmlHttp){
		form.submit();
		return true;
	}
	// Crear la URL del request
	request = form.action + '&AjaxRequest';
	// Conectarse al servidor
	try{
	// Continuar si el objeto no esta ocupado
		if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0){
			// Enviar la peticion
			xmlHttp.open("GET", request, true);
			xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
			xmlHttp.send();
			xmlHttp.onreadystatechange = addToCartStateChange;
		}
	}catch (e){
		// Muestro el error si existe
		handleError(e.toString());
	}
	
	
}

// Funcion para recibir la respuesta
function addToCartStateChange(){
	
	// Leemos la respuesta cuando el estado es 4
	if (xmlHttp.readyState == 4){
        // Continuo si el HTTP status es OK
        if (xmlHttp.status == 200){
            try {
                //funcion para mostrar que se agrego
                updateCartSummary();
            }
            catch (e){
                handleError(e.toString());
            }
        }else{
            handleError(xmlHttp.statusText);
        }
    }
	
}

// Actualizar cesta
function updateCartSummary(){
	
	// Leo la respuest
    response = xmlHttp.responseText;
	// Si existe un error lo muestro
    if (response.indexOf("ERRNO") >= 0 || response.indexOf("error") >= 0) {
        handleError(response);
        alert("error")
    }else{
		
		divCartSum = document.getElementById("cart-summary");
		divCartSum.style.display = "inline"
		mostrarDiv("cart-summary")
		divCartSum.innerHTML = response;
		//cant = document.getElementById("numeroProductos").innerHTML 
		/*
		cantidadCarrito = parseInt(cant)+1;
		actualizaNumeroCarrito(cantidadCarrito)
        */
		window.scrollTo(0,0);
		
    }
	
	
}

/************************************************
FUNCIONES DE VENTANA PEQUEÑA DE COPMPRA
************************************************/
var opacidad=0;
var hilo;

function mostrarDiv(id) {
	clearInterval(hilo);
	opacidad=100;
	document.getElementById(id).style.opacity=".1";
	document.getElementById(id).style.filter="alpha(opacity=100)";
	hilo=setInterval("hacerOpaco('"+id+"')",7);
}

function ocultarCartSum(){
	divCartSum = document.getElementById("cart-summary");
	divCartSum.style.display = "none";
}


function hacerOpaco( id ) {
	opacidad++;
	opacidadFireFox=opacidad/100;
	document.getElementById(id).style.opacity=opacidadFireFox;
	document.getElementById(id).style.filter="alpha(opacity="+opacidad+")";
	if (opacidad>99) {
		clearInterval(hilo);
		document.getElementById(id).style.opacity="1";
		document.getElementById(id).style.filter="alpha(opacity=100)";
		opacidad=100;
		clearInterval(hilo);
		return;
	}
}

function hacerOpacoHasta( id , hasta) {
	opacidad+=5;
	//opacidad = 100;
	opacidadFireFox=opacidad/100;
	document.getElementById(id).style.opacity=opacidadFireFox;
	document.getElementById(id).style.filter="alpha(opacity="+opacidad+")";
	if (opacidad>hasta) {
		//document.getElementById("bodyPrincipal").style.overflowY = "hidden";
		if(ban==0){
			document.getElementById("divLogin").style.display="block";
		}else if(ban==3){
			document.getElementById("divSaleAlert").style.display="block";
		}else{
			document.getElementById("divSizeChart").style.display="block";
		}
		clearInterval(hilo);
		ban=0;
		return;
	}
}

function mostrarDivHasta(id, hasta) {
	clearInterval(hilo);
	opacidad=1;
	document.getElementById(id).style.opacity=".0";
	document.getElementById(id).style.filter="alpha(opacity=0)";
	hilo=setInterval("hacerOpacoHasta('"+id+"', "+hasta+")",7);
}

/*Funcion que me devuelve el numero de caracteres - blancos de una cadena*/
function trim(cadena){
	var nuevacadena="";
	nuevacadena=cadena.replace(/\ /g,"");
	return nuevacadena.length;
}

/******************************************************/
//traer listado de cuidades de un departamento
function TraerCiudades(ruta,iddept){
	//alert(ruta)
	document.getElementById('div_ciudades').style.display='inline';
	divResultado = document.getElementById('div_ciudades');
	datos=ruta+'consultasAjax.php?iddeptar='+iddept;
	
	xmlHttp.open("GET", datos);
	xmlHttp.onreadystatechange=function() {
		if (xmlHttp.readyState==4) {
			//alert(ajax.responseText)
			divResultado.innerHTML = xmlHttp.responseText
			
		}
	}
	xmlHttp.send(null)
	
}
//traer listado de cuidades que soportan envios
function TraerCiudadesEnvios(ruta,iddept){
	
	document.getElementById('div_ciudades').style.display='inline';
	divResultado = document.getElementById('div_ciudades');
	datos=ruta+'consultasAjax.php?iddeptarEnvio='+iddept;
	
	xmlHttp.open("GET", datos);
	xmlHttp.onreadystatechange=function() {
		if (xmlHttp.readyState==4) {
			//alert(ajax.responseText)
			divResultado.innerHTML = xmlHttp.responseText
			
		}
	}
	xmlHttp.send(null)
	
}
/*******************************************************/
//Funcionalidad para los clicks de los banners
function ClickBanner(id,ruta){
	
	datos=ruta+'consultasAjax.php?idbanner='+id;
	
	xmlHttp.open("GET", datos);
	xmlHttp.onreadystatechange=function() {
		if (xmlHttp.readyState==4) {
			repu = xmlHttp.responseText.substring(0, 2)
			resto = xmlHttp.responseText.substring(2)
			
			if(repu == "#i"){
			   document.location.href=ruta+'banner/'+id+"/"
			}else if(repu == "#u"){
			   window.open(resto,"nueva")
			}
			
			//return true;
			
		}
	}
	xmlHttp.send(null)
	return false;
	
}


/*******************************************************/
//CARGA DE GENEROS DEPENDIENDO DEL FORMATO DE UN TIPO
var ruta_ajax = "";

function TraerGenerosMusica(ruta,id,id_tipo,div){
	
	document.getElementById(div).style.display='inline';
	divResultado = document.getElementById(div);
	datos=ruta+'consultasAjax.php?idtipo='+id_tipo+'&idformato='+id;
	
	xmlHttp.open("GET", datos);
	xmlHttp.onreadystatechange=function() {
		if (xmlHttp.readyState==4) {
			//alert(ajax.responseText)
			divResultado.innerHTML = xmlHttp.responseText
			
		}
	}
	xmlHttp.send(null)
	
}

function TraerGenerosMusicaBuscar(id,id_tipo,div){
	
	ruta = ruta_ajax
	document.getElementById(div).style.display='inline';
	divResultado = document.getElementById(div);
	datos=ruta+'consultasAjax.php?idtipo='+id_tipo+'&idformato='+id;
	
	xmlHttp.open("GET", datos);
	xmlHttp.onreadystatechange=function() {
		if (xmlHttp.readyState==4) {
			//alert(ajax.responseText)
			divResultado.innerHTML = xmlHttp.responseText
			
		}
	}
	xmlHttp.send(null)
	
}

//Traer formatos de un tipo producto
function TraerFormatos(id_tipo,div){
	
	ruta = ruta_ajax; 
	
	document.getElementById(div).style.display='inline';
	divResultado = document.getElementById(div);
	datos=ruta+'consultasAjax.php?idtipoFomato='+id_tipo;
	
	xmlHttp.open("GET", datos);
	xmlHttp.onreadystatechange=function() {
		if (xmlHttp.readyState==4) {
			//alert(ajax.responseText)
			divResultado.innerHTML = xmlHttp.responseText
			
		}
	}
	xmlHttp.send(null)
	
}

//Funcion de llamada para opciones buscador
function pre_buscar(id_valor,ruta){
	
	if(id_valor == "catalogo"){
		TraerTipos(ruta,"catalogo",'div_tipos');
		document.getElementById('arti_pro').checked='';
		document.getElementById('todo_pro').checked='';
	}else if(id_valor == "todo"){
		document.getElementById('cata_pro').checked='';
		document.getElementById('arti_pro').checked='';
		document.getElementById('div_tipos').style.display='none';
		document.getElementById('div_formatos').style.display='none';
		document.getElementById('div_buscar_generos').style.display='none';
	}else if(id_valor == "artistas"){
		document.getElementById('cata_pro').checked='';
		document.getElementById('todo_pro').checked='';
		document.getElementById('div_tipos').style.display='none';
		document.getElementById('div_formatos').style.display='none';
		document.getElementById('div_buscar_generos').style.display='none';
	}
	
}



//Trae los tipos de productos
function TraerTipos(ruta,id_tipo,div){
	ruta_ajax = ruta; 
	if(id_tipo == "catalogo"){
		document.getElementById(div).style.display='inline';
		divResultado = document.getElementById(div);
		datos=ruta+'consultasAjax.php?idCatBuscar=tipo';
		
		xmlHttp.open("GET", datos);
		xmlHttp.onreadystatechange=function() {
			if (xmlHttp.readyState==4) {
				divResultado.innerHTML = xmlHttp.responseText
				
			}
		}
		xmlHttp.send(null)
		
	}
	
}

//Cambiar de videos en la comunidad
function TraerVideos(ruta,id_media,div){
	ruta_ajax = ruta; 
	
	document.getElementById(div).style.display='inline';
	divResultado = document.getElementById(div);
		
	datos=ruta+'consultasAjax.php?idVideo=si&idmedia='+id_media;
		
	xmlHttp.open("GET", datos);
	xmlHttp.onreadystatechange=function() {
		if (xmlHttp.readyState==4) {
			divResultado.innerHTML = xmlHttp.responseText
		}
	}
	xmlHttp.send(null)
		
}

function getFlashMovieObject(movieName)
{
  if (window.document[movieName]) 
  {
      return window.document[movieName];
  }
  if (navigator.appName.indexOf("Microsoft Internet")==-1)
  {
    if (document.embeds && document.embeds[movieName])
      return document.embeds[movieName]; 
  }
  else
  {
    return document.getElementById(movieName);
  }
}

var nom_parlante = "";
//Llamado al reproductor en flash
function nombremetodo2(url,nombre,parlante)
{
  /*
  if(nom_parlante != ""){
  	document.getElementById(nom_parlante).style.display='none';
  }
  nom_parlante = parlante
  
  document.getElementById(nom_parlante).style.display='block';
  */
  if (navigator.appName.indexOf("Microsoft Internet")==-1){
	   if (window.document.embeds && window.document.embeds["flashjavascript"])
    	  window.document.embeds["flashjavascript"].nombremetodo(url,nombre) 
  
  }else{
	   document.getElementById("flashjavascript").nombremetodo(url,nombre)
  }
   
   
}


//Llamado al reproductor en flash
function pararmetodo2(url,nombre)
{
  
  if (navigator.appName.indexOf("Microsoft Internet")==-1){
	   if (window.document.embeds && window.document.embeds["flashjavascript"])
    	  window.document.embeds["flashjavascript"].pararmetodo() 
  
  }else{
	   document.getElementById("flashjavascript").pararmetodo()
  }
   
   
}


//Validar si el correo existe y es un usuario antiguo
function validar_usuario_antiguo(ruta,correo){
	
	datos=ruta+'consultasAjax.php?correo='+correo;
	
	xmlHttp.open("GET", datos);
	xmlHttp.onreadystatechange=function() {
		if (xmlHttp.readyState==4) {
			if(xmlHttp.responseText == 3){
				alert("Usted ya se encuentra registrado en la pagina anterior")
				document.location.href=ruta+'password/'
			}
			
		}
	}
	
	xmlHttp.send(null)
	
}

//Extension permitida imagen 
function validar_form_perfil(ima){
	   if(document.form_foto.imagen_usuario.value != "" || ima != ""){
		    comprueba_extension(document.form_foto.imagen_usuario.value)
	        var respuesta = comprueba_extension(document.form_foto.imagen_usuario.value)
			
			if(ima != ""){
				respuesta = 1
			}
			
			if(respuesta == 1){
				document.forms.form_foto.submit();
			}else{
				alert(respuesta)
			}
			
		}else{
			alert("Falta imagen");
		}
		
}

function comprueba_extension(archivo) { 
   var extensiones_permitidas = new Array(".gif", ".jpg",".GIF",".JPG"); 
   mierror = ""; 
   
   //recupero la extensión de este nombre de archivo 
   extension = (archivo.substring(archivo.lastIndexOf("."))).toLowerCase(); 
   //compruebo si la extensión está entre las permitidas 
   permitida = false; 
   for (var i = 0; i < extensiones_permitidas.length; i++) { 
     if (extensiones_permitidas[i] == extension) { 
       permitida = true; 
       break; 
     } 
   } 
   if (!permitida) { 
        mierror = "Comprueba la extensión de los archivos a subir. \nSólo se pueden subir archivos con extensiones: " + extensiones_permitidas.join(); 
		return mierror; 
   }else{ 
      //submito! 
      return 1; 
   } 
      
} 

opi=false;

function habilitarcomen() {

   if(opi!=true){
        document.getElementById('comen').style.display='';
        opi=true;
   }else{
        document.getElementById('comen').style.display='none';
        opi=false;
   }
}
