//Generic updates #userbox with info retrieved  
//Generic updates #userbox with info retrieved  
//from services  
var connected = false;
var userinfo = "";
var profile_id = "";
var page_id = "";
var blog_exception = false;
function update_userbox(name, image, url, logout) {
	connected = true;
	//populate the data in #userbox and show it  
	if (url != "") {
		var userbox = "<table><tr><td align='right'><a href='"+url+"' class='ne12'>"  
		+ "<img style='border:2px solid #EA8A2D' alt='"+name+"' src='"+image+"' /></a></td></tr><tr>"+
		"<td align='right'><a href='"+url+"' class='ne12'>" + name + "</a> "
		+ "<br>(<a href='javascript:;' onclick='" + logout + "' class='na12'><b>Salir</b></a>)</td></tr></table>"
	} else {
		var userbox = "<table><tr><td align='right'>"  
		+ "<img style='border:2px solid #EA8A2D' alt='"+name+"' src='"+image+"' /></td></tr><tr>"+
		"<td class='ne12' align='right'>" + name + ""
		+ "<br>(<a href='javascript:;' onclick='" + logout + "' class='na12'><b>Salir</b></a>)</td></tr></table>"
	}
	
	userinfo = "<table><tr><td align='right'>"  
		+ "<img style='border:2px solid #EA8A2D' alt='"+name+"' src='"+image+"' /></td></tr><tr>"+
		"<td class='ne12' align='right'>" + name + ""
		+ "</td></tr></table>";
	
	$('#userbox').html( userbox ).show();

	//hide name input and service  
	//login buttons  
	$('#userinfo').hide();  
	 
	 
	//populate the values of the inputs  
	//using data from service  
	$('#name').val(name);
	$('#url').val(url);
	$('#image').val(image);
	$('#botones').hide();
	$('#boton_enviar').attr('disabled','');
	$.ajax({
		type: "POST",
		url: "/newuser_response.php",
		data: "auth="+$('#auth').val()+"&name="+name+"&url="+escape(url)+"&image="+escape(image)+"&profile_id="+profile_id+"&email="+escape($('#email').val()),
		success: function(msg){  }
	});
}

function update_userbox_anom(nombre,id,sesion_msg) {
	connected=true;
	$('#sesion').html(sesion_msg);
	var userbox = "<table><tr><td align='right'>"  
		+ "<img style='border:2px solid #EA8A2D' alt=\""+nombre+"\" src='/images/user.gif' /></td></tr><tr>"+
		"<td class='ne12' align='right'>"+ nombre
		+ "<br>(<a href='javascript:;' onclick='sign_out()' class='na12'><b>Salir</b></a>)</td></tr></table>";
	$('#userbox').html( userbox ).show();
	
	//hide name input and service  
	//login buttons  
	$('#userinfo').hide();  
	
	//populate the values of the inputs  
	//using data from service
	profile_id = id;
	$('#profile_id').val(profile_id);
	$('#name').val(nombre);
	$('#auth').val("anom");
	$('#url').val("");  
	$('#image').val("/images/user.gif");
	$('#botones').hide();
	$('#boton_enviar').attr('disabled','');
}

function sign_out() {
	var userbox = '<table><tr><td align="center"><a href="" onclick="show_login();return false;"><img src="/images/user.gif" border="0" title="Usuario sin identificar" alt="Usuario sin identificar"></a></td></tr><tr><td align="center"><a href="" onclick="show_login();return false;" class="gr"><b>Sin identificar</b><br><a href="" onclick="show_login();return false;" class="na10">Con&eacute;ctate</a></td></tr></table>';
	$('#userbox').html(userbox);
	$('#name').val("");  
	$('#url').val("");  
	$('#image').val("");
	$('#botones').show();
	$('#auth').val("");
	$('#profile_id').val("");
	$('#email').val("");
	profile_id = "";
	connected = false;
	userinfo = "";
	logout();
}

function logout() {
	$.ajax({
		type: "GET",
		url: "/login_anom.php?mode=exit&negro="+negro,
		success: function(msg){
			$('#sesion').html(msg);
		}
	});
}

//Facebook Connect  
function auth_using_fb() {
	//get the users data from FB  
	var uid = FB.Facebook.apiClient.get_session().uid;
	var viewer  = FB.Facebook.apiClient.fql_query('SELECT name, pic_square_with_logo,profile_url,proxied_email FROM user WHERE uid='+uid,
		function(results) {
			$('#auth').val("fbc");
			profile_id = uid;
			$('#profile_id').val(profile_id);
			$('#email').val(results[0].proxied_email);
			update_userbox(results[0].name,
			results[0].pic_square_with_logo,
			results[0].profile_url,
			'FB.Connect.logout();sign_out();');
			check_session("fb",results[0].name);
		}
	);
}

//Google Friend Connect  
function auth_using_gfc() {
	//Request GFC to send extra profile data  
	var params = {};  
	params[opensocial.DataRequest.PeopleRequestFields.PROFILE_DETAILS] =  
	[opensocial.Person.Field.URLS];  


	// Create a request to grab the current viewer.  
	var req = opensocial.newDataRequest();  
	req.add(req.newFetchPersonRequest('VIEWER', params), 'viewer_data');

	// Sent the request  
	req.send(function(data) {
		// If the view_data had an error, then user is not signed in  
		if (!data.get('viewer_data').hadError()) { 
			//get the users data from GFC
			var viewer = data.get('viewer_data').getData();
			
			if (typeof(viewer.getField(opensocial.Person.Field.URLS)) != "undefined")
				var url = viewer.getField(opensocial.Person.Field.URLS)[0].getField('address');
			else
				var url = "";
			
			profile_id = viewer.getField(opensocial.Person.Field.ID);
			$('#auth').val("gfc");
			$('#profile_id').val(profile_id);
			$('#email').val("");
			update_userbox( viewer.getDisplayName(),
				viewer.getField(opensocial.Person.Field.THUMBNAIL_URL),
				url,
				'google.friendconnect.requestSignOut();sign_out();');
			check_session("gfc",viewer.getDisplayName());
		}
	});
}

function check_session(type,name) {
	$.ajax({
		type: "GET",
		url: "/login_anom.php?lang="+lang+"&mode=check&auth="+type+"&name="+name+"&negro="+negro,
		success: function(msg){
			var campos = msg.split("##");
			if (campos[0] == "1") {
				connected = true;
				$('#sesion').html(campos[1]);
			}
		}
	});
}

function auth_using_despania() {
	check_session("","");
}

function load_comunidad() {
	$.ajax({
		type: "GET",
		url: "/login_anom.php?lang="+lang+"&mode=check&negro="+negro,
		success: function(msg){
			var campos = msg.split("##");
			$('#sesion').html(campos[1]);
			if (campos[0] == "0") {
				// Initialize Facebook Connect
				FB.init("4b9d7ee5fef2d165760ba6e4c6a4ca91", "xd_receiver.htm", {"ifUserConnected" : auth_using_fb});
				// Initialize the Google Friend Connect OpenSocial API.
				//google.friendconnect.container.setParentUrl('/' /* location of rpc_relay.html and canvas.html */);
				/*
				google.friendconnect.container.initOpenSocialApi({
				site: '12070991411306856614',
				onload: function(securityToken) { auth_using_gfc(); }
				});
				*/
			} else {
				connected = true;
			}
		}
	});
}

function getops(id) {
	$.ajax({
		type: "POST",
		url: "/get_ops.php?id="+id,
		data: "",
		success: function(msg){
			var dataOps = parseJSON (msg);
			$('#newcommentdiv').html("");
			$('.comentarios').html("");
			//$('#newcommentdiv').append(msg);
			for (i = 0; i < dataOps.length; i++) {
				if (dataOps[i].id_padre != "")
					$('#comentarios_'+dataOps[i].id_padre).append(dataOps[i].content);
				else
					$('#newcommentdiv').append(dataOps[i].content);
			}
		}
	});
}
function show_login() {
	GB_show('Identificate en deSpania','/login_anom.php?lang='+lang+'&negro='+negro,300,445);
	//window.open('/login_anom.php?lang='+lang+'&negro='+negro,'Identificate','status=0,toolbar=0,width=445,height=300');
}
function show_login_send() {
	GB_show('Identificate en deSpania','/login_anom.php?send=1&'+lang+'&negro='+negro,300,445);
	//window.open('/login_anom.php?send=1&negro='+negro,'Identificate','status=0,toolbar=0,width=545,height=400');
}
var scomment = "";
var escribido = "";
function send_op() {
	if (escribido != "" || adjuntandoflag) {
		if (!connected) {
			show_login_send();
		} else {
			var auth = $('#auth').val();
			var name = document.commentform.name.value;
			var url = document.commentform.url.value;
			var image = document.commentform.image.value;
			var comment = document.commentform.comment.value;
			var nombre_destino = document.commentform.nombre_destino.value;
			var idobj = document.commentform.idobj.value;
			var url_destino = document.commentform.url_destino.value;
			var link = "";
			var thumb = "";
			var title = "";
			var descr = "";
			var imgfile = "";
			var video_id = "";
			var lugar = "";
			var dia = "";
			if (document.getElementById('link') != null
				&& document.getElementById('title') != null
				&& document.getElementById('title').value != "") {
				adjuntando = "enlace";
				link = document.getElementById('link').value;
				title = document.getElementById('title').value;
				descr = document.getElementById('descr').value;
				thumb = document.getElementById('thumb').value;
				if (document.getElementById('nofoto') != null && document.getElementById('nofoto').checked == true) thumb = "";
			}
			if (document.getElementById('imgfile') != null
				&& document.getElementById('imgfile').value == "1") {
				adjuntando = "foto";
			}
			if (document.getElementById('video_id') != null
				&& document.getElementById('video_id').value != "") {
				adjuntando = "video";
				video_id = document.getElementById('video_id').value;
				title = document.getElementById('title').value;
				descr = document.getElementById('descr').value;
			}
			if (document.getElementById('evento') != null
				&& document.getElementById('evento').value != "") {
				adjuntando = "evento";
				title = document.getElementById('evento').value;
				descr = document.getElementById('descr').value;
				lugar = document.getElementById('lugar').value;
				dia = document.getElementById('dia').value+"_"+document.getElementById('mes').value+"_"+document.getElementById('hora').value;
			}
			if (document.getElementById('articulo') != null
				&& document.getElementById('articulo').value != "") {
				adjuntando = "articulo";
				descr = document.getElementById('articulo').value;
				title = document.getElementById('titulo').value;
			}
			//alert("auth="+auth+"&name="+name+"&url="+escape(url)+"&image="+escape(image)+"&comment="+comment+"&id="+idobj+"&nombre_destino="+nombre_destino+"&url_destino="+escape(url_destino)+"&profile_id="+profile_id+"&link="+link+"&title="+title+"&descr="+descr+"&thumb="+thumb+"&imgfile="+imgfile+"&que="+adjuntando);
			$.ajax({
				type: "POST",
				url: "/mod_comunidad_send.php",
				data: "auth="+auth+"&name="+name+"&url="+escape(url)+"&image="+escape(image)+"&comment="+comment+"&id="+idobj+"&nombre_destino="+nombre_destino+"&url_destino="+escape(url_destino)+"&profile_id="+profile_id+"&link="+link+"&title="+title+"&descr="+descr+"&thumb="+thumb+"&imgfile="+imgfile+"&video_id="+video_id+"&lugar="+lugar+"&dia="+dia+"&que="+adjuntando,
				success: function(msg){
					if (msg == "bot") {
						alert("Tienes varios comentarios pendientes de validar, intentalo mas tarde...");
					}
					else if (msg != "error") {
						if (adjuntando == "articulo") document.location.href="/blog-nuevo-articulo.html";
						getops(page_id);
						$('#comment').val("Escribe otro comentario...");
						$('#comment').css('color','gray');
						adjunta_cierra("");
						escribido = "";
						adjuntandoflag = false;
					} else {
						$('#newcommentdiv').append("Se ha producido un error en la autenticaci&oacute;n. Int&eacute;ntalo en otro momento por favor.");
					}
				}
			});
		}
	}
}
function send_sop(que) {
	if (!connected) {
		window.open('/login_anom.php','Identificate','status=0,toolbar=0,width=545,height=380');
	} else {
		var auth = document.commentform.auth.value;
		var name = document.commentform.name.value;
		var url = document.commentform.url.value;
		var image = document.commentform.image.value;
		var comment = $('#scomentario_'+que).val();
		var nombre_destino = document.commentform.nombre_destino.value;
		var idobj = document.commentform.idobj.value;
		var url_destino = document.commentform.url_destino.value;
		$('#comentar_form_'+que).html("<img src='/images/loading.gif'>");
		$.ajax({
			type: "POST",
			url: "/mod_comunidad_send.php",
			data: "auth="+auth+"&name="+name+"&url="+url+"&image="+escape(image)+"&comment="+comment+"&id="+idobj+"&nombre_destino="+nombre_destino+"&url_destino="+escape(url_destino)+"&profile_id="+profile_id+"&cid="+que,
			success: function(msg){
				$('#comentar_form_'+que).html("");
				if (msg == "bot") {
					alert("Tienes varios comentarios pendientes de validar, intentalo mas tarde...");
				}
				else if (msg != "error") {
					if (blog_exception) getops(0);
					else getops(page_id);
					$('#comment').val("Escribe otro comentario...");
					$('#comment').css('color','gray');
				} else {
					$('#newcommentdiv').append("Se ha producido un error en la autenticaci&oacute;n. Int&eacute;ntalo en otro momento por favor.");
				}
			}
		});
	}
}
function send_dest() {
	if (!connected) {
		window.open('/login_anom.php','Identificate','status=0,toolbar=0,width=545,height=380');
	} else {
		var auth = $('#auth').val();
		var name = document.commentform.name.value;
		var url = document.commentform.url.value;
		var image = document.commentform.image.value;
		var comment = document.commentform.comment.value;
		var tipo = document.commentform.tipo.value;
		var provincia_id = document.commentform.provincia.value;
		var lat = document.commentform.lat.value;
		var lng = document.commentform.lng.value;
		var sat = document.commentform.sat.value;
		var zoomnow = document.commentform.zoom.value;
		if (comment == ""
			|| comment.match(/el nombre/)) $('#msg').html("Introduce un nombre para el nuevo destino.");
		else if (provincia_id == "") $('#msg').html("Selecciona un provincia, por favor.");
		else {
			$.ajax({
				type: "POST",
				url: "/mod_comunidad_send.php",
				data: "auth="+auth+"&name="+name+"&url="+escape(url)+"&image="+escape(image)+"&comment="+comment+"&profile_id="+profile_id+"&provincia_id="+provincia_id+"&lat="+lat+"&lng="+lng+"&que=destino&tipo="+tipo+"&sat="+sat+"&zoom="+zoomnow,
				success: function(msg){
					if (msg != "error") {
						document.location.href='mod_comunidad_gracias.php';
					} else {
						$('#msg').html("Se ha producido un error en la autenticaci&oacute;n. Int&eacute;ntalo en otro momento por favor.");
					}
				}
			});
		}
	}
}
function ph() {
	alert("subiendo foto");
}
var adjuntando = "";
var adjuntandoflag = false;
function adjunta(que) {
	$('#adjuntar_botones').hide();
	$('#adjuntar_form').html("<center><img src='/images/ajax-loader.gif'></center>");
	$.ajax({
		type: "GET",
		url: "/mod_comunidad_form.php?form="+que,
		data: "",
		success: function(msg){
			//adjuntando = que;
			adjuntandoflag = true;
			$('#adjuntar_form').html(msg);
			/*
			$('#textarea').wysiwyg({
				css : { fontFamily: 'Arial, Tahoma', fontSize : '13px'}
			});*/
		}
	});
}
function adjunta_cierra(que) {
	$('#adjuntar_form').html("");
	$('#adjuntar_botones').show();
	adjuntando = "";
	adjuntandoflag = false;
}
function comenta(que) {
	$('#comentar_form_'+que).html("<center><img src='/images/ajax-loader.gif'></center>");
	$.ajax({
		type: "GET",
		url: "/mod_comunidad_form.php?form=op_"+que,
		data: "",
		success: function(msg){
			$('#comentar_form_'+que).html(msg);
		}
	});
}
function comenta_blog(que) {
	$('#comentar_form_'+que).html("<center><img src='/images/ajax-loader.gif'></center>");
	$.ajax({
		type: "GET",
		url: "/mod_comunidad_form.php?form=blog_"+que,
		data: "",
		success: function(msg){
			$('#comentar_form_'+que).html(msg);
		}
	});
}

function descomenta(que) {
	$('#comentar_form_'+que).html("");
}
function megusta(que) {
	var auth = $('#auth').val();
	$.ajax({
		type: "POST",
		url: "/mod_comunidad_send.php",
		data: "auth="+auth+"&profile_id="+profile_id+"&megusta=1&que="+que,
		success: function(msg){
			if (msg == "error") $('#gustos_'+que).html("Identif&iacute;cate primero...");
			else if (msg != "") $('#gustos_'+que).html(msg);
		}
	});
}
function nomegusta(que) {
	var auth = $('#auth').val();
	$.ajax({
		type: "POST",
		url: "/mod_comunidad_send.php",
		data: "auth="+auth+"&profile_id="+profile_id+"&nomegusta=1&que="+que,
		success: function(msg){
			if (msg == "error") $('#gustos_'+que).html("Identif&iacute;cate primero...");
			else if (msg != "") $('#gustos_'+que).html(msg);
		}
	});
}
function acl(element,flag,c) {
	if (c != '' && profile_id+"" == c) {
		$('#e_'+element).show();
	}
}
function dp(c,c_id,q) {
	$('#entry_'+c).css('background-color','#F2F2F2');
	$.ajax({
		type: "POST",
		url: "/mod_comunidad_dp.php",
		data: "c="+c+"&profile_id="+profile_id+"&id="+c_id+"&q="+q,
		success: function(msg){
			if (blog_exception) getops(0);
			else getops(page_id);
		}
	});
}
function dc() {

}
var imgdisplay = 1;
var imgnum = 0;
function adj_link() {
	var url = $('#link').val();
	$('#link_results').html("<center><img src='/images/ajax-loader.gif'></center>");
	$.ajax({
		type: "POST",
		url: "/mod_comunidad_get_link.php",
		data: "url="+escape(url),
		success: function(msg){
			if (msg == "error") {
				$('#link_results').html("<center><font class='ne10'>Imposible conectar a esta direcci&oacute;n</font></center>");
			} else {
				$('#link_results').html(msg);
				imgnum = $('#snapnum').html();
				imgdisplay = 1;
			}
		}
	});
}
function inic_thumbs(num) {
	var w; var h;
	var images = "";
	var k = 1;
	for (i=1;i<=num;i++) {
		w = $('#imgsrc'+i).width();
		h = $('#imgsrc'+i).height();
		if (w > 20 && h > 20 && w < 400 && h < 400) {
			if (k == 1) images += '<div id="snap_'+k+'">';
			else images += '<div id="snap_'+k+'" style="display:none">';
			images += '<input type="hidden" name="img'+k+'" id="img'+k+'" value="'+$('#imgsrc'+i).attr("src")+'">';
			images += '<img src="'+$('#imgsrc'+i).attr("src")+'" alt="">';
			images += '</div>';
			k++;
		}
		/*<input type="hidden" name="img<?=$i?>" id="img<?=$i?>" value="<?=$img?>">*/
	}
	if (k > 1) {
		$('#thumblist').html(images);
		$('#snapnum').html(k);
	} else {
		$('#thumblist').html("");
		$('#thumbstd').html("");
		$('#thumbscheck').html("");
		$('#thumb').val("");
	}
}
function prev_img() {
	if (imgdisplay > 1) {
		$('#snap_'+imgdisplay).hide();
		imgdisplay--;
		$('#snapnow').html(imgdisplay);
		$('#snap_'+imgdisplay).show();
		$('#thumb').val($('#img'+imgdisplay).val());
	}
}
function next_img() {
	if (imgdisplay < imgnum) {
		$('#snap_'+imgdisplay).hide();
		imgdisplay++;
		$('#snapnow').html(imgdisplay);
		$('#snap_'+imgdisplay).show();
		$('#thumb').val($('#img'+imgdisplay).val());
	}
}

function adj_video() {
	var url = $('#videolink').val();
	$('#video_results').html("<center><img src='/images/ajax-loader.gif'></center>");
	$.ajax({
		type: "POST",
		url: "/mod_comunidad_get_video.php",
		data: "url="+escape(url),
		success: function(msg){
			if (msg == "error1") {
				$('#video_results').html("<center><font class='ne10'>Pega aqu&iacute; una direcci&oacute;n correcta de Youtube</font></center>");
			} else if (msg == "error2") {
				$('#video_results').html("<center><font class='ne10'>Imposible conectar con este video</font></center>");
			} else {
				$('#video_results').html(msg);
				var params = { allowScriptAccess: "always" };
				var atts = { id: "myytplayer" };
				var video_id = $('#video_id').val();
				swfobject.embedSWF("http://www.youtube.com/v/"+video_id+"&enablejsapi=1&playerapiid=ytplayer", "ytapiplayer", "200", "150", "8", null, null, params, atts);
			}
		}
	});
}

function ajaxFileUpload() {
	$('#downimage').html("<img src='/images/loading.gif' width='16'>&nbsp;Subiendo foto...");
	$('#imgfile').val('');
	$.ajaxFileUpload (
		{
			url:'mod_comunidad_send.php',
			secureuri:false,
			fileElementId:'fileToUpload',
			dataType: 'json',
			success: function (data, status) {
				alert(data);
				if(typeof(data.error) != 'undefined') {
					if(data.error != '') {
						$('#downimage').html(data.error);
					} else {
						var rand = Math.floor(Math.random()*1001);
						alert(data.msg);
						$('#downimage').html("<img src='/downimage.php?id="+data.msg+"' alt='Foto subida'>");
						$('#imgfile').val('1');
					}
				}
			},
			error: function (data, status, e) {
				alert("error");
				$('#downimage').html(e);
			}
		}
	)
	
	return false;
}

function ajaxFileUpload_framed() {
	$('#downimage').html("<img src='/images/loading.gif' width='16'>&nbsp;Subiendo foto...");
	$('#imgfile').val('');
	$.ajaxFileUpload (
		{
			url:'mod_comunidad_send.php',
			secureuri:false,
			fileElementId:'fileToUpload',
			dataType: 'json',
			success: function (data, status) {
				if(typeof(data.error) != 'undefined') {
					if(data.error != '') {
						$('#downimage').html(data.msg);
					} else {
						var rand = Math.floor(Math.random()*1001);
						$('#imgfile').val('1');
						window.parent.push_image(data.msg,data.w);
					}
				}
			},
			error: function (data, status, e) {
				$('#downimage').html(e);
			}
		}
	)
	
	return false;
}

function load_greybox() {
	$("a.greybox250").click(function(){
		var t = this.title || $(this).text() || this.href;
		var w = 400;
		var h = 250;
		GB_show(t,this.href,h,w);
		return false;
	});
	$("a.greybox160").click(function(){
		var t = this.title || $(this).text() || this.href;
		var w = 400;
		var h = 160;
		GB_show(t,this.href,h,w);
		return false;
	});
	$("a.greybox300").click(function(){
		var t = this.title || $(this).text() || this.href;
		var w = 400;
		var h = 300;
		GB_show(t,this.href,h,w);
		return false;
	});
	$("a.greybox400").click(function(){
		var t = this.title || $(this).text() || this.href;
		var w = 400;
		var h = 400;
		GB_show(t,this.href,h,w);
		return false;
	});
}

function load_carousel() {
	jQuery('#mycarousel').jcarousel({
		vertical: true,
		auto: 2,
		scroll: 1,
        wrap: 'last',
        initCallback: mycarousel_initCallback
    });
	document.getElementById('wrap').style.visibility = 'visible';
}
function mycarousel_initCallback(carousel)
{
    // Disable autoscrolling if the user clicks the prev or next button.
    carousel.buttonNext.bind('click', function() {
        carousel.startAuto(0);
    });

    carousel.buttonPrev.bind('click', function() {
        carousel.startAuto(0);
    });

    // Pause autoscrolling if the user moves with the cursor over the clip.
    carousel.clip.hover(function() {
        carousel.stopAuto();
    }, function() {
        carousel.startAuto();
    });
}

