// JavaScript Document
var wait = '...realizando operaciones, espere por favor';
var done = 'hecho';
var baseUrl;
var addToList;

window.addEvent('domready', function(){
/* valida y envia la forma de contacto */
	if($('formaDeContacto')) $('formaDeContacto').addEvent('submit', function(e) {
		e = new Event(e).stop();
		var laForma = this;
		var emailEval = new RegExp("^[A-Za-z0-9\_\.-]+@[A-Za-z0-9\_\.-]+[\.]{1}[A-Za-z0-9\_-]+");
		var error = false;
		/* valida que los campos obligatorios no esten vacios */
		this.getElements('*.obligatorio').each(function(el){
			if((el.getValue().trim()=='' && el.getProperty('name')!='eMail') || (el.getProperty('name')=='eMail' && !emailEval.test(el.getValue()))) {
				if(!el.hasClass('error')) el.addClass('error'); 
				if(!error) el.focus();
				error=true;
			} else if(el.hasClass('error')) el.removeClass('error');
		});
		/* si algn campo obligatorio est vacio, regresa y da el foco al primero que marc vacio  */
		if(error) return(false);
		/**/
		var lbOverlay = new Element('div', { 
			'class': 'lbOverlay', 
			'styles': {
				'width': laForma.getSize().size.x,
				'height': laForma.getSize().size.y 
			}
		}).injectBefore(laForma);
		var ajaxLoading = new Element('p',{
			'id': 'ajaxLoading'
		}).setHTML('Enviando su mensaje...<br />espere unos segundos por favor').injectInside(lbOverlay);
		/* centrar pAjaxLoading */
		var centrarMsg = function(){
			ajaxLoading.setStyle('top', ((laForma.getSize().size.y-ajaxLoading.getSize().size.y)/2));
		}
		centrarMsg();
		/* enviar y recibir */
		this.send({
			update: ajaxLoading,
			onComplete: function(){
				var linkFormulario = new Element('a',{
					'id': 'linkRegresarAFormulario',
					'href': 'javascript:void(0);',
					'events': {
						'click': function(e){
							e = new Event(e).stop();
							lbOverlay.remove();
						}
					},
					'styles': {
						'color': '#EF0000' /*'#D3FE28'*/
					}
				}).setHTML('<br /><br />&raquo; Regresar al formulario').injectInside(ajaxLoading);
				ajaxLoading.setStyle('background', 'none');
				centrarMsg();
			}
		});
	});
	
	/* operations for the table articles */
	$$('table#articulos tbody, table#secciones tbody, table#fotonotas tbody, table#comentarios tbody').each(function(TBody){
		new Sortables(TBody,{
			handles: '.handles',
			onDragStart: function(element, ghost){
				element.setStyle('visibility','hidden');
				ghost.inject(element.getParent());
				ghost.setStyles({
					'background-color': '#FFEA93',
					'width': element.getSize().size.x
				});
			},
			onDragComplete: function(element, ghost){
				element.setStyle('visibility','visible');
				ghost.remove();
			},
			onComplete: function(){
				var url = baseUrl+'administrador/idx_' + TBody.getParent().id;
				var tmp = new Array();
				var org = new Array();
				$$('.handles').each(function(element){
					var id = element.getProperty('title').toInt();
					org.push(id);
					tmp.push(Array(id,id));
				});
				/* ordenar antes el arreglo temporal */
				tmp.sort(function(a,b){
					if(a[0]<b[0]) return 1;
					if(a[0]>b[0]) return -1;
					if(a[0]==b[0]) return 0;
				});
				/* reasignar según posiciones en el arreglo original
				   La col0 es el valor de indice y la col1 es el id del artículo */
				for (i in tmp) tmp[i][0]=org[i];
				$('status').getElement('span').setHTML(wait).addClass('loading');
				new Ajax(url.toLowerCase(),{
					data: 'indice='+tmp,
					method: 'post',
					update: $('status').getElement('span'),
					onComplete: function(){
						$('status').getElement('span').removeClass('loading');
					}
				}).request();
				if(TBody.getParent().id=='pub_digitales') window.location.reload();
			}
		});
		
		$$('a.btn_erase').addEvent('click',function(e){
			var e = new Event(e).stop();
			var row = this.getParent().getParent();
			var msj = '¿Esta seguro de eliminar «'+this.rel+'»?';
			var url = this.href + '/ajax';
			var upd = $('status').getElement('span');
			
			if(confirm(msj)){
				upd.setHTML(wait).addClass('loading');
				new Ajax(url,{
					update: upd,
					data: 'namefile='+this.rel,
					method: 'post',
					onComplete: function(){
						if(upd.getText()=='hecho') row.remove();
						upd.removeClass('loading');
					}
				}).request();
			}
		});
		
		$$('a.inGreen', 'a.inRed').addEvent('click',function(e){
			var e = new Event(e).stop();
			var lnk = this;
			var url = this.href + '/ajax';
			var upd = $('status').getElement('span');
			
			upd.setHTML(wait).addClass('loading');
			new Ajax(url,{
				update: upd,
				onComplete: function(){
					if(TBody.getParent().id=='fotonotas'){
						var inGreen = TBody.getElement('a.inGreen');
						if(inGreen && inGreen!=lnk) inGreen.removeClass('inGreen').addClass('inRed');
					}
					switch(true){
						case lnk.hasClass('inGreen'):
							lnk.removeClass('inGreen').addClass('inRed');
							lnk.href = lnk.href.replace(/\/off\_/,'/on_');
							break;
						case lnk.hasClass('inRed'):
							lnk.removeClass('inRed').addClass('inGreen');
							lnk.href = lnk.href.replace(/\/on\_/,'/off_');
							break;
					}
					upd.removeClass('loading');
				}
			}).request();
		});
		
		$$('a.tipo').addEvent('click',function(e){
			var e = new Event(e).stop();
			var lnk = this;
			var url = this.href + '/ajax';
			var rev = this.rev;
			var upd = $('status').getElement('span');
			
			upd.setHTML(wait).addClass('loading');
			new Ajax(url,{
				update: upd,
				onComplete: function(){
					lnk.rev = (rev==1 ? 0 : 1);
					if(rev==1) lnk.setHTML('Política y Sociales');
					else lnk.setHTML('Humor e Interés');
					upd.removeClass('loading');
				}
			}).request();
		});
	}); /* end of procedure for operations of the tabe sortables*/
	
	$$('.readMore').addEvent('click',function(){
		new Element('div',{
			'styles':{
				'background': '#fe0000 url('+baseUrl+'public/pics/spinner_fe0000.gif) 6px center no-repeat',
				'color': '#ffffff',
				'border': '1px solid #ddd',
				'line-height': '32px',
				'padding-left': '28px',
				'padding-right': '12px',
				'position': 'absolute',
				'left': 24,
				'top': window.getScrollTop() + 24,
				'z-index': 1
			}
		}).setHTML('Cargando datos... espere unos segundos, por favor.').injectInside(document.body);
	});
	
	var pagAdm = new RegExp("\/administrador\/");
	if(pagAdm.test(location.href)){
		$$('form').addEvent('submit',function(e){
			var e = new Event(e).stop();
			var bodyTag = $E('body');
			var formTag = this;
			var alto = bodyTag.getSize().size.y;
				alto = (alto>window.getHeight() ? alto : window.getHeight());
			var ext = /\.(jpg|gif)$/i;
			var noimg = null;
			$$('label.lbFile input').each(function(input){
				if(input.value=='' || ext.test(input.value)==false){
					input.getParent().addClass('empty');
					noimg = true;
				}
			});
			if(noimg){
				alert("NO Seleccionó un archivo de imagen JPG o GIF.\nIntentelo de nuevo");
				return false;
			}
			var overlay = new Element('div',{ 'class':'overlay'}).setStyle('height',alto);
			var msgbox = new Element('p',{'class':'inprocess'}).setStyle('top',window.getScrollTop()+((window.getHeight()-50))/2);
			msgbox.injectInside(overlay);
			overlay.injectInside(bodyTag);
			var enviar = function(){ 
				formTag.submit();
			}
			enviar.delay(2000);
		});
	}
	
	if($E('form#new_comentario')){
		$('new_comentario').addEvent('submit',function(e){
			var e = new Event(e).stop();
			var regresar_a = this.getElement('input[name=regresar_a]');
			var textarea = this.getElement('textarea');
			var inputEmail = this.getElement('input[name=email]');
			var validator = this.getElement('input[name=validator]');
			var emailEval = new RegExp("^[A-Za-z0-9\_\.-]+@[A-Za-z0-9\_\.-]+[\.]{1}[A-Za-z0-9\_-]+");
			var lbOverlay = new Element('div',{
				'styles': {
					'background': '#f3f3f3 url(../public/pics/spinner.gif) center center no-repeat',
					'opacity': 0.85,
					'width': 270,
					'height': this.getParent().getSize().size.y,
					'position': 'absolute',
					'margin-top': 25,
					'z-index': 3
				}
			});
			switch(true){
				case textarea.value=='':
					alert('No escibió su comentario.\nEl campo es obligatorio');
					return false;
					break;
				case inputEmail.value=='':
					alert('No escibió su email.\nEl campo es obligatorio');
					return false;
					break;
				case !emailEval.test(inputEmail.value):
					alert('El email que ha escrito no es valido.\nVerifique y vuelva a intentar');
					return false;
					break;
				case validator.value=='':
					alert('Es necesario que escibia lo que leé en el recuadro.\nEl campo es obligatorio');
					return false;
					break;
				default:
					lbOverlay.injectTop(this.getParent());
					break;
			}
			regresar_a.value = 'ajax';
			this.send({
				update: 'comentarios',
				onComplete: function(){
					lbOverlay.remove();
					textarea.value = null;
					inputEmail.value = null;
					validator.value = null;
					$('captcha_validator').src = baseUrl + 'captcha/' + (new Date()).getTime();
				}
			}); 
		});
	}

	$$('label.lbFile input').each(function(input){
		input.addEvent('change',function(){
			var strong;
			var jpg = this.value;
				jpg = jpg.substr((jpg.lastIndexOf('\\')>0 ? jpg.lastIndexOf('\\')+1 : 0));
			if(strong = this.getParent().getElement('strong')) strong.setHTML(jpg);
			else strong = new Element('strong').setHTML(jpg).injectInside(this.getParent());
			if(this.getParent().hasClass('empty')) this.getParent().removeClass('empty');
			var pags = new RegExp("\/administrador\/(fotonota\s|pub_digitale\s)");
			if(pags.test(location.href)){
				if(!$E('a.otherfile')) new Element('a',{
					'class':'otherfile',
					'events':{
						'click': function(e){
							var e = new Event(e).stop();
							var lbFile = new Element('label',{'class':'lbFile'});
								lbFile.injectAfter(this);
							new Element('input',{'type':'file','name':'file[]'}).cloneEvents(input).injectInside(lbFile);
							new Element('span').setHTML('&laquo; Examinar').injectInside(lbFile);
							new Element('a',{'class':'removefile'}).addEvent('click',function(e){
								var e = new Event(e).stop();
								this.getParent().remove();
							}).setHTML('&nbsp;').injectTop(lbFile);
							this.remove();
						}
					}
				}).setHTML('&nbsp;').injectAfter(this.getParent());
			}
		});
		input.value = null;
	});
	
	if($E('#diario')){
		$$('.pagina a.btn_erase').addEvent('click',function(e){
			var e = new Event(e).stop();
			var href = this.href;
			if(confirm('¿Seguro que deseas eliminar «'+this.rel+'»?')){
				var bodyTag = $E('body');
				var alto = bodyTag.getSize().size.y;
					alto = (alto>window.getHeight() ? alto : window.getHeight());
				var overlay = new Element('div',{ 'class':'overlay'}).setStyle('height',alto);
				var msgbox = new Element('p',{'class':'inprocess'}).setStyle('top',window.getScrollTop()+((window.getHeight()-50))/2);
					msgbox.injectInside(overlay);
					overlay.injectInside(bodyTag);
				var doErase = function(){
					window.location.href=href; 
				}
				doErase();
			} else return false;
		});
		var activo;
		$$('.pagina img').addEvent('mousedown',function(e){
			var e = new Event(e).stop();
			activo = this.getParent();
			var clone = this.clone()
				.setStyles(this.getCoordinates()) /* this returns an object with left/top/bottom/right, so its perfect */
				.setStyles({'opacity': 0.7, 'position': 'absolute', 'width': this.getSize().size.x})
				.addEvent('emptydrop', function() {
					this.remove();
				}).inject('diario');
			var drag = clone.makeDraggable({
				droppables: '.pagina',
				container: 'diario'
			}); // this returns the dragged element
			drag.start(e); // start the event manual
		});
		$$('.pagina').addEvent('drop',function(el,obj){
			var dragObj = el.getCoordinates();
			var dropObj = this.getCoordinates();
			if(dragObj.left < dropObj.left && dragObj.right < dropObj.right) activo.injectBefore(this);
			else activo.injectAfter(this);
			el.remove();
			activo = null;
			/**/
			var tmp = new Array();
			$$('.pagina img').each(function(element,id){
				tmp.push(element.getProperty('title').toInt());
				element.setProperty('title',id);
			});
			var url = baseUrl + 'administrador/idx_pub_digitales' + this.getParent().title;
			new Ajax(url,{
				data: 'indice='+tmp,
				method: 'post',
				onComplete: function(){ /*window.location.reload();*/ }
			}).request();
		});
	}

	var pagVer = new RegExp("\/ver\/");
	if(pagVer.test(location.href)){
		if(!window.opera){
			var fxScroll = new Fx.Scroll(window,{ offset: {'x': 0, 'y': -12}, duration:500, wait:false });
				fxScroll.toElement('column_left');
		}
	}
	/*
		últimas noticias
	*/
	if($('barraDePestanas')){
		var liUN = $('barraDePestanas').getElements('li');
		var liAc = 0;
		(function(){
			liUN[liAc].setOpacity(0.01);
			liAc = (liAc==(liUN.length-1) ? 0 : liAc + 1);
			liUN[liAc].effect('opacity',{wait:false,duration:500}).start(0.01,1.0);
		}).periodical(5000);
	}
	/*
		galeria de fotonotas
	*/
	var obscuro = 0.75;
	var avance = 1;
	if($('fotografias')){
		var pieDeFoto = new Element('span',{'id':'pieDeFotos'}).setOpacity(0).injectAfter('fotografias');
		var avanzar = function(){
			if(avance == 1){
				$('fotografias').getFirst().injectInside('fotografias');
				$('fotografias').scrollTo(0,0);
			}
			pieDeFoto.setText($('fotografias').getFirst().title).setStyle('width',($('fotografias').getFirst().offsetWidth-12));
			if(pieDeFoto.innerHTML != '') pieDeFoto.effect('opacity',{wait:false,duration:350}).start(1);
		}
		var fxFotografias = new Fx.Scroll('fotografias',{
			wait:false, duration:500, wheelStops:false, 
			transition:Fx.Transitions.Circ.easeOut,
			onStart:function(){
				pieDeFoto.setOpacity(0);
			}, onComplete:avanzar, onCancel:avanzar
		});
		var fxGaleria = function(){
			fxFotografias.scrollTo($('fotografias').getFirst().offsetWidth,false);
		}
		/* iniciar animación */
		$('fotografias').getLast().injectTop('fotografias');
		var siGaleria = fxGaleria.periodical(8000);
		fxGaleria();
		/* pausar la galeria cuando el mouse esta sobre una foto */
		$('fotografias').getParent().addEvent('mouseenter',function(){
			siGaleria = $clear(siGaleria);
		});
		$('fotografias').getParent().addEvent('mouseleave',function(){
			siGaleria = fxGaleria.periodical(8000);
		});
		/* tooltips */
		var divTooltip = new Element('div',{'id':'tooltips'}).injectInside(document.body);
		/*var divTooltip = new Element('div',{'id':'tooltips'}).injectInside('picture_area_center');*/
		var fnTooltip = function(event){
			var event = new Event(event);
			var x = ((event.page.x + 332) < window.getWidth() ? event.page.x+12 : event.page.x-332);
			divTooltip.setStyles({'left':x, 'top':event.page.y});
		}
		$('fotografias').getChildren('img').addEvents({
			'mouseenter':function(event){
				if(this.title.clean()=='') return false;
				else {
					divTooltip.empty().setText(this.title);
					this.title = '';
				}
				if(this==$('fotografias').getFirst()) return false;
				/*else divTooltip.setStyles({
					'display':'block', 
					'width':this.offsetWidth-12,
					'left':this.offsetLeft
				});*/
				else divTooltip.setStyle('display','block');
				document.addListener('mouseover', fnTooltip);
				document.addListener('mousemove', fnTooltip);
			},
			'mouseleave':function(event){
				if(divTooltip.innerHTML=='') return false;
				else {
					this.title = divTooltip.innerHTML;
					divTooltip.empty();
				}
				if(this==$('fotografias').getFirst()) return false;
				else divTooltip.setStyle('display','none');
				document.removeListener('mouseover', fnTooltip);
				document.removeListener('mousemove', fnTooltip);
			}
		});
		/* acción de las flechas de avance/regreso */
		$('flechaIzquierda').addEvent('click',function(){
			siGaleria = $clear(siGaleria);
			avance = 0;
			$('fotografias').scrollTo($('fotografias').getLast().injectTop('fotografias').offsetWidth,0);
			fxFotografias.scrollTo(0,false);
		});
		$('flechaDerecha').addEvent('click',function(){
			siGaleria = $clear(siGaleria);
			avance = 1;
			$('fotografias').scrollTo(0,0);
			fxFotografias.scrollTo($('fotografias').getFirst().offsetWidth,false);
		});
	}
});
/* End Document */

