$(window).load(function(){
	//Manejador tamaņo texto
	$("a.aumentar").click(function(){
		var ourText = $("#desarrollo");
		var currFontSize = ourText.css("fontSize");
		var finalNum = parseFloat(currFontSize, 10);
		var stringEnding = currFontSize.slice(-2);
		finalNum *= 1.1;
		ourText.css("fontSize", finalNum + stringEnding);
	});
	
	$("a.disminuir").click(function(){
		var ourText = $("#desarrollo");
		var currFontSize = ourText.css("fontSize");
		var finalNum = parseFloat(currFontSize, 10);
		var stringEnding = currFontSize.slice(-2);
		finalNum /=1.1;
		ourText.css("fontSize", finalNum + stringEnding);
	});
	
	//Efectos de Utilidades
	$("#utilidades").hover(
		function(){
			//setTimeout(function(){
				$("#opciones").css("position", "absolute");
				$("#opciones").css("display", "block");
			//},100);
		},  
		function () {
			setTimeout(function(){
				$("#opciones").css("display", "none");
			},400);
		}
	);
	
	//Busqueda de Ongs
	$("a#busquedas").click(function(){
		$("#opciones_busquedas").toggle("fast");
		return false;
	});
	
	$.ajaxSetup ({cache: false});
	
	// Formularios de contacto
	$('.errorform').hide();
	$('input.text-input').css({backgroundColor:"#FFFFFF"});
	$('input.text-input').focus(function(){
		$(this).css({backgroundColor:"#FFDDAA"});
	});
	$('input.text-input').blur(function(){
		$(this).css({backgroundColor:"#FFFFFF"});
	});
	
	$(".buttonmail").click(function() {
		// validate and process form
		// first hide any error messages
		$('.errorform').hide();
		
		var nombre = $("input#nombre").val();
		if (nombre == "") {
			$("label#nombre_error").show();
			$("input#nombre").focus();
			return false;
		}
		var email = $("input#email").val();
		if (email == "") {
			$("label#email_error").show();
			$("input#email").focus();
			return false;
		}
		var asunto = $("input#asunto").val();
		if (asunto == "") {
			$("label#asunto_error").show();
			$("input#asunto").focus();
			return false;
		}
		var consulta = $("textarea#consulta").val();
		if (consulta == "") {
			$("label#consulta_error").show();
			$("textarea#consulta").focus();
			return false;
		}
		if ($('input#copia').attr('checked')) {
			var copia = 'true';
		} else {
			var copia = 'false';
		}
		var destinatario = $("select#destinatario").val();
		
		var urlactual = $("input#urlactual").val();
		
		var dataString = 'nombre='+ nombre + '&email=' + email + '&asunto=' + asunto + '&destinatario=' + destinatario + '&consulta=' + consulta + '&copia=' + copia + '&url=' + urlactual;
		//alert (dataString);return false;
		
		$.ajax({
			type: "POST",
			url: urlactual,
			data: dataString,
			beforeSend: function(data){
				$('#formulario-contacto').html("<div id='message'></div>");
				$('#message').html("<h2>Enviando...</h2>").fadeIn(30);
			},
			success: function() {
				$('#message').html("<h2>Mensaje enviado con &eacute;xito!</h2>")
				.append("<p>Por&eacute;monos en contacto en breve.</p><br />")
				.hide()
				.fadeIn(1500);
			}
		});
		return false;
	});
	
	
	//Suscripcion al boletin
	$(".botonboletin").click(function() {
		$('.errorform').hide();
		var nombre = $("input#bnombre").val();
		if (nombre == "") {
			$("label#bnombre_error").show();
			$("input#bnombre").focus();
			return false;
		}
		var email = $("input#bemail").val();
		if (email == "") {
			$("label#bemail_error").show();
			$("input#bemail").focus();
			return false;
		}
		
		var dataString = 'nombre='+ nombre + '&email=' + email;
		//alert (dataString);return false;
		
		$.ajax({
			type: "POST",
			url: 'boletin.php',
			data: dataString,
			beforeSend: function(data){
				$('#boletin').html("<div id='message' style='padding:5px;'></div>");
				$('#message').html("<h3>Enviando...</h3>").fadeIn(30);
			},
			success: function() {
				$('#message').html("<p><strong>Suscrici&oacute;n ao bolet&iacute;n con &eacute;xito!<strong></p>")
				.hide()
				.fadeIn(1500);
			}
		});
		return false;
	});
	
	//Selector de localidades
	$("select#provincia").change(function() {
		var localidad = $("#localidad");
		if($(this).val() == '') {
			localidad.empty();
			localidad.append('<option value="">Seleccione unha Provincia</option>');
			return false;
		} else {
			localidad.empty();
			localidad.append('<option value="">Cargando...</option>');
			
			$.post("/inc/combos.php", {valor: $(this).val(), tipo: "localidad"}, function(xml){
				localidad.empty();
				$(xml).find("option").each(function(x,el) {
					localidad.append('<option value="'+$(el).attr("value")+'">' +$(el).text() + '</option>');
				});
			}, "xml");
		}
	});
	
	//Selector de Tipo Documento
	$("select#categoriadocumento").change(function() {
		var tipodocumento = $("#tipodocumento");
		if($(this).val() == '') {
			tipodocumento.empty();
			tipodocumento.append('<option value="">Seleccione unha Categoria</option>');
			return false;
		} else {
			tipodocumento.empty();
			tipodocumento.append('<option value="">Cargando...</option>');
			
			$.post("/inc/combos.php", {valor: $(this).val(), tipo: "tipo_documento"}, function(xml){
				tipodocumento.empty();
				$(xml).find("option").each(function(x,el) {
					tipodocumento.append('<option value="'+$(el).attr("value")+'">' +$(el).text() + '</option>');
				});
			}, "xml");
		}
	});
	

	// Imprimir contenido
	$("a.imprimir").click(function(){
		//$("div#desarrollo").imprimirContenido();
		$("div#desarrollo").printElement({printMode:'iframe'}); 
		//return false;
	});
	
	/********************************** 
		Descargar contenido
	**********************************/
	var informacion = $("div#desarrollo");
	
	$("a.descargar").click(function() {
	
		var titulo = document.title;
		var contenido = informacion.html();
		var url = document.location;
		
		var titulo_noticia = $("#noticia_titulo").text();
		var template2 = '<table width="100%" border="0" cellspacing="0" cellpadding="0" class="tabla">'+
							'  <tr>'+
							'    <td valign="middle" class="bordetr" width="400"><strong>' + titulo + '</strong></td>'+
							'    <td align="right" class="bordetr marginleft" width="50"><img src="http://www.galiciasolidaria.org/img/logo.jpg" width="269" height="87" /></td>'+
							'  </tr>'+
							'  <tr>'+
							'    <td valign="top" class="miniatura">' + url + '</td>'+
							'    <td valign="top" align="right" class="miniatura"><?php echo date("d/m/Y H:i"); ?></td>'+
							'  </tr>'+
							'</table>';

		var template =  '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n'+
						'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">\n'+
						'<head>\n'+
						'<title>' + titulo + '</title>\n'+
						'<style type="text/css">\n'+
						'	body,td,th {font-family: Helvetica, Arial, sans-serif;font-size: 11px;}\n table.tabla { border:none; font-size:8px;}\n table.tabla td { font-size:8px; padding:0; margin:0;}\n #desarrollo { padding:10px;}\n small { font-size:8px; }\n'+
						'	h1 { font-size:18px; margin:10px 0; font-weight:900; }\n h2 { font-size:16px; font-weight:900; margin:10px 0; }\n h3 { font-size:14px; }\n blockquote { font-style:oblique; border-left:#FC6 solid 3px; padding-left:5px; margin:0 15px; }\n strong { font-weight:900; }\n em { font-style:oblique; }\n img.borde { border:1px dotted #999;}\n'+
						'	table { border-collapse:separate;border-spacing:0; margin: 15px 0;} td { padding:3px;}.tcab { background-color:#ffd9b3; font-weight:900; border-bottom:#979797 solid 1px;}.tc1 { background-color:#ECECEC; border-bottom:#979797 solid 1px;}.tc2 { background-color:#F7F7F7; border-bottom:#979797 solid 1px;}.cc1 { background:none; color:#333 !important;}.cc2 { color:#fff !important; background:none;}.cc3 { color:#FF0000 !important; background:none;}'+
						'	h1#noticia_titulo { margin:0; margin-bottom:10px; }\n p#noticia_fecha { text-align:right; font-size:12px; color:#666; }\n span#noticia_tema {font-size:12px; color:#666; margin:0; }\n .invisible, a.irarriba { display:none !important; }\n td.bordetr { border-bottom:1px solid #666; padding-bottom:2px; margin-bottom:2px; }\n td.marginleft {margin-left: 5px; }\n td.miniatura { font-style:oblique; font-size:6px; }\n'+
						'</style>\n'+
						'</head>\n'+
						'<body>\n'+
						template2 +
						'<div id="desarrollo">' +contenido + '</div>'+'\n'+
						'<script type="text/php">\n'+
						'if ( isset($pdf) ) {\n'+
						'  $font = Font_Metrics::get_font("Helvetica");\n'+
						'  $size = 6;\n'+
						'  $color = array(0,0,0);\n'+
						'  $text_height = Font_Metrics::get_font_height($font, $size);\n'+
						'  $foot = $pdf->open_object();\n'+
						'  $w = $pdf->get_width();\n'+
						'  $h = $pdf->get_height();\n'+
						'  $y = $h - 2 * $text_height - 16;\n'+
						'  $y += $text_height;\n'+
						'  $text = "GaliciaSolidaria.org";\n'+
						'  $pdf->text(16, $y, $text, $font, $size, $color);'+ '\n'+
						'  $pdf->close_object();'+'\n'+
						'  $pdf->add_object($foot, "all");'+'\n'+
						'  global $initials;'+'\n'+
						'  $initials = $pdf->open_object();'+'\n'+
						'  $text = "<a href=\"http://www.galiciasolidaria.org\">www.galiciasolidaria.org</a>";'+'\n'+
						'  $width = Font_Metrics::get_text_width($text, $font, $size);'+'\n'+
						'  $pdf->text($w - 16 - $width - 38, $y, $text, $font, $size, $color);'+'\n'+
						'  $pdf->close_object();'+'\n'+
						'  $pdf->add_object($initials);'+'\n'+
						'  $text = "Pagina {PAGE_NUM} de {PAGE_COUNT}";  '+'\n'+
						'  $width = Font_Metrics::get_text_width("Pagina 1 de 2", $font, $size);'+'\n'+
						'  $pdf->page_text($w / 2 - $width / 2, $y, $text, $font, $size, $color);'+'\n'+
						'}'+'\n'+
						'</script>'+'\n'+
						'</body>'+'\n'+
						'</html>';

		$("#pdf_html").val(template);
		$("#pdf_archivo").val(titulo);
		document.pdf.submit();
		return false;
	});

	
	
	jQuery.fn.escuchar=function(){
		var texto = $("div#desarrollo").html();
		texto = texto.replace(/(^\s*)|(\s*$)/,"");
		texto = texto.replace(/&nbsp;/,"");
		for (i=0; i <= texto.length; i++) {
			texto = texto.replace(/<(\w*)>/,"");
			texto = texto.replace(/<p class="right">/,"");
			texto = texto.replace(/<\/(\w*)>/,"");
		}
		texto = texto.replace(/\n+/,"");
		texto = texto.replace(/\t+/,"");
		texto = encodeURIComponent(texto);
		
		var flashvars = {
			tit:		encodeURIComponent('++++++++. Coordinadora Galega de ONG para o Desenvolvemento.'),
			enc: 		"1",
			cat: 		"",
			url:		document.URL,
			lang:		"es",
			text:		"",
			txt: 		texto,
			autoplay:	"1"
		};
		var params = {
			quality:			"high",
			allowfullscreen: 	"false",
			allowscriptaccess:	"always",
			flash_component:	"ImageViewer.swc"
		};
		var attributes = {
			id: 		"myDynamicContent",
			name: 		"myDynamicContent"
		};
	
		swfobject.embedSWF("http://www.sonowebs.com/tts.swf", "escuchar", "1", "1", "9.0.0","expressInstall.swf", flashvars, params, attributes);
	}
	var reproducir=$("#reproducir");reproducir.click(function(){reproducir.escuchar();});

	//Formulario Suscripcion Boletin
	var fboletin = $("div#boletin");
	$("h4#bsuscripcion").click(function(){
		fboletin.toggle("fast");
		if (fboletin.css("display") == 'block') {
			$(this).removeClass("bmostrar").addClass("bocultar");
		} else {
			$(this).removeClass("bocultar").addClass("bmostrar");
		}
		return false;
	});		
});