I created a chapter selector for some youtube videos I was embedding. This method used to work but has stopped recently. I can't figure out what's going on.
I'm using their recommended format but use loadVideoById to show each chapter
<div class="wrapper">
<div id="player"></div>
<script type="text/javascript">
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
width: '625',
videoId: 'FE5jN0rqMtM',
events: {
'onStateChange': onPlayerStateChange
},
playerVars:{
rel: 0,
wmode: "opaque"
}
});
}
function onPlayerStateChange(evt) {
if (evt.data == 0) {
$('#video_popup').removeClass('hide_pop');
$('#video_popup').addClass('display_pop');
}
else if (evt.data == -1) {
$('#video_popup').removeClass('display_pop');
$('#video_popup').addClass('hide_pop');
}
else {
$('#video_popup').removeClass('display_pop');
$('#video_popup').addClass('hide_pop');
}
}
function chapter1() {
player.loadVideoById({'videoId': 'FE5jN0rqMtM', 'startSeconds': 0});
}
function chapter2() {
player.loadVideoById({'videoId': 'FE5jN0rqMtM', 'startSeconds': 63});
}
function chapter3() {
player.loadVideoById({'videoId': 'FE5jN0rqMtM', 'startSeconds': 135});
}
</script>
<div id="video_popup" class="hide_pop">
<div class="video_layover">
<div class="promo">Thank you for watching!<br /><br /></div>
<div class="link">Replay Video</div>
</div>
</div>
<div style="margin: 0 auto 20px auto; width:625px; height:98px; text-align:center;">
<ul class="player">
<li>Chapter 1</li>
<li>Chapter 2</li>
<li>Chapter 3</li>
</ul>
</div>
I'm guessing it is a bug though I wasn't able to find it documented. You could report the bug if you want.
Regardless, I think cueVideoById is a better method which is working for me in all browsers:
Example: JS Bin
function chapter2() {
player.cueVideoById('FE5jN0rqMtM', 63); // BETTER WAY
player.playVideo();
}
If you experienced an error like "TypeError: ytPlayer.loadVideoById is not a function",
then I believe you have to wait for the onReady event to fire.
Here is the sample code (part of) I use:
var ytPlayer;
var ytPlayerIsReady = false;
// this methods only works if defined in the global scope !!
window.onYouTubeIframeAPIReady = function () {
ytPlayer = new YT.Player('ytplayer', {
playerVars: {
enablejsapi: 1,
controls: 0,
fs: 1,
autoplay: 1,
rel: 0,
showinfo: 0,
modestbranding: 1
},
events: {
onReady: onReady,
onError: onError,
onStateChange: onStateChange
}
});
};
// youtube code for calling the iframe api
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
function onError(event) {
console.log("error with code" + event.data);
}
function onStateChange(event) {
console.log("change state to " + event.data);
}
function onReady(event) {
ytPlayerIsReady = true;
console.log("I'm ready");
}
window.myVideoPlayer = {
init: function (options) {
// some arbitrary code...
// the trick is to fire options.callback,
// which contains all the logic needed
function timeout() {
setTimeout(function () {
if (false === ytPlayerIsReady) {
timeout();
}
else {
if (options.callback) {
options.callback();
}
}
}, 1000);
}
timeout();
}
};
myVideoPlayer.init({
callback: function(){
// now the youtube api is ready, you should be able to call
// loadVideoById without problems (at least it worked for me)
// ytPlayer.removeEventListener('onStateChange');
// ytPlayer.addEventListener('onStateChange', '_myYtPlayerOnChange');
// ytPlayer.loadVideoById({
// videoId: 'xxxx',
// startSeconds: 12
// });
}
});
You need to make sure var player is ready before calling loadVideoById
If(player != null)
{
loadVideoById ..
}
Related
The MeteorJS method "get.jade" is not returning jade object to client as expected. I'm using redis-livedata and manuel:reactivearray packages, and Redis is functioning locally correctly. I have put console.log in the code where there is a problem is returning server side data to client
jades.html
<template name="jades">
{{#if jadeslength}}
<div class="row">
<div class="user-card" id="swipe">
<img src="{{jade.img}}" style="width:100%">
<div class="card-container">
<h5>{{jade.name}}, {{jade.gender}}</h5>
</div>
</div>
</div>
<div class="row">
<div class="one-half column">
<button class="no" type="button">no</button>
</div>
<div class="one-half column">
<button class="button-primary yes" type="button">yes</button>
</div>
</div>
{{else}}
<div class="row">
<button class="button-primary search-jades" type="button" id="search">search</button>
</div>
{{/if}}
</template>
jades.js
import { Meteor } from 'meteor/meteor';
import { Session } from 'meteor/session';
import './jades.html';
Template.jades.onCreated(function () {
var jades = new ReactiveArray([]);
Session.set({'jadeId':""});
});
Template.jades.helpers({
jade: function() {
return jades.list();
},
jadeslength: function() {
var jades = jades.list();
return jades.length;
},
});
Template.jades.events({
...
'click .search-jades' () {
Template.instance.jades = [];
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var client_location = {"lat": position.coords.latitude, "lng": position.coords.longitude};
if (client_location) {
var lng = client_location.lng;
var lat = client_location.lat;
Meteor.call('client.profile', (error, result) => {
if (error) {
FlashMessages.sendError(error, 3000);
} else {
var user_profile = result;
Session.set({'user_profile': user_profile});
var prefer = user_profile.prefer;
switch (prefer) {
case "cis women":
Meteor.call('search.cw', lng, lat, (error, result) => {
if (error) {
FlashMessages.sendError(error, 3000);
return;
} else {
searched = result;
if (searched.length == 0) {
FlashMessages.sendWarning("no more providers found in your area", 3000);
} else {
for (var found of searched) {
var user_profile = Session.get('user_profile');
var right = user_profile.right;
if (!(found._id in right)) {
Template.instance.jades.push(found._id);
}
}
var jadeId = Template.instance.jades.pop();
console.log(jadeId); // returns ofQj98LBQWrSJ8gJs on client
if (jadeId) {
Meteor.call('get.jade', jadeId, (error, result) => {
if (error) {
FlashMessages.sendError(error, 3000);
} else {
Session.set({'jadeId': jadeId});
Session.set({'jade': result});
console.log(result); // returns undefined on client
}
});
} else {
FlashMessages.sendWarning("no more providers found in your area", 3000);
}
}
}
});
break;
case "trans women":
...
methods.js
'get.jade': function(jadeId) {
var redisCollection = new Meteor.RedisCollection("redis");
redisCollection.hgetall(jadeId, function(error, object) {
if (error) {
console.log(error);
} else {
console.log(object); // returns { name: 'alex', img: 'null', gender: 'cis woman' } on server
return object;
}
});
},
I solved this by changing the method as follows:
'get.jade': function(jadeId) {
var redisCollection = new Meteor.RedisCollection("redis");
return redisCollection.hgetall(jadeId)
},
I have following starting setup:
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
Then in onPlayerReady handler I added event listener to button which is outside iframe:
function onPlayerReady(event) {
button.addEventListener('click', () => event.target.playVideo());
}
In onPlayerStateChange I'm just logging what is happening:
function onPlayerStateChange(event) {
console.log(event.data);
}
After hitting that button in Chrome (v.72.0.3626.119) there are 3 entries in console: -1 (UNSTARTED), 3 (BUFFERING), -1 (UNSTARTED). When I try to hit button again nothing happens.
This works perfectly in Firefox, IE giving in console: -1 (UNSTARTED), 3 (BUFFERING),1 (PLAYING) and simply video starts playing.
Do you have any idea how to solve it?
You have to add in the onPlayerReady function this line:
event.target.playVideo();
As is shown in the documentation:
Example:
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
}
I can't say for sure why, but, in Google Chrome, for autoplay the video, you need to set the value 1 to the mute parameter, otherwise, autoplay the video wont work.
Example:
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '360',
width: '640',
videoId: '<YOUR_VIDEO_ID>',
playerVars: {
'autoplay': 1,
'loop': 1,
'mute': 1 // N.B. here the mute settings.
},
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
You can check this jsfiddle for guide yourself how you can set custom controls for play/pause your embed video.
I have sent a key after load html, and it works for me.
KeyEvent k = new KeyEvent();
k.WindowsKeyCode = 0x0D;
k.FocusOnEditableField = true;
k.IsSystemKey = false;
k.Type = KeyEventType.Char;
webytb.GetBrowser().GetHost().SendKeyEvent(k);
From this answer, Google Chrome need the allow="autoplay" attribute on iframe to let JS controls the player or make auto play function work.
This is required if you manually use <iframe> instead of <div> tag.
Example:
Attention! Please note that it maybe not work if the result iframe of this site don't have allow="autoplay" attribute on iframe. Copy and paste HTML & JavaScript into your .html file is the best way to test that it is really working.
var player;
/**
* Load YouTube API JavaScript
*/
function loadYTAPIScript() {
console.log('loading YouTube script.');
let tag = document.createElement('script');
tag.src = 'https://www.youtube.com/iframe_api';
firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
}
/**
* On YouTube iframe API ready
*
* This function will be called automatically by YouTube.
*/
function onYouTubeIframeAPIReady() {
console.log('function `onYouTubeIframeAPIReady` was called.');
player = new YT.Player('player', {
events: {
'onError': onError,
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onError(event) {
console.error('YouTube API error!', event);
} // _onError
/**
* On player ready.
*
* This is callback function from `onReady` event in `onYouTubeIframeAPIReady()`.
*/
function onPlayerReady(e) {
console.log('function `onPlayerReady` was called from `onReady` event callback.', e);
listClickButtons();
}
/**
* On player state change.
*
* This is callback function from `onStateChange` event in `onYouTubeIframeAPIReady()`.
*/
function onPlayerStateChange(e) {
console.log('function `onPlayerStateChange` was called from `onStateChange` event callback.', e);
let state = e.target.getPlayerState();
let stateText = '';
if (state === -1) {
stateText = 'unstarted';
} else if (state === YT.PlayerState.ENDED) {
stateText = 'ended';
} else if (state === YT.PlayerState.PLAYING) {
stateText = 'playing';
} else if (state === YT.PlayerState.PAUSED) {
stateText = 'paused';
} else if (state === YT.PlayerState.BUFFERING) {
stateText = 'buffering';
} else if (state === YT.PlayerState.CUED) {
stateText = 'cued';
}
console.log('State text: ', stateText);
}
/**
* Listen on click buttons to controls the video.
*
* This method was called from `onPlayerReady()`.
*/
function listClickButtons() {
console.log('Listen click buttons.');
let isPlayed = false;
let playpauseBtn = document.getElementById('yt-playpause');
let stopBtn = document.getElementById('yt-stop');
playpauseBtn.addEventListener('click', (e) => {
e.preventDefault();
console.log('User click on play/pause button.');
if (isPlayed === false) {
player.playVideo();
isPlayed = true;
} else {
player.pauseVideo();
isPlayed = false;
}
});
stopBtn.addEventListener('click', (e) => {
e.preventDefault();
console.log('User click on stop button.');
player.stopVideo();
});
}
document.addEventListener('DOMContentLoaded', (e) => {
console.log('DOM ready.');
loadYTAPIScript();
});
<iframe id="player"
width="560" height="315"
src="https://www.youtube.com/embed/1L904pgYbOE?enablejsapi=1"
title="YouTube video player"
allow="autoplay"
allowfullscreen=""
></iframe>
<!--
The `iframe` URL (`src` attribute) must contain enablejsapi=1 query string to let JS API work.
The `iframe` must contain `allow="autoplay"` attribute to allow JS controls the player.
-->
<div class="yt-controllers">
<button id="yt-playpause" type="button">
Play/Pause
</button>
<button id="yt-stop" type="button">
Stop
</button>
</div>
See full code on jsfiddle.
Reference:
Iframe
Iframe allow features list
YouTube Iframe API
I'm trying to use this technique http://www.bicobic.com/posts/BkFDo4CqcSnGcGtri to add the google analytics to Meteor, but it's not working (I already checked with the Google Analytics Debugger). And I'm trying with the Universal Analytics code.
Here is my code
<template name="ganalytics">
<div id="ganalytics">
</div>
</template>
Meteor.startup(function() {
isGanalyticsLoaded = false;
//a scriptloaderfunction
//if the script jsE1 loaded the callback is executed
myScriptLoader = function funcMyScriptLoader(jsEl, callback) {
if (window.attachEvent) {
// for IE (sometimes it doesn't send loaded event but only complete)
jsEl.onreadystatechange = function funcOnReadyStateChange() {
if (jsEl.readyState === 'complete') {
jsEl.onreadystatechange = "";
} else if (jsEl.readyState === 'loaded') {
jsEl.onreadystatechange = "";
}
if (typeof callback === 'function') {
callback();
}
};
} else {
// most browsers
jsEl.onload = function funcOnLoad () {
if (typeof callback === 'function') {
callback();
}
};
}
};
});
Template.ganalytics.rendered = function() {
if(!isGanalyticsLoaded) {
window['GoogleAnalyticsObject']='ga';
window['ga']=window['ga']||function(){
(window['ga'].q=window['ga'].q||[]).push(arguments)
}, window['ga'].l=1*new Date();
var myGAJs = document.createElement('script'),
s = document.getElementsByTagName('script')[0];
myGAJs.type ='text/javascript';
myGAJs.async = true;
myGAJs.src = '//www.google-analytics.com/analytics.js';
myScriptLoader(myGAJs, function funcEventLoaded() {
isGanalyticsLoaded = true;
ga('create', 'UA-XXXXXX', 'url');
ga('send', 'pageview');
});
s.parentNode.insertBefore(myGAJs, s);
}
};
<template name="layout">
<div>
{{yield}}
</div>
{{yield 'ganalytics'}}
</template>
What could be wrong with my code?
Thanks in advance.
The newer Google Analytics snippet doesn't seem to work in Meteor but putting this older, optimized style in the HEAD does:
var _gaq=[['_setAccount','UA-xxx'],['_setDomainName', 'example.com'],['_trackPageview']];
(function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];
g.src=('https:'==location.protocol?'//ssl':'//www')+'.google-analytics.com/ga.js';
s.parentNode.insertBefore(g,s)}(document,'script'));
You can also do this to log client-side errors to GA:
// log client-side errors to Google Analytics
window.onerror = function(message, file, line) {
_gaq.push(['_trackEvent', 'JS Error', file + ':' + line + '\n\n' + message]);
};
I have multiple YouTube iFrames embedded on a page. If one of the movies is already playing, and a user then decides to start playing a different movie, is it possible to stop playing the first movie so there is only ever one playing at a time?
I have looked at the 'YouTube Player API Reference for iframe Embeds' https://developers.google.com/youtube/iframe_api_reference but if i'm honest I just don't understand it. My developer skills are very limited.... clearly.
Pitiful I know, but this is all I have at the moment (just the iFrames)... http://jsfiddle.net/YGMUJ/
<iframe width="520" height="293" src="http://www.youtube.com/v/zXV8GMSc5Vg?version=3&enablejsapi=1" frameborder="0" allowfullscreen></iframe>
<iframe width="520" height="293" src="http://www.youtube.com/v/LTy0TzA_4DQ?version=3&enablejsapi=1" frameborder="0" allowfullscreen></iframe>
I thought all I needed to do was add '&enablejsapi=1' at the end of the video URLs.
Any help would be much appreciated.
Thank you in advance.
Here is an advanced version of #Matt Koskela's version. It does not require you to create the videos by JavaScript. It works for example if the videos are generated on the PHP side (think Wordpress).
JsFiddle demo here.
<script>
var tag = document.createElement('script');
tag.src = "//www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
function onYouTubeIframeAPIReady() {
var $ = jQuery;
var players = [];
$('iframe').filter(function(){return this.src.indexOf('http://www.youtube.com/') == 0}).each( function (k, v) {
if (!this.id) { this.id='embeddedvideoiframe' + k }
players.push(new YT.Player(this.id, {
events: {
'onStateChange': function(event) {
if (event.data == YT.PlayerState.PLAYING) {
$.each(players, function(k, v) {
if (this.getIframe().id != event.target.getIframe().id) {
this.pauseVideo();
}
});
}
}
}
}))
});
}
</script>
One:
<iframe frameborder="0" allowfullscreen="1" title="YouTube video player" width="160" height="100" src="http://www.youtube.com/embed/zXV8GMSc5Vg?enablejsapi=1&origin=http%3A%2F%2Ffiddle.jshell.net"></iframe>
<br/>
Two:
<iframe frameborder="0" allowfullscreen="1" title="YouTube video player" width="160" height="100" src="http://www.youtube.com/embed/LTy0TzA_4DQ?enablejsapi=1&origin=http%3A%2F%2Ffiddle.jshell.net"></iframe>
Edit: Check out Jennie Sadler's fine-tuned version below if your videos start as thumbnails.
Instead of using iframes, you actually want to use the iFrame Player API. Depending on how many videos you actually wanted to embed, you might want to make this javascript more dynamic, but this working example should give you enough to get started.
Basically what I'm doing here is initializing the two players, and pausing the opposite video when a player state changes to play.
You can play with the following code at http://jsfiddle.net/mattkoskela/Whxjx/
<script>
var tag = document.createElement('script');
tag.src = "//www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubeIframeAPIReady() {
player1 = new YT.Player('player1', {
height: '293',
width: '520',
videoId: 'zXV8GMSc5Vg',
events: {
'onStateChange': onPlayerStateChange
}
});
player2 = new YT.Player('player2', {
height: '293',
width: '520',
videoId: 'LTy0TzA_4DQ',
events: {
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING) {
stopVideo(event.target.a.id);
}
}
function stopVideo(player_id) {
if (player_id == "player1") {
player2.stopVideo();
} else if (player_id == "player2") {
player1.stopVideo();
}
}
vbence's solution is really close, but there's one edit I would suggest. You should check that the other players are playing before you pause them, otherwise, playing the first embed on the page will play/pause every other embed on the page, removing the preview thumbnail and creating startling side-effects.
<script>
var tag = document.createElement('script');
tag.src = "//www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
function onYouTubeIframeAPIReady() {
var $ = jQuery;
var players = [];
$('iframe').filter(function(){return this.src.indexOf('http://www.youtube.com/') == 0}).each( function (k, v) {
if (!this.id) { this.id='embeddedvideoiframe' + k }
players.push(new YT.Player(this.id, {
events: {
'onStateChange': function(event) {
if (event.data == YT.PlayerState.PLAYING) {
$.each(players, function(k, v) {
if (this.getPlayerState() == YT.PlayerState.PLAYING # checks for only players that are playing
&& this.getIframe().id != event.target.getIframe().id) {
this.pauseVideo();
}
});
}
}
}
}))
});
}
</script>
One:
<iframe frameborder="0" allowfullscreen="1" title="YouTube video player" width="160" height="100" src="http://www.youtube.com/embed/zXV8GMSc5Vg?enablejsapi=1&origin=http%3A%2F%2Ffiddle.jshell.net"></iframe>
<br/>
Two:
<iframe frameborder="0" allowfullscreen="1" title="YouTube video player" width="160" height="100" src="http://www.youtube.com/embed/LTy0TzA_4DQ?enablejsapi=1&origin=http%3A%2F%2Ffiddle.jshell.net"></iframe>
The above script of vbence works perfectly.
Here is the same script in javascript.
var tag = document.createElement("script");
tag.src = "//www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName("script")[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
function onYouTubeIframeAPIReady() {
var i,
frames,
players = [];
frames = document.getElementsByTagName("iframe");
const arr = Array.from(frames);
const arrnew = arr.filter((e) => {
return e.src.indexOf("https://www.youtube.com/") == 0;
});
arrnew.forEach((ele, index) => {
if (!ele.id) {
ele.id = "embeddedvideoiframe" + index;
}
players.push(
new YT.Player(ele.id, {
events: {
onStateChange: (event) => {
if (event.data == YT.PlayerState.PLAYING) {
players.forEach((ply) => {
if (ply.getIframe().id != event.target.getIframe().id) {
ply.pauseVideo();
}
});
}
},
},
})
);
});
}
I'm super new to this. I am posting this to see if this is fine.
Also I do not know jQuery so this was just a simpler way for me.
I also only have one iframe and change src. Is this a problem???
I put an id on an iframe to populate it with an array of videos.
I ran into a problem where it would keep playing it after I closed a modal box.
After looking for answers I decided to try making the iframe reference nothing.
It works but probably is not the best solution if you want both videos on screen.
function stopVid(){
var iframe = document.getElementById("videoPlayer");
iframe.src = "";
}
Vanilla JS based on answer by Jennie Sadler.
var tag = document.createElement('script');
tag.src = "//www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
function onYouTubeIframeAPIReady() {
var players = [];
Array.prototype.slice.call(document.getElementsByTagName("iframe")).filter(function(e) {
return e.src.indexOf("https://www.youtube.com/") == 0;
}).forEach(function(youtubevideo, k, v) {
if (!youtubevideo.id) {
youtubevideo.id = 'embeddedvideoiframe' + k;
}
players.push(new YT.Player(youtubevideo.id, {
events: {
'onStateChange': function(event) {
if (event.data == YT.PlayerState.PLAYING) {
Array.prototype.slice.call(players).forEach(function(youtubevideo, k, v) {
if (youtubevideo.getPlayerState() == YT.PlayerState.PLAYING //# checks for only players that are playing
&& youtubevideo.getIframe().id != event.target.getIframe().id) {
youtubevideo.pauseVideo();
}
});
}
}
}
}))
});
}
My code was working fine until the past 24 hours. I did not change anything, but now the #fb-button is smaller and it no longer says "Log Out" when it should.
You can see this in action at Homewrd.
The following code is nested in BODY > ROOT:
<div id="fb-root"></div>
<script type="text/javascript">
// Load the SDK Asynchronously
(function(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
// Init the SDK upon load
window.fbAsyncInit = function() {
FB.init({
appId:'271193286279763',
channelUrl:'//'+window.location.hostname+'/channel',
status:true,
cookie:true,
xfbml:true
});
// Conditional UI for landing page
if (landing) {
FB.getLoginStatus(function(response) {
if(response && response.status == 'connected') {
FB.api('/me', function(response) {
var heading = $('#goods h1').text().replace('Homewrd','Welcome '+response.first_name+'!');
$('#goods h1').text(heading);
});
}
});
}
// listen for and handle auth.statusChange events
FB.Event.subscribe('auth.statusChange', function(response) {
fbEventful = true;
if (response.authResponse) {
fbToken = response.authResponse.accessToken;
$('#fb-button').css({'display':'inline','float':'left'});
$('#toolbox').css({'display':'inline'});
$('#local-login').hide();
$('#local-logout').hide();
currentUser = {
fbid:response.authResponse.userID
}
displayPicture();
} else {
$.cookie('cuat', null);
$.ajax({
url:'/logout.json',
type:'delete',
success:function() {
ajaxOff();
renderLocal();
}
});
}
});
FB.Event.subscribe('auth.login',
function(response) {
FB.api('/me', function(me){
if (me.name) {
currentUser = {
fbid:me.id,
email:me.email,
first_name:me.first_name,
last_name:me.last_name
}
params = {
fbid: currentUser.fbid,
user: {
fbid:currentUser.fbid,
email:currentUser.email,
first_name:currentUser.first_name,
last_name:currentUser.last_name
}
}
$.ajax({
url:domain+'/user.json',
data:params,
dataType:'json',
type:'post',
success:function(e) {
cuat = e.user.auth_token;
$.cookie('cuat', cuat, {
path:'/',
expires:7
}
);
if (rurl) {
refreshSession();
}
if (storedProcedure!==null) {
storedProcedure();
}
}
});
}
});
}
);
$('#local-logout a').click(function(e) {
e.preventDefault();
var x = confirm('Are you sure that you want to logout?');
if (x===true) {
ajaxOn();
$.ajax({
url:'/logout.json',
type:'delete',
success:function() {
ajaxOff();
window.location.reload();
}
});
}
return false;
});
setTimeout(function() {
if (!fbEventful) {
renderLocal();
}
},1000);
}
</script>
<div id="header">
<div id="logo">
<h1>Logo Link</h1>
</div>
<div id="session">
<div id="fb-button" autologoutlink="true" class="fb-login-button" scope="publish_stream,email,user_about_me,user_birthday,user_hometown,offline_access"></div>
<div id="fb-picture"></div>
<div id="local-login"><p>local login link</p></div>
<div id="local-logout"><p>local logout link</p></div>
</div>
</div>