//Cargar div con informacion
var XMLHttpRequestObject = false;

if (window.XMLHttpRequest) {
        XMLHttpRequestObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
        XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}

function loadMember(fuenteDatos, divID){
        if(XMLHttpRequestObject) {
               var obj = document.getElementById(divID);
               XMLHttpRequestObject.open("GET", fuenteDatos);
               XMLHttpRequestObject.onreadystatechange = function(){
                       if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200) {
                           obj.innerHTML = XMLHttpRequestObject.responseText;
                       }
               }
               XMLHttpRequestObject.send(null);
        } 
}

function loadContents(fuenteDatos, divID){
        if(XMLHttpRequestObject) {
               var obj = document.getElementById(divID);
               XMLHttpRequestObject.open("GET", fuenteDatos);
               XMLHttpRequestObject.onreadystatechange = function(){
                       if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200) {
                           obj.innerHTML = XMLHttpRequestObject.responseText;
                       }
               }
               XMLHttpRequestObject.send(null);
        } 
}

function pedirDatos(fuenteDatos, divID){
        if(XMLHttpRequestObject) {
               var obj = document.getElementById(divID);
               XMLHttpRequestObject.open("GET", fuenteDatos);
               XMLHttpRequestObject.onreadystatechange = function(){
                       if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200) {
                           obj.innerHTML = XMLHttpRequestObject.responseText;
                       }
               }
               XMLHttpRequestObject.send(null);
        } 
}

function reloadContent() {
	sendNewsletters('enviar-proceso.php','webFormContent');
}
function sendNewsletters(fuenteDatos, divID){
        if(XMLHttpRequestObject) {
               var obj = document.getElementById(divID);
               XMLHttpRequestObject.open("GET", fuenteDatos);
               XMLHttpRequestObject.onreadystatechange = function(){
                       if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200) {
						   var functionEnding = XMLHttpRequestObject.responseText.split('####');
                           obj.innerHTML = functionEnding[0];
						   if(functionEnding[1] != 'Fin'){
							   setTimeout("reloadContent()",3650000);
						   }
                       }
               }
               XMLHttpRequestObject.send(null);
        } 
}


function cargaDatos(fuenteDatos, divID){
        if(XMLHttpRequestObject) {
               var obj = document.getElementById(divID);
               XMLHttpRequestObject.open("GET", fuenteDatos);
               XMLHttpRequestObject.onreadystatechange = function(){
                       if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200) {
                           obj.innerHTML = XMLHttpRequestObject.responseText;
                       }
               }
               XMLHttpRequestObject.send(null);
        } 
}

//Validaciones formularios
$(document).ready(function() { 
//Contact form
    $('#contactForm').ajaxForm({ 
        target: '#formContacto', 
        success: function() { 
            $('#formContacto').fadeIn('slow'); 
        } 
    }); 	
//Newsletter form
    $('#newsForm').ajaxForm({ 
        target: '#formNewsletter', 
        success: function() { 
            $('#formNewsletter').fadeIn('slow'); 
        } 
    }); 	
//Panel forms
    $('#webForm').ajaxForm({ 
        target: '#webForm', 
        success: function() { 
            $('#webForm').fadeIn('slow'); 
        } 
    }); 	
//Login
$('#loginForm').ajaxForm({ 
        target: '#formLogin', 
        success: function() { 
            $('#formLogin').fadeIn('slow'); 
        } 
    }); 	
//Validate barcode
$('#barcodeForm').ajaxForm({ 
        target: '#formBarcode', 
        success: function() { 
            $('#formBarcode').fadeIn('slow'); 
        } 
    }); 	
//SocioBuscar
$('#socioBuscar').ajaxForm({ 
        target: '#webFormContent', 
        success: function() { 
            $('#webFormContent').fadeIn('slow'); 
        } 
    }); 	
});

//Load info millon
function loadClubMillon() {
	loadMember('lib/modules/center/clubMillon.php','getMiembro');
}	
//Load club 500 000
function loadClub500Mil() {
	loadMember('lib/modules/center/club500Mil.php','getMiembro');
}	



// IE5.5+ PNG Alpha Fix v2.0 Alpha: Background Tiling Support
var IEPNGFix = window.IEPNGFix || {};

IEPNGFix.tileBG = function(elm, pngSrc, ready) {
	// Params: A reference to a DOM element, the PNG src file pathname, and a
	// hidden "ready-to-run" passed when called back after image preloading.

	var data = this.data[elm.uniqueID],
		elmW = Math.max(elm.clientWidth, elm.scrollWidth),
		elmH = Math.max(elm.clientHeight, elm.scrollHeight),
		bgX = elm.currentStyle.backgroundPositionX,
		bgY = elm.currentStyle.backgroundPositionY,
		bgR = elm.currentStyle.backgroundRepeat;

	// Cache of DIVs created per element, and image preloader/data.
	if (!data.tiles) {
		data.tiles = {
			elm: elm,
			src: '',
			cache: [],
			img: new Image(),
			old: {}
		};
	}
	var tiles = data.tiles,
		pngW = tiles.img.width,
		pngH = tiles.img.height;

	if (pngSrc) {
		if (!ready && pngSrc != tiles.src) {
			// New image? Preload it with a callback to detect dimensions.
			tiles.img.onload = function() {
				this.onload = null;
				IEPNGFix.tileBG(elm, pngSrc, 1);
			};
			return tiles.img.src = pngSrc;
		}
	} else {
		// No image?
		if (tiles.src) ready = 1;
		pngW = pngH = 0;
	}
	tiles.src = pngSrc;

	if (!ready && elmW == tiles.old.w && elmH == tiles.old.h &&
		bgX == tiles.old.x && bgY == tiles.old.y && bgR == tiles.old.r) {
		return;
	}

	// Convert English and percentage positions to pixels.
	var pos = {
			top: '0%',
			left: '0%',
			center: '50%',
			bottom: '100%',
			right: '100%'
		},
		x,
		y,
		pc;
	x = pos[bgX] || bgX;
	y = pos[bgY] || bgY;
	if (pc = x.match(/(\d+)%/)) {
		x = Math.round((elmW - pngW) * (parseInt(pc[1]) / 100));
	}
	if (pc = y.match(/(\d+)%/)) {
		y = Math.round((elmH - pngH) * (parseInt(pc[1]) / 100));
	}
	x = parseInt(x);
	y = parseInt(y);

	// Handle backgroundRepeat.
	var repeatX = { 'repeat': 1, 'repeat-x': 1 }[bgR],
		repeatY = { 'repeat': 1, 'repeat-y': 1 }[bgR];
	if (repeatX) {
		x %= pngW;
		if (x > 0) x -= pngW;
	}
	if (repeatY) {
		y %= pngH;
		if (y > 0) y -= pngH;
	}

	// Go!
	this.hook.enabled = 0;
	if (!({ relative: 1, absolute: 1 }[elm.currentStyle.position])) {
		elm.style.position = 'relative';
	}
	var count = 0,
		xPos,
		maxX = repeatX ? elmW : x + 0.1,
		yPos,
		maxY = repeatY ? elmH : y + 0.1,
		d,
		s,
		isNew;
	if (pngW && pngH) {
		for (xPos = x; xPos < maxX; xPos += pngW) {
			for (yPos = y; yPos < maxY; yPos += pngH) {
				isNew = 0;
				if (!tiles.cache[count]) {
					tiles.cache[count] = document.createElement('div');
					isNew = 1;
				}
				var clipR = Math.max(0, xPos + pngW > elmW ? elmW - xPos : pngW),
					clipB = Math.max(0, yPos + pngH > elmH ? elmH - yPos : pngH);
				d = tiles.cache[count];
				s = d.style;
				s.behavior = 'none';
				s.left = (xPos - parseInt(elm.currentStyle.paddingLeft)) + 'px';
				s.top = yPos + 'px';
				s.width = clipR + 'px';
				s.height = clipB + 'px';
				s.clip = 'rect(' +
					(yPos < 0 ? 0 - yPos : 0) + 'px,' +
					clipR + 'px,' +
					clipB + 'px,' +
					(xPos < 0 ? 0 - xPos : 0) + 'px)';
				s.display = 'block';
				if (isNew) {
					s.position = 'absolute';
					s.zIndex = -999;
					if (elm.firstChild) {
						elm.insertBefore(d, elm.firstChild);
					} else {
						elm.appendChild(d);
					}
				}
				this.fix(d, pngSrc, 0);
				count++;
			}
		}
	}
	while (count < tiles.cache.length) {
		this.fix(tiles.cache[count], '', 0);
		tiles.cache[count++].style.display = 'none';
	}

	this.hook.enabled = 1;

	// Cache so updates are infrequent.
	tiles.old = {
		w: elmW,
		h: elmH,
		x: bgX,
		y: bgY,
		r: bgR
	};
};


IEPNGFix.update = function() {
	// Update all PNG backgrounds.
	for (var i in IEPNGFix.data) {
		var t = IEPNGFix.data[i].tiles;
		if (t && t.elm && t.src) {
			IEPNGFix.tileBG(t.elm, t.src);
		}
	}
};
IEPNGFix.update.timer = 0;

if (window.attachEvent && !window.opera) {
	window.attachEvent('onresize', function() {
		clearTimeout(IEPNGFix.update.timer);
		IEPNGFix.update.timer = setTimeout(IEPNGFix.update, 100);
	});
}

//Galeria
$(function(){
  var div = $('div.thumbs'),
               ul = $('ul.thumbsPics'),
               ulPadding = 15;

  var divWidth = div.width();
  div.css({overflow: 'hidden'});
  var lastLi = ul.find('li:last-child');
  div.mousemove(function(e){
    var ulWidth = lastLi[0].offsetLeft + lastLi.outerWidth() + ulPadding;
    var left = (e.pageX - div.offset().left) * (ulWidth-divWidth) / divWidth;
    div.scrollLeft(left);
  });
});

//Galeria DI
$(function(){
  var div = $('div.thumbsDI'),
               ul = $('ul.thumbsPicsDI'),
               ulPadding = 15;

  var divWidth = div.width();
  div.css({overflow: 'hidden'});
  var lastLi = ul.find('li:last-child');
  div.mousemove(function(e){
    var ulWidth = lastLi[0].offsetLeft + lastLi.outerWidth() + ulPadding;
    var left = (e.pageX - div.offset().left) * (ulWidth-divWidth) / divWidth;
    div.scrollLeft(left);
  });
});

//Filtro para las suscripciones
var colum=0; // columna por la que se filtrará
var valor; // value del botón que se ha pulsado

function selecciona(obj,num) {
  t = document.getElementById('tab');
  filas = t.getElementsByTagName('tr');
  // Deseleccionar columna anterior
  for (i=0; ele=filas[i]; i++) 
    ele.getElementsByTagName('td')[colum].className='';
  // Seleccionar columna actual
  colum=num;
  for (i=0; ele=filas[i]; i++)
    ele.getElementsByTagName('td')[colum].className='celdasel';
  // Cambiar botón por cuadro de texto
  valor = obj.value;
  celda = obj.parentNode;
  celda.removeChild(obj);
  txt = document.createElement('input');
  txt.className='input';
  celda.appendChild(txt);
  txt.focus();
  txt.onblur = function() {ponerBoton(this,num)};
  txt.onkeyup = function() {filtra(this.value)};
}

function ponerBoton(obj,num) {
  celda = obj.parentNode;
  celda.removeChild(obj);
  boton = document.createElement('input');
  boton.type = 'button';
  boton.value = valor;
  boton.className='boton';
  boton.onclick = function() {selecciona(this,num)}
  boton.onkeypress = function() {selecciona(this,num)}
  celda.appendChild(boton);
  // Activar botones
  for (i=0; ele=t.getElementsByTagName('input')[i]; i++)
    ele.disabled=false;
}

function filtra(txt) {
  t = document.getElementById('tab');
  filas = t.getElementsByTagName('tr');
  for (i=0; ele=filas[i]; i++) {
    texto = ele.getElementsByTagName('td')[colum].innerHTML.toUpperCase();
    num = 2;
      
    if (num==0) posi = (texto.indexOf(txt.toUpperCase()) == 0);
    else if (num==1) posi = (texto.lastIndexOf(txt.toUpperCase()) == texto.length-txt.length);
    else posi = (texto.indexOf(txt.toUpperCase()) != -1);
    ele.style.display = (posi) ? '' : 'none';
  } 
}

/*Ticker*/
function createAjaxObj(){
	var httprequest=false
	if (window.XMLHttpRequest &&!window.ActiveXObject){ // if Mozilla, Safari etc
		httprequest=new XMLHttpRequest()
		if (httprequest.overrideMimeType)
			httprequest.overrideMimeType('text/xml')
	}
	else if (window.ActiveXObject){ // if IE
		try {
			httprequest=new ActiveXObject("Msxml2.XMLHTTP");
		} 
		catch (e){
			try{
				httprequest=new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e){}
		}
	} //end IE
	return httprequest
}

// -------------------------------------------------------------------
// Main Ajax Ticker Object function
// ajax_ticker(xmlfile, divId, divClass, delay, optionalfadeornot)
// -------------------------------------------------------------------

function ajax_ticker(xmlfile, divId, divClass, delay, fadeornot){
	this.xmlfile=xmlfile //Variable pointing to the local ticker xml file (txt)
	this.tickerid=divId //ID of ticker div to display information
	var delay=(typeof delay=="number")? [delay] : delay //convert parameterif string into array [delay, refetchdelay]
	this.delay=delay[0] //Delay between msg change, in miliseconds.
	this.refetchdelay=delay[1] //Delay between refetching of Ajax contents
	this.mouseoverBol=0 //Boolean to indicate whether mouse is currently over ticker (and pause it if it is)
	this.pointer=0
	this.opacitystring=(typeof fadeornot!="undefined")? "width: 100%; filter:progid:DXImageTransform.Microsoft.alpha(opacity=100); opacity: 1" : ""
	if (this.opacitystring!="") this.delay+=500 //add 1/2 sec to account for fade effect, if enabled
		this.opacitysetting=0.2 //Opacity value when reset. Internal use.
	this.messages=[] //Arrays to hold each message of ticker
	this.ajaxobj=createAjaxObj()
	document.write('<div id="'+divId+'" class="'+divClass+'"><div style="'+this.opacitystring+'"></div></div>')
	this.getXMLfile()
}

// -------------------------------------------------------------------
// getXMLfile()- Use Ajax to fetch xml file (txt)
// -------------------------------------------------------------------

ajax_ticker.prototype.getXMLfile=function(){
	this.ajaxobj=createAjaxObj() //recreate Ajax object (IE seems to require it)
	if (this.ajaxobj){
		var instanceOfTicker=this
		var url=this.xmlfile+"?bustcache="+new Date().getTime()
		this.ajaxobj.onreadystatechange=function(){instanceOfTicker.initialize()}
		this.ajaxobj.open('GET', url, true)
		this.ajaxobj.send(null)
	}
}

// -------------------------------------------------------------------
// initialize()- Initialize ticker method.
// -Gets contents of xml file and parse it using JavaScript DOM methods 
// -------------------------------------------------------------------

ajax_ticker.prototype.initialize=function(){
	if (this.ajaxobj.readyState == 4){ //if request of file completed
		if (this.ajaxobj.status==200 || window.location.href.indexOf("http")==-1){ //if request was successful
			this.contentdiv=document.getElementById(this.tickerid).firstChild //div of inner content that holds the messages
			var xmldata=this.ajaxobj.responseText
			this.contentdiv.style.display="none"
			this.contentdiv.innerHTML=xmldata
			if (this.contentdiv.getElementsByTagName("div").length==0){ //if no messages were found
				this.contentdiv.innerHTML="<b>Error</b> fetching remote ticker file!"
				return
			}
		var instanceOfTicker=this
		document.getElementById(this.tickerid).onmouseover=function(){instanceOfTicker.mouseoverBol=1}
		document.getElementById(this.tickerid).onmouseout=function(){instanceOfTicker.mouseoverBol=0}
		clearTimeout(this.fadetimer1) //clear timers
		clearTimeout(this.pausetimer)
		clearTimeout(this.rotatetimer)
		this.mouseoverBol=0
		this.messages=[] //reset messages[] to blank array (in the event initialize is being called again)
		//Cycle through XML object and store each message inside array
		for (var i=0; i<this.contentdiv.getElementsByTagName("div").length; i++){
			if (this.contentdiv.getElementsByTagName("div")[i].className=="mensaje")
				this.messages[this.messages.length]=this.contentdiv.getElementsByTagName("div")[i].innerHTML
		}
		this.contentdiv.innerHTML=""
		this.contentdiv.style.display="block"
		this.rotatemsg()
		if (this.refetchdelay>5000) //if refetch data delay is greater than 5 seconds
			setTimeout(function(){instanceOfTicker.getXMLfile()}, this.refetchdelay)
		}
	}
}

// -------------------------------------------------------------------
// rotatemsg()- Rotate through ticker messages and displays them
// -------------------------------------------------------------------

ajax_ticker.prototype.rotatemsg=function(){
	var instanceOfTicker=this
	if (this.mouseoverBol==1) //if mouse is currently over ticker, do nothing (pause it)
		this.pausetimer=setTimeout(function(){instanceOfTicker.rotatemsg()}, 100)
	else{ //else, construct item, show and rotate it!
		if (this.contentdiv.filters) //In IE, reapply filter attribute each time
			this.contentdiv.style.filter="progid:DXImageTransform.Microsoft.alpha(opacity="+(this.opacitysetting*100)+")";
		this.fadetransition("reset")
		this.contentdiv.innerHTML=this.messages[this.pointer]
		this.fadetimer1=setInterval(function(){instanceOfTicker.fadetransition('up', 'fadetimer1')}, 100) //FADE EFFECT- PLAY IT
		this.pointer=(this.pointer<this.messages.length-1)? this.pointer+1 : 0
		this.rotatetimer=setTimeout(function(){instanceOfTicker.rotatemsg()}, this.delay) //update container periodically
	}
}

// -------------------------------------------------------------------
// fadetransition()- cross browser fade method for IE5.5+ and Mozilla/Firefox
// -------------------------------------------------------------------

ajax_ticker.prototype.fadetransition=function(fadetype, timerid){
	var contentdiv=this.contentdiv
	if (fadetype=="reset")
		this.opacitysetting=0.2
	if (contentdiv.filters && contentdiv.filters[0]){
		if (typeof contentdiv.filters[0].opacity=="number") //IE6+
			contentdiv.filters[0].opacity=this.opacitysetting*100
		else //IE 5.5
			contentdiv.style.filter="alpha(opacity="+this.opacitysetting*100+")"
	}
	else if (contentdiv.style.opacity!="undefined"){
		contentdiv.style.opacity=this.opacitysetting
	}
	else
		this.opacitysetting=1
	if (fadetype=="up")
		this.opacitysetting+=0.1
	if (fadetype=="up" && this.opacitysetting>=1){
		if (contentdiv.style && contentdiv.style.removeAttribute)
			contentdiv.style.removeAttribute('filter') //fix IE clearType problem
		clearInterval(this[timerid])
	}
}

