var porid = {
	idname: function(e) {
		if(e.target.id){
			if(eval("this."+e.target.id)!=undefined){
				eval("this."+e.target.id)(e.target);
				}
			}
	}
}

var globales = {
	num:0
}

var porclass = {
	elPrev : function(e){ // previsualización de datos para crear nuevo debate
		var defMes = $('.'+e.target.id, 'div.nvDebPrev').attr('title');
		var whatPrev = '';
		var whatPrev = $('.'+e.target.id, 'div.nvDebPrev');
		if ( jQuery.trim( $('#'+e.target.id, 'form.nvDeba').val() ) == '' )
			{ $(whatPrev, 'div.nvDebPrev').html( defMes ) }
		else
			{ $(whatPrev, 'div.nvDebPrev').html( $('#'+e.target.id, 'form.nvDeba').val() ); }
	}, 	
	tooltip : function(e){ // tooltips informativos, para elementos con clase .help - formato: <span class="help" title="Este es el título; Texto informativo"> o bien <span class="help" title="Texto informativo">
		var txt = e.target.title;
		var hasTitle = false;
		var partes = txt.split(' | ');
		if ( partes[1] ) {
			var alt = '<strong title="'+txt+'">'+partes[0]+'</strong><br>'+partes[1];
		}
		e.target.title = '';
		var mouseX = e.pageX;
		var mouseY = e.pageY;
		if(!document.getElementById("toolTip")){
			var toolTip = document.createElement("div");
			toolTip.style.display = 'none';
			toolTip.id = "toolTip";
			if ( partes[1] ) { 
				toolTip.innerHTML = "<p>"+alt+"</p>";
				toolTip.innerHTML += '<span></span>';
			} else {
				toolTip.innerHTML = '<p title="'+txt+'">'+partes[0]+'</p>';
				toolTip.innerHTML += '<span></span>';
			}
			document.getElementsByTagName('body')[0].appendChild(toolTip);
			}
		else{
			var toolTip = document.getElementById("toolTip");
			}
		var toolTipHeight = $('#toolTip').height();
		 if(parseInt(document.documentElement.clientWidth) < parseInt(toolTip.offsetWidth + mouseX)){
			if(navigator.userAgent.match(/MSIE/))
			toolTip.style.top = (mouseY-toolTipHeight-40)+'px';
			else
			toolTip.style.top = (mouseY-toolTipHeight-30)+'px';
			toolTip.style.left = (mouseX-(toolTip.offsetWidth+15))+'px';
		}
		 else{
			toolTip.style.top = (mouseY-toolTipHeight-33)+'px';
			toolTip.style.left = (mouseX-29)+'px';
		}
		toolTip.style.position = 'absolute';
		toolTip.style.zIndex = 100;
		$(toolTip).css('opacity','.95');
		$(toolTip).show();
	},
	pTooltip : function(e){ // tooltips para mostrar información sobre debatientes - formato: <cite class="pInfo" title="Cargo; Grado académico; Áreas de Interés: Uno, dos, tres">Nombre Apellido</cite>
		var txt = e.target.title;
		var partes = txt.split('; ')
		var nombre = $(e.target).text();
		var alt = '<strong title="'+txt+'">'+nombre+'</strong><br />'+partes[0]+'<br />'+partes[1];
		var areas = txt.split(': ');
		e.target.title = '';
		var mouseX = e.pageX;
		var mouseY = e.pageY;
		if(!document.getElementById("toolTip")){
			var toolTip = document.createElement("div");
			toolTip.style.display = 'none';
			toolTip.id = "toolTip";
			toolTip.innerHTML = "<p>"+alt+"</p>";
			toolTip.innerHTML += "<p><em>Áreas de Interés</em>: "+areas[1]+"</p>";
			toolTip.innerHTML += "<span></span>";
			document.getElementsByTagName('body')[0].appendChild(toolTip);
			}
		else{
			var toolTip = document.getElementById("toolTip");
			}
		var toolTipHeight = $('#toolTip').height();
		if(parseInt(document.documentElement.clientWidth) < parseInt(toolTip.offsetWidth + mouseX)){
			if(navigator.userAgent.match(/MSIE/)) 
			toolTip.style.top = (mouseY-52)+'px';
			else
			toolTip.style.top = (mouseY-toolTipHeight-35)+'px';
			toolTip.style.left = (mouseX-(toolTip.offsetWidth+15))+'px';
		}
		else{
			toolTip.style.top = (mouseY-toolTipHeight-25)+'px';
			toolTip.style.left = (mouseX-12)+'px';
		}
		toolTip.style.position = 'absolute';
		toolTip.style.zIndex = 100;
		$(toolTip).css('opacity','.95');
		$(toolTip).show();
	},	
	tooltip_out : function(e){ // elimina el elemento #toolTip
		if ( $('#toolTip p').attr('title') ) {
			var title = $("#toolTip p").attr("title");
		} else if ( $("#toolTip strong").attr("title") ) {
			var title = $("#toolTip strong").attr("title");
		}
		e.target.title = title;
		$('#toolTip').remove();
	},
	show_login : function(){ // muestra caja de login y oscurece resto de la página
		$('body').append('<div id="overlayBg" />');
		$('embed, object, select').css({
			'visibility': 'hidden'
		});
		$('#overlayBg').css({
			'width': $('body').width(),
			'height': $('body').height(),
			'opacity': '0.8',
			'background-color': '#fff',
			'position': 'absolute',
			'top': '0',
			'left': '0',
			'z-index': '1'
		}).click( function(e) { porclass.remove_overlay(e); return false; } );
		$('a[href=#doLogin]', 'div#login').hide();
		$('div#doLogin', 'div#login').slideDown();
		return false;
	},
	remove_overlay : function(e){ // esconde caja de loguin y quita fondo
		$('div#doLogin').slideUp();
		$('embed, object, select').css({
			'visibility': 'visible'
		});
		$('a[href=#doLogin]', 'div#login').show('normal');
		$('div#overlayBg').fadeOut('fast', function(){$(this).remove()});
	},
	suggest : function(e){ // sugerencias de debates planteados anteriormente
		$(e.target).parents('fieldset').addClass('loading');
		$.getJSON("/busqueda/debates.json/1/"+e.target.value, function(r) {
			$(e.target).parents('fieldset').removeClass('loading');
			if($.id("#ndTSug")) $('#ndTSug').remove();
			if($(".see-more").length > 0) $('.see-more').remove();
			if(e.target.value=="") {
				var valor="null";
			}
			else{
				valor=e.target.value;
				valor=valor.replace(/ /g, '_');
				porclass.elPrev(e)
			}
			var spot = eval("r.resultado."+valor) || "";
			var ulspot = document.createElement("ul");
			ulspot.id = "ulspot";
			ulspot.className = "ndTSug";
			$("#ndTitulo").after(ulspot);
			if (spot!=''){
				$('#ndTitulo').css({'margin-bottom': '0.3em'});
				$('#ndTitulo').after('<samp class="alert">Quizás el debate que tienes en mente <strong>ya esté creado</strong>, revisa los siguientes:</samp>');
				$('#ndTitulo + samp.alert').css({ 'font-size': '1.0909em'});
				globales.lista="";
				$.each(spot,function(i,datos) {
					globales.lista = globales.lista+"<li class=\"lispot \"><strong><a href=\""+datos.url+"\" title=\""+datos.descripcion+"\">"+datos.titulo+"</a></strong><span>"+datos.descripcion+"</span></li>";
				});
				$('#ulspot').html(globales.lista).after('<p class="see-more"><a href="../busqueda/debates.html/1/'+e.target.value+'">Ver todos</a></p>');
				$('#ndTitulo + samp.alert, #ulspot, p.see-more').wrapAll('<div id="ndTSug"></div>');
				var stopInterval;
			} else {
				$('p.see-more, ul#ulspot').remove();
				$('#ndTitulo').css({'margin-bottom': '1em'});
			}
		});
	},
	closeSpot : function (){ //función auxiliar para control de intervalos de tiempo en buscador spot
		$('#ulspot').remove();
		if (globales.intval!="") window.clearInterval(globales.intval);
		if (globales.noresult!="") window.clearInterval(globales.noresult);
	}
}

jQuery.fn.buscDef = function() { // limpia cajas de búsqueda; si no se modifica, devuelve valores originales
	var orVal = jQuery(this).val();
	if ( jQuery.trim(orVal) != '' ) {
		jQuery(this).data( 'defVal', orVal )
	} else {
		jQuery(this).data( 'defVal', 'Ingresa tu búsqueda' )
	}
	jQuery(this).blur(function() {
			if ( jQuery(this).val() == '' ) {
			jQuery(this).val( jQuery(this).data('defVal') )
			}
		}).focus(function() {
			jQuery(this).select();
			if ( jQuery(this).val() == jQuery(this).data('defVal') ) {
				jQuery(this).val('');
			}
		});
}

jQuery.fn.animateBars = function(options) { // función para animar barras. aplicar a listas
	
	function sortNumber(a, b){
		return b - a;
	};
	
	var listEl = jQuery(this).children();
	
	var freqArr = new Array();
	
	for( i = 0; i < listEl.length; i++ ){
		var freqList = listEl[i].innerHTML;
		var mayorTxt = freqList.split(options.seps);
		var mayorTxt = mayorTxt[1].split(options.sepe);
		freqArr.push(mayorTxt[0]);
	};		
	sortedFreq = freqArr.sort(sortNumber);
	var elMayor = sortedFreq[0];
	
	jQuery(listEl).children().css('background-position', '152% 0').each(function() {
		var txt = jQuery(this).html();
		var freq = txt.split(options.seps);
		var freq = freq[1].split(options.sepe);
		var valor = 0;
		var valor = freq[0] / elMayor;
		var valor = valor * 52;
		var valor = 152 - valor;
		var valor = valor+'% 0';
		jQuery(this).animate({'backgroundPosition': valor}, 1500);
	});		

};

$(document).ready( function() {

	// sugerencias 
	$('#ndTitulo', 'form.nvDeba fieldset').keyup(function(e){porclass.suggest(e); return false;});
	if ( typeof(ciudades) != 'undefined' ) {
		$('#regCiudad').jsonSuggest(ciudades.resultado,{maxResults:5});
		$('#regCiudad').css({'margin-bottom': '0'});
		$('label[for=regAbout]').css({'padding-top': '1em'});
	}

	// tooltips	
	$('.help').mousemove( function(e){ porclass.tooltip(e); return false; } );
	$('.help').mouseout( function(e){ porclass.tooltip_out(e); return false; } );
	$('cite.pInfo', 'div#main').mousemove( function(e){ porclass.pTooltip(e); return false; } );
	$('cite.pInfo', 'div#main').mouseout( function(e){ porclass.tooltip_out(e); return false; } );

	// valores para cajas de búsqueda
	$('#q').buscDef();
	$('#us').buscDef();

	// selecciona texto en datos de formulario para modificar perfil
	$('input', '.modPerf #main form').focus(function() {
		$(this).select();
	});

	// caja de login
	$('div#doLogin', 'div#login').hide();
	$('a.ingr', 'div#login').click( function(){ porclass.show_login(); } );
	$('a.ingresar').click( function(){ porclass.show_login(); } );

	$('a.cerr').click(function(e){ porclass.remove_overlay(e); return false; } );

	// esconde mensaje de bienvenida
	$('a.cerr', 'div#welcomeLogin').click(function() { $('div#welcomeLogin').slideUp(); });

	// mis últimos debates
	$('div.debaDato:gt(0)', 'ol.ultDeb').hide();
	$('div.debaMeta:gt(0)', 'ol.ultDeb').each(function() { $(this).append('<span class="toggle">Mostrar</span>'); });
	$('div.debaMeta:first', 'ol.ultDeb').append('<span class="toggle acti">Ocultar</span>');
	$('span.toggle', 'ol.ultDeb').click(function() {
		if ( $(this).hasClass('acti') ) { 
			var whatAction = 'Mostrar';
		} else { whatAction = 'Ocultar'; }
		$(this).html(whatAction).toggleClass('acti').parents('li').children('div.debaDato').slideToggle('normal');
	});	


	// previsualización de datos en formulario para crear debate
	$('#ndDesc, #ndOpc1, #ndOpc2', 'form.nvDeba').keyup( function(e){ porclass.elPrev(e) } );
	$('#ndTema input', 'form.nvDeba').each(function() { // previsualización de 'temas' en formulario para crear debate
		$(this).bind('click keyup', function(){
			var checkedTemas = $('#ndTema input:checked', 'form.nvDeba');
			if ( checkedTemas.length == 0 ) {
				$('p.entry-cat a', 'div.nvDebMeta').replaceWith('<span class="' + $(this).attr('id') + '"><a href="#" class="check-sociedad">Sociedad</a></span>');
			} else if ( checkedTemas.length == 1 && $(this).is(':checked') ) {
				$('p.entry-cat span', 'div.nvDebMeta').remove();
				$('p.entry-cat', 'div.nvDebMeta').append('<span class="' + $(this).attr('id') + '"><a href="#">' + $(this).parent().text() + '</a></span>');
			} else {
				$('p.entry-cat span').remove();
				$('#ndTema input:checked', 'form.nvDeba').each(function() {
				$('p.entry-cat', 'div.nvDebPrev').append( '<span class="' + $(this).attr('id') + '"><a href="#">' + $(this).parent().text() + '</a></span>');
				$('p.entry-cat span:last', 'div.nvDebMeta').append(', ');
			})
			}
		});
	});

	// previsualizar valores anteriormente seleccionados
	if ( $('#ndTitulo', 'form.nvDeba').val() !== '') { $('h3.entry-title', 'div.nvDebPrev').html( $('#ndTitulo', 'form.nvDeba').val() ) }
	if ( $('#ndDesc', 'form.nvDeba').val() !== '') { $('p.entry-summary', 'div.nvDebPrev').html( $('#ndDesc', 'form.nvDeba').val() ) }
	if ( $('#ndOpc1', 'form.nvDeba').val() !== '') { $('div.entry-opt1 strong', 'div.nvDebPrev').html( $('#ndOpc1', 'form.nvDeba').val() ) }
	if ( $('#ndOpc2', 'form.nvDeba').val() !== '') { $('div.entry-opt2 strong', 'div.nvDebPrev').html( $('#ndOpc2', 'form.nvDeba').val() ) }
	if ( $('#ndTema input:checked', 'form.nvDeba').length > 0 ) {
		$('p.entry-cat a', 'div.nvDebPrev').remove();
		$('#ndTema input:checked', 'form.nvDeba').each(function() {
				$('p.entry-cat', 'div.nvDebPrev').append( '<span class="' + $(this).attr('id') + '"><a href="#">' + $(this).parent().text() + '</a></span>');
				$('p.entry-cat span:last', 'div.nvDebMeta').append(', ');
			})
		}

	// expandir info debates históricos
	$('div.historico div.entry-content', 'body#historicos div#cont').hide();
	$('a.read-more-link', 'body#historicos div#cont div.historico').toggle(
		function() {
			$(this).text('Cerrar').parents('div.debate').toggleClass('extended').children('div.entry-content').slideDown(500);
		},
		function() {
			$(this).text('Más información').parents('div.debate').toggleClass('extended').children('div.entry-content').slideToggle();
		}
	);

	// animación en barras de utilización de tags
	$('ul.listTags').animateBars({ seps: '(', sepe: ')'});
	$('ul.listTemas').animateBars({ seps: '(', sepe: ')'});
	
	// scroll - destacados del debate
	var destDeb = $('div.destDeb-first ul', 'div.dest');
	var scrollLimit = eval(destDeb.outerHeight()) - 100;
	
	$('ul.pagi li:eq(1)', 'div.dest').click(function() {
		var debTop = destDeb.css('top');
		var debTop = debTop.split('px');
		var newDebTop = eval(debTop[0]) - 100;
		if ( eval(debTop[0] * -1) < scrollLimit )
		{
			destDeb.animate({'top': newDebTop+'px'});
			$('ul.pagi li:eq(0)', 'div.dest').removeClass('back-disabled').addClass('back-enabled');
		} else {
			$(this).removeClass().addClass('next-disabled');
		}
		return false;
	});
	$('ul.pagi li:eq(0)', 'div.dest').click(function() {
		var debTop = destDeb.css('top');
		var debTop = debTop.split('px');
		var newDebTop = eval(debTop[0]) + 100;
		if ( eval(debTop[0] * -1) > 0 )
		{
			destDeb.animate({'top': newDebTop+'px'});
			$('ul.pagi li:eq(1)', 'div.dest').removeClass().addClass('next-enabled');
		} else {
			$(this).removeClass().addClass('back-disabled');
		}
		return false;
	});
	
	// reemplazar imagen promocional por video
	$('.videoCont img').css('cursor', 'pointer').click(function() {
		$('.videoCont img').hide(); 
		//$('.videoCont object').css({ 'height': '360px', 'width': '640px', 'visibility': 'visible', 'display': 'block !important' }).show();important trae problemas con ie8
		//$('.videoCont embed').css({ 'height': '360px', 'width': '640px', 'visibility': 'visible', 'display': 'block !important' }).show();important trae problemas con ie8
		$('.videoCont object').show().css({ 'height': '360px', 'width': '640px', 'visibility': 'visible', 'display': 'block' });
		$('.videoCont embed').show().css({ 'height': '360px', 'width': '640px', 'visibility': 'visible', 'display': 'block' });
	});
	
	$('.destDeb-first a').css('cursor', 'pointer').click(function() {
		$('.videoCont img').hide();
		$('.videoCont').hide();
		//$('#video_debate').css({ 'height': '360px', 'width': '640px', 'visibility': 'visible', 'display': 'block !important' }).show();
		$('#video_debate').css({ 'height': '360px', 'width': '640px', 'visibility': 'visible', 'display': 'block' }).show();
	});
	
	
	// cambiar pestañas
	$('ul.blogSter:gt(0)').hide();
	$('ul.menuPest li a', '#side').click(function() {
		var target = $(this).attr('href');
		$('ul.menuPest li.acti', '#side').removeClass();
		$(this).parent('li').addClass('acti');
		$('ul.blogSter:visible').slideUp();
		$('ul'+target).slideDown();
		return false;
	});
	
	

}); //$(document).ready();


jQuery.extend({ //extension de metodo $
	id : function(id) {
		var id = id.split("#");
		return document.getElementById(id[1])?true:false;
	}
});


$(function(){

	$('#cropbox').Jcrop({
		aspectRatio: 1,
		onSelect: updateCoords
	});

});

function updateCoords(c)
{
	$('#x').val(c.x);
	$('#y').val(c.y);
	$('#w').val(c.w);
	$('#h').val(c.h);
};

function checkCoords()
{
	if (parseInt($('#w').val())) return true;
	alert('Seleccione un área para su foto.');
	return false;
};