by Richard (Rick) Mills
Forward of the Herd
As a common rule, probably the most profitable man in life is the person who has the very best info.
Gold has immunity, silver has ratio
On Monday Wall Road pared again losses from final week’s sell-off, the worst since 2008, however it was solely the promise of decreasing rates of interest, the return of the “punch bowl” hearkening again to recession-era stimulus, that has briefly ameliorated coronavirus fears and its rising menace to the worldwide financial system.
Arguably, extra financial risks than could be solved by a easy charge minimize lie forward, and gold is reacting as regular, in instances of economic turmoil, by going up.
The dear steel recovered from Friday’s drubbing when it misplaced about $87, by climbing to inside shouting distance of [US]$1,600/oz. On the shut of buying and selling in New York spot gold was at $1,589.10 and Comex gold futures had been pushing $28 larger than Friday’s shut, to $1,594.80. The spot worth continued to rise on the 24-hour chart and was at $1,598.30, as of this writing. [$1640/oz at time of publication.]
On Friday as shares had been falling, US Federal Reserve Chair Jerome Powell tried to quiet the market by saying the Fed is able to act if circumstances warrant. His feedback had been broadly interpreted to imply one other discount in rates of interest from the present vary of 1.5% to 1.75%. Different heads of central banks made related feedback, organising the inventory market rally that got here Monday.
[Tuesday brought and emergency -50 point cut.]
Regardless of poor world and US financial knowledge, together with a weaker-than-expected studying within the ISM manufacturing index and a record-low studying in China’s buying managers index (PMI) equities “closed up strongly on the hope that fiscal and financial stimulus is on the best way,” stated Kathy Lien, managing director of FX technique at BK Asset Administration, in a observe quoted by Marketwatch.
Market worry across the coronavirus has sunk the yield on the 10-year Treasury bond to new lows, as buyers flock to the protection of Treasuries (and gold), elevating their costs, inflicting yields to plummet. On Friday the yield on the benchmark 10-year observe dropped to a document 1.16%. Following information over the weekend of China’s PMI manufacturing knowledge sinking to 35.7 (the providers PMI was even worse at 28.9), in opposition to expectations of 45, the 10-year on Monday slumped to a brand new document of 1.13%. (PMIs beneath 50 symbolize an financial contraction).
[Tuesday down to 0.90% before rebounding to 1.01%.]
Virus ‘uncontainable’
As of Monday the coronavirus has stricken 80,000 folks in China and triggered nearly 3,000 deaths. Outdoors China, there have been greater than 7,000 circumstances in 60 international locations, and over 100 have died from it. These numbers are very out of whack, seems to be like for those who get it in China you’ve gotten a lot much less probability of dying then for those who get sick outdoors China. Exhausting for me to imagine that.
Because it continues to unfold, some medical consultants say the containment section has handed and that Covid-19 is inevitable. That will imply residing with the respiratory virus in our communities, very similar to the flu and managing its doubtlessly deadly prognosis.
“That is spreading all through the world and it’ll proceed to unfold all through the world,” Isaac Bogoch, an infectious illness doctor at Toronto Common Hospital, advised CBC.
Amesh Adalja, an infectious illness doctor and a senior scholar on the Johns Hopkins Middle for Well being Safety, stated, “It’s not one thing that we will forestall from occurring within the absence of a vaccine. It’s not containable in the best way that these viruses had been. So this may change into endemic.” He added:
“That is going to change into like among the different coronaviruses that we have now. There are 4 of them that trigger illness yearly. That is prone to change into the fifth coronavirus at that capability.”
Financial fallout
In the meantime the financial fallout from Covid-19 continues to worsen. The OECD issued a report saying that the coronavirus outbreak might ding world financial development by half a share level, placing it at 2.4%, in a best-case situation.
PMIs not solely in China have been severely whacked as a result of virus’ influence on provide chains. In line with Zero Hedge the worldwide manufacturing sector has suffered its steepest contraction since 2009. Out of 31 nations for which knowledge was obtainable, 15 noticed their output contract. They embody China, Japan, Germany, France, Italy, South Korea and Australia.
To this point we have now principally seen the consequences of the virus on the availability facet, corresponding to Apple warning its earnings shall be down due to disruptions in China, however we’re additionally beginning to see demand destruction.
Goldman Sachs says the world is dealing with the most important commodity demand shock for the reason that monetary disaster, because the outbreak and its results unfold from Asia and the Center East to Europe and the US.
The financial institution’s head of worldwide commodities analysis, Jeff Currie, notes that disruptions to demand for oil and different vitality merchandise will possible be unrecoverable, whereas for different commodities like metal and aluminum they may simply be deferred.
However, gold has “immunity to the virus” and has outperformed different safe-haven property just like the Japanese yen or Swiss franc, stated Goldman, through Bloomberg.
In a Feb. 28 report, Currie stated China has misplaced an estimated Four million barrels a day of oil demand, in comparison with 5 Mbod in 2008-09, and that 45% of container vessel sailings from Europe to Asia had been canceled within the 4 weeks following Chinese language New 12 months.
On Monday Oxford Economics downgraded China’s annual development projections this yr to 4.8% – the worst in a long time.
Some economists assume the coronavirus is so harmful, it might trigger the subsequent recession. Nevertheless, Harvard financial prof Kenneth Rogoff, writing for Mission Syndicate, says in contrast to the 2 earlier world recessions this century, the brand new coronavirus, COVID-19, implies a provide shock in addition to a requirement shock:
[W]hen tens of hundreds of thousands of individuals can’t go to work (both due to a lockdown or out of worry), world worth chains break down, borders are blocked, and world commerce shrinks as a result of international locations mistrust of each other’s well being statistics, the availability facet suffers at the least as a lot.
Rogoff thinks the consequences of this may trigger huge deficit spending to shore up well being methods and prop up economies, which can push up inflation. Value will increase shall be exacerbated by provide pressures – akin to the gasoline shortages of the 1970s – and a sustained retreat behind nationwide borders, owing to a COVID-19 pandemic (and even lasting worry of pandemic), on high of rising commerce frictions, is a recipe for the return of upward worth pressures. On this situation, rising inflation might prop up rates of interest and problem each financial and monetary policymakers.
US financial system sickens
Studying between the traces, Rogoff is clearly speaking right here about the US. The commerce battle between the US and China has already hit world development (which in 2019 was solely 2.9%), and now comes alongside a pandemic – what as soon as appeared like a 15% probability of a recession beginning earlier than the presidential and congressional elections in November now appears a lot larger, he writes.
Wouldn’t that be ironic for Donald Trump? He’s been bragging since he took workplace about how he alone is answerable for making the US financial system nice once more, principally by commerce warring with China. The coronavirus which begins in China causes a pandemic that takes down the US financial system, and with it, Trump’s re-election probabilities. Karma’s a bitch.
We’re seeing the predictable politicization of the coronavirus change into particularly virulent, no pun supposed, throughout this election yr.
There may be rising hypothesis as to what might occur if the US enters recession earlier than November and blame is laid on the ft of Trump, for failing to arrange for and deal with the pandemic. May Trump lose the election to Bernie Sanders who’s proposing a radical medical system overhaul?
A cost from Democrats that Trump proposed price range cuts to the Facilities for Illness Management and Prevention was denied by administration officers. Nevertheless in response to [US] ABC Information, the president did suggest in his 2021 price range, 10 days after the WHO declared coronavirus a public well being emergency, a 16% discount in CDC funding. ABC Information provides:
In reality, all of Trump’s price range proposals have referred to as for cuts to CDC funding, however Congress has intervened every time by passing spending payments with year-over-year will increase for the CDC that Trump then signed into regulation.
Republican assaults on Democrats re Covid-19 have been past the pale. Witness Donald Trump Junior showing on Fox Information saying “For them to attempt to take a pandemic and seemingly hope that it comes right here and kills hundreds of thousands of individuals in order that they may finish Donald Trump’s streak of profitable is a brand new degree of illness.”
Not a phrase was uttered by Trump in response. No stern rebuke to Don Jr. for evaluating Democrats to Pol Pot, Hitler or different architects of genocide. At a rally on Friday Trump accused Democrats of politicizing the coronavirus, calling it “their new hoax” after the Russian investigation and impeachment. Quoted in The Guardian, Trump stated,
“We’re doing the whole lot in our energy to maintain the an infection and people carrying the an infection from getting into the nation. We’ve no selection,” Trump stated on the Coliseum and Performing Arts Middle. “Whether or not it’s the virus that we’re speaking about, or the various different public well being threats, the Democrat coverage of open borders is a direct menace to the well being and wellbeing of all Individuals.”
As coronavirus fears chunk and the fallout drifts to the US (the place six folks have died thus far), the US greenback index has fallen from 99.86 on Feb. 20 to the present 97.43. [97.19]
In line with ISM knowledge from January and February, the US gauge of provider deliveries rose to the best since 2018, indicating provide disruptions from Covid-19. The imports index fell probably the most since 2009, and new order development slowed to 9-month lows. Right here’s Chris Williamson, chief enterprise economist at IHS Markit, for his tackle the alarming figures:
“Manufacturing manufacturing and order e book traits deteriorated markedly in February as producers struggled in opposition to the double headwinds of falling export gross sales and provide chain delays, each in flip usually linked to the coronavirus outbreak.
Whereas commerce battle fears have eased, serving to push corporations’ expectations for future development to the best since final April, coronavirus-related provide chain points threaten to constrain manufacturing in coming months. On the identical time, corporations have change into more and more involved that the COVID-19 outbreak may even hit demand, which is reportedly already cooling amid uncertainly main as much as the presidential election. Latest inventory market volatility might additionally additional dampen client spending and deter enterprise funding.”
On Sunday Goldman Sachs projected GDP development of simply 0.9% within the first quarter and 0 development in Q2 – the worst six-month window for the reason that Nice Recession, US Information reported.
Though the nation is prone to narrowly keep away from recession, “the state of affairs has confirmed worse than we anticipated” and that “the draw back dangers have clearly grown,” in response to the funding financial institution’s baseline situation.
Plunging yields à charge cuts
Is there a treatment, a way of diverting course from what seems to be to be the Titanic world financial system about to run headlong into an enormous iceberg? All eyes are on the Federal Reserve for what ought to by now be a well-known resolution to financial troubles: minimize charges. [Which it has.]
Goldman expects the Fed to chop rates of interest 4 instances between now and the tip of the second quarter, perhaps even earlier than the March 17-18 assembly of the Federal Open Market Committee (FOMC). [It did.] The influential financial institution justifies gloomy outlook on world development for 2020 slowing from 3% to round 2%.
Keep in mind, when development in different international locations falters, regardless that the US is doing pretty nicely, for now, because the world’s largest financial system, any slowdown impacts American suppliers, huge time.
The upshot will possible be a 50-basis-point charge minimize by March 18 [done], adopted by one other 50 bp within the second quarter, for a complete of 100 bp within the first half, Which implies that the US Fed Funds charge shall be simply above zero because the US enters the second half, and has a excessive probability of tipping destructive across the time of the election notes Zero Hedge with barely-disguised glee.
The CME Group’s FedWatch device additionally suggests there may be nearly a 100% probability that the central financial institution will launch a 50-point rate of interest minimize by mid-March.
There might even be coordinated financial easing for the primary time for the reason that monetary disaster, with the central banks of Canada, the UK, Australia, New Zealand, Norway, India, South Korea, the EU and Switzerland all performing in live performance to slash charges to get financial development shifting once more, Goldman forecasts.
On Monday Trump weighed in on the speed cuts, blaming Fed Chair Jerome Powell for being too gradual to react (ie. to decrease charges) and arguing that the central financial institution has put the US at a drawback throughout the outbreak. The Fed minimize charges 3 times in 2019 as a response to slowing world development and considerations over not excessive sufficient inflation. That was earlier than the coronavirus.
Paper vs bodily gold
Getting again to gold, the takedown on the gold worth we noticed final Friday could also be puzzling to some, contemplating that gold usually does extraordinarily nicely throughout inventory market corrections. Roland Manley over at Bullion Star provides a complete account of what occurred and why. With out entering into the minutia, we will say that gold’s worth motion is at the moment extra pushed by the “paper” markets ie. gold ETFs and gold futures, than by the “bodily” markets ie. gold bars/ cash and gold jewellery.
Certainly Manley factors out that there’s a disconnect between the paper and the bodily gold markets, evidenced by the truth that gold went down final week within the face of unprecedented demand for the bodily steel, in response to Bullion Star.
It’s additionally fascinating to notice, as Bloomberg does, that Over the previous couple of weeks, gold patrons [gold shops that buy used jewelry] have seen a frantic push by people racing to promote their little-used jewellery within the U.S. and Europe amid worries that the extraordinary worth rally fueled by the coronavirus for the reason that begin of the yr might quickly run its course.
We all know that gold scrap accounts for about 30% of worldwide provide. We additionally know that mined gold in 2019 was principally flat. The world’s mines can not meet the present demand for gold with out recycling jewellery. With scrap gold provide rising by an estimated 2.5%, resulting from jewellery homeowners “cleansing out their safes” to capitalize on excessive costs, will it offset the quantity of bodily gold shopping for?
It’s onerous to say however in response to Manley’s evaluation, the gold worth fall final Friday was not related to the bodily gold market.
Gold-silver ratio soars
It’s additionally fascinating to have a look at how gold and silver are doing in relation to one another, in periods of safe-haven demand.
We are able to use the gold-silver ratio to learn how silver costs examine to gold, for the reason that valuable metals have roughly the identical quantity of above-ground provide – 6.1 billion ounces, and across the identical degree of 0.999 tremendous bullion used for investments – 2.5Boz.
The gold-silver ratio is the quantity of silver one should buy with an oz of gold. Merely divide the present gold worth by the value of silver, to seek out the ratio.
On June 12, 2019, the gold-silver ratio hit a 26-year excessive by breaking by way of the 90-ounce mark – which means it took over 90 ounces of silver to buy one ounce of gold. The upper the quantity, the extra undervalued is silver or, to place it one other means, the farther gold is pulling away from silver, valued in {dollars} per ounce.
For the previous a number of weeks the gold-silver ratio has stayed round 86-88:1. Because the coronavirus outbreak although, the gold-silver ratio has rocketed to a brand new document of 95:1.
That is thus far out of whack from the historic ratio of 54:1, that silver is on sale.
The query valuable metals buyers have to ask themselves is, with the world having change into a way more harmful place with the coronavirus spreading and all the opposite sizzling spots, like Syria, North Korea, and so forth., nonetheless in play, will gold transfer down to regulate to a extra regular ratio, or will silver costs head up?
Silver is anticipated to do nicely this yr by way of a mix of upper industrial and funding demand, and tightened provide owing to mine manufacturing points and output cuts.
At this level we see each purpose to imagine that the commerce deal is on maintain – with provide chains so tousled it is probably not lengthy earlier than US-China commerce grinds to an entire halt, the border to China shut – world development is falling, the US greenback is tanking, bond yields are dropping (when yields go under 2% it’s time to purchase gold as a result of the actual yield rates of interest minus inflation is 0%), and rates of interest are going to be additional minimize, which means this a particularly bullish time for gold.
The gold-silver ratio retains going up and it’s solely a matter of time earlier than silver corrects, as a result of imho, gold goes larger.
Northern Syria sizzling zone
Everyone knows that gold is the world’s oldest secure haven and buyers transfer their investments into bullion after they now not belief equities and bonds. The coronavirus is actually driving many of the safe-haven gold demand as of late however we will’t overlook geopolitics.
Buried within the headlines over the election and the coronavirus is a sizzling battle breaking out between Syria and Turkey in northern Syria. Final week, The Nationwide Publish reported Turkey has deployed “swarms of killer drones” to strike Russian-backed Syrian authorities forces, in retaliation for the killing of 33 Turkish troopers. Keep in mind Turkey is a NATO ally and any assault on one NATO member is taken into account an assault on all its members:
The tactic threatens to convey NATO member Turkey into direct confrontation with Russia, including to strains in relations between Erdogan and Russian President Vladimir Putin as they put together to fulfill this week in an effort to ease tensions over Syria. The 2 leaders have labored collectively to attempt to finish the Syrian civil battle, regardless of backing opposing sides, however have repeatedly stumbled over who ought to management the northwestern Syrian province of Idlib that borders Turkey.
Russia dominates the skies over Syria as a part of Putin’s army assist of Syrian chief Bashar al-Assad, deploying superior S-400 missile-defence methods to safe the air house whereas its warplanes support Syrian forces battling to take the final insurgent stronghold in Idlib. Turkish forces again the rebels and Ankara says it fears a contemporary exodus of refugees flocking into Turkey if Idlib falls to Assad.
Erdogan is reportedly urging US and NATO to halt the Syrian-Russian offensive in Idlib. On Friday the USS Dwight D. Eisenhower, a provider strike group, crossed the Strait of Gibraltar and entered the Mediterranean, accompanied by a number of assist ships. The US Navy says the presence of the USS “Ike” is for “conducting operations within the US sixth Fleet to assist maritime safety operations in worldwide waters, alongside our allies and companions” however the timing is actually suspicious.
May the Trump administration’s choice to drag troops from northern Syria have something to do with this newest conflagration that threatens to engulf a NATO ally?
Australian summers lengthening
We all know we will’t draw a direct line between gold costs and local weather change however we discover it of curiosity to notice proper now, amidst all the opposite secure haven demand for gold, a headline relating to Australian summers heating up.
Information launched Monday by the Australia Institute, a assume tank, reveals summers Down Below over the previous 5 years are, on common, 50% longer than they had been within the mid-20th century.
“Our findings are usually not a projection of what we might even see sooner or later,” stated Richie Merzian, local weather and vitality program director on the Australia Institute. “It’s occurring proper now.”
The discovering is particularly potent, contemplating Australia simply skilled a devastating bushfire season that burned almost 12 million hectares, killing 33 folks and an estimated 1 billion animals native to Australia, Reuters stated.
We all know from our analysis {that a} key facet of worldwide warming is that when the planet warms, dry areas get dryer, summers change into longer and winters shorter. That will look like excellent news to these within the northern hemisphere however it may possibly solely means extra dangerous information for drought-stricken areas amid the worldwide contemporary water disaster we have now written on extensively.
Conclusion
I stated it not too long ago however I’ll say it once more. We’re shifting nearer to gold’s Minsky Second. Issues are occurring to trigger instability within the world financial system, together with a worsening coronavirus, a slowdown in manufacturing, a denting of the most important economies, and a capturing battle in Syria that threatens to contain NATO members.
We all know that the US inventory market is a bubble and all bubbles pop. The volatility over the previous few days is probably not a pop however it’s undoubtedly a correction.
We additionally know that a lot has been performed by the Trump administration to fray current alliances and to inflame tensions with buying and selling partners-turned-adversaries, specifically China, the European Union and even its two NAFTA “amigos”, Canada and Mexico.
China, Russia, Turkey and others, are already shifting away from pricing commerce in US {dollars} and shopping for US debt by way of Treasury purchases. Central banks have been stocking up on gold.
Will the remainder of the world comply with and punt the US$ because the world’s reserve forex? Lengthy-term, we at AOTH assume so. Brief-term, we see the whole lot that’s occurring proper now to be excellent for gold and silver.
Take into account: the greenback is falling and bond yields have hit the skids. 2% is the quantity that sways buyers into bullion from different asset courses as a result of the web yield is near zero or destructive. Effectively, the 10-year Treasury has fallen to 1.1%, so with inflation operating at 2.5% we’re clearly in destructive territory. Why purchase a negative-yielding T-bill when you should buy gold that final yr gained 18%?
Rates of interest are already low however are going decrease; count on at the least two charge cuts within the subsequent two weeks, perhaps 4 by the tip of the second quarter, if Goldman Sachs is appropriate. Gold being a non-yielding asset, low charges are at all times good for bullion.
Donald Trump has all through his presidential time period rallied for a weak greenback and low rates of interest to repair the commerce deficit. He’s personally taken credit score for the booming inventory market, which is generally resulting from inventory buybacks, enabling document insider promoting. Keep in mind share repurchases artificially inflate earnings per share. They profit administration on the expense of firm development and in the end, shareholders.
Trump seems to be getting his low greenback however he’s additionally going to get a inventory market crash. Why? As a result of we all know the coronavirus is hurting provide chains, it’s killing world development, and its results are being felt within the US, mirrored in weak manufacturing knowledge and the decrease greenback. As US company earnings drop, so will share costs, and most significantly, there received’t be further money for inventory buybacks. With out buybacks there may be nothing to prop up the inventory market. Poof.
How about bonds? At yields above 2%, buyers have been piling into US Treasuries as a secure haven amid coronavirus fears and different geopolitical tensions. They’re enticing compared to the trillions of negative-yielding sovereign debt sloshing round. However with numerous rate of interest cuts predicted, bonds are beginning to seem like a poor funding. If international buyers gradual or cease shopping for US Treasuries, as Russia has performed and China did final Could, the US is in actual hassle. With out purchasers of US debt (Treasuries) the US has no means of financing its annual deficits and $23 trillion pile of debt, with out printing cash. Printing cash on a big scale causes hyperinflation.
A worsening US financial system will flip buyers away from bonds and Treasuries. The greenback will fall and commodities will rise, together with gold and silver, pushed larger by funding demand for ETFs and bodily steel.
Which is the higher purchase, gold or silver? The gold-silver ratio is at the moment at 95 and rising as each silver and gold maintain climbing on virus fears. Nevertheless the ratio is way larger than its historic common of 50-60:1, which means both gold should fall or silver should rise. Gold’s going larger, imo rather a lot larger, however I’ve nonetheless received my cash on a 2020 run on silver.
Richard (Rick) Mills
Richard is the proprietor of Aheadoftheherd.com and invests within the junior useful resource/bio-tech sectors. His articles have been printed on over 400 web sites, together with:
WallStreetJournal, USAToday, NationalPost, Lewrockwell, MontrealGazette, VancouverSun, CBSnews, HuffingtonPost, Londonthenews, Wealthwire, CalgaryHerald, Forbes, Dallasnews, SGTReport, Vantagewire, Indiatimes, ninemsn, ibtimes and the Affiliation of Mining Analysts.
In case you’re thinking about studying extra concerning the junior useful resource and bio-med sectors, and high quality particular person firm’s inside these sectors, please come and go to us at www.aheadoftheherd.com
Content material included on this article shouldn’t be by affiliation essentially the view of FNArena (see our disclaimer).
Authorized Discover / Disclaimer
This doc shouldn’t be and shouldn’t be construed as a proposal to promote or the solicitation of a proposal to buy or subscribe for any funding.
Richard Mills has primarily based this doc on info obtained from sources he believes to be dependable however which has not been independently verified.
Richard Mills makes no assure, illustration or guarantee and accepts no accountability or legal responsibility as to its accuracy or completeness. Expressions of opinion are these of Richard Mills solely and are topic to vary with out discover. Richard Mills assumes no guarantee, legal responsibility or assure for the present relevance, correctness or completeness of any info supplied inside this Report and won’t be held responsible for the consequence of reliance upon any opinion or assertion contained herein or any omission.
Moreover, I, Richard Mills, assume no legal responsibility for any direct or oblique loss or injury or, specifically, for misplaced revenue, which you’ll incur because of the use and existence of the knowledge supplied inside this Report.
Technical limitations
If you’re studying this story by way of a 3rd get together distribution channel and you can’t see charts included, we apologise, however technical limitations are accountable.
Discover out why FNArena subscribers just like the service a lot: “Your Feedback (Thank You)” – Warning this story accommodates unashamedly optimistic suggestions on the service supplied.
FNArena is proud about its monitor document and previous achievements: Ten Years On
var fn_do_fb_login; var fn_check_login_state; var fn_get_fb_login_button; var fn_remove_fb_loading_btn; var fn_status_change_callback;
jQuery(document).ready(function(e){
window.fbAsyncInit = function() { FB.init({ appId : '2003222569780759', // dev version: 500318794096450 cookie : true, // Enable cookies to allow the server to access the session. xfbml : true, // Parse social plugins on this webpage. version : 'v4.0' // Use this Graph API version for this call. });
//check if all fb elements done rendering //========== fn_get_fb_login_button();
FB.Event.subscribe('xfbml.render', function(response) { fn_remove_fb_loading_btn(); }); //==========
FB.getLoginStatus(function(response) { // Called after the JS SDK has been initialized.
var fb_r = response;
if (fb_r && fb_r.status === 'connected') {
get_detail_data(fb_r.authResponse.userID); // Returns the login status.
// logout function // FB.logout(function(response) { // console.log('do logout'); // }); } }); };
(function(d, s, id){ var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) {return;} js = d.createElement(s); js.id = id; js.src = "https://connect.facebook.net/en_US/sdk.js"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk'));
//fb functionality //======================================================= fn_check_login_state = function check_login_state() { // Called when a person is finished with the Login Button.
//everytime event login triggered, reset the form fn_reset_form();
FB.getLoginStatus(function(response) {
var status_change_callback = fn_status_change_callback(response);
if (status_change_callback) {
FB.api('/me', function(response) {
console.log(response);
});
}
});
}
//new function to do fb login - since might need a separate function //between checking and login fn_do_fb_login = function do_fb_login() { // Called when a person is finished with the Login Button.
//everytime event login triggered, reset the form fn_reset_form();
FB.getLoginStatus(function(response) {
e('.form_loading').show();
var status_change_callback = fn_status_change_callback(response);
if (status_change_callback) {
FB.api('/me', function(response) {
console.log(response); set_detail_data_to_form_and_submit(response.id);
});
} else {
FB.login(function(fb_l_r) {
if (fb_l_r.authResponse && fb_l_r.status == 'connected') {
console.log(fb_l_r.authResponse.userID); set_detail_data_to_form_and_submit(fb_l_r.authResponse.userID);
} else { e('.form_loading').hide(); }
});
}
});
}
fn_status_change_callback = function status_change_callback(response) { // Called with the results from FB.getLoginStatus().
var check_status;
console.log('status_change_callback'); console.log(response); // The current login status of the person.
if (response.status === 'connected') { // Logged into your webpage and Facebook.
get_detail_data(response.id); check_status = true;
} else { // Not logged into your webpage or we are unable to tell.
console.log('facebook is not logged in'); check_status = false;
}
return check_status;
}
function get_detail_data(fb_id) {
FB.api( '/'+fb_id+'/', {fields: 'id,first_name,last_name,email'}, function (fb_r) {
var fb_data_json = JSON.stringify(fb_r);
if (fb_r && !fb_r.error) {
e('#fb_data').html(fb_data_json);
}
} );
}
//it's kinda silly, but since fb is an async, cannot use passing parameter on a function like jquery //so instead put it on FB.api function set_detail_data_to_form_and_submit(fb_id) {
e('.form_loading').show();
FB.api( '/'+fb_id+'/', {fields: 'id,first_name,last_name,email'}, function (fb_r) {
var fb_data_json = JSON.stringify(fb_r);
if (fb_r && !fb_r.error) {
var fb_id = fb_r.id; var fb_firstname = fb_r.first_name; var fb_lastname = fb_r.last_name; var fb_email = fb_r.email;
e('.sns_facebook').val(1); e('.sns_facebook_id').val(fb_id);
e('#fb_data').html(fb_data_json); do_submit_form();
//no form_loading hide - we gonna lock the form IF it's success
} else {
e('.form_loading').hide();
}
} );
}
fn_get_fb_login_button = function get_fb_login_button() {
var html = '
'+ ' '; e('.fb_button_placeholder').html(html);}
fn_remove_fb_loading_btn = function remove_fb_loading_btn() {
e('.fb_loading_btn').hide(); e('.fb_login_wrapper').show();
}
fn_reset_form = function reset_form() {
e('.sns_facebook').val(''); e('.sns_facebook_id').val(''); e('.form_loading').hide();
}
function do_submit_form() {
var the_form = e('.formLogin:visible');
if (the_form.length) {
var target_form = the_form[0]; target_form.submit();
} else {
console.log('form not exist');
}
} //=======================================================
//initialize fn_reset_form();
});
Source link