// JavaScript Document
var page_path = '/';
function busca_contactos(provider,url){
	var valbus={
		username:$("#username"+provider).val(),
		password:$("#password"+provider).val(),
		provider:provider,
		parte:"getContacts"
	}
	$.ajax({
		type: "POST",
		url: url,
		data: valbus,
		success: function( data, status, xhr ) {
			eval(data);
		},
		error: function() {
			//alertx("El servidor ha tardado en responder","Error");
		},
		dataType: "text"
	});
	$("#listas_contactos_registrados"+provider).html("<div align='center'><img  src='http://toakistatic.toaki.com/assets/images/misc/ajax-loader.gif'></div>");
	$("#listas_contactos_e"+provider).html("");
	$("#listas_contactos"+provider).html("");
}
function reportComment(commentId){
	var valbus={
		c:commentId
	}
	$.ajax({
		type: "POST",
		data: valbus,
		url: page_path+'comments/report',
		success: function( data, status, xhr ) {
			eval(data);
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			if (textStatus == "timeout") {
				alertx("The request timed out, please resubmit","Error");
			}else {
				alertx("ERROR: " + textStatus, "Error");
			}
		},
		dataType: "text"
	});
}
function alertx(txt,title,bot){
	if (!bot) bot={
			Ok: function() {
				$( this ).dialog( "close" );
			}
	};
	$('#dialog').remove();
	$('body').append('<div id="dialog">'+txt+'</div>');
	$('#dialog').dialog({
		resizable: false,
		modal: true,
		draggable: false,
		width:450,
		minHeight:150,
		zIndex:99999,
		title: title,
		buttons: bot

	});
}

function confirmRemoveCheckin(cid,place,hour,title){
	$( "#dialogCheck" ).dialog({
		resizable: false,
		modal: true,
		draggable: false,
		width:450,
		minHeight:100,
		zIndex:99999,
		title: title,
		open: function(event, ui) {
			var txt ='<a class="but_gray_small right" onclick="$(\'#dialogCheck\' ).dialog( \'destroy\' );">No</a><a class="but_blue_small butconfirm right" onclick="$(\'#dialogCheck\' ).dialog( \'destroy\' );removeCheckin('+cid+');">Yes, Remove</a>';
			$('#buttonsRemove').html(txt);
			$('#place').html(place+ ' at '+hour);
		}
	});
}
function removeCheckin(cid){
	$.post(page_path+"checkins/remove", {
		cid: cid
	},
	function(data) {
		$("#histCheck").html(data);
	});
}
function muestra_registrados(datos,tipo,sid,provider){
	var txt='',c=0;

	txt+='<br/><form name="requester'+provider+'" onsubmit="sendFriendRequest(\''+provider+'\'); return false; " method="POST" id="requester'+provider+'">'+
		'<table class="registered_users">'+
	'<tr><td>Já registado</td></tr>'+
	'<tr><td><input type="submit" class="but_gray right skip" value="Enviar pedido amigo" /></td></tr>'+
	'</table>'+
	'<div id="reg_'+provider+'" class="grures_max"><table>'+
	'<tr><td style="width:16px;"><input id="selrid_'+provider+'" type="checkbox" onclick="toggleAll(this.id,\'reg_'+provider+'\')" name="toggle_all" title="Select/Deselect all" checked="checked" /></td><td><b>Nome</b></td></tr>';

	for(c = 0; c < datos.length; c++){
		txt+= '<tr>';
		txt+= '<td style="width:16px;"><input class="chkImpR'+provider+'" name="checkR['+c+']" value="'+c+'" type="checkbox" checked="checked" /><input type="hidden" name="uid['+c+']" value="'+datos[c][0]+'" /></td>';
		txt+= '<td>'+datos[c][2]+datos[c][1]+'</td>';
		txt+='</tr>';
	}
	txt+='<input type="hidden" name="numR" value='+c+' />';
	txt+='</table></div></form><br/>';
	$("#listas_contactos_registrados"+provider).html(txt);
}
function envia_invitacion(provider){
	$("#listas_contactos_e"+provider).html("");
	var valbus={
		vars:$("#inviter"+provider).serialize(),
		username:$("#username"+provider).val(),
		provider:provider
	}
	$.ajax({
		type: "POST",
		data: valbus,
		url: page_path+"sendInvites",
		success: function( data, status, xhr ) {
			eval(data);
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			if (textStatus == "timeout") {
				alertx("The request timed out, please resubmit","Error");
			}else {
				alertx("ERROR: " + textStatus,"Error");
			}
		},
		dataType: "text"
	});
	$("#listas_contactos"+provider).html("<div align='center'><img  src='http://toakistatic.toaki.com/assets/images/misc/ajax-loader.gif'></div>");
}
function muestra_res(datos,provider){
	var txt='';
	for (var x in datos){
		txt+='<div>'+datos[x]+'</div>';
	}
	$("#listas_contactos"+provider).html(txt);
}
function muestra(datos,tipo,sid,provider){
	var txt='',c=0;

	txt+='<form  id="inviter'+provider+'" method="POST" name="inviter'+provider+'" onsubmit="envia_invitacion(\''+provider+'\');return false;">'+
		'<table>'+
	'<tr><td><textarea id="message_body" name="message_body"></textarea></td></tr>'+
	'<tr><td>'+
	'<input type="submit" class="but_gray right skip" value="Envie convites" />'+
	'<input type="hidden" name="v" value="sendInvites" />'+
	'<input type="hidden" name="oi_session_id" value="'+sid+'" />'+
	'</td></tr>'+
	'<tr><td>Seus contatos</td></tr>'+
	'</table>'+
	'<div id="gru_'+provider+'" class="grures_max"><table>'+
	'<tr><td style="width:16px;"><input id="selid_'+provider+'" type="checkbox" onclick="toggleAll(this.id,\'gru_'+provider+'\')" name="toggle_all" title="Select/Deselect all" checked="checked" /></td><td><b>Nome</b></td>'+(tipo=='email'?'<td><b>E-mail</b></td>':'')+'</tr>';
	for (var x in datos){
		txt+='<tr>'+
		'<td style="width:16px;"><input class="chkImp'+provider+'" name="check['+c+']" value="'+c+'" type="checkbox" checked="checked" /><input type="hidden" name="email['+c+']" value="'+x+'" /><input type="hidden" name="name['+c+']" value="'+datos[x]+'" /></td>'+
		'<td>'+convertjEsc2Char(datos[x],true)+'</td>'+
		(tipo == 'email'?'<td>'+x+'</td>':'')+'</tr>';
		c++;
	}
	txt+='</table></div></form>';
	$("#listas_contactos"+provider).html(txt);
}
function muestra_err(datos,provider){
	var txt='';
	for (var x in datos){
		txt+='<div>'+datos[x]+'</div>';
	}
	$("#listas_contactos_e"+provider).html(txt);
	$("#listas_contactos_registrados"+provider).html("");
}

function toggleAll(id,pID){
	$( "#" + pID + " :checkbox").attr('checked', $('#' + id).is(':checked'));
}
/**
 * Send Request to all the registered users that you found, when you link one of your social accounts
 */
function sendFriendRequest(provider){

	$.post(page_path+"sendRequests", {
		vars: $("#requester"+provider).serialize()
	},
	function(data) {
		$("#listas_contactos_registrados"+provider).html(data);
	});
	$("#listas_contactos_registrados"+provider).html("<div align='center'><img  src='assets/images/misc/ajax-loader.gif'></div>");
}
/**
 * Send Request to a user in its profile
 */
function requestFriendDialog(title){
	$( "#pop_containerRequest" ).dialog({
		resizable: false,
		modal: true,
		draggable: false,
		minHeight:100,
		title:title,
		width:400,
		zIndex:99999
	});
}
function requestFriend(id){
	$.post(page_path+'friends/request', {
		id:id
	},
	function(data) {
		$("#requestDiv").html(data);
	});
}
function rejectFriend(id,index){
	$("#pop_containerAccept").dialog("destroy");
	removeFriend(id,index);
}
function acceptFriend(id,index,username){
	$.post(page_path+"friends/acceptRequest", {
		id: id,
		username:username
	} ,
	function(data) {
		$("dd.friend"+index).html(data);
		$("#requestDiv").html(data);
		$("#friend"+index).remove();
		var val = $("#total").html();
		val--;
		$("#total").html(val);
		if(val==0)
		{location.replace('friends/index');
		}
	});
}
function showDialogFriend(title){
	$( "#pop_containerAccept" ).dialog({
		resizable: false,
		modal: true,
		draggable: false,
		minHeight:100,
		title:title,
		zIndex:99999,
		width:400
	});

}

function removeFriend(id, index){

	$.post(page_path+"friends/remove", {
		id: id
	},
	function(data) {
		if(data == 'true'){
			$("#friend"+index).remove();
			var val = $("#total").html();
			val--;
			$("#total").html(val);
		}
		else{

	}
	});


}
function convertjEsc2Char ( str, shortEscapes ) {

	str = str.replace(/\\U([A-Fa-f0-9]{8})/g,
		function(matchstr, parens) {
			return hex2char(parens);
		}
		);
	str = str.replace(/\\u([A-Fa-f0-9]{4})/g,
		function(matchstr, parens) {
			return hex2char(parens);
		}
		);

	if (shortEscapes) {
		//str = str.replace(/\\0/g, '\0');
		str = str.replace(/\\b/g, '\b');
		str = str.replace(/\\t/g, '\t');
		str = str.replace(/\\n/g, '\n');
		str = str.replace(/\\v/g, '\v');
		str = str.replace(/\\f/g, '\f');
		str = str.replace(/\\r/g, '\r');
		str = str.replace(/\\\'/g, '\'');
		str = str.replace(/\\\"/g, '\"');
		str = str.replace(/\\\\/g, '\\');
	}
	return str;
}


function hex2char ( hex ) {
	var result = '';
	var n = parseInt(hex, 16);
	if (n <= 0xFFFF) {
		result += String.fromCharCode(n);
	}
	else if (n <= 0x10FFFF) {
		n -= 0x10000
		result += String.fromCharCode(0xD800 | (n >> 10)) + String.fromCharCode(0xDC00 | (n & 0x3FF));
	}
	else {
		result += 'hex2Char error: Code point out of range: '+dec2hex(n);
	}
	return result;
}


function like(l,url){
	$.ajax({
		type: "POST",
		url: url+l,
		success: function( data, status, xhr ) {
			$("#recommended").html(data);
			$("#recommendPlace").html('');
		},
		error: function() {

		},
		dataType: "text"
	});
}
function showCommentsPlace(l,limit,url){
	$.post(url+l, {
		l:l,
		limit:limit
	},callbackShowComment);
}
function showCheckinsPlace(l,limit,url){
	$.post(url+l, {
		l:l,
		limit:limit
	},
	function callbackShowComment(data){

		$("#checkinss").html(data);
	});
}
function showDirectorsPlace(l){
	$.post(page_path+"place/directors", {
		l:l
	},
	function callbackShowComment(data){

		$("#leaders").html(data);
	});
}
function showLeadersPlace(l,limit){
	$.post("?v=leaderPlace", {
		l:l,
		limit:limit
	},
	function callbackShowComment(data){

		$("#commentsPost").html(data);
	});
}
function showCommentsUser(limit,user_id){
	$.post(page_path+"comments/user/"+user_id, {
		limit:limit,
		user_id:user_id
	},
	function(data) {
		$("#comments").html(data);
	});
}
function showCheckinsUser(limit,user_id){
	$.post(page_path+"checkins/user/"+user_id, {
		limit:limit,
		user_id:user_id
	},
	function(data) {
		$("#checkinss").html(data);
	});
}

function callbackShowComment(data){

	$("#commentsPost").html(data);
}

var login=0;
function showLoginOn(logged)
{
	if (login) return;
	p=$('#loginbuton').offset();
	p.left-=($('#signin_menuOff').width()-$('#loginbuton').width())+25;
	p.top+=31;
	$('#signin_menuOff').css({
		'top':p.top+'px',
		'left':p.left+'px',
		'width':'200px'
		});
	$('#signin_menuOff').show();
	$('#header').unbind('click');
	setTimeout('login=1;', 100);
	//document.getElementById("signin_menuOff").className = "signin_menu";
	if(logged){
	    document.getElementById("loginbuton").className = "contabutactive right";
	}
	else{
	    document.getElementById("loginbuton").className = "imgbut logintxtop_active right";
	}

}
function showLoginOff(logged)
{
	if (!login) return;
	$('#signin_menuOff').hide();
	login=0;
	if(logged){
	    document.getElementById("loginbuton").className = "contabut right";
	}
	else{
	    document.getElementById("loginbuton").className = "imgbut logintxtop right";
	}
}

$(document).ready(function() {
	$("#warning_notice").slideDown("slow");
	//reescritura de la funcion de tabs,
	//nota: no dejar que los de diseño creen sus propias funciones con librerias incompatibles
	var tabactual='';
	var nuevo='';
	$('.tabnav li a').click(function(){
		nuevo=$(this).attr('href');
		if (tabactual==nuevo) return false;
		$('.tabnav li').removeClass('ui-tabs-selected');
		$(this).parent().addClass('ui-tabs-selected');
		$(tabactual).slideUp('normal', function(){
			tabactual=nuevo;
			$(nuevo).slideDown('normal')
		})
		return false;
	});
	$('#tabvanilla > div').hide();
	$('#tabvanilla > div:first').slideDown();
	tabactual=$('#tabvanilla .tabnav li a:first').attr('href');
	$('#tabvanilla .tabnav li:first').addClass('ui-tabs-selected');
});

$(function() {
	$(".butPost").click(function() {

		var comment = jQuery.trim($("textarea[name=comment]").val());
		var place = $("input[name=p]").val();
		var advId = $("input[name=aI]").val();
		var url = $("input[name=url]").val();
		$("textarea[name=comment]").val('');
      if(comment != ''){
		$.post(url+place, {
			comment: comment
		},
		function(data){
		values = data.split('##$##');
		eval(values[0]);
		$('#total_comments').html(values[1]);
		});
      }


	});
	$(".butlogin").click(function() {
		$('#err_nodata').fadeOut('normal');
		$('#err_user').fadeOut('normal');
		var name = $("input#login_username").val();
		var pass = $("input#login_password").val();

		if(name=='' || pass==''){
			$('#err_nodata').fadeIn('normal');
			return false;
		}
		else{
			var remember=0;
			if($('#login_equipo').is(':checked')){
				remember=1;
			}
			validate(name,pass,remember,'');

			return false;
		}
	});
});


function validate(name,pass,remember,facebook){
	var varpos={
		'name': name,
		'password': pass ,
		'remember': remember,
		'facebook': facebook
		}
	$.ajax({
		type: "POST",
		url: page_path+"login",
		data: varpos,
		success: function( data, status, xhr ) {
			eval(data);
		},
		error: function() {
			//alertx("El servidor ha tardado en responder","Error");
		},
		dataType: "text"
	});
};

var Url = {

	// public method for url encoding
	encode : function (string) {
		return escape(this._utf8_encode(string));
	},

	// public method for url decoding
	decode : function (string) {
		return this._utf8_decode(unescape(string));
	},

	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";

		for (var n = 0; n < string.length; n++) {

			var c = string.charCodeAt(n);

			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}

		}

		return utftext;
	},

	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;

		while ( i < utftext.length ) {

			c = utftext.charCodeAt(i);

			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}

		}

		return string;
	}

}
$(document).ready(function() {

	//ACCORDION BUTTON ACTION (ON CLICK DO THE FOLLOWING)
	$('.accordionButton').click(function() {

		//REMOVE THE ON CLASS FROM ALL BUTTONS
		$('.accordionButton').removeClass('on');

		//NO MATTER WHAT WE CLOSE ALL OPEN SLIDES
		$('.accordionContent').slideUp('normal');

		//IF THE NEXT SLIDE WASN'T OPEN THEN OPEN IT
		if($(this).next().is(':hidden') == true) {

			//ADD THE ON CLASS TO THE BUTTON
			$(this).addClass('on');

			//OPEN THE SLIDE
			$(this).next().slideDown('normal');
		}

	});


	/*** REMOVE IF MOUSEOVER IS NOT REQUIRED ***/

	//ADDS THE .OVER CLASS FROM THE STYLESHEET ON MOUSEOVER
	$('.accordionButton').mouseover(function() {
		$(this).addClass('over');

	//ON MOUSEOUT REMOVE THE OVER CLASS
	}).mouseout(function() {
		$(this).removeClass('over');
	});

	/*** END REMOVE IF MOUSEOVER IS NOT REQUIRED ***/


	/********************************************************************************************************************
	CLOSES ALL S ON PAGE LOAD
	********************************************************************************************************************/
	$('.accordionContent').hide();



});

/************Paginacion*************/
function pag_search(p,id,num){
	$(p+' .paginacion').hide();
	$(p+' #res_'+num).show();

	$(p+' .page-nav li a').removeClass('current')
	$(id).addClass('current');
}

function closeconfirmbox(id){
document.getElementById('fondo_oscuro').style.display='none';
document.getElementById('dialog-confirm-friends-'+id).style.display='none';

}

/*
function confirmRemoveFriend(id, index,name,title){


	$( "#dialog-confirm-friends" ).dialog({
		resizable: false,
		modal: true,
		draggable: false,
		width:450,
		minHeight:100,
		zIndex:99999,
		title: title,
		open: function(event, ui) {
			var txt ='<a class="but_gray_small right" onclick="$(\'#dialog-confirm-friends\' ).dialog( \'destroy\' );">No</a><a class="but_blue_small butconfirm right" onclick="$(\'#dialog-confirm-friends\' ).dialog( \'destroy\' );removeFriend('+id+','+index+');">Yes, Remove</a>';
			$('#buttonsRemove').html(txt);
			$('#username').html(name);
		}
	});

}*/


function confirmRemoveFriend(id){
document.getElementById('fondo_oscuro').style.display='block';
document.getElementById('dialog-confirm-friends-'+id).style.display='block';
}

function confirmAcceptFriend(id, index,username,title){

	$( "#dialog-confirm-friends" ).dialog({
		resizable: false,
		modal: true,
		draggable: false,
		width:450,
		minHeight:100,
		zIndex:99999,
		title: title,
		open: function(event, ui) {
			var txt ='<a class="but_gray_small right" onclick="$(\'#dialog-confirm-friends\' ).dialog( \'destroy\' );">Close</a><a class="but_gray_small right butconfirm" onclick="$(\'#dialog-confirm-friends\' ).dialog( \'destroy\' );removeFriend('+id+','+index+');">Reject</a><a class="but_blue_small butconfirm right butacceptfriend" onclick="$(\'#dialog-confirm-friends\' ).dialog( \'destroy\' );acceptFriend('+id+','+index+',\''+username+'\')">Aceitar</a>';
			$('#buttonsAdd').html(txt);
			$('#username').html(username);
		}
	});

}
function busqueda(c,url){
	var valor;
	if(c == 'cellphone'){
		var number = $('#cellphone').val();
		number = number.replace('-','');
		number = number.replace(' ','');
		valor = number;
	}
	else{
		valor = $('#'+c).val();
	}
	valor=jQuery.trim(valor);
	if (valor=='') return false;
	$('#f_'+c+' .load_input').show();
	var valbus={
		campo:c,
		valor:valor
	};
	$.ajax({
		type: "POST",
		url: url,
		data: valbus,
		success: function( data) {
			$('#f_'+c+' .load_input').hide();
			eval(data);
		},
		error: function() {
			//alertx("El servidor ha tardado en responder","Error");
		},
		dataType: "text"
	});
}
/*Mueve la barra de directores*/
function muestra_dir(n){
	if(n<1) n=dir_num;
	if(n>dir_num) n=1;
	if(dir_pos==n) return;
	$('#cont_dir_'+dir_pos).fadeOut('slow');
	$('#cont_dir_'+n).fadeIn('slow');
	$('#btn_muesy_'+dir_pos).hide();
	$('#btn_muesx_'+dir_pos).show();
	dir_pos=n;
	$('#btn_muesx_'+dir_pos).hide();
	$('#btn_muesy_'+dir_pos).show();
}
/*Peticion de confimar mail*/
function conf_mail(){
	$('#warning_notice').html('...');
	$.ajax({
		type: "POST",
		url: page_path+'profile/sendConfirmationMail',
		success: function( data) {
			eval(data);
		},
		error: function() {
			//alertx("El servidor ha tardado en responder","Error");
		},
		dataType: "text"
	});
}
function subir_nivel(v){
	var valbus={
		place_id:v
	}
	$.ajax({
		type: "POST",
		url: page_path+'user/subirNivel',
		data: valbus,
		success: function( data) {
			eval(data);
		},
		error: function() {
			//alertx("El servidor ha tardado en responder","Error");
		},
		dataType: "text"
	});
}
function geoLocation(formulario){

   if(navigator.geolocation) {
      var geoC = new google.maps.Geocoder();
    navigator.geolocation.getCurrentPosition(function(position) {
        $('#locLng').val(position.coords.longitude);
        $('#locLat').val(position.coords.latitude);
        var latlng = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
       geoC.geocode( {
            'location': latlng

         }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            // alert(results[0].address_components[0].long_name);
          var countryI = results[0].address_components.length-1;
          var cityI = countryI-2;
          $('#locCountry').val(results[0].address_components[countryI].long_name);
          $('#locCity').val(results[0].address_components[cityI].long_name);

        } else {
            $('#locCountry').val('');
            $('#locCity').val('');
        }
          // Commented by Persistent System, Submit is not needed on the event of Submit itself
		  //$('#'+formulario).submit();
      });
    },function(error){
       $('#locCountry').val('');
       $('#locCity').val('');
	   // Commented by Persistent System, Submit is not needed on the event of Submit itself
       //$('#'+formulario).submit();
    });
  }
  else{

    $('#locCountry').val('');
    $('#locCity').val('');
	// Commented by Persistent System, Submit is not needed on the event of Submit itself
    //$('#'+formulario).submit();

  }
}

/***********FACEBOOK***********/
function fb_init() {
	FB.init({appId: '118809681509509', status: true, cookie: true, xfbml: true});
}

function signout(link){
fb_init();
  FB.getLoginStatus(function(response) {
    if (response.session) {
      FB.logout(function(response) {window.location = link;});
    } else {
      window.location = link;
    }
  }, 'force');
}

var fb_access_token = false;
function facebook_ready() {
fb_init();
	FB.signin = function(act) {
		FB.Event.subscribe('auth.login', function(){
		});
		FB.login(function(r) {
			if (typeof r.session.access_token != 'undefined') {
				fb_access_token = r.session.access_token;
			}
			if (!r.session && r.status == 'connected') {
				FB.getLoginStatus();
			} else if (r.session) {
				FB.callback(act,r.session);
			}
		}, {perms: 'user_about_me, user_activities,user_birthday, user_location, user_likes, user_interests, user_hometown, user_checkins, email, publish_stream, offline_access,read_friendlists'});
	}

	FB.unlink = function() {
		$.ajax({type: 'post', url: '/social-ajax.php', data: 'cmd=Facebook::Account::unlink', dataType: 'json', success: FB.link_cb});
	}

	FB.callback = function(act,session) {
		switch (act) {
			case 'register':
				if (fb_access_token) {
					$.getScript('https://graph.facebook.com/me?access_token='+fb_access_token+'&callback=FB.register_cb');
				}
				break;
			case 'signingin':
				if (fb_access_token) {
					$.getScript('https://graph.facebook.com/me?access_token='+fb_access_token+'&callback=FB.signingin_cb');
				}
				break;
			default:
				var remember=0;
				if($('#login_equipo').is(':checked')){
					remember=1;
				}
				validate('','',remember,session.uid);
		}
	}
	FB.signingin_cb = function(r) {

		//window.location = "http://test.toaki.com/register/index/facebookdone/"+r.first_name+"/"+r.last_name+"/"+r.email;
		validate( r.email , 'pass' , 0 , '' );
	}
	FB.register_cb = function(r) {
		$('#btnFB').remove();
		$('#btnFBMsj').show();

		if (typeof r.first_name != 'undefined') {
			$('#name').val(r.first_name);
		}
		if (typeof r.last_name != 'undefined') {
			$('#lastname').val(r.last_name);
		}
		if (typeof r.link != 'undefined') {
			var username = r.link.split('/')[3];
			if (isNaN(username) && username.substr(0, 11) != 'profile.php') {
				$('#username').val(username)
			} else {
				$('#username').focus();
			}
		}
		if (typeof r.email != 'undefined') {
			$('#email').val(r.email);
		}
	}
}
/********/
function dialogol(datosx){

	var p=30,lp=($('body').width()-659)/2;
	tp=($('body').height()-300)/2;

	$('#dialog').css({
	'z-index':'20001',
	'display':'block',
	'width': '400px',
	'height': 'auto',
	'margin':'0 auto',
	'top':tp+'px',
	'left':lp+'px'
	});
	$('#fondo_oscuro').css({
		'z-index':'20000',
		'display':'block',
		'width': $('body').width()+'px',
		'height': $('body').height()+'px'
	});
	/*$("#dialog").draggable({
		cursor: 'crosshair'
	});*/
}
function closeDialog(){
	$('#dialog').hide();
	$('#fondo_oscuro').hide();
}
function displayDiv()
{
	var divstyle = new String();
	divstyle = document.getElementById("cities").style.display;
	if(divstyle.toLowerCase()=="block" || divstyle == "")
	{
		document.getElementById("cities").style.display = "none";
	}
	else
	{
		document.getElementById("cities").style.display = "block";
	}
}

function textCounter(field,cntfield,maxlimit) {
if (field.value.length > maxlimit) // if too long...trim it!
field.value = field.value.substring(0, maxlimit);
else
cntfield.value = maxlimit - field.value.length;
}
