var e24Gallery = new Class ({
	initialize: function(sessid, ishome, options) {
		this.ishome = ishome;
		this.sessid = sessid;
		this.zindex = 7000;
		this.playing = false;
		this.categories = [];
		this.clearFilters();
		this.width = 390;
		this.height = 376;
		this.currentPage = 0;
		this.currentPhoto = 0;
		this.pages = [];
		
		this.externallinks();
		this.emptyinputs();		
		
		if (!this.ishome) {
			//Gallery things...
			this.container = $('gallery');
			this.pageinfo = $('pageinfo');
			this.pagination = $('pages');
			this.pagesloading = $('pagesloading');
			this.previewnores = $('previewnores');
			this.previewloading = $('previewloading');
			this.previewzoom = $('previewzoom');
			this.previewimg = $('previewimg');
			this.photocategory = $('photocategory');
			this.photodate = $('photodate');
			this.phototime = $('phototime');
			this.photoviews = $('photoviews');
			this.photodownloads = $('photodownloads');
			this.playerimg = $('playerimg');
			this.ratingEl = $('rabidRating1');
			this.ratingEl2 = $('rabidRating2');			
			this.menu = $('menu');			
			this.eventname = $('eventname');			
			//EOf Gallery things...

			//Info Panel things...
			this.eventlink = $('eventlink');
			this.eventmap = $('eventmap');
			this.infopanel = $('infopanel');
			//EOF Info Panel things...


			//Time selector filter
			this.initime = $('initime');
			this.endtime = $('endtime');
			//EOF Time selector filter

			//Categories selector filter
			this.catcontainer = $('categories');
			
			//Share it things..
			this.shareform = $('shareform');
			this.shareemail = $('shareemail');
			this.sharename = $('sharename');
			this.friendemail1 = $('friendemail1');
			this.friendemail2 = $('friendemail2');
			this.friendemail3 = $('friendemail3');
			this.friendemail4 = $('friendemail4');
			this.friendemail5 = $('friendemail5');
			this.friendname1 = $('friendname1');
			this.friendname2 = $('friendname2');
			this.friendname3 = $('friendname3');
			this.friendname4 = $('friendname4');
			this.friendname5 = $('friendname5');
			this.sharecapcha = $('sharecapcha');
			this.sharecapchares = $('sharecapchares');
			this.sharemsg = $('sharemsg');
			this.shareitbtn = $('shareitbtn');
			this.closesharebtn = $('closesharebtn');
			this.shareimg = $('shareimg');
			//EOF Share it things..
			
			//Zoom photo window...
			this.zoomwin = new e24mooWin($('player'), {closebtn: $('closebtn'), width: 200, height: 100, callback:this.onShowWin.bind(this)});
			//Ratings engine...
			this.rating = new RabidRatings({onvote:this.vote.bind(this)});
			
			this.pagesloadingappear = new Fx.Style(this.pagesloading, 'opacity', {duration:500, onComplete: function() {this.pagesloading.setStyle('display', 'none');}.bind(this)});
			this.loadingappear = new Fx.Style(this.previewloading, 'opacity', {duration:500, onComplete: function() {this.previewloading.setStyle('display', 'none');}.bind(this)});
			this.scroll = new Fx.Scroll('gallerywrapper', {
				wait: false,
				offset: {'x': 0, 'y': 0},
				wheelStops: false,			
				duration: 500,
				transition: Fx.Transitions.Quad.easeInOut
			});			
			
			//Menu Event Hnadlers...
			$('menucata').addEvent('click', function(e) {
				e = new Event(e);
				e.stop();	
				this.getPhotos(1);
			}.bind(this));
			$('menucata2').addEvent('click', function(e) {
				e = new Event(e);
				e.stop();	
				this.getPhotos(1);
			}.bind(this));
			$('menucruces').addEvent('click', function(e) {
				e = new Event(e);
				e.stop();	
				this.getPhotos(2);
			}.bind(this));
			$('menucruces2').addEvent('click', function(e) {
				e = new Event(e);
				e.stop();	
				this.getPhotos(2);
			}.bind(this));
			$('menuferia').addEvent('click', function(e) {
				e = new Event(e);
				e.stop();	
				this.getPhotos(4);
			}.bind(this));
			$('menuferia2').addEvent('click', function(e) {
				e = new Event(e);
				e.stop();	
				this.getPhotos(4);
			}.bind(this));
			$('menupatios').addEvent('click', function(e) {
				e = new Event(e);
				e.stop();	
				this.getPhotos(3);
			}.bind(this));
			$('menupatios2').addEvent('click', function(e) {
				e = new Event(e);
				e.stop();	
				this.getPhotos(3);
			}.bind(this));
			//EOF Menu Event Hnadlers...
			
			//Photo Player Event Hnadlers...
			$('prev').addEvent('click', function (e) {
				e = new Event(e);
				e.stop();	
				if (!this.playing && this.currentPhoto > 0) {
					this.previewPhoto(this.currentPhoto-1);
				}	
			}.bind(this));
			$('next').addEvent('click', function (e) {
				e = new Event(e);
				e.stop();	
				if (!this.playing && this.currentPhoto < this.data.total - 1) {
					this.previewPhoto(this.currentPhoto+1);
				}	
			}.bind(this));
			$('play').addEvent('click', function(e) {
				e = new Event(e);
				e.stop();	
				if (this.currentPhoto < this.data.total - 1) {
					this.playing = true;
					this.previewPhoto(this.currentPhoto+1);
				}
			}.bind(this));
			$('stop').addEvent('click', function(e) {
				e = new Event(e);
				e.stop();
				this.playing = false;	
				$clear(this.playTimer);
			}.bind(this));
			$('zoom').addEvent('click', this.zoom.bind(this));
			$('leftarrow').addEvent('click', this.goLeft.bind(this));
			$('rightarrow').addEvent('click', this.goRight.bind(this));
			$('previewzoom').addEvent('click', this.zoom.bind(this));
			$('shareit').addEvent('click', function(e) {
				e = new Event(e);
				e.stop();	
				this.showShareIt(this.previewimg);
			}.bind(this));
			$('shareit2').addEvent('click', function(e) {
				e = new Event(e);
				e.stop();	
				this.showShareIt(this.previewimg);
			}.bind(this));
			//EOF Photo Player Event Hnadlers...
			
			//Time filter Event Hnadlers...
	     	this.inislider = new Slider('slideContainer', 'slideHandle1',{step:0, steps:24, onChange: this.onIniSliderChange.bind(this), onComplete: this.onIniSlider.bind(this)});
	     	this.endslider = new Slider('slideContainer', 'slideHandle2',{step:24, steps:24, onChange: this.onEndSliderChange.bind(this), onComplete: this.onEndSlider.bind(this)});		
			$('amanecer').addEvent('click', function(e) {
				this.presetTime(0, 6);
			}.bind(this));
			$('dia').addEvent('click', function(e) {
				this.presetTime(6, 12);
			}.bind(this));
			$('atardecer').addEvent('click', function(e) {
				this.presetTime(12, 18);
			}.bind(this));
			$('noche').addEvent('click', function(e) {
				this.presetTime(18, 24);
			}.bind(this));
			//EOF Time filter Event Hnadlers...

			//Other filters Event Hnadlers...
			$('delfilters').addEvent('click', function(e) {
				e = new Event(e);
				e.stop();	
				this.clearFilters();
				this.showPhotos();
			}.bind(this));
			$('delfilters2').addEvent('click', function(e) {
				e = new Event(e);
				e.stop();	
				this.clearFilters();
				this.showPhotos();
			}.bind(this));
			
			$ES('a','calendar').each(function (item) {
				item.addEvent('click', this.goDate.bindWithEvent(this, item.getText()));  ;
			}.bind(this));
			//EOF Other filters Event Hnadlers...			
			
			this.shareitbtn.addEvent('click', function(e) {
				e = new Event(e);
				e.stop();	
				this.onShareIt();
			}.bind(this));
		}
		

		/*
		//Banners Event Hnadlers...
		$('banner5').addEvent('click', function(e) {
			e = new Event(e);
			e.stop();	
			this.showMsg($('banner5'), '<h1>Abad cepedello</h1> <h2>Asesoría laboral</h2>Tlf. 957232048<br/>Avda República Argentina,<br/>14004 Córdoba<br/>Córdoba (España)<br/><a target="blank" href="http://maps.google.es/maps?f=q&hl=es&geocode=&q=Avda+R%C3%A9p%C3%BAblica+Argentina+c%C3%B3rdoba&sll=37.887352,-4.789824&sspn=0.007722,0.014505&ie=UTF8&ll=37.886793,-4.788795&spn=0.007722,0.014505&t=h&z=16&iwloc=addr">Ver Mapa</a>', undefined, 350, 300);
		}.bind(this));
		$('banner6').addEvent('click', function(e) {
			e = new Event(e);
			e.stop();	
			this.showMsg($('banner6'), '<h1>Bulebar</h1> Pasa un rato agradable entre amigos y tapas en Bulevar Hernán Ruiz<br/><a target="blank" href="http://maps.google.es/maps?f=q&hl=es&geocode=&q=hernan+ruiz+c%C3%B3rdoba&sll=37.886184,-4.789599&sspn=0.001931,0.003626&ie=UTF8&ll=37.887352,-4.789824&spn=0.007722,0.014505&t=h&z=16&iwloc=addr">Ver Mapa</a>', undefined, 350, 250);
		}.bind(this));
		$('banner10').addEvent('click', function(e) {
			e = new Event(e);
			e.stop();	
			this.showMsg($('banner10'), '<h1>EXPO MIRADAS MONTERAS</h1> <h2>García-Gálvez</h2><p>Salón Gran Capitán. Fundación CajaSur</p><p>Del 4 al 18 de junio</p><p>En esta nueva exposición, presentamos varios retratos de estudio, donde los protagonistas han sido algunos representantes de la raza canina, anónimos actores de los mil y un lances que acaecen durante las jornadas de caza mayor en Sierra Morena, intentando captar la personalidad de cada perro, su carácter, nobleza y señorío.</p><p>Se trata de una serie limitada. De cada obra sólo existen 5 copias, más la de autor. Todas ellas llevan su correspondiente certificado de autenticidad.</p><p>Cada copia se ha realizado primorosamente sobre el prestigioso papel texturizado HP Hahnemühle de 310gr/m2. </p>', undefined, 400, 380);
		}.bind(this));
		//EOF Time filter Event Hnadlers...
		*/

		//Login form things...
		this.email = $('email');
		this.password = $('password');
		//this.remenber = $('remenber');
		this.loginform = $('loginform');
		this.email2 = $('email2');
		this.password2 = $('password2');
		//this.remenber2 = $('remenber2');
		this.loginform2 = $('loginform2');
		this.loggedin = $('loggedin');
		this.welcome = $('welcome');
		//EOF Login form things...
		
		//Profile  form things...
		this.profile = $('profile');
		this.profilebtn = $('profilebtn');
		this.regemail2 = $('regemail2');
		this.regpassword3 = $('regpassword3');
		this.regpassword4 = $('regpassword4');
		this.fullname2 = $('fullname2');
		this.sex2 = $('sex2');
		this.day2 = $('day2');
		this.month2 = $('month2');
		this.year2 = $('year2');
		this.allowpubli2 = $('allowpubli2');
		this.accept2 = $('accept2');
		this.capcha2 = $('capcha2');
		this.capchares2 = $('capchares2');
		//EOF Profile form things...
		
		//Register form things...
		this.register = $('register');
		this.registerbtn = $('registerbtn');
		this.registertext = $('registertext');
		this.regemail = $('regemail');
		this.regpassword = $('regpassword');
		this.regpassword2 = $('regpassword2');
		this.fullname = $('fullname');
		this.sex = $('sex');
		this.day = $('day');
		this.month = $('month');
		this.year = $('year');
		this.allowpubli = $('allowpubli');
		this.accept = $('accept');
		this.capcha = $('capcha');
		this.capchares = $('capchares');
		//EOF Register form things...
		
		//Forgot pw form...
		this.forgotpwform = $('forgotpwform');
		this.forgotbtn = $('forgotbtn');
		this.closeforgotbtn = $('closeforgotbtn');
		this.forgotemail = $('forgotemail');
		this.forgotcapcha = $('forgotcapcha');
		this.forgotcapchares = $('forgotcapchares');
		//EOFForgot pw form...

		//Contact form...
		this.contactform = $('contactform');
		this.contactbtn = $('contactbtn');
		this.closecontactbtn = $('closecontactbtn');
		this.contactname = $('contactname');
		this.contactemail = $('contactemail');
		this.contactsubject = $('contactsubject');
		this.contactmsg = $('contactmsg');
		this.contactcapcha = $('contactcapcha');
		this.contactcapchares = $('contactcapchares');
		//EOF Contact form...

		
		this.download = $('download');

		this.screenScroll = new SmoothScroll({ duration: 800, links: [] });		
		

		//Login form event handlers...
		$('loginbtn').addEvent('click', function(e) {
			e = new Event(e);
			e.stop();	
			this.login();
		}.bind(this));
		$('loginbtn2').addEvent('click', function(e) {
			e = new Event(e);
			e.stop();	
			this.login2();
		}.bind(this));
		$('logout').addEvent('click', function(e) {
			e = new Event(e);
			e.stop();	
			this.logout();
		}.bind(this));
		$('unregister').addEvent('click', function(e) {
			e = new Event(e);
			e.stop();	
			this.unregister();
		}.bind(this));
		$('registernow').addEvent('click', function(e) {
			e = new Event(e);
			e.stop();	
			this.showRegister(this.loginform, 'Tome 15 segundos de su valioso tiempo y regístrese');
		}.bind(this));
		$('editprofile').addEvent('click', function(e) {
			e = new Event(e);
			e.stop();	
			this.showProfile(this.loggedin);
		}.bind(this));
		$('forgotlink').addEvent('click', function(e) {
			e = new Event(e);
			e.stop();	
			this.showForgot(this.loginform);
		}.bind(this));
		$('forgotlink2').addEvent('click', function(e) {
			e = new Event(e);
			e.stop();	
			this.showForgot(this.loginform);
		}.bind(this));
		$('menucontact').addEvent('click', function(e) {
			e = new Event(e);
			e.stop();	
			this.showContact(this.loginform);
		}.bind(this));
		$('menucontact2').addEvent('click', function(e) {
			e = new Event(e);
			e.stop();	
			this.showContact(this.loginform);
		}.bind(this));
		//EOF Login form event handlers...		
		

		//Window buttons event handlers...	
		this.profilebtn.addEvent('click', function(e) {
			e = new Event(e);
			e.stop();	
			this.onProfile();
		}.bind(this));
		this.registerbtn.addEvent('click', function(e) {
			e = new Event(e);
			e.stop();	
			this.onRegister();
		}.bind(this));
		this.forgotbtn.addEvent('click', function(e) {
			e = new Event(e);
			e.stop();	
			this.onForgot();
		}.bind(this));
		this.contactbtn.addEvent('click', function(e) {
			e = new Event(e);
			e.stop();	
			this.onContact();
		}.bind(this));
		//EOF Window buttons event handlers...
		
		
	},

	externallinks: function() {
		$ES('a').each(function(el) {
			if (el.getProperty('rel') == 'external') {
				el.addEvent('click', function(e) {
					e = new Event(e);
					e.stop();	
					window.open(this.getProperty('href'));
				}.bind(el));
			}	
	    });
	},
	
	emptyinputs: function() {
		$ES('input').each(function(el) {
			el.setProperty('value', ''); 
	    });
		$ES('textarea').each(function(el) {
			el.setHTML(''); 
	    });
	},
	
	hideLoading: function(loadingdata) {
		loadingdata.fx.start(0.8, 0); 	
		loadingdata.div.remove();	
	},
	
	showLoading: function(el) {
	   var coords = el.getCoordinates();
	   loadingdiv = new Element('div', {
		    'styles': {
		        'position': 'absolute',
		        'background': '#fff',
		        'opacity': '0',
		        'left': 0 + 'px',
		        'top': 0 + 'px',
		        //'left': coords.left + 'px',
		        //'top': coords.top + 'px',
		        'width': coords.width + 'px',
		        'height': coords.height + 'px'
		    }
		});	
		loadingdiv.injectInside(el);
		//loadingdiv.injectInside(document.body);
		loadingdiv.setHTML('<TABLE WIDTH="100%" HEIGHT="100%"><TR><TD VALIGN="MIDDLE" ALIGN="CENTER"><IMG SRC="images/loader.gif" /></TD></TR></TABLE>');
		/*var loadergif = new Element('div', {
		    'styles': {
		        'display': 'block',
		        'background': 'url(images/loader.gif)',
		        'margin': '50% auto',
		        'margin-left': '50%',
		        'width': '35px',
		        'height': '35px'
		    }
		});	
		loadergif.injectInside(loadingdiv);*/
		var loadingfx = new Fx.Style(loadingdiv, 'opacity', {duration:800, onComplete: function() {
			//if (this.now == 0) this.remove();
		}});
		//}.bind(loadingdiv)});
		loadingdiv.setStyle('display', 'block'); 		
		loadingfx.start(0, 0.8);
		return {div: loadingdiv, fx: loadingfx};
	},

	showMsg: function(el, text, yesbtn, pwidth, pheight) {
	   var  width = pwidth?pwidth:248;
	   var  height = pheight?pheight:100;
	   
	    var wrapper = new Element('div', {
		    'styles': {
		        'width': width + 'px',
		        'height': height + 'px'
		    },
		    'class': 'win_cell'		    
		});	
	    var textdiv = new Element('div', {
		    'styles': {
		        'float': 'left',
		        'padding': '5px',
		        'width': width + 'px',
		        'height': (height - 60) + 'px'
		    }
		}).setHTML(text);	
	    textdiv.injectInside(wrapper);
	    var toolbardiv = new Element('div', {
		    'styles': {
		        'float': 'left',
		        'text-aling': 'center',
		        'width': width + 'px',
		        'height': '50px'
		    }
		}).injectInside(wrapper);
	    
		
		if (yesbtn) {
		    var btn = new Element('a', {
			    'styles': {
			        'float': 'left',
			        'margin-left': '10px'
			    },
		   		'class': 'btn'
		    }).setHTML('Cancelar');	

			var msgwin = new e24mooWin(wrapper, {closebtn: btn, width: width + 2, height: height + 20});		

		    var ybtn = new Element('a', {
			    'styles': {
			        'float': 'left',
			        'margin-left': '40px'
			    },
				'events': {
					'click': function(e, win){
						e = new Event(e);
						e.stop();
						win.close();
						yesbtn();
					}.bindWithEvent(this, msgwin)
				},												
		   		'class': 'btn'
		    }).setHTML('Aceptar');				
			ybtn.injectInside(toolbardiv);
			btn.injectInside(toolbardiv);			
		}	
		else {
		    var btn = new Element('a', {
			    'styles': {
			        'float': 'left',
			        'margin-left': (width - 80)/2 + 'px'
			    },
		   		'class': 'btn'
		    }).setHTML('Aceptar');	
			btn.injectInside(toolbardiv);
			var msgwin = new e24mooWin(wrapper, {closebtn: btn, width: width + 2, height: height + 20});		

		}

	    this.zindex += 2;
	    msgwin.show(el, {zindex:this.zindex, width: (width + 12) + 'px', height: (height + 10) + 'px', remove: true });
	},

	
	showProfile: function(el) {
	    this.profilewin = new e24mooWin(this.profile, {closebtn: $('closeprofilebtn'), width: 500, height: 340, callback: this.getProfile.bind(this)});		
	    this.zindex += 2;
	    this.profilewin.show(el, {zindex:this.zindex, width: '500px', height: '340px', remove: false });
	},
	
	getProfile: function() {
		this.getCapcha();
		this.loadinghandle = this.showLoading(this.profilewin.window);
		this.jsonRequest = new Json.Remote("ajaxapi/getphotos.php?sid=" + this.sessid + "&task=gprofile&idevent=" + this.idevent, {onComplete: this.getProfileOk.bind(this), onFailure: this.profileFail.bind(this)}).send();		
	},

	getProfileOk: function(data) {
		if (data.success) {
			this.hideLoading(this.loadinghandle);			
			this.checkLoginStatus(data);		
			this.regemail2.setProperty('value', data.user.email);
			this.fullname2.setProperty('value', data.user.fullname);
			this.sex2.setProperty('value', data.user.sex?'h':'m');
			this.day2.setProperty('value', date('j', data.user.birthdate));
			this.month2.setProperty('value', date('n', data.user.birthdate));
			this.year2.setProperty('value', date('Y', data.user.birthdate));
			this.allowpubli2.setProperty('checked', data.user.allowpubli);
		}
		else {
			this.showMsg(this.loggedin, data.msg);
			this.hideLoading(this.loadinghandle);			
		}
	},
	
	showRegister: function(el, text) {
		this.registertext.setHTML(text);
	    this.registerwin = new e24mooWin(this.register, {closebtn: $('closeformbtn'), width: 500, height: 540, callback: this.getCapcha.bind(this)});		
	    this.zindex += 2;
	    this.registerwin.show(el, {zindex:this.zindex, width: '500px', height: '540px', remove: false });
	},
	
	showShareIt: function(el) {
	    this.shareitwin = new e24mooWin(this.shareform, {closebtn: $('closesharebtn'), width: 539, height: 540, callback: this.getCapcha.bind(this)});		
	    this.zindex += 2;
	    this.shareimg.setProperty('src', this.photoPath(this.data.results[this.currentPhoto],'small'));
	    this.shareitwin.show(el, {zindex:this.zindex, width: '539px', height: '540px', remove: false });
	},
	
	showForgot: function(el) {
	    this.forgotwin = new e24mooWin(this.forgotpwform, {closebtn: $('closeforgotbtn'), width: 480, height: 200, callback: this.getCapcha.bind(this)});		
	    this.zindex += 2;
	    this.forgotwin.show(el, {zindex:this.zindex, width: '480px', height: '200px', remove: false });
	},
	
	showContact: function(el) {
	    this.contactwin = new e24mooWin(this.contactform, {closebtn: $('closecontactbtn'), width: 480, height: 370, callback: this.getCapcha.bind(this)});		
	    this.zindex += 2;
	    this.contactwin.show(el, {zindex:this.zindex, width: '480px', height: '370px', remove: false });
	},
	
	getCapcha: function() {
		this.jsonRequest = new Json.Remote("ajaxapi/getphotos.php?sid=" + this.sessid + "&task=capcha",
											{onComplete: this.capchaOk.bind(this)}).send();		
		
	},

	capchaOk: function(data) {
		if (data.success) {
			this.capcha.setHTML(data.capcha);
			this.capcha2.setHTML(data.capcha);
			if (!this.ishome) {
				this.sharecapcha.setHTML(data.capcha);
			}	
			this.contactcapcha.setHTML(data.capcha);
			this.forgotcapcha.setHTML(data.capcha);
		}
	},
	
	vote: function(votePercent) {
		if (this.session.status == 'login') {
			this.jsonRequest = new Json.Remote("ajaxapi/getphotos.php?sid=" + this.sessid + "&task=vote&idevent=" + this.idevent + '&idphoto=' + this.data.results[this.currentPhoto].id + '&vote=' + votePercent,
												{onComplete: this.voteOk.bind(this), onFailure: this.voteFail.bind(this)}).send();		
		}
		else {
			this.rating.startVote(this.ratedata.rateinfo.percent, this.ratingEl, this.ratedata.rateinfo.voted);
			this.rating.startVote(this.ratedata.rateinfo.percent, this.ratingEl2, this.ratedata.rateinfo.voted);
			//this.showMsg(this.ratingEl, 'Necesita estar registrado para votar');
			this.showRegister(this.ratingEl, 'Necesita estar registrado para votar');
		}										
	},

	voteOk: function(data) {
		if (data.success) {
			this.checkLoginStatus(data);	
			this.loadRate(data);	
			this.ratingEl.showSuccess(data.msg);
			this.ratingEl2.showSuccess(data.msg);
		}
		else {
			this.checkLoginStatus(data, true, 'votar');		
			this.ratingEl.updateText(data.msg, true);			
			this.ratingEl2.updateText(data.msg, true);			
			this.rating.startVote(this.ratedata.rateinfo.percent, this.ratingEl, this.ratedata.rateinfo.voted);			
			this.rating.startVote(this.ratedata.rateinfo.percent, this.ratingEl2, this.ratedata.rateinfo.voted);			
			if (data.code != 403) {
				this.showMsg(this.ratingEl, data.msg);
			}	
		}
	},
	
	voteFail: function(data) {
		this.ratingEl.updateText('Inténtelo de nuevo más tarde', true);
		this.ratingEl2.updateText('Inténtelo de nuevo más tarde', true);
		this.rating.startVote(this.ratedata.rateinfo.percent, this.ratingEl, this.ratedata.rateinfo.voted);
		this.rating.startVote(this.ratedata.rateinfo.percent, this.ratingEl2, this.ratedata.rateinfo.voted);
		this.showMsg(this.ratingEl, 'El servicio no se encuentra disponible en este momento. Inténtelo de nuevo más tarde.');
	},
	
	loadRate: function(data) {
		if (data.success) {
			this.ratedata = data;
			this.rating.startVote(data.rateinfo.percent, this.ratingEl, data.rateinfo.voted);
			this.rating.startVote(data.rateinfo.percent, this.ratingEl2, data.rateinfo.voted);
			if (data.rateinfo.total) {
				this.ratingEl.updateText(data.rateinfo.rate + ' (' + data.rateinfo.total + ' voto' + (data.rateinfo.total>1?'s':'') + ')');
				this.ratingEl2.updateText(data.rateinfo.rate + ' (' + data.rateinfo.total + ' voto' + (data.rateinfo.total>1?'s':'') + ')');
			}
			else {
				this.ratingEl.updateText('Se el primero votarla!');				
				this.ratingEl2.updateText('Se el primero votarla!');				
			}	
		}
		else {
			this.rating.startVote(0, this.ratingEl, false);
			this.rating.startVote(0, this.ratingEl2, false);
			this.ratingEl2.updateText('Desconocido');
		}		
	},
	
	
	logout: function() {
		this.loadinghandle = this.showLoading(this.loggedin);
		this.jsonRequest = new Json.Remote("ajaxapi/getphotos.php?sid=" + this.sessid + "&task=logout&idevent=" + this.idevent, {onComplete: this.logoutOk.bind(this), onFailure: this.logoutFail.bind(this)}).send();		
	},

	unregister: function() {
		this.showMsg(this.loggedin, '¿Está seguro de darse de baja permanentemente de nuestro sitio?', this.yesUnregister.bind(this));
	},

	yesUnregister: function() {
		this.loadinghandle = this.showLoading(this.loggedin);
		this.jsonRequest = new Json.Remote("ajaxapi/getphotos.php?sid=" + this.sessid + "&task=unreg&idevent=" + this.idevent, {onComplete: this.unregOk.bind(this), onFailure: this.logoutFail.bind(this)}).send();		
	},

	unregOk: function(data) {
		if (data.success) {
			this.hideLoading(this.loadinghandle);			
			this.checkLoginStatus(data);		
			this.showMsg(this.loggedin, 'Ha sido dado de baja de nuestros servicios. Esperamos verle de vuelta pronto.');
		}
		else {
			this.showMsg(this.loggedin, data.msg);
			this.hideLoading(this.loadinghandle);			
		}
	},
	
	
	onShowWin: function() {
		this.rating.startVote(this.ratedata.rateinfo.percent, this.ratingEl2, this.ratedata.rateinfo.voted);
	},

	logoutOk: function(data) {
		if (data.success) {
			this.hideLoading(this.loadinghandle);			
			this.checkLoginStatus(data);		
		}
		else {
			this.showMsg(this.loggedin, data.msg);
			this.hideLoading(this.loadinghandle);			
		}
	},
	
	logoutFail: function(data) {
		this.showMsg(this.loggedin, 'El servicio no se encuentra disponible en este momento. Inténtelo de nuevo más tarde.');
		this.hideLoading(this.loadinghandle);			
	},
	
	checkLoginStatus: function(data, forceregister, forcetext) {
		this.session = data.session;
		this.sessid = data.session.sid;
		
		if (data.session.status == 'login') {
			this.welcome.setHTML('<strong>Hola, </strong> ' + data.session.fullname);
			this.loginform.setStyle('display', 'none');
			this.loggedin.setStyle('display', 'block');
		}
		else {
			this.loggedin.setStyle('display', 'none');
			this.loginform.setStyle('display', 'block');			
			if (forceregister) {
				this.showMsg(this.previewimg, 'Necesita estar registrado para ' + forcetext);
			}
		}
	},
	
	login: function() {
		this.loadinghandle = this.showLoading(this.loginform);
		var email = this.email.getValue();
		var password = this.password.getValue();
		//var remenber = this.remenber.getProperty('checked');
		this.jsonRequest = new Json.Remote("ajaxapi/getphotos.php?sid=" + this.sessid + "&task=login&idevent=" + this.idevent, {onComplete: this.loginOk.bind(this), onFailure: this.loginFail.bind(this)}).send(
			{email: email, pw: password}
			//{email: email, pw: password/*, remenber: remenber*/}
		);		
	},
		
	login2: function() {
		this.loadinghandle = this.showLoading(this.loginform2);
		var email = this.email2.getValue();
		var password = this.password2.getValue();
		//var remenber = this.remenber2.getProperty('checked');
		this.jsonRequest = new Json.Remote("ajaxapi/getphotos.php?sid=" + this.sessid + "&task=login&idevent=" + this.idevent, {onComplete: this.loginOk.bind(this), onFailure: this.loginFail.bind(this)}).send(
			{email: email, pw: password}
			//{email: email, pw: password, remenber: remenber}
		);		
	},
		
	loginOk: function(data) {
		if (data.success) {
			this.hideLoading(this.loadinghandle);			
			this.checkLoginStatus(data);
			if (this.registerwin) {
				this.registerwin.close();
				this.registerwin = undefined;
			}
		}
		else {
			this.showMsg(this.loginform, data.msg);
			this.hideLoading(this.loadinghandle);			
		}
	},
	
	loginFail: function(data) {
		this.showMsg(this.loginform, 'El servicio no se encuentra disponible en este momento. Inténtelo de nuevo más tarde.');
		this.hideLoading(this.loadinghandle);			
	},

	checkEmail: function(email)	{
	  var re;
	  re = /^\s+/g;
	  email = email.replace(re, "");
	  re = /\s+$/g;
	  email = email.replace(re, "");
	
	  var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	
	  if (!filter.test(email)) {
	    return false;
	  }
	  return true;
	  
	},
	
	onRegister: function() {
		var email = this.regemail.getValue();
		var password = this.regpassword.getValue();
		var password2 = this.regpassword2.getValue();
		var fullname = this.fullname.getValue();
		var sex = this.sex.getValue();
		var day = this.day.getValue();
		var month = this.month.getValue();
		var year = this.year.getValue();
		var birthdate = new Date(year, month, day);
		var allowpubli = this.allowpubli.getProperty('checked');
		var accept = this.accept.getProperty('checked');
		var capchares = this.capchares.getValue();
		
		if (!email || !this.checkEmail(email)) {
			this.showMsg(this.regemail, 'Debe introducir una dirección de email válida.');
			return;
		}
		if (!password || password.length < 2 || password.length > 10) {
			this.showMsg(this.regpassword, 'Su contraseña debe tener entre 2 y 10 caracteres de longitud.');
			return;
		}
		if (password != password2) {
			this.showMsg(this.regpassword2, 'La contraseña y su repetición no coinciden.');
			return;
		}
		if (!fullname) {
			this.showMsg(this.fullname, 'Debe introducir su nombre.');
			return;
		}
		if (!sex) {
			this.showMsg(this.sex, 'Debe seleccionar el sexo.');
			return;
		}
		if (!day) {
			this.showMsg(this.day, 'Debe seleccionar el día de nacimiento.');
			return;
		}
		if (!month) {
			this.showMsg(this.month, 'Debe seleccionar el mes de nacimiento.');
			return;
		}
		if (!year) {
			this.showMsg(this.year, 'Debe seleccionar el año de nacimiento.');
			return;
		}	
		if (!accept) {
			this.showMsg(this.accept, 'Debe leer y aceptar las normas del sitio.');
			return;
		}
		if (!capchares) {
			this.showMsg(this.capchares, 'Debe responder la pregunta de control.');
			return;
		}

		this.loadinghandle = this.showLoading(this.registerwin.window);
		this.jsonRequest = new Json.Remote("ajaxapi/getphotos.php?sid=" + this.sessid + "&task=reg&idevent=" + this.idevent, {onComplete: this.registerOk.bind(this), onFailure: this.registerFail.bind(this)}).send(
			{email: email, pw: password, fullname: fullname, 
			 sex: sex, day: day, month: month, year: year, allowpubli: allowpubli, capcha: capchares }
		);		
	},
		
	registerOk: function(data) {
		if (data.success) {
			this.hideLoading(this.loadinghandle);			
			this.checkLoginStatus(data);
			if (this.registerwin) {
				this.registerwin.close();
				this.registerwin = undefined;
			}
		}
		else {
			this.showMsg(this.registerbtn, data.msg);
			this.hideLoading(this.loadinghandle);			
		    if (data.code == 4) {
				this.getCapcha();
		    }	
			
		}
	},
	
	registerFail: function(data) {
		this.showMsg(this.registerbtn, 'El servicio no se encuentra disponible en este momento. Inténtelo de nuevo más tarde.');
		this.hideLoading(this.loadinghandle);			
	},
	
	onProfile: function() {
		var email = this.regemail2.getValue();
		var fullname = this.fullname2.getValue();
		var sex = this.sex2.getValue();
		var day = this.day2.getValue();
		var month = this.month2.getValue();
		var year = this.year2.getValue();
		var birthdate = new Date(year, month, day);
		var allowpubli = this.allowpubli2.getProperty('checked');
		var capchares = this.capchares2.getValue();
		
		if (!fullname) {
			this.showMsg(this.fullname2, 'Debe introducir su nombre.');
			return;
		}
		if (!sex) {
			this.showMsg(this.sex2, 'Debe seleccionar el sexo.');
			return;
		}
		if (!day) {
			this.showMsg(this.day2, 'Debe seleccionar el día de nacimiento.');
			return;
		}
		if (!month) {
			this.showMsg(this.month2, 'Debe seleccionar el mes de nacimiento.');
			return;
		}
		if (!year) {
			this.showMsg(this.year2, 'Debe seleccionar el año de nacimiento.');
			return;
		}	
		if (!capchares) {
			this.showMsg(this.capchares2, 'Debe responder la pregunta de control.');
			return;
		}

		this.loadinghandle = this.showLoading(this.profilewin.window);
		this.jsonRequest = new Json.Remote("ajaxapi/getphotos.php?sid=" + this.sessid + "&task=uprofile&idevent=" + this.idevent, {onComplete: this.profileOk.bind(this), onFailure: this.profileFail.bind(this)}).send(
			{fullname: fullname, 
			 sex: sex, day: day, month: month, year: year, allowpubli: allowpubli, capcha: capchares }
		);		
	},
		
	profileOk: function(data) {
		if (data.success) {
			this.hideLoading(this.loadinghandle);			
			this.checkLoginStatus(data);
			if (this.profilewin) {
				this.profilewin.close();
				this.profilewin = undefined;
			}
		}
		else {
			this.showMsg(this.profilebtn, data.msg);
			this.hideLoading(this.loadinghandle);			
		    if (data.code == 4) {
				this.getCapcha();
		    }	
			
		}
	},
	
	profileFail: function(data) {
		this.showMsg(this.profilebtn, 'El servicio no se encuentra disponible en este momento. Inténtelo de nuevo más tarde.');
		this.hideLoading(this.loadinghandle);			
	},
	
	onShareIt: function() {
		var shareemail = this.shareemail.getValue();
		var sharename = this.sharename.getValue();
		var friendemail1 = this.friendemail1.getValue();
		var friendemail2 = this.friendemail2.getValue();
		var friendemail3 = this.friendemail3.getValue();
		var friendemail4 = this.friendemail4.getValue();
		var friendemail5 = this.friendemail5.getValue();
		var friendname1 = this.friendname1.getValue();
		var friendname2 = this.friendname2.getValue();
		var friendname3 = this.friendname3.getValue();
		var friendname4 = this.friendname4.getValue();
		var friendname5 = this.friendname5.getValue();
		var sharemsg = this.sharemsg.getValue();
		var sharecapchares = this.sharecapchares.getValue();
		
		if (!sharename) {
			this.showMsg(this.sharename, 'Debe introducir su nombre.');
			return;
		}
		if (!shareemail || !this.checkEmail(shareemail)) {
			this.showMsg(this.shareemail, 'Debe introducir una dirección de email válida.');
			return;
		}
		if (!friendemail1 || !this.checkEmail(friendemail1)) {
			this.showMsg(this.friendemail1, 'Debe introducir al menos una dirección de email válida de un amigo.');
			return;
		}
		if (friendemail2 && !this.checkEmail(friendemail2)) {
			this.showMsg(this.friendemail2, 'Dirección de email del amigo 2 no válida.');
			return;
		}
		if (friendemail3 && !this.checkEmail(friendemail3)) {
			this.showMsg(this.friendemail3, 'Dirección de email del amigo 3 no válida.');
			return;
		}
		if (friendemail4 && !this.checkEmail(friendemail4)) {
			this.showMsg(this.friendemail4, 'Dirección de email del amigo 4 no válida.');
			return;
		}
		if (friendemail5 && !this.checkEmail(friendemail5)) {
			this.showMsg(this.friendemail5, 'Dirección de email del amigo 5 no válida.');
			return;
		}
		if (!sharecapchares) {
			this.showMsg(this.sharecapchares, 'Debe responder la pregunta de control.');
			return;
		}

		this.loadinghandle = this.showLoading(this.shareitwin.window);
		this.jsonRequest = new Json.Remote("ajaxapi/getphotos.php?sid=" + this.sessid + "&task=share&idevent=" + this.idevent + "&idphoto=" + this.data.results[this.currentPhoto].id, {onComplete: this.shareItOk.bind(this), onFailure: this.shareItFail.bind(this)}).send(
			{email: shareemail, name: sharename, email1:friendemail1,email2:friendemail2,email3:friendemail3,email4:friendemail4,email4:friendemail4, 
			friendname1: friendname1, friendname2: friendname2, friendname3: friendname3, friendname4: friendname4, friendname5: friendname5, msg: sharemsg, 
			capcha: sharecapchares }
		);		
	},
		
	shareItOk: function(data) {
		if (data.success) {
			this.hideLoading(this.loadinghandle);			
			this.checkLoginStatus(data);
			if (this.shareitwin) {
				this.shareitwin.close();
				this.shareitwin = undefined;
			}
		}
		else {
			this.showMsg(this.registerbtn, data.msg);
			this.hideLoading(this.loadinghandle);			
		    if (data.code == 4) {
				this.getCapcha();
		    }				
		}
	},
	
	shareItFail: function(data) {
		this.showMsg(this.registerbtn, 'El servicio no se encuentra disponible en este momento. Inténtelo de nuevo más tarde.');
		this.hideLoading(this.loadinghandle);			
	},
	
	onForgot: function() {
		var forgotemail = this.forgotemail.getValue();
		var forgotcapchares = this.forgotcapchares.getValue();
		
		if (!forgotemail || !this.checkEmail(forgotemail)) {
			this.showMsg(this.forgotemail, 'Debe introducir una dirección de email válida.');
			return;
		}
		if (!forgotcapchares) {
			this.showMsg(this.forgotcapchares, 'Debe responder la pregunta de control.');
			return;
		}

		this.loadinghandle = this.showLoading(this.forgotwin.window);
		this.jsonRequest = new Json.Remote("ajaxapi/getphotos.php?sid=" + this.sessid + "&task=forgot&idevent=" + this.idevent, {onComplete: this.forgotOk.bind(this), onFailure: this.forgotFail.bind(this)}).send(
			{email: forgotemail, capcha: forgotcapchares }
		);		
	},
		
	forgotOk: function(data) {
		if (data.success) {
			this.hideLoading(this.loadinghandle);			
			this.checkLoginStatus(data);
			if (this.forgotwin) {
				this.forgotwin.close();
				this.forgotwin = undefined;
			}
		}
		else {
			this.showMsg(this.forgotbtn, data.msg);
			this.hideLoading(this.loadinghandle);			
		    if (data.code == 4) {
				this.getCapcha();
		    }				
		}
	},
	
	forgotFail: function(data) {
		this.showMsg(this.forgotbtn, 'El servicio no se encuentra disponible en este momento. Inténtelo de nuevo más tarde.');
		this.hideLoading(this.loadinghandle);			
	},
	
	onContact: function() {
		var contactemail = this.contactemail.getValue();
		var contactname = this.contactname.getValue();
		var contactsubject = this.contactsubject.getValue();
		var contactmsg = this.contactmsg.getValue();
		var contactcapchares = this.contactcapchares.getValue();

		if (!contactname) {
			this.showMsg(this.contactname, 'Debe introducir su nombre.');
			return;
		}		
		if (!contactemail || !this.checkEmail(contactemail)) {
			this.showMsg(this.contactemail, 'Debe introducir una dirección de email válida.');
			return;
		}
		if (!contactsubject) {
			this.showMsg(this.contactsubject, 'Debe introducir un asunto.');
			return;
		}
		if (!contactmsg) {
			this.showMsg(this.contactmsg, 'Debe introducir un mensaje.');
			return;
		}
		if (!contactcapchares) {
			this.showMsg(this.contactcapchares, 'Debe responder la pregunta de control.');
			return;
		}

		this.loadinghandle = this.showLoading(this.contactwin.window);
		this.jsonRequest = new Json.Remote("ajaxapi/getphotos.php?sid=" + this.sessid + "&task=contact&idevent=" + this.idevent, {onComplete: this.contactOk.bind(this), onFailure: this.contactFail.bind(this)}).send(
			{email: contactemail, name: contactname, subject: contactsubject, msg: contactmsg, capcha: contactcapchares }
		);		
	},
		
	contactOk: function(data) {
		if (data.success) {
			this.hideLoading(this.loadinghandle);			
			this.checkLoginStatus(data);
			if (this.contactwin) {
				this.contactwin.close();
				this.contactwin = undefined;
			}
		}
		else {
			this.showMsg(this.contactbtn, data.msg);
			this.hideLoading(this.loadinghandle);			
		    if (data.code == 4) {
				this.getCapcha();
		    }				
		}
	},
	
	contactFail: function(data) {
		this.showMsg(this.contactbtn, 'El servicio no se encuentra disponible en este momento. Inténtelo de nuevo más tarde.');
		this.hideLoading(this.loadinghandle);			
	},
	
	
	goDate: function(e, day) {
		e = new Event(e);
		e.stop();
		this.filters.clear = false;
		this.filters.date.clear = false;
		if (isNaN(day)) {
			var today = new Date();
			this.filters.date.day = today.getDay();			
			if (day == 'Todos') {
				this.filters.clear = true;
				this.filters.date.clear = true;				
				this.showPhotos();
				return;
			}
		}
		else {
			this.filters.date.day = day.toInt();	
		}
		
		this.filters.date.month = 3;
		this.filters.date.year = 2008;
		this.showPhotos();
		
	},
	
	fotmatTime: function(val) {
		return (val < 10?'0' + val:val) + ':00';	
	},
	
	realDay: function(val, format) {
		val = val.toInt();
		var newval = (val + 8)%24;
		if (format) {
			return this.fotmatTime(newval);
		}
	    else
			return newval; 
		
	},
	
	presetTime: function(ini, end) {
			this.onIniSlider(ini, true);
			this.onEndSlider(end, true);			
			this.endslider.setDefault(end);
			this.inislider.setDefault(ini);
			this.showPhotos();			
	},
	
	clearFilters: function() {
		this.filters = {clear: true, time: {clear:true, ini:8, end:8}, date: {clear: true, day: undefined, month: undefined, year: undefined}};
		if (this.inislider) {
			this.onIniSlider(0, true);
			this.onEndSlider(24, true);			
			this.endslider.setDefault(24);
			this.inislider.setDefault(0);
		}	
		for (var i=0; i < this.categories.length;i++) {
 			this.categories[i].setProperty('checked', false);
		}	
	},
	
	onIniSliderChange: function(val) {
		this.initime.setHTML(this.realDay(val, true));
	},
	
	onEndSliderChange: function(val, silent) {
		this.endtime.setHTML(this.realDay(val, true));
	},
	
	onIniSlider: function(val, silent) {
		this.initime.setHTML(this.realDay(val, true));
		if (this.endslider) this.endslider.setStepsMin(val.toInt()+1);
		this.filters.clear = false;
		this.filters.time.clear = false;
		this.filters.time.ini = this.realDay(val, false);
		if (!silent) this.showPhotos();			
	},
	
	onEndSlider: function(val, silent) {
		this.endtime.setHTML(this.realDay(val, true));
		if (this.inislider) this.inislider.setStepsMax(val.toInt()-1);		
		this.filters.clear = false;
		this.filters.time.clear = false;
		this.filters.time.end = this.realDay(val, false);
		if (!silent) this.showPhotos();			
	},
	
	goLeft: function(e) {
		e = new Event(e);
		e.stop();

		if (this.currentPage > 0) {
			this.changePage(this.currentPage-1);
		}	
	},
	
	goRight: function(e) {
		e = new Event(e);
		e.stop();

		if (this.currentPage < Math.ceil(this.data.total/16) - 1) {
			this.changePage(this.currentPage+1);
		}	
	},
	
	zoom: function(e) {
		e = new Event(e);
		e.stop();

		if (this.session.status == 'login') {
			this.download.setProperty('href', 'descargar.php?sid=' + this.sessid + '&idevent=' + this.idevent + '&idphoto=' + this.data.results[this.currentPhoto].id);
			this.previewloading.setStyles({display: 'block', opacity: 0.8});
			var context = this;
			new Asset.image(this.photoPath(this.data.results[this.currentPhoto],'big'), {alt: 'Foto ' + (this.data.results[this.currentPhoto].id), onload: function() {
				context.loadingappear.start(0.8, 0); 		
				context.playerimg.setProperty('src', this.getProperty('src'));
				context.playerimg.setProperty('alt', this.getProperty('alt'));
				context.previewzoom.setProperty('title', this.getProperty('alt'));
				//var coords = this.getCoordinates();
				context.zindex += 2;
				context.zoomwin.show(context.previewimg, {zindex: context.zindex, width: (this.width + 10) + 'px', height: (this.height + 75) + 'px'});
			}});
		}	
		else {
			this.showRegister(this.previewimg, 'Necesita estar registrado para ver o descargar la foto a tamaño original.');
		}	
		
			
	},
	
	changePage: function(p) {
		this.pages[this.currentPage].link.removeClass('currentpage');
		this.pages[this.currentPage].link.addClass('normalpage');
		this.currentPage = p;
		this.scroll.toElement(this.pages[p].layer);
		this.pageinfo.setHTML('Mostrando ' + (p*16+1) + ' a ' + Math.min(((p+1)*16), this.data.total) + ' de ' + this.data.total);
		this.pages[p].link.removeClass('normalpage');
		this.pages[p].link.addClass('currentpage');
	},
	
	photoPath: function(photo, phototype) {
		return this.data.base + phototype + 's/' + photo.id + '_' + phototype + '.jpg'; 
	},
		
	previewPhoto: function(index, nogoup) {
		this.pages[this.currentPage].thumbs[this.currentPhoto % 16].img.setStyle('background', '');
		this.changePage(Math.floor(index/16));
		this.pages[this.currentPage].thumbs[index % 16].img.setStyle('background', '#C02830');
		this.currentPhoto = index;
		this.previewloading.setStyles({display: 'block', opacity: 0.8});
		if (!nogoup) this.screenScroll.toElement('preview');
		
		var cats = '';
		for (var i=0;i < this.data.results[index].cats.length;i++) {
			if (i > 0) cats += ', ';
			cats += this.data.cats[this.data.results[index].cats[i]].name;
		}
		this.photocategory.setHTML(cats);
		this.photodate.setHTML(date('j \\de F, Y', this.data.results[index].date));
		this.phototime.setHTML(date('H:i', this.data.results[index].date));
		this.photoviews.setHTML(this.data.results[index].views);
		this.photodownloads.setHTML(this.data.results[index].downloads);
		this.data.results[index].views++;
		new Json.Remote("ajaxapi/getphotos.php?sid=" + this.sessid + "&task=viewed&idphoto=" + this.data.results[index].id, {onComplete: this.loadRate.bind(this)}).send();					
		
		var context = this;
		new Asset.image(this.photoPath(this.data.results[index],'medium'), {alt: 'Foto ' + (this.data.results[index].id), onload: function() {
			context.previewimg.setProperties({src: this.getProperty('src'), alt: this.getProperty('alt')});
			context.previewzoom.setProperties({title: this.getProperty('alt')});
			context.loadingappear.start(0.8, 0); 		
			if (context.playing) {
				if (context.currentPhoto < context.data.total - 1) {
					context.playTimer = context.previewPhoto.delay(1200, context, context.currentPhoto+1);
				}
				else context.playing = false;	
			}
		}});
	},
	
	getPhotos: function(idevent, idphoto, idcategory) {
		this.idevent = idevent;
		this.idphoto = idphoto;
		this.idcategory = idcategory;
		switch (idevent) {
			case 1: 
				this.eventlink.setProperty('href', 'cata.php');
				this.eventlink.setHTML('Acerca de La Cata');
				this.eventmap.setProperty('href', 'cata.php#mapa');
				this.eventmap.setHTML('Mapa de La Cata');
				this.eventname.setHTML('La Cata');
				break;
			case 2: 
				this.eventlink.setProperty('href', 'cruces.php');
				this.eventlink.setHTML('Acerca de Las Cruces');
				this.eventmap.setProperty('href', 'cruces.php#mapa');
				this.eventmap.setHTML('Mapa de Las Cruces');
				this.eventname.setHTML('Las Cruces');
				break;
			case 3: 
				this.eventlink.setProperty('href', 'patios.php');
				this.eventlink.setHTML('Acerca de Los Patios');
				this.eventmap.setProperty('href', 'patios.php#mapa');
				this.eventmap.setHTML('Mapa de Los Patios');
				this.eventname.setHTML('Los Patios');
				break;
			case 4: 
				this.eventlink.setProperty('href', 'feria.php');
				this.eventlink.setHTML('Acerca de La Feria');
				this.eventmap.setProperty('href', 'feria.php#mapa');
				this.eventmap.setHTML('Mapa de La Feria');
				this.eventname.setHTML('La Feria');
				break;
			default: this.eventname.setHTML('Mayo en Córdoba');	
		}
		this.infopanel.setStyle('display', this.idevent?'block':'none');
		this.pagesloading.setStyles({display: 'block', opacity: 0.8});
		this.jsonRequest = new Json.Remote("ajaxapi/getphotos.php?sid=" + this.sessid + "&task=read&idevent=" + idevent, {onComplete: this.dataReady.bind(this)}).send();		
	},

	filterData: function() {
		if (!this.filters.clear) {
			var date1;
			var date2;
	 		if (!this.filters.date.clear) {
	 			date1 = new Date(this.filters.date.year, this.filters.date.month, this.filters.date.day, 8);	
	 			date2 = new Date(date1.getTime() + 1*24*60*60*1000); //add one day
	 		}		
			this.data.results = this.originalData.filter(function(item, index){
			  	var result = true;	
			  	var itemjsdate = new Date(item.date*1000);
	 			if (!this.filters.date.clear) {
	 				result = result && (itemjsdate >= date1 && itemjsdate <= date2);
	 			}
	 			if (!this.filters.time.clear) {
	 				var hours = itemjsdate.getHours();
	 				if (this.filters.time.ini < 8 || this.filters.time.end > 8) {
	 					result = result && (hours >= this.filters.time.ini && hours < this.filters.time.end);
	 				}
	 				else {
	 					result = result && ((hours >= this.filters.time.ini && hours <= 24) || (hours < this.filters.time.end && hours >= 0));
	 				}	
	 			}
 				var catresult = false;
 				var checks = 0;
	 			for (var i=0; i < this.categories.length;i++) {
 					if (this.categories[i].getProperty('checked'))	{
 						var id = this.categories[i].getProperty('value');
 						catresult = catresult || item.cats.contains(id);
 						checks++;
 					}	
 				}
 				if (checks) result = result && catresult;

 				return result;
			}.bind(this));
			this.data.total = this.data.results.length;
		}
		else if (this.originalData.length != this.data.results.length) {
			this.data.results = this.originalData.copy();
			this.data.total = this.data.results.length;
		}	
	},
	
	showPhotos: function(nogoup) {
		this.pagesloading.setStyles({display: 'block', opacity: 0.8});
		this.filterData();
	    this.container.setHTML('');
	    this.pagination.setHTML('');
		this.pageinfo.setHTML('');
		this.currentPhoto = 0;

		if (this.data.total > 0) {
			this.previewnores.setStyle('display', 'none');
			this.menu.setStyle('display', 'block');
			this.previewimg.setStyle('display', 'block');
		    this.container.setStyle('width', this.width * Math.ceil(this.data.total/16));
		    p = 0;
			for(var i = 0; i < Math.ceil(this.data.total/16); i++) {
				this.pages[i] = {link: undefined, scroll: undefined, layer: undefined, thumbs: []};
				this.pages[i].layer = new Element('div', {
				    'styles': {
				        'width': this.width + 'px',
				        'height': this.height + 'px'
				    },
				    'class': 'gallerypage'
				});
				this.pages[i].layer.injectInside(this.container);
				this.pages[i].link = new Element('a', {
					    'events': {
					        'click': function(e, index){
					        	e = new Event(e);
								e.stop();
					            this.changePage(index);
					        }.bindWithEvent(this, i)
					    },				
					    'class': 'normalpage',
				    	'href': '#'
				}).setHTML(i+1);;
				this.pages[i].link.injectInside(this.pagination);
	
				for (var j = 0; j < 16 && p < this.data.total; j++) {
					this.pages[i].thumbs[j] = {link: undefined, img: undefined, data: undefined};
					this.pages[i].thumbs[j].link = new Element('a', {
						'events': {
					        'click': function(e, index) {
					        	e = new Event(e);
								e.stop();
								if (!this.playing) this.previewPhoto(index);
					        }.bindWithEvent(this, p)
					    },									
					    'title': 'Foto ' + this.data.results[p].id,
					    'href': '#'
					});
					this.pages[i].thumbs[j].link.injectInside(this.pages[i].layer);
					this.pages[i].thumbs[j].img = new Element('img', {
					    'styles': {
					        'width': '80px',
					        'height': '80px'
					    },
					    src: 'images/pixel_trans.gif',
					    alt: 'Foto ' + this.data.results[p].id
					});
					this.pages[i].thumbs[j].img.injectInside(this.pages[i].thumbs[j].link);
					this.pages[i].thumbs[j].data = this.data.results[p];
					var context = this;
					new Asset.image(this.photoPath(this.data.results[p],'small'), {alt: i + '', title: j + '', onload: function() {
						if (context.pages[this.getProperty('alt')] && context.pages[this.getProperty('alt')].thumbs[this.getProperty('title')]) {
							context.pages[this.getProperty('alt')].thumbs[this.getProperty('title')].img.setProperties({src: this.getProperty('src')});
						}	
					}});
					if (this.idphoto == this.data.results[p].id) {
						this.currentPhoto = p;
					}
					
					p++;
				}
			}	
			if (this.data.total > 0) {
				this.changePage(this.currentPage);		
				this.previewPhoto(this.currentPhoto, nogoup);
				if (nogoup) this.idphoto = -1;
			}	
		}	
		else {
			this.pageinfo.setHTML('No hay fotos. Modifique los criterios de filtrado para obtener resultados');
			this.photocategory.setHTML('');
			this.photodate.setHTML('');
			this.phototime.setHTML('');
			this.photoviews.setHTML('');
			this.previewimg.setProperty('src', 'images/pixel_trans.gif');
			this.previewimg.setStyle('display', 'none');
			this.previewnores.setStyle('display', 'block');
			this.menu.setStyle('display', 'none');
		}
		this.pagesloadingappear.start(0.8, 0); 		
		
		
	},
	
	dataReady : function(data) {
		this.checkLoginStatus(data);		
		this.data = data;
		this.originalData = this.data.results.copy();
		this.categories = [];		
		this.catcontainer.setHTML('');
		var i = 0;
		if (this.data.totalcats > 0) {
			for (var cat in this.data.cats) {
			 	this.categories[i] = new Element('input', {
				    'class': 'catcheck',
				    'type': 'checkbox',
					'checked' : this.idcategory == this.data.cats[cat].id?'checked':'',
				    'value': data.cats[cat].id
				}).injectInside(this.catcontainer);
			 	var span = new Element('span').injectInside(this.catcontainer);
				span.setHTML(this.data.cats[cat].name);
			 	new Element('br').injectInside(this.catcontainer);
				
				this.categories[i].addEvent('click', function(e) {
					this.filters.clear = false;
					this.filters.categories = true;
					this.showPhotos();
				}.bind(this));
				if (this.idcategory == this.data.cats[cat].id) {
					this.filters.clear = false;
					this.filters.categories = true;
					this.idcategory = -1;
				}
			 	
				i++;
			}
		}	
		else {
		 	var span = new Element('span').injectInside(this.catcontainer);
			span.setHTML('No hay categorías');
		}
		
		this.showPhotos(true);
	}	
});	
