/* master.js --------- Script loaded on all sites Major revision March 2019 Requirements: On most pages, place script tag in head tag above all other scripts On streamlined pages, place script tag just before end of body tag Script tag should have: id: "jsSite" data-site: (ex: "politics") Optional: Script tag can have: data-site-page: (ex: "home") data-gaTag: (ex: ?) Dependencies: None Table of Contents: GLOBAL VARIABLES / CONSTANTS MAIN LOGIC PRESERVE COMPATIBILITY BROWSER / OS DETECTION NOTIFICATIONS TEMPSHOW LIBRARY EVOLOK LIBRARY EVOLOK NOTIFIERS COOKIE CONSENT LIBRARY JQUERY TOOLS LIBRARY FACEBOX LIBRARY FARK WIDGET FLOATING LEADERBOARD (order doesn't matter for these function definitions) ADS FUNCTIONS SOCIAL FUNCTIONS UTILITY FUNCTIONS SCRIPT LOADING FUNCTIONS EVOLOK FUNCTIONS DISTROSCALE FUNCTIONS SPOT.IM FUNCTIONS STORY STREAM FUNCTIONS HOMEPAGE FUNCTIONS COMMENTS FUNCTIONS HP RECENTS FUNCTIONS OTHER FUNCTIONS */ //////////////////////////////////////////////////////////////////////////////// // GLOBAL VARIABLES / CONSTANTS //////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //set SITE_PAGE for Google Analytics default - will change per module "body.class" in site configs area if need be //ONLY List Mod uses rc-load-widgets.js currently - Once updated this check will include Video Pages - all other pages get SITE_PAGE="story" var SITE_PAGE = document.querySelector("#jsSite").getAttribute("data-site-page"); if( typeof SITE_PAGE === "undefined" || SITE_PAGE == "" ){ SITE_PAGE = 'story'; // Default value } //get "OAS_TAG" for specific page to control specific targeting for Google Analytics var GA_TAG = document.querySelector("#jsSite").getAttribute("data-gaTag"); var stream_tags = {}; // ? //var RC_welcome_interval; //TRACKING INVERVAL FOR welcome_ad //var RC_homepage_video_interval; // ? var SITE_NAME = document.querySelector("#jsSite").getAttribute("data-site"); var SITES_INFO = [ { name: 'politics', prebid_src: '//s3.amazonaws.com/ssl-intgr-net/prebid/264.js', //prebid_src: '/concepts/home/prebid_new_hp/264.js', disable_all_ads: false, lazy_ads: true, site_title: 'RealClearPolitics', // facebook link for main icon in new header menu bar facebook_url: 'https://www.facebook.com/RealClearPolitics-27088225427/timeline/', // twitter link for main icon in new header menu bar twitter_url: 'https://twitter.com/RealClearNews', twitter_related: 'RealClearNews,rcpvideo,TomBevanRCP', global_site_url: window.location.protocol+'//www.realclearpolitics.com', site_color: '#DC0000', FB_app_id: '1593718380910611', global_data_loc: 'rcp', // REVCONTENT -- SPONSORED CONTENT IDS revc_id: 'rcjsload_802e64', revc_w: '39765', revc_id_side: '', // we do not have code for politics // ZERG SPONSORED CONTENT SITE ID zerg_id: '56045', // Newsletter Promo Pop-up Auto List Select auto_list_ids: 'a4db5f2336|51f930c5ce|8c65b915a9|d6a76c9ec3|9da46952f0|7d83b1601b', spot_production_id: 'sp_v0xu5oCZ', evolok_enabled: false, story_stream_related: true, gotchosen_id: 'GC_e4431c0a82261742f007d36f767de82097f19bc6', }, { name: 'science', prebid_src: '//s3.amazonaws.com/ssl-intgr-net/prebid/369.js', //prebid_src: '//www.realclearpolitics.com/concepts/home/prebid_new_hp/369.js', disable_all_ads: false, lazy_ads: true, site_title: 'RealClearScience', //facebook link for main icon in new header menu bar facebook_url: 'https://www.facebook.com/realclearscience/', //twitter link for main icon in new header menu bar twitter_url: 'https://twitter.com/rcscience', twitter_related: 'rcscience', global_site_url: window.location.protocol+'//www.realclearscience.com', site_color: '#37414A', FB_app_id: '815061235213552', global_data_loc: 'rcsc', //rev content revc_id: 'rcjsload_bbbfdc', revc_w: '44986', revc_id_side: 'rcjsload_1c39c0', revc_w_side: '44987', // ZERG SPONSORED CONTENT SITE ID zerg_id: '', auto_list_ids: '267b89dc8a', spot_production_id: 'sp_8lO2c91e', evolok_enabled: true, story_stream_related: true, gotchosen_id: 'GC_5fe7981788ab4d52787073ab4ba4da08736240ce', }, { name: 'world', prebid_src: '', disable_all_ads: false, lazy_ads: true, site_title: 'RealClearWorld', //facebook link for main icon in new header menu bar facebook_url: 'https://www.facebook.com/RealClearWorld/', //twitter link for main icon in new header menu bar twitter_url: 'https://twitter.com/RealClearWorld', twitter_related: 'RealClearNews', global_site_url: window.location.protocol+'//www.realclearworld.com', site_color: '#0C124D', FB_app_id: '2093313384226659', global_data_loc: 'rcw', //rev content revc_id: 'rcjsload_ff92c1', revc_w: '44988', revc_id_side: 'rcjsload_33e8a5', revc_w_side: '44989', // ZERG SPONSORED CONTENT SITE ID zerg_id: '', auto_list_ids: 'd519acabbf|9960d29f6a|1630639ffc', spot_production_id: 'sp_LQqoi1VA', evolok_enabled: true, story_stream_related: false, gotchosen_id: 'GC_26a00fabb18c91dc38b21cfd18c00f09f22bf991', }, { name: 'health', prebid_src: '', disable_all_ads: false, lazy_ads: true, site_title: 'RealClearHealth', //facebook link for main icon in new header menu bar facebook_url: 'https://www.facebook.com/realclearhealth/', //twitter link for main icon in new header menu bar twitter_url: 'https://twitter.com/RealClearHealth', twitter_related: 'realclearhealth', global_site_url: window.location.protocol+'//www.realclearhealth.com', site_color: '#DBB706', FB_app_id: '1767191100208431', global_data_loc: 'rche', //rev content revc_id: 'rcjsload_114cfb', revc_w: '45008', revc_id_side: 'rcjsload_d59572', revc_w_side: '45009', // ZERG SPONSORED CONTENT SITE ID zerg_id: '', //Newsletter Promo Pop-up Auto List Select auto_list_ids: 'b4baf6b587', spot_production_id: 'sp_C6rOxoF6', evolok_enabled: false, story_stream_related: true, gotchosen_id: 'GC_88287009d64ebb9e5c1323cbcfa8acd524684150', }, { name: 'investigations', prebid_src: '', disable_all_ads: true, lazy_ads: true, site_title: 'RealClearInvestigations', //facebook link for main icon in new header menu bar facebook_url: 'https://www.facebook.com/realclearinvestigations/', //twitter link for main icon in new header menu bar twitter_url: 'https://twitter.com/RealClearInvestigations', twitter_related: 'realclearinvestigations', global_site_url: window.location.protocol+'//www.realclearinvestigations.com', site_color: '#5d5d5d', FB_app_id: '1615740298756569', global_data_loc: 'rci', // ZERG SPONSORED CONTENT SITE ID zerg_id: '', auto_list_ids: 'd042379c8d', spot_production_id: 'sp_fGGCea9F', evolok_enabled: false, story_stream_related: true, }, { name: 'defense', prebid_src: '', disable_all_ads: false, lazy_ads: true, site_title: 'RealClearDefense', //facebook link for main icon in new header menu bar facebook_url: 'https://www.facebook.com/realcleardefense/', //twitter link for main icon in new header menu bar twitter_url: 'https://twitter.com/RCDefense', twitter_related: 'RCDefense', global_site_url: window.location.protocol+'//www.realcleardefense.com', site_color: '#485228', FB_app_id: '1640169792979601', global_data_loc: 'rcd', //rev content revc_id: 'rcjsload_bbbfdc', revc_w: '44986', revc_id_side: 'rcjsload_1c39c0', revc_w_side: '44987', // ZERG SPONSORED CONTENT SITE ID zerg_id: '', auto_list_ids: '694f73a8dc', spot_production_id: 'sp_DzWAHE1J', evolok_enabled: true, story_stream_related: true, gotchosen_id: 'GC_2547344cf6e04e73ce1abfadff9da2186b8ebafb', }, { name: 'energy', prebid_src: '', disable_all_ads: false, lazy_ads: true, site_title: 'RealClearEnergy', //facebook link for main icon in new header menu bar facebook_url: 'https://www.facebook.com/realclearenergy/', //twitter link for main icon in new header menu bar twitter_url: 'https://twitter.com/realclearenergy', twitter_related: 'realclearenergy', global_site_url: window.location.protocol+'//www.realclearenergy.org', site_color: '#70AB41', FB_app_id: '255745351486296', global_data_loc: 'rce', //rev content revc_id: 'rcjsload_bbbfdc', revc_w: '44986', revc_id_side: 'rcjsload_1c39c0', revc_w_side: '44987', // ZERG SPONSORED CONTENT SITE ID zerg_id: '', auto_list_ids: '462961a8ae|7d83b1601b', spot_production_id: 'sp_yhuNbXOh', evolok_enabled: true, story_stream_related: true, gotchosen_id: 'GC_f92cf3e7212877dba6e1d6fb969addc15917131a', }, { name: 'policy', prebid_src: '', disable_all_ads: false, lazy_ads: true, site_title: 'RealClearPolicy', //facebook link for main icon in new header menu bar facebook_url: 'https://www.facebook.com/realclearpolicy', //twitter link for main icon in new header menu bar twitter_url: 'https://twitter.com/realclearpolicy', twitter_related: 'realclearpolicy', global_site_url: window.location.protocol+'//www.realclearpolicy.com', //site_color: '#37414A', site_color: '#65198e', FB_app_id: '1815769415347224', global_data_loc: 'rcpc', //rev content revc_id: 'rcjsload_bbbfdc', revc_w: '44986', revc_id_side: 'rcjsload_1c39c0', revc_w_side: '44987', // ZERG SPONSORED CONTENT SITE ID zerg_id: '', auto_list_ids: 'ebf02493b3|113ee1bc69', spot_production_id: 'sp_YRUF6DPr', evolok_enabled: true, story_stream_related: true, gotchosen_id: 'GC_e2ef102a0ff5f0d4f77141e685d917450278897d', }, { name: 'religion', prebid_src: '', disable_all_ads: false, lazy_ads: true, site_title: 'RealClearReligion', //facebook link for main icon in new header menu bar facebook_url: 'https://www.facebook.com/realclearreligion', //twitter link for main icon in new header menu bar twitter_url: 'https://twitter.com/realclearreligion', twitter_related: 'realclearreligion', global_site_url: window.location.protocol+'//www.realclearreligion.org', site_color: '#81C0C8', FB_app_id: '346345255724798', global_data_loc: 'rcr', //rev content revc_id: 'rcjsload_bbbfdc', revc_w: '44986', revc_id_side: 'rcjsload_1c39c0', revc_w_side: '44987', // ZERG SPONSORED CONTENT SITE ID zerg_id: '', auto_list_ids: '7f0a4512a1', spot_production_id: 'sp_QKKE0vl2', evolok_enabled: true, story_stream_related: true, gotchosen_id: 'GC_4fd3da3e573b20bda65b0e8d498e0c6909be936b', }, { name: 'education', prebid_src: '', disable_all_ads: false, lazy_ads: true, site_title: 'RealClearEducation', //facebook link for main icon in new header menu bar facebook_url: 'https://www.facebook.com/realcleareducation', //twitter link for main icon in new header menu bar twitter_url: 'https://twitter.com/realcleared', twitter_related: 'realcleared', global_site_url: window.location.protocol+'//www.realcleareducation.com', site_color: '#8b0000', FB_app_id: '1734472916875035', global_data_loc: 'rced', //rev content revc_id: 'rcjsload_bbbfdc', revc_w: '44986', revc_id_side: 'rcjsload_1c39c0', revc_w_side: '44987', // ZERG SPONSORED CONTENT SITE ID zerg_id: '', auto_list_ids: '8a051b373b', spot_production_id: 'sp_4wiiImwx', evolok_enabled: false, story_stream_related: true, gotchosen_id: 'GC_4d726c2f8be9384b8213df11ce85e79f05438901', }, { name: 'books', prebid_src: '', disable_all_ads: false, lazy_ads: true, site_title: 'RealClearBooks', //facebook link for main icon in new header menu bar facebook_url: 'https://www.facebook.com/realclearbooks', //twitter link for main icon in new header menu bar twitter_url: 'https://twitter.com/realclearbooks', twitter_related: 'realclearbooks', global_site_url: window.location.protocol+'//www.realclearbooks.com', site_color: '#553c2d', FB_app_id: '336545073384960', global_data_loc: 'rcb', //rev content revc_id: 'rcjsload_bbbfdc', revc_w: '44986', revc_id_side: 'rcjsload_1c39c0', revc_w_side: '44987', // ZERG SPONSORED CONTENT SITE ID zerg_id: '', auto_list_ids: 'ea772b1135', spot_production_id: 'sp_sJMa8VBM', evolok_enabled: true, story_stream_related: true, gotchosen_id: 'GC_08cbadf551e2af130ce5a70c29c788e3bbde01fe', }, { name: 'history', prebid_src: '', disable_all_ads: false, lazy_ads: true, site_title: 'RealClearHistory', //facebook link for main icon in new header menu bar facebook_url: 'https://www.facebook.com/realclearhistory', //twitter link for main icon in new header menu bar twitter_url: 'https://twitter.com/realclearhistry', twitter_related: 'realclearhistry', global_site_url: window.location.protocol+'//www.realclearhistory.com', site_color: '#cc6600', FB_app_id: '377784295946894', global_data_loc: 'rchi', //rev content revc_id: 'rcjsload_bbbfdc', revc_w: '44986', revc_id_side: 'rcjsload_1c39c0', revc_w_side: '44987', // ZERG SPONSORED CONTENT SITE ID zerg_id: '', auto_list_ids: 'fbced764bd', // Update with new list id spot_production_id: 'sp_0xpjnq0B', //SPOT Production evolok_enabled: true, story_stream_related: true, gotchosen_id: 'GC_e97f0ff112ae2aaa0aec5780e51c7e70e4cba1e2', }, { name: 'markets', prebid_src: '', disable_all_ads: false, lazy_ads: true, site_title: 'RealClearMarkets', //facebook link for main icon in new header menu bar facebook_url: 'https://www.facebook.com/realclearmarkets', //twitter link for main icon in new header menu bar twitter_url: 'https://twitter.com/rc_markets', twitter_related: 'rc_markets', global_site_url: window.location.protocol+'//www.realclearmarkets.com', site_color: '#669933', FB_app_id: '1798801117051770', global_data_loc: 'rcm', //M.B. REMOVED 1.9.17 //rev content //revc_id: 'rcjsload_bbbfdc', //revc_w: '44986', //revc_id_side: 'rcjsload_1c39c0', //revc_w_side: '44987', // ZERG SPONSORED CONTENT SITE ID zerg_id: '', auto_list_ids: '1f71a1eaa2', // Update with new list id spot_production_id: 'sp_9W7bDUIH', evolok_enabled: true, story_stream_related: true, gotchosen_id: 'GC_b10b9282e82eb93c968d2888fbc0aa757483040c', }, { name: 'publicaffairs', prebid_src: '', disable_all_ads: true, lazy_ads: true, site_title: 'RealClearPublicAffairs', //facebook link for main icon in new header menu bar facebook_url: 'https://www.facebook.com/realclearpublicaffairs/', //twitter link for main icon in new header menu bar twitter_url: 'https://twitter.com/RealClearPublicAffairs', twitter_related: 'realclearpublicaffairs', global_site_url: window.location.protocol+'//www.realclearpublicaffairs.com', site_color: '#013220', FB_app_id: '', global_data_loc: 'rcpa', // ZERG SPONSORED CONTENT SITE ID zerg_id: '', auto_list_ids: '', spot_production_id: 'sp_rIO3togj', evolok_enabled: false, story_stream_related: true, }, ]; var SITE_INFO = {}; // Find site info based on detected site for(var i = 0; i < SITES_INFO.length; i++) { if(SITES_INFO[i]['name'] == SITE_NAME) { SITE_INFO = SITES_INFO[i]; break; } } // More scripts added later. Runs through scripts at end of MAIN LOGIC. var rcmg_top_scripts = []; var rcp_page_refresh_interval = ''; //DEFINING GLOBAL REFRESH INTERVAL SET IN rcp.js var dateMenuVisible = false; // ADS ///////////////////////////////////////////////////////////////////////// var AD_ID = '1004503'; var ads_info = { 'div-gpt-ad-1390595004947-7' : { 'sizes' : [ [728, 90] ], 'name' : '/'+AD_ID+'/RC_728_by_90_top', 'class' : 'RC-AD-TOP-BANNER', 'loaded' : false, 'closeable_pages' : ['home','article','polls'], 'ic_override' : '//ads.investingchannel.com/adtags/realclearmarkets/economics/728x90.js' }, 'div-gpt-ad-1390595004947-6' : { 'sizes' : [ [728, 90] ], 'name' : '/'+AD_ID+'/RC_728_by_90_bottom', 'class' : 'RC-AD-BOTTOM-BANNER', 'loaded' : false, 'closeable_pages' : [] }, 'div-gpt-ad-1416850836025-4' : { 'sizes' : [ [300, 600] ], 'name' : '/'+AD_ID+'/RC_300_by_600_bottom', 'class' : 'RC-AD-BOX-BOTTOM-600', 'loaded' : false, 'closeable_pages' : [] }, 'div-gpt-ad-1390595004947-3' : { 'sizes' : [ [300, 250] ], 'name' : '/'+AD_ID+'/RC_300_by_250_bottom', 'class' : 'RC-AD-BOX-BOTTOM', 'loaded' : false, 'closeable_pages' : [] }, 'div-gpt-ad-1390595004947-5' : { 'sizes' : [ [300, 250], [300, 600] ], 'name' : '/'+AD_ID+'/RC_300_by_250_top', 'class' : 'RC-AD-BOX-TOP', 'loaded' : false, 'closeable_pages' : [], 'ic_override' : '//ads.investingchannel.com/adtags/realclearmarkets/economics/300x250.js' }, 'div-gpt-ad-1390595004947-4' : { 'sizes' : [ [300, 250] ], 'name' : '/'+AD_ID+'/RC_300_by_250_middle', 'class' : 'RC-AD-BOX-MIDDLE', 'loaded' : false, 'closeable_pages' : [] }, 'div-gpt-ad-1390595004947-2' : { // NOT IN PUBLIR 264 'sizes' : [ [160, 600] ], 'name' : '/'+AD_ID+'/RC_160_by_600_top', 'class' : 'RC-AD-SKY-TOP', 'loaded' : false, 'closeable_pages' : [] }, 'div-gpt-ad-1390595004947-1' : { // NOT IN PUBLIR 264 'sizes' : [ [160, 600] ], 'name' : '/'+AD_ID+'/RC_160_by_600_bottom', 'class' : 'RC-AD-SKY-BOTTOM', 'loaded' : false, 'closeable_pages' : [] }, 'div-gpt-ad-1416850836025-5' : { // NOT IN PUBLIR 264 'sizes' : [ [300, 250] ], 'name' : '/'+AD_ID+'/RC_300_by_250_widget', 'class' : 'RC-AD-BOX-WIDGET', 'loaded' : false, 'closeable_pages' : [] }, 'div-gpt-ad-1340813990105-0' : { // NOT IN PUBLIR 264 'sizes' : [ [320, 50] ], 'name' : '/'+AD_ID+'/RC_mobile', 'class' : 'RC-AD-MOBILE-BANNER', 'loaded' : false, 'closeable_pages' : [] }, 'div-gpt-ad-welcome' : { // NOT IN PUBLIR 264, 369 'sizes' : [ [1, 1] ], 'name' : '/'+AD_ID+'/RC_1_by_1_welcome', 'class' : 'RC-AD-WELCOME', 'loaded' : false, 'closeable_pages' : [] }, 'div-gpt-ad-1416850836025-7' : { // NOT IN PUBLIR 264, 369 'sizes' : [ [216, 40] ], 'name' : '/'+AD_ID+'/RC_Lc', 'class' : 'RC-AD-LC', 'loaded' : false, 'closeable_pages' : [] }, 'div-gpt-ad-1448303538392-0' : { // NOT IN PUBLIR 264, 369 'sizes' : [ [970,90],[970,250] ], 'name' : '/'+AD_ID+'/RC_970_by_90', 'class' : 'RC-AD-TOP-BANNER-BIG', 'loaded' : false, 'closeable_pages' : [] }, 'div-gpt-ad-1390595004947-8' : { // NOT IN PUBLIR 264, 369 'sizes' : [ [300, 250] ], 'name' : '/'+AD_ID+'/RC_300_by_250_carousel', 'class' : 'RC-AD-BOX-MOBILE_1', 'loaded' : false, 'closeable_pages' : [] }, 'div-gpt-ad-1390595004947-9' : { // NOT IN PUBLIR 264, 369 'sizes' : [ [300, 250] ], 'name' : '/'+AD_ID+'/RC_300_by_250_house', 'class' : 'RC-AD-BOX-MOBILE_2', 'loaded' : false, 'closeable_pages' : [] }, 'div-gpt-ad-1496845181660-0' : { // NOT IN PUBLIR 264, 369 'sizes' : [ [1, 1] ], 'name' : '/'+AD_ID+'/RC_1_by_1_tynt', 'class' : 'RC-AD-TYNT', 'loaded' : false, 'closeable_pages' : [] }, }; var LAZY_ADS_ENABLED = false; if( typeof SITE_INFO['lazy_ads'] !== 'undefined' && SITE_INFO['lazy_ads'] == true ) { LAZY_ADS_ENABLED = true; } var PREBIDDING_ENABLED = false; if( typeof SITE_INFO['prebid_src'] !== 'undefined' && SITE_INFO['prebid_src'] != '' ) { PREBIDDING_ENABLED = true; } var allow_ad_render = false; // We want to wait until publir prebid is initialized fully var lazy_ad_list = []; // populated as scrolling down page var notif_banner_enabled = false; // ? var fire_gdpr_consent = true; // simple enable/disable flag var story_stream_related_tags_html = ''; // Used for story streams related topics var network_ads_loaded = false; // EVOLOK ////////////////////////////////////////////////////////////////////// var evolok_init_finished = false; var evolok_block_ads = false; var evolok_do_ads = false; // WIDGETS ///////////////////////////////////////////////////////////////////// var $w_ss = []; // Holds multiple story streams var rcp_avg_w_total = 0; var rcp_avg_w_data = []; // SOCIAL ////////////////////////////////////////////////////////////////////// var fbShares = 0; var linkedCount = 0; var sharePosition = 0; var share_urls = []; var fbDone = false; var linDone = false; //////////////////////////////////////////////////////////////////////////////// // MAIN LOGIC ////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// init_network_ads(); // Load dynamic synchronous scripts, MUST NOT BE IN DOC READY, has to happen now loadTopScripts(); // Run logic immediately or in doc ready, depending on where master is (head, or at end of body) if(document.querySelector("body")) { init_master(); } else { $(document).ready(function(){ init_master(); }); } function init_master() { init_story_stream_related(); // Clicks on document that should close menus click_outside_menus(); // Evolok Metering Init // Will run loadAds immediately if evolok not enabled evolok_init(); if(typeof load_spot_recirculation == 'function') {load_spot_recirculation(); } if(typeof load_investingchannel_88x31 == 'function') {load_investingchannel_88x31(); } if(typeof load_investingchannel_300 == 'function') {load_investingchannel_300(); } spot_right_rail_init(); sitesMenu(); sectionsMenu(); sectionsInnerMenu(); sitesMenuHover(); recommendedSitesMenuHover(); // Why does this function exist twice? recentItemsSlider(); //LOAD DYNAMIC SOCIAL TOOLS IN TOOLS CONTAINER if( $('.socialBar').length>0 ) { loadSocialTools(); initEmailDrawer(); } loadGotChosen(); distroscale_init(); markets_investingchannel(); showComments(); hideComments(); showHideComments(); initSocialDrawer(); onScroll(); onResize(); showMobileSearch(); //M.B. TURNED OF STREAM TAG POPUPS FOR LAUNCH - TURN BACK ON POST LAUNCH //event checker - replaces width checks used to determine resolution //used to determine if a mouse event or touch event is fired if(!$('body').hasClass('article-landing')){ $( ".stream-tag" ).on({ click: function(e) { storyStreamClick(e); }, mouseenter: function(e) { storyStreamHover(e); }, touchstart: function(e) { storyStreamClick(e); }, touchmove: function(e) { setTimeout(function(){ storyStreamClick(e); },250); }, touchleave: function(e) { setTimeout(function(){ storyStreamClick(e); },250); } }); } $(document).on('click', '', function(e){ if(!$(e.target).hasClass('stream-tag')){ $('.story-stream-hover-wrapper').hide(); } }); //homepage hover menu handlers //smart check for touch events to cover all devices without device/width checks $( ".main-nav-bar .links-container ul li a" ).on({ mouseenter: function(e) { mainNavHover(e); }, touchstart: function(e) { homeNavClick(e); }, touchmove: function(e) { homeNavClick(e); } }); toggleCBTsearch(); customSelectBox(); cbtSearch(); viewSwitcher(); dateMenu(); displayStaff(); siteSearch(); /************************************************ DOC READY UTILITY FUNCTIONS **************************************************/ //ANIMATE SCROLLING - REPLACES TRADITIONAL HTML BOOKMARKING BY CLICKING LINK AND SCROLLING DOWN TO BOOKMARK RATHER THAN JUMP DOWN $(".gamma > ul > li > a").click(function(e) { // Prevent a page reload when a link is pressed e.preventDefault(); // Call the scroll function goToByScroll($(this).attr("id")); }); loadInfinityAds(); //we wait for body class to load so we can check what section we're on //Google Site Translator if( SITE_INFO['name'] == 'world' && $('body.article').length > 0 ){ setTimeout(function(){ $('.goog-te-gadget-icon').removeClass('goog-te-gadget-icon'); $('.goog-te-gadget-simple').html('Select Language'); $('.goog-te-gadget-simple').css({ "background-color" : "transparent", "border-width" : "0", "padding-bottom" : "5px", "padding-top" : "5px" }); $('.goog-te-gadget-simple .goog-te-menu-value').css({ "color" : "#999999" }); $('.goog-te-menu-value img').css({ "margin-left" : "7px" }); }, 2100); }else{ setTimeout(function(){ $('.goog-te-gadget-icon').removeClass('goog-te-gadget-icon'); $('.goog-te-gadget-simple').html('Select Language'); }, 2100); } //Newsletter Promo Pop-Up Handlers $("body").append('
'); //Hide Member Pop-up - click anywhere outside pop-up to hide $(document).click(function(event) { if(!$(event.target).closest('#facebox').length) { if($('#facebox').is(":visible")) { $("body > .overlay_newsletter_promo").hide("fast"); }else{ $("body > .overlay_newsletter_promo").hide("fast"); } } }); //END DOC .click - hide pop-up ///Newsletter widget I agree checkbox $(document).on('click', ':checkbox#i-agree' , function(e){ console.log('i-'); $('.right-options input:checkbox').prop('checked',this.checked); }); // Temp disabled, seeing if we don't need it anymore //load_fb_sdk(); } //////////////////////////////////////////////////////////////////////////////// // PRESERVE COMPATIBILITY ////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// var siteName = SITE_INFO['name']; var sitePage = SITE_PAGE; var gaTag = GA_TAG; var site_title = SITE_INFO['site_title']; var facebook_url = SITE_INFO['facebook_url']; var twitter_url = SITE_INFO['twitter_url']; var twitter_related = SITE_INFO['twitter_related']; var global_site_url = SITE_INFO['global_site_url']; var site_color = SITE_INFO['site_color']; var FB_app_id = SITE_INFO['FB_app_id']; var global_data_loc = SITE_INFO['global_data_loc']; //var revc_id = SITE_INFO['revc_id']; //var revc_w = SITE_INFO['revc_w']; //var revc_id_side = SITE_INFO['revc_id_side']; //var revc_w_side = SITE_INFO['revc_w_side']; var zerg_id = SITE_INFO['zerg_id']; var auto_list_ids = SITE_INFO['auto_list_ids']; var spot_production_id = SITE_INFO['spot_production_id']; //////////////////////////////////////////////////////////////////////////////// // BROWSER / OS DETECTION ////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // Adds ability to detect browser navigator.browserInfo = (function(){ var ua= navigator.userAgent, tem, M= ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || []; if(/trident/i.test(M[1])){ tem= /\brv[ :]+(\d+)/g.exec(ua) || []; return 'IE '+(tem[1] || ''); } if(M[1]=== 'Chrome'){ tem= ua.match(/\b(OPR|Edge)\/(\d+)/); if(tem!= null){ var temp = tem.slice(1); return { 'browser': temp[0].replace('OPR', 'Opera'), 'version': temp[1] }; } } M= M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?']; if((tem = ua.match(/version\/(\d+)/i))!= null) M.splice(1, 1, tem[1]); return { 'browser': M[0], 'version': M[1] }; })(); // Adds ability to detect OS navigator.osInfo= (function(){ var ua = navigator.userAgent; var av = navigator.appVersion; var os = 'unknown'; var clientStrings = [ {s:'Windows 10', r:/(Windows 10.0|Windows NT 10.0)/}, {s:'Windows 8.1', r:/(Windows 8.1|Windows NT 6.3)/}, {s:'Windows 8', r:/(Windows 8|Windows NT 6.2)/}, {s:'Windows 7', r:/(Windows 7|Windows NT 6.1)/}, {s:'Windows Vista', r:/Windows NT 6.0/}, {s:'Windows Server 2003', r:/Windows NT 5.2/}, {s:'Windows XP', r:/(Windows NT 5.1|Windows XP)/}, {s:'Windows 2000', r:/(Windows NT 5.0|Windows 2000)/}, {s:'Windows ME', r:/(Win 9x 4.90|Windows ME)/}, {s:'Windows 98', r:/(Windows 98|Win98)/}, {s:'Windows 95', r:/(Windows 95|Win95|Windows_95)/}, {s:'Windows NT 4.0', r:/(Windows NT 4.0|WinNT4.0|WinNT|Windows NT)/}, {s:'Windows CE', r:/Windows CE/}, {s:'Windows 3.11', r:/Win16/}, {s:'Android', r:/Android/}, {s:'Open BSD', r:/OpenBSD/}, {s:'Sun OS', r:/SunOS/}, {s:'Linux', r:/(Linux|X11)/}, {s:'iOS', r:/(iPhone|iPad|iPod)/}, {s:'Mac OS X', r:/Mac OS X/}, {s:'Mac OS', r:/(MacPPC|MacIntel|Mac_PowerPC|Macintosh)/}, {s:'QNX', r:/QNX/}, {s:'UNIX', r:/UNIX/}, {s:'BeOS', r:/BeOS/}, {s:'OS/2', r:/OS\/2/}, {s:'Search Bot', r:/(nuhk|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask Jeeves\/Teoma|ia_archiver)/} ]; for (var id in clientStrings) { var cs = clientStrings[id]; if (cs.r.test(ua)) { os = cs.s; break; } } var osVersion = 'unknown'; if (/Windows/.test(os)) { osVersion = /Windows (.*)/.exec(os)[1]; os = 'Windows'; } switch (os) { case 'Mac OS X': osVersion = /Mac OS X (10[\.\_\d]+)/.exec(ua)[1]; if(osVersion == null) { osVersion = 'unknown'; } break; case 'Android': osVersion = /Android ([\.\_\d]+)/.exec(ua)[1]; if(osVersion == null) { osVersion = 'unknown'; } break; case 'iOS': osVersion = /OS (\d+)_(\d+)_?(\d+)?/.exec(av); if(osVersion == null) { osVersion = 'unknown'; } else { osVersion = osVersion[1] + '.' + osVersion[2] + '.' + (osVersion[3] | 0); } break; } return { 'os': os, 'os_version': osVersion }; })(); //////////////////////////////////////////////////////////////////////////////// // NOTIFICATIONS /////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// function loadNotificationsPromo() { var bc; if( $("body.article").length>0 ){ bc = "article"; }else if( $("body.entry").length>0 ){ bc = "entry"; }else if( $("body.video").length>0 ){ bc = "video"; }else if( $("body.polls").length>0 ){ bc = "polls"; }else if( $("body.election").length>0 ){ bc = "election"; }else if( $("body.story-stream").length>0 ){ bc = "story-stream"; }else if( $("body.custom-topic").length>0 ){ bc = "custom-topic"; }else if( $("body.cartoon").length>0 ){ bc = "cartoon"; }else if( $("body.about").length>0 ){ bc = "about"; }else if( $("body.list").length>0 ){ bc = "list"; }else if( $("body.static").length>0 ){ bc = "static"; }else if( $("body.author").length>0 ){ bc = "author"; }else if( $("body.changingLanes").length>0 ){ bc = "changingLanes"; }else if( $("body.entry-date-based").length>0 ){ bc = "entry-date-based"; }else if( $("body.links").length>0 ){ bc = "links"; }else if( $("body.event").length>0 ){ bc = "event"; }else{ bc = $("body").attr("class"); } var notificationsPopCookie = readCookie('notificationsScrollPop'); var commenter_id = readCookie('realclear_user'); if(!commenter_id){ commenter_id = 0; } if( !notificationsPopCookie ){ //_gaq.push(['_trackEvent', 'Notifications', 'Auto Pop', "'"+bc+"'"]); _gaq.push(['_trackEvent', 'Notifications', 'Auto Pop', SITE_INFO['name']+' : '+bc, null, true]); var site_settings = notification_settings(SITE_INFO['name']); var notifications_copy = '\
\
\ \

Notifications Notifications

\
\
\ \ \

Would you like to receive nonobstrusive notifications?

\

Notifications can come in whether you are on our site or not, and even if your browser is closed.

\

You can always disable notifications in the future.

\
\ \ \
\ \
\ \
\
\
'; jQuery.facebox(notifications_copy); $('#enable_notifications').click(function(){ //_gaq.push(['_trackEvent', 'Notifications EnableClick : ' + bc + ' module', 'Site: ' + SITE_INFO['name']]); _gaq.push(['_trackEvent', 'Notifications', 'Click', 'Pop Button-1', 1]); $('.overlay').remove(); $(document).trigger('close.facebox'); var this_url = encodeURIComponent(location.href); var notif_url = 'https://notifications.realclearpolitics.com/web_notifications/sign_up.html?'; var query_string = 'site_shortname='+SITE_INFO['global_data_loc']+'&site='+SITE_INFO['name']+'§ion='+bc+'&auto_list_ids='+SITE_INFO['auto_list_ids']+'&commid='+commenter_id+'&url='+this_url+'&enable=1'; window.location = notif_url+query_string; //window.open(notif_url+query_string); }); $('.notif_btn_ignore').click(function() { //_gaq.push(['_trackEvent', 'Notifications Not Now : ' + bc + ' module', 'Site: ' + SITE_INFO['name']]); _gaq.push(['_trackEvent', 'Notifications', 'Click', 'Pop Button-0', 0]); $('.overlay').remove(); $(document).trigger('close.facebox'); }); $(".overlay").show("fast"); goToByScroll("facebox"); createCookie('notificationsScrollPop','1','365'); //fire google tracking event //_gaq.push(['_trackEvent', 'Notifications Pop : ' + bc + ' module', 'Site: ' + SITE_INFO['name']]); }else{ } } function notification_settings(site){ var site_settings; var notifs_root = "https://notifications.realclearpolitics.com/web_notifications/"; switch(site){ case 'politics': site_settings = { "notif_preview_url":notifs_root+"images/notification_rcp.png", "notif_preview_250":notifs_root+"images/notification_rcp_250px.png" }; break; case 'world': site_settings = { "notif_preview_url":notifs_root+"images/notification_rcw.png" }; break; case 'future': site_settings = { "notif_preview_url":notifs_root+"images/notification_rcf.png" }; break; case 'health': site_settings = { "notif_preview_url":notifs_root+"images/notification_rch.png" }; break; case 'markets': site_settings = { "notif_preview_url":notifs_root+"images/notification_rcm.png" }; break; case 'defense': site_settings = { "notif_preview_url":notifs_root+"images/notification_rcd.png" }; break; case 'energy': site_settings = { "notif_preview_url":notifs_root+"images/notification_rce.png" }; break; case 'science': site_settings = { "notif_preview_url":notifs_root+"images/notification_rcs.png" }; break; case 'religion': site_settings = { "notif_preview_url":notifs_root+"images/notification_rcr.png" }; break; case 'education': site_settings = { "notif_preview_url":notifs_root+"images/notification_rced.png" }; break; case 'sports': site_settings = { "notif_preview_url":notifs_root+"images/notification_rcsp.png" }; break; case 'history': site_settings = { "notif_preview_url":notifs_root+"images/notification_rchi.png" }; break; case 'books': site_settings = { "notif_preview_url":notifs_root+"images/notification_rcb.png" }; break; case 'investigations': site_settings = { "notif_preview_url":notifs_root+"images/notification_rci.png" }; break; case 'policy': site_settings = { "notif_preview_url":notifs_root+"images/notification_rcpo.png" }; break; default: site_settings = {}; break; } return site_settings; } function loadNewsletterPromo(){ var bc; if( $("body.article").length>0 ){ bc = "article"; }else if( $("body.entry").length>0 ){ bc = "entry"; }else if( $("body.video").length>0 ){ bc = "video"; }else if( $("body.polls").length>0 ){ bc = "polls"; }else if( $("body.election").length>0 ){ bc = "election"; }else if( $("body.story-stream").length>0 ){ bc = "story-stream"; }else if( $("body.custom-topic").length>0 ){ bc = "custom-topic"; }else if( $("body.cartoon").length>0 ){ bc = "cartoon"; }else if( $("body.about").length>0 ){ bc = "about"; }else if( $("body.list").length>0 ){ bc = "list"; }else if( $("body.static").length>0 ){ bc = "static"; }else if( $("body.author").length>0 ){ bc = "author"; }else if( $("body.changingLanes").length>0 ){ bc = "changingLanes"; }else if( $("body.entry-date-based").length>0 ){ bc = "entry-date-based"; }else if( $("body.links").length>0 ){ bc = "links"; }else if( $("body.event").length>0 ){ bc = "event"; }else{ bc = $("body").attr("class"); } if( SITE_INFO['name'] != "investigations" && (!$("body").hasClass("home") && !$("body").hasClass("welcome")) ){ var news_letter_page = false; if(bc == 'static'){ var script_url = 'http://www.realclearpolitics.com/scripts/rc-newsletters.js'; var script_url2 = 'https://www.realclearpolitics.com/scripts/rc-newsletters.js'; var scripts = document.getElementsByTagName('script'); for (var i = scripts.length; i--;) { if (scripts[i].src == script_url || scripts[i].src == script_url2) { news_letter_page = true; } } } if( news_letter_page == false){ var sign_in_copy=''; jQuery.facebox(sign_in_copy); $(".overlay").show("fast"); loadscript('https://www.realclearpolitics.com/asset/top/rc-newsletters.js', 'jqNewsPop', '', ''); goToByScroll("facebox"); createCookie('newsletterScrollPop','1','365'); //fire google tracking event _gaq.push(['_trackEvent', 'Newsletters Pop', 'Auto Pop', SITE_INFO['name']+' : '+bc, null, true]); //_gaq.push(['_trackEvent', 'Newsletter/Notifications Pop', 'Auto Pop', SITE_INFO['name']+' : '+bc, '', true]); //_gaq.push(['_trackEvent', 'Newsletters Pop', 'Auto Pop', "'+bc+'", true]); //console.log(test); } } } /** * Displays inline content for articles, videos and polls to sign up for notifications * and to sign up for newsletters. * * inline_widget.create_notifs_sign_up_for_warning() is used by warning_widget to display * notifications sign up * * @type {Object} */ var inline_widget = {}; inline_widget = notification_settings(SITE_INFO['name']); inline_widget.siteName = SITE_INFO['name']; inline_widget.site = SITE_INFO['global_data_loc']; inline_widget.list_ids = SITE_INFO['auto_list_ids']; inline_widget.perma; inline_widget.browser = navigator.browserInfo.browser; inline_widget.os = navigator.osInfo.os; inline_widget.no_cache = new Date().getTime(); inline_widget.notif_icon = '//www.realclearpolitics.com/asset/img/notifications_icon.png'; inline_widget.notif_text = 'Sign Up For Browser Push Notifications'; inline_widget.create_notifs_sign_up = function(){ return this.notifications_inline = '\ \ '; } inline_widget.create_notifs_sign_up_for_warning = function(){ return this.notifications_inline = '\ \ '; } inline_widget.create_news_sign_up = function(){ return this.newsletters_inline = '\ \ '; } inline_widget.notifications_actions = function(){ $('#notifications_hover').on({ mouseenter: function(){ if($(window).width() >= 1024){ _gaq.push(['_trackEvent', 'Notifications', 'Inline Sign Up', 'Hover '+inline_widget.perma, null, true]); $('.hover_notif_preview').css('left', '260px'); $('.inline_hover_details').css('display', 'table'); $(".hover_notif_preview").animate({ "left": "0px" }, "slow" ); } }, mouseleave: function(){ $('.inline_hover_details').css('display', 'none'); $(".hover_notif_preview").attr('style', ''); } }); } inline_widget.insert_html = function(element){ var notifications_inline_article = readCookie('notifications_inline_article'); var newsletter_inline_article = readCookie('newsletter_inline_article'); if( $(element).length == 0 ){ console.log('Inline widget div "'+element+'" is missing form the page. Exiting early.'); return; } // 03-07-2019 disable notifications sign ups until resolved A.A. var disableNewNotifications = true; if(disableNewNotifications == false && notifs.notifs_work == true && notifs.enabled == false ){ _gaq.push(['_trackEvent', 'Notifications', 'Display Inline', 'Auto '+this.perma, null, true]); if(this.perma == 'article'){ $(element).after(this.create_notifs_sign_up()); }else if(this.perma == 'video'){ $(element).after(this.create_notifs_sign_up()); }else if(this.perma == 'latest_polls' || this.perma == 'poll'){ this.notif_text = 'Sign Up for Polls Push Notifications'; this.notif_icon = '//www.realclearpolitics.com/asset/img/notif_poll_icon.png'; $(element).after(this.create_notifs_sign_up()); } this.notifications_actions(); createCookie('notifications_inline_article','1','7'); eraseCookie('newsletter_inline_article'); }else{ _gaq.push(['_trackEvent', 'Newsletters', 'Display Inline', 'Auto '+this.perma, null, true]); if(this.perma == 'article'){ $(element).after(this.create_news_sign_up()); }else if(this.perma == 'video'){ $(element).after(this.create_news_sign_up()); }else if(this.perma == 'latest_polls' || this.perma == 'poll'){ $(element).after(this.create_news_sign_up()); } createCookie('newsletter_inline_article','1','7'); eraseCookie('notifications_inline_article'); } } inline_widget.article = function(){ this.perma = 'article'; /*var paragraphs = $('.alpha .article-body-text p'); var half_paragraphs = parseInt(parseInt(paragraphs.length) / 2); if(half_paragraphs > 3){ this.insert_html(paragraphs[half_paragraphs]); }*/ this.insert_html('.article-social-bottom-wrapper'); } inline_widget.video = function(){ this.perma = 'video'; this.insert_html('#related-footer'); } inline_widget.poll = function(){ var location = window.location.pathname; if(location == '/epolls/latest_polls/' || location == '/epolls/latest_polls/index.html'){ this.perma = 'latest_polls'; this.insert_html('p#my-nav'); }else{ this.perma = 'poll'; this.insert_html('div#chart_slider_holder'); } } inline_widget.insert_widget_into_page = function(){ setTimeout(function(){ if($('body').hasClass('article') && !$('body').hasClass('article-landing') && !$('body').hasClass('long')){ inline_widget.article(); }else if($('body').hasClass('video-perma')){ inline_widget.video(); }else if($('body').hasClass('polls')){ inline_widget.poll(); } },1500); } $(document).on('click', '.new_notif_sign_up', function(){ notifs.register(); }); /** * Displays underlay at the bottom of the page * Currently displays: * notifications sign up * ad block message * will use for ad targeting * will user for newsletter sign up * @type {Object} */ //initialize object and default settings var warning_widget = {}; warning_widget.empty_div = '
'; warning_widget.siteName = SITE_INFO['name']; warning_widget.close_icon = ""; warning_widget.icon = "https://www.realclearpolitics.com/asset/img/Asset_3.png"; warning_widget.info_message = "Our website is partially funded by displaying online advertisements to our visitors. Please consider supporting us by disabling your Ad-Blocker."; warning_widget.info = ""; warning_widget.footer_pos = 0; warning_widget.scroll_fix = 0; warning_widget.active = false; warning_widget.active_notice = ""; warning_widget.ad_block_ready_for_check = false; warning_widget.warning_template = function(){ var warning_ad_block_enabled = readCookie('warning_ad_block_enabled'); if(!warning_ad_block_enabled){ if( $('#warning_empty_div').length == 0 ){ $(this.empty_div).appendTo('body'); } $('#warning_empty_div').html(this.set_message()); this.event_listeners(); $('.warning-wrapper').show(); $('.warning-wrapper').css('display', 'block'); $('div.overlay').css('z-index', 500).show(); $('.warning-wrapper .container').css({ top: '50%', transform : 'translateY(-50%)', }); this.set_scroll_settings(); this.active = true; this.active_notice = "ad block message"; createCookie('warning_ad_block_enabled', 'temp', 5, true); _gaq.push(['_trackEvent', 'notices', 'Underlay', 'option: ad block message', null, true]); // var body_class = $('body').attr('class'); // _gaq.push(['_trackEvent', 'AdBlocker', 'adblocker-blocked', 'section: '+body_class, null, true]); } } warning_widget.set_notifications_sign_up = function(){ var warning_notif_underlay = readCookie('warning_notif_underlay'); if(!warning_notif_underlay){ if( $('#warning_empty_div').length == 0 ){ $(this.empty_div).appendTo('body'); } $('#warning_empty_div').html(this.set_notification()); this.event_listeners(); $('.inline_sign_up_box').css({ 'bottom': '14px', 'left': '0', 'right': '0', }); $('.warning-wrapper').show(); $('.warning-wrapper').css('display', 'block'); this.set_scroll_settings(); this.active = true; this.active_notice = "notifications sign up"; createCookie('warning_notif_underlay', 'temp', '12', true); _gaq.push(['_trackEvent', 'notices', 'Underlay', 'option: notifications sign up', null, true]); } } warning_widget.set_newslettter_sign_up = function(){ var warning_newsletter_underlay = readCookie('warning_newsletter_underlay'); if(!warning_newsletter_underlay){ if( $('#warning_empty_div').length == 0 ){ $(this.empty_div).appendTo('body'); } $('#warning_empty_div').html(this.newsletter_html()); $('.warning-wrapper').show(); $('.warning-wrapper').css('display', 'block'); this.set_scroll_settings(); this.newsletter_listeners(); this.event_listeners(); this.active = true; this.active_notice = "newsletter sign up"; createCookie('warning_newsletter_underlay', 'temp', '12', true); _gaq.push(['_trackEvent', 'notices', 'Underlay', 'option: newsletter sign up', null, true]); } } warning_widget.set_message = function(){ return "\
\ "+ this.close_icon +"\
\
\
"+ this.info_message +"
\
\
"; } warning_widget.set_notification = function(){ return "\
\ "+ this.close_icon +"\
\ "+inline_widget.create_notifs_sign_up_for_warning()+ "\
\
"; } warning_widget.newsletter_html = function(){ return "\
\ "+ this.close_icon +"\
\ "+inline_widget.create_news_sign_up()+ "\
\
"; } warning_widget.position_div = function(scrollPosition){ if (scrollPosition >= this.footer_pos - 15) { // If the function is only supposed to fire once var footer_height = $('.footer-wrapper').height(); $('.warning-wrapper').css({'position': 'fixed', 'bottom': footer_height+'px' }); }else{ $('.warning-wrapper').css({'position': 'fixed', 'bottom': '0px'}); } } warning_widget.event_listeners = function(){ $('.warning_close').on('click', function(){ $('.warning-wrapper').hide(); $('div.overlay').css('z-index', 1).hide(); warning_widget.active = false; //on close, check how many times it has been closed before //if closed three times create cookie to seven days //else create cookie for two days //warning underlay cookie that applies to all types of underlays var underlay_close_click_count = readCookie('underlay_close_click_count'); var underlay_close_clicks; if(!underlay_close_click_count){ underlay_close_clicks = 1; }else{ underlay_close_clicks = parseInt(underlay_close_click_count) + 1; } createCookie('underlay_close_click_count', underlay_close_clicks, 365); eraseCookie('warning_underlay'); if(underlay_close_clicks >= 3){ createCookie('warning_underlay', 'temp', 7); }else{ createCookie('warning_underlay', 'temp', 2); } _gaq.push(['_trackEvent', 'notices', 'Underlay', 'option: '+warning_widget.active_notice+' close', null, true]); return false; }); //change the position of the elemtent when reached to the bottom of the page -150px $(window).on('scroll', function() { var scrollPosition = $(this).scrollTop() + warning_widget.scroll_fix; warning_widget.position_div(scrollPosition); }); } warning_widget.newsletter_listeners = function(){ var window_width = $(window).width(); if(window_width <= 415){ $('.warning-wrapper').css('height', '75px'); $('.inline_sign_up_box').css({ top: '-15px', }); }else if(window_width < 1024){ $('.warning-wrapper').css('height', '100px'); } $(document).on('focus', '.warning-wrapper #list_email', function(){ var $this = this; setTimeout(function(){ var height = $($this).parents('.inline_sign_up_box').css('height'); var warning_height = ''; if(window_width >= 768){ warning_height = parseInt(height) + 20; }else{ warning_height = parseInt(height) - 30; } $('.warning-wrapper').css('height', warning_height+'px'); $('.sign_up_open').css({ 'height' : (height-10) + 'px', 'position' : 'relative', 'top' : '-15px', }); },150); }); } warning_widget.set_scroll_settings = function(){ if($('.footer').length) { var footer_pos = $('.footer').offset(); this.footer_pos = footer_pos.top; var window_height = $(window).height(); this.scroll_fix = window_height - $('.footer-wrapper').height(); } } warning_widget.check_ad_block_status = function(){ //see if page has doubleclick.js ad block check file var doubleclick_js_found = false; var scripts = document.getElementsByTagName('script'); var regex = /.*doubleclick\.([^/]+\.)?js/; //looks for investigations.js in script tags for (var i = 0; i < scripts.length; i++) { var this_script = scripts[i]; if( this_script.src.match(regex) ) { doubleclick_js_found = true; } } //console.log('double click check: '+doubleclick_js_found); //if it doesn't load it in into the body //it will be blocked by ad block plugins //then run the ad block checks if(doubleclick_js_found == false){ var script = document.createElement("script"); script.type = "text/javascript"; script.src = window.location.origin+"/asset/section/doubleclick.js"; $(script).appendTo("body"); //console.log('double click not there'); //let doubleclick.js try to run. Run this function once again to do the check setTimeout(function(){ warning_widget.check_ad_block_status(); }, 1500); return; } Utils.global_settings.realclear_ad_block_check = null; //CHECK RCNATIVE ADBLOCKER CHECK JS (ON PARENT FILE) //this is giving false positives on pages because it doesn't exists at all //console.log($('#AEVBvthGXnCs').length); if ( $('#AEVBvthGXnCs').length > 0 ) { Utils.global_settings.realclear_ad_block_check = false; //console.log('js file check false'); } else { Utils.global_settings.realclear_ad_block_check = true; //console.log('js file check true'); } //console.log('ad block check check status 4: '+Utils.global_settings.realclear_ad_block_check); if(SITE_INFO['name'] == 'politics'){ checkIfAnalyticsLoaded2(); } if(!_gaq){ setTimeout(function(){ warning_widget.check_ad_block_status(); }, 50); return; } warning_widget.ad_block_ready_for_check = true; //console.info('Finished With isAdBlockActive '+Utils.global_settings.realclear_ad_block_check); if(Utils.global_settings.realclear_ad_block_check == true){ var body_class = $('body').attr('class'); _gaq.push(['_trackEvent', 'Adblock Tracker', 'Adblocker enabled', 'section: '+body_class, null, true]); } } //if user is referred to site from a newsletter link //then we don't want to show the underlay for newsletters for a year warning_widget.check_for_newsletter_referer = function(){ var utm_campaign = Utils.get_query_param('utm_campaign'); var utm_medium = Utils.get_query_param('utm_medium'); if( (utm_campaign !== null && typeof utm_campaign === 'string') && (utm_medium !== null && typeof utm_medium === 'string') ){ //check if from mailchimp email if( /EMAIL_CAMPAIGN/i.test(utm_campaign) && utm_medium === 'email' ){ //create newseltter cookie to expire in one year eraseCookie('warning_newsletter_underlay'); createCookie('warning_newsletter_underlay', 'From Newsletter', '365', false); _gaq.push(['_trackEvent', 'notices', 'Underlay', 'newsletter click: disable notice', null, true]); } } } $(document).ready(function(){ warning_widget.set_scroll_settings(); $(warning_widget.empty_div).appendTo('body'); setTimeout(function(){ warning_widget.set_scroll_settings(); },1000); setTimeout(function(){ warning_widget.set_scroll_settings(); },2000); setTimeout(function(){ warning_widget.set_scroll_settings(); },3000); setTimeout(function(){ warning_widget.set_scroll_settings(); },4000); setTimeout(function(){ warning_widget.set_scroll_settings(); },5000); setTimeout(function(){ warning_widget.set_scroll_settings(); },6000); }); $(window).resize(function(){ warning_widget.set_scroll_settings(); $(window).scroll(); }); /** * Notifications object to handle all subscriptions and background resubscriptions * * Entry point to the code is notifs.check_notif_status(); * Will check if notifications work and if so, either check subscription or display subscription sign up * If signed up, it can check for ads, ad block, and newsletter sign up. * Uses warning_widget object to display UI to user. * * @type {Object} */ //create notifs object and set innitial settings var notifs = {}; notifs.valid_browser = false; notifs.valid_os = false; notifs.enabled = false; notifs.denied = false; notifs.new_subscription = true; notifs.notifs_work = false; notifs.landing_page = false; notifs.on_dashboard = false; notifs.subscription = {}; notifs.subscription.site = SITE_INFO['name']; notifs.options; notifs.site_params; notifs.pub_key = 'BGncia3Ae8MPryjmKAodlUL1yArlbxvcG9WsUD6ZL2WFi1WfJbrYMMLwvgH+TVAayH37BoMYa1oHqtTmZ6Oia4s='; notifs.form_html_inserted = false; //takes the pub_key and creates and encrypted array for the subscription notifs.urlBase64ToUint8Array = function(base64String) { const padding = '='.repeat((4 - base64String.length % 4) % 4); const base64 = (base64String + padding) .replace(/\-/g, '+') .replace(/_/g, '/'); const rawData = atob(base64); const outputArray = new Uint8Array(rawData.length); for (var i = 0; i < rawData.length; ++i) { outputArray[i] = rawData.charCodeAt(i); } return outputArray; } //checks if the browser can do notifications //also checks site notifs.check_if_valid_browser = function() { this.valid_browser = true; if(window.location.protocol != 'https:'){ this.valid_browser = false; return; } if (this.subscription.site != 'politics') { this.valid_browser = false; return; } if (!'serviceWorker' in navigator) { this.valid_browser = false; } if (!'PushManager' in window) { this.valid_browser = false; return; } if (typeof ServiceWorkerRegistration == 'undefined') { this.valid_browser = false; return; } else if (!'showNotification' in ServiceWorkerRegistration.prototype) { this.valid_browser = false; return; } if (navigator.browserInfo.browser != 'Opera' && navigator.browserInfo.browser != 'Chrome' && navigator.browserInfo.browser != 'Firefox' && navigator.browserInfo.browser != 'Edge') { this.valid_browser = false; return; }else{ //checking for minimum valid version of the browser that has push notifications switch(navigator.browserInfo.browser){ case 'Chrome': if(parseInt(navigator.browserInfo.version) < 42 ){ this.valid_browser = false; } break; case 'Firefox': if(parseInt(navigator.browserInfo.version) < 44 ){ this.valid_browser = false; } break; case 'Opera': if(parseInt(navigator.browserInfo.version) < 39 ){ this.valid_browser = false; } break; case 'Edge': if(parseInt(navigator.browserInfo.version) < 17 ){ this.valid_browser = false; } break; } return; } } //checks if the operating system can do notifications notifs.check_if_valid_os = function() { this.valid_os = true; if (navigator.osInfo.os != 'Linux' && navigator.osInfo.os != 'Mac OS X' && navigator.osInfo.os != 'Mac OS' && navigator.osInfo.os != 'Windows' && navigator.osInfo.os != 'Android') { this.valid_os = false; return; } } notifs.notif_check_finished = function() {}; //callls both browser and operating system checks //if both are good then notifs_work is set to true //site parameters are set notifs.check_if_notifs_work = function() { this.check_if_valid_browser(); this.check_if_valid_os(); if (this.valid_os == true && this.valid_browser == true) { this.notifs_work = true; this.notif_check_finished(); this.set_site_params(); } } //sets sites parameters //called if notifications work notifs.set_site_params = function(){ switch(this.subscription.site){ case 'politics': this.site_params = { "site_name":"RealClearPolitics", "title":"Welcome to RCP Notifications", "icon":"/web_notifications/icons/default_icons/rcp_default.png", "notif_preview":"https://util.realclearpolitics.com/web_notifications/images/notification_rcp.png", "manifest_file":"https://www.realclearpolitics.com/asset/vertical/rcp/manifest.json" }; break; case 'world': this.site_params = { "site_name":"RealClearWorld", "title":"Welcome to RCW Notifications", "icon":"/web_notifications/icons/default_icons/rcw_default.png", "notif_preview":"https://util.realclearpolitics.com/web_notifications/images/notification_rcw.png", "manifest_file":"https://www.realclearpolitics.com/asset/vertical/rcp/manifest.json" }; break; case 'future': this.site_params = { "site_name":"RealClearFuture", "title":"Welcome to RCF Notifications", "icon":"/web_notifications/icons/default_icons/rcf_default.png", "notif_preview":"https://util.realclearpolitics.com/web_notifications/images/notification_rcf.png", "manifest_file":"https://www.realclearpolitics.com/asset/vertical/rcp/manifest.json" }; break; case 'health': this.site_params = { "site_name":"RealClearHealth", "title":"Welcome to RCH Notifications", "icon":"/web_notifications/icons/default_icons/rch_default.png", "notif_preview":"https://util.realclearpolitics.com/web_notifications/images/notification_rch.png", "manifest_file":"https://www.realclearpolitics.com/asset/vertical/rcp/manifest.json" }; break; case 'markets': this.site_params = { "site_name":"RealClearMarkets", "title":"Welcome to RCM Notifications", "icon":"/web_notifications/icons/default_icons/rcm_default.png", "notif_preview":"https://util.realclearpolitics.com/web_notifications/images/notification_rcm.png", "manifest_file":"https://www.realclearpolitics.com/asset/vertical/rcp/manifest.json" }; break; case 'defense': this.site_params = { "site_name":"RealClearDefense", "title":"Welcome to RCD Notifications", "icon":"/web_notifications/icons/default_icons/rcd_default.png", "notif_preview":"https://util.realclearpolitics.com/web_notifications/images/notification_rcd.png", "manifest_file":"https://www.realclearpolitics.com/asset/vertical/rcp/manifest.json" }; break; case 'energy': this.site_params = { "site_name":"RealClearEnergy", "title":"Welcome to RCE Notifications", "icon":"/web_notifications/icons/default_icons/rce_default.png", "notif_preview":"https://util.realclearpolitics.com/web_notifications/images/notification_rce.png", "manifest_file":"https://www.realclearpolitics.com/asset/vertical/rcp/manifest.json" }; break; case 'science': this.site_params = { "site_name":"RealClearScience", "title":"Welcome to RCS Notifications", "icon":"/web_notifications/icons/default_icons/rcs_default.png", "notif_preview":"https://util.realclearpolitics.com/web_notifications/images/notification_rcs.png", "manifest_file":"https://www.realclearpolitics.com/asset/vertical/rcp/manifest.json" }; break; case 'religion': this.site_params = { "site_name":"RealClearReligion", "title":"Welcome to RCR Notifications", "icon":"/web_notifications/icons/default_icons/rcr_default.png", "notif_preview":"https://util.realclearpolitics.com/web_notifications/images/notification_rcr.png", "manifest_file":"https://www.realclearpolitics.com/asset/vertical/rcp/manifest.json" }; break; case 'education': this.site_params = { "site_name":"RealClearEducation", "title":"Welcome to RCED Notifications", "icon":"/web_notifications/icons/default_icons/rced_default.png", "notif_preview":"https://util.realclearpolitics.com/web_notifications/images/notification_rced.png", "manifest_file":"https://www.realclearpolitics.com/asset/vertical/rcp/manifest.json" }; break; case 'sports': this.site_params = { "site_name":"RealClearSports", "title":"Welcome to RCSP Notifications", "icon":"/web_notifications/icons/default_icons/rcsp_default.png", "notif_preview":"https://util.realclearpolitics.com/web_notifications/images/notification_rcsp.png", "manifest_file":"https://www.realclearpolitics.com/asset/vertical/rcp/manifest.json" }; break; case 'history': this.site_params = { "site_name":"RealClearHistory", "title":"Welcome to RCHI Notifications", "icon":"/web_notifications/icons/default_icons/rchi_default.png", "notif_preview":"https://util.realclearpolitics.com/web_notifications/images/notification_rchi.png", "manifest_file":"https://www.realclearpolitics.com/asset/vertical/rcp/manifest.json" }; break; case 'books': this.site_params = { "site_name":"RealClearBooks", "title":"Welcome to RCB Notifications", "icon":"/web_notifications/icons/default_icons/rcb_default.png", "notif_preview":"https://util.realclearpolitics.com/web_notifications/images/notification_rcb.png", "manifest_file":"https://www.realclearpolitics.com/asset/vertical/rcp/manifest.json" }; break; case 'investigations': this.site_params = { "site_name":"RealClearInvestigations", "title":"Welcome to RCI Notifications", "icon":"/web_notifications/icons/default_icons/rci_default.png", "notif_preview":"https://util.realclearpolitics.com/web_notifications/images/notification_rci.png", "manifest_file":"https://www.realclearpolitics.com/asset/vertical/rcp/manifest.json" }; break; case 'policy': this.site_params = { "site_name":"RealClearPolicy", "title":"Welcome to RCPO Notifications", "icon":"/web_notifications/icons/default_icons/rcpo_default.png", "notif_preview":"https://util.realclearpolitics.com/web_notifications/images/notification_rcpo.png", "manifest_file":"https://www.realclearpolitics.com/asset/vertical/rcp/manifest.json" }; break; default: this.site_params = { "site_name":"RealClearPolitics", "title":"Welcome to RCP Notifications", "icon":"/web_notifications/icons/default_icons/rcp_default.png", "notif_preview":"https://util.realclearpolitics.com/web_notifications/images/notification_rcp.png", "manifest_file":"https://www.realclearpolitics.com/asset/vertical/rcp/manifest.json" }; break; } } //manifest file added to head //used for old chrome versions using GCM notifications notifs.append_manifest_file = function(){ var link = document.createElement('link'); link.rel = 'manifest'; link.href = this.site_params.manifest_file; document.head.appendChild(link); } //called to unregister the user from notifications notifs.unregister = function() { _gaq.push(['_trackEvent', 'Notifications', 'Click', 'Triggered Disabling Notifications', null, true]); navigator.serviceWorker.ready.then(function(serviceWorkerRegistration) { // To unsubscribe from push messaging, you need get the // subcription object, which you can call unsubscribe() on. serviceWorkerRegistration.pushManager.getSubscription().then( function(subscription) { // Check we have a subscription to unsubscribe if (!subscription) { // No subscription object, so set the state // to allow the user to subscribe to push return; } // Make a request to the server to remove // the users data from your data store so you // don't attempt to send them push messages anymore notifs.sub_object = subscription; notifs.un_save(); //this removes all services workers. We don't want to do that though. /*navigator.serviceWorker.getRegistrations().then(function(registrations){ for(let registration of registrations) { //console.log(registration); registration.unregister(); } });*/ // We have a subcription, so call unsubscribe on it subscription.unsubscribe().then(function() { _gaq.push(['_trackEvent', 'Notifications', 'Click', 'User manually unsubscribed', null, true]); }). catch (function(e) { // We failed to unsubscribe, this can lead to // an unusual state, so may be best to remove // the subscription id from your data store and // inform the user that you disabled push var response = 'There was an error while unsubscribing you. Error: ' + e; notifs.show_response(response, 'error'); }); }). catch (function(e) { var response = 'There was an error while unsubscribing you. Error: ' + e; notifs.show_response(response, 'error'); }); }); } //change the status on our system to unsubscribed notifs.un_save = function(){ this.set_params(0); //console.log(this.subscription); fetch('https://util.realclearpolitics.com/web_notifications/paramsv2.php', { method: 'post', body: JSON.stringify(this.subscription) }).then(function(response) { return response.json(); }).then(function(json) { var response = ''; var type = ''; if (json.result == 'ok') { response = 'You have been removed from receiving notifications.'; type = 'success'; notifs.enabled = false; eraseCookie('notif_sub'); createCookie('notif_sub_removed', 'removed', '365'); } else { response = 'Sorry, there was an issue removing you.'; type = 'error'; notifs.enabled = false; } //console.log(typeof notifs.options); if (typeof notifs.options != 'undefined') { for (var i in notifs.options) { //console.log(i); $('#' + i + '_cb').prop('checked', false); } }else{ $('.nt_list').hide(); } $('#notif_cb').prop('checked', false); $('#action_spinnner').hide(); notifs.show_response(response, type); }). catch (function(e) { notifs.show_response('There was an error unsubscribing you. Please try again. Error: ' + e, 'error'); }); } //registers the services worker to browser and calles the sign up for notifications function //if ad block is on then it shows a message telling the user to unenable ad block notifs.register = function() { if(this.new_subscription == true){ _gaq.push(['_trackEvent', 'Notifications', 'Click', 'Triggered Enabling Notifications', null, true]); }else{ _gaq.push(['_trackEvent', 'Notifications', 'Auto', 'Resubscribe User registration', null, true]); } //console.log('notifications register service worker and notifications'); // if ( typeof Utils.global_settings.realclear_ad_block_check !== 'undefined' // && Utils.global_settings.realclear_ad_block_check === true // && this.new_subscription === true ){ // //console.log('adblock'); // eraseCookie('warning_notif_underlay'); // eraseCookie('warning_ad_block_enabled'); // warning_widget.info_message = "ERROR: Unable to subscribe to notifications if you have Ad Block on. Please disable your Ad Block plugin for our site, refresh page and try again."; // warning_widget.warning_template(); // $('.warning-wrapper').show(); // } else { //console.log('notification'); $('.warning-wrapper').hide(); this.show_response('Subscribing you. Please wait.', 'warning'); navigator.serviceWorker.register('/service-worker.js') .then(function(reg) { if(notifs.new_subscription == true){ _gaq.push(['_trackEvent', 'Notifications', 'Click', 'Service Worker Installed', null, true]); }else{ _gaq.push(['_trackEvent', 'Notifications', 'Auto', 'Service Worker ReInstalled', null, true]); } notifs.sign_up_for_notifs(); }); // } } notifs.sign_up_success = function() {} notifs.sign_up_fail = function() {} notifs.options_ready = function() {} //after service worker installed this subscribes the user to notifications notifs.sign_up_for_notifs = function() { if(Notification.permission == 'default'){ $(notifs.overlay()).appendTo('body'); $('#notification_overlay').show(); } console.log('calling serviceworker.ready.then'); console.log(navigator.serviceWorker.ready); navigator.serviceWorker.ready.then(function(serviceWorkerRegistration) { console.log('inside serviceworker.ready.then'); console.log(serviceWorkerRegistration); console.log('pub_key: '+notifs.pub_key); serviceWorkerRegistration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: notifs.urlBase64ToUint8Array(notifs.pub_key) }) .then(function(subscription) { console.log('inside serviceWorkerRegistration.pushManager.subscribe then'); notifs.sign_up_success(); notifs.sub_object = subscription; notifs.save(); $('#notification_overlay').hide(); notifs.enabled = true; if(notifs.new_subscription == true){ _gaq.push(['_trackEvent', 'Notifications', 'Click', 'User subscribed', null, true]); }else{ _gaq.push(['_trackEvent', 'Notifications', 'Auto', 'User Resubscribed', null, true]); } }). catch (function(e) { console.log('inside serviceWorkerRegistration.pushManager.subscribe catch'); notifs.sign_up_fail(); $('#action_spinnner').hide(); $('#notif_cb').prop('checked', false); eraseCookie('warning_notif_underlay'); if (Notification.permission === 'denied') { // The user denied the notification permission which // means we failed to subscribe and the user will need // to manually change the notification permission to // subscribe to push messages var response = 'Notifications have been blocked on your browser. Please enable them on your browser and refresh the page.'; response += '

Error from browser if any: '+e; var notif_settings_url = ""; if (navigator.browserInfo.browser == 'Chrome') { notif_settings_url = "chrome://settings/content?search=notifications"; response += '

\ Copy this url and paste in a new window or tab ' + notif_settings_url + ' on your browser. \ Find ' + window.location.hostname + ' click on "Block" to the right and select "Allow".\

After this refresh this page and you\'ll be able to enable notifications from us.'; }else if(navigator.browserInfo.browser == 'Firefox'){ notif_settings_url = "about:preferences#content"; response += '\

\ Copy this url and paste in a new window or tab ' + notif_settings_url + ' on your browser.
\ To the right of Notifications click on "Choose". In the overlay menu find ' + window.location.hostname + ' and click on it.
\ Below there is button that says "Remove". Click on it and then save your changes.\

After this, refresh this page and you\'ll be able to enable notifications from us.\ '; }else if(navigator.browserInfo.browser == 'Opera'){ notif_settings_url = "opera://settings/contentExceptions?search=notifications#notifications"; response += '

\ Copy this url and paste in a new window or tab ' + notif_settings_url + ' on your browser. \ Find ' + window.location.hostname + ' click on "Block" to the right and select "Allow". Click "Done".\

After this refresh this page and you\'ll be able to enable notifications from us.'; } if(notifs.new_subscription == true){ _gaq.push(['_trackEvent', 'Notifications', 'Click', 'User browser denied notifications. '+e, null, true]); }else{ _gaq.push(['_trackEvent', 'Notifications', 'Auto', 'User browser denied notifications. '+e, null, true]); } } else { // A problem occurred with the subscription, this can // often be down to an issue or lack of the gcm_sender_id // and / or gcm_user_visible_only var response = 'Unable to subscribe. Reason: ' + e; var browser = navigator.browserInfo.browser; var version = navigator.browserInfo.version; var operating_sys = navigator.osInfo.os; if(notifs.new_subscription == true){ _gaq.push(['_trackEvent', 'Notifications', 'Click', 'User subscription error: '+e+' | adblock: '+Utils.global_settings.realclear_ad_block_check, null, true]); _gaq.push(['_trackEvent', 'Notifications', 'Click', 'User subscription error: '+e+' | '+browser+' | '+version+' | '+operating_sys, null, true]); }else{ _gaq.push(['_trackEvent', 'Notifications', 'Auto', 'User subscription error: '+e+' | adblock: '+Utils.global_settings.realclear_ad_block_check, null, true]); _gaq.push(['_trackEvent', 'Notifications', 'Auto', 'User subscription error: '+e+' | '+browser+' | '+version+' | '+operating_sys, null, true]); } } response += '

If you are browsing on private mode or incognito then notifications will not work.'; response += '

If you have an old version of your browser we would recommend updating it and trying again.'; response += '

Click the checkbox below to try again.'; if(notifs.new_subscription == true || notifs.landing_page == true){ $('#notification_overlay').hide(); $('#pop_up_success_title').hide(); $('#pop_up_fail_title').show(); $('#overlay_notif_pop_up').show(); $('.nt_form').show(); notifs.show_response(response, 'error'); } }); }); } //if user has granted permission to notifications then check if their subscriptin is still valid //if it isn't valid hit the register function again notifs.check_registration = function() { var unsub_cook = readCookie('notif_sub_removed'); //console.log(unsub_cook); if (!unsub_cook) { if (navigator.serviceWorker.controller == null) { //console.log('no service worker'); _gaq.push(['_trackEvent', 'Notifications', 'Auto', 'Resubscribe User: No Service Worker', null, true]); this.register(); notifs.form(); } else { navigator.serviceWorker.ready.then(function(serviceWorkerRegistration) { //console.log(serviceWorkerRegistration); if (!serviceWorkerRegistration) { //console.log('bad service worker'); _gaq.push(['_trackEvent', 'Notifications', 'Auto', 'Resubscribe User: No Service Worker', null, true]); notifs.register(); notifs.form(); } else { serviceWorkerRegistration.pushManager.getSubscription() .then(function(subscription) { //console.log(subscription); if (!subscription) { //console.log('bad subscription'); _gaq.push(['_trackEvent', 'Notifications', 'Auto', 'Resubscribe User: No Push Subscription', null, true]); notifs.register(); notifs.form(); } else { /*if(typeof subscription.expirationTime !== 'undefined'){ console.log(subscription.expirationTime); }*/ notifs.sub_object = subscription; console.log(subscription); notifs.enabled = true; var cookie_sub = readCookie('notif_sub'); var endpointSections = subscription.endpoint.split('/'); var subscriptionId = endpointSections[endpointSections.length - 1]; //console.log(cookie_sub); //console.log(subscriptionId); if (cookie_sub != subscriptionId) { _gaq.push(['_trackEvent', 'Notifications', 'Auto', 'Resubscribe User: Subscription ID Changed', null, true]); notifs.save(); notifs.form(); } else { //checks to see if subscription still valid by cron //turned off for now. //Waiting on future test to see if needed. //notifs.check_subscription(cookie_sub, subscription); notifs.set_params(1); notifs.form(); } } }). catch (function(e) { //console.log('serviceWorkerRegistration.pushManager failed '+e); _gaq.push(['_trackEvent', 'Notifications', 'Auto', 'Resubscribe User: No Push Subscription '+e, null, true]); notifs.register(); notifs.form(); }); } }). catch (function(e) { //console.log('navigator.serviceWorker.ready failed '+e); _gaq.push(['_trackEvent', 'Notifications', 'Auto', 'Resubscribe User: No Service Worker '+e, null, true]); notifs.register(); notifs.form(); }); } } else { notifs.form(); } } //this is a future fix notification to check our system if subscription is good //not used right now notifs.check_subscription = function(cookie_sub, subscription) { fetch('https://util.realclearpolitics.com/web_notifications/sub_check.php', { method: 'post', body: JSON.stringify({ 'sub_id': cookie_sub }) }).then(function(response) { //console.log(response); return response.json(); }).then(function(json) { //console.log(json); if (parseInt(json.count) == 0) { notifs.save(); } }); } //save subscription to our system //also displays the html if new subscription or on landing page notifs.save = function() { this.set_params(1); //console.log(this.subscription); fetch('https://util.realclearpolitics.com/web_notifications/paramsv2.php', { method: 'post', body: JSON.stringify(this.subscription) }).then(function(response) { return response.json(); }).then(function(json) { var response = ''; var type = ''; if (json.result == 'ok') { response = 'Congrats! You have been added to receive notifications.'; type = 'success'; notifs.enabled = true; //var welcome_notif = readCookie('welcome_notif'); //var notif_sub = readCookie('notif_sub'); if(notifs.new_subscription == true){ notifs.send_welcome_notif(); } eraseCookie('notif_sub'); createCookie('notif_sub', notifs.subscription.sub_id, '365'); eraseCookie('notif_sub_removed'); } else { response = 'Sorry, there was an issue adding you.'; type = 'error'; notifs.enabled = false; } $('#notif_cb').prop('checked', true); $('#action_spinnner').hide(); if(notifs.new_subscription == true || notifs.landing_page == true){ notifs.get_segments(); } if(notifs.new_subscription == true){ if(notifs.form_html_inserted == false){ notifs.form(); } notifs.new_subscription = false; if(notifs.on_dashboard == false){ $('#overlay_notif_pop_up').show(); $('.nt_form').show(); } } notifs.show_response(response, type); }). catch (function(e) { notifs.show_response('There was an error subscribing you. Please try again. Error: ' + e, 'error'); }); } //if new subscription send welcome notification notifs.send_welcome_notif = function(){ var welcome = { "title":this.site_params.title, "body":"You have successfully enabled push notifications. Thanks for subscribing!", "tag": "welcome_to_notications", "redirect":window.location.origin, "site":this.subscription.site, "icon":this.site_params.icon, "endpoint":this.subscription.endpoint + this.subscription.sub_id, "p256dh":this.subscription.p256dh, "auth":this.subscription.auth, "sub_id":this.subscription.sub_id }; fetch('https://util.realclearpolitics.com/web_notifications/welcome_notif.php', { method: 'post', body: JSON.stringify(welcome) }).then(function(response){ return response.json(); }).then(function(json){ createCookie("welcome_notif", "Welcome Notification Sent", 365); }); } //when saving subscription for registering or unregistering, //this sets the subscription object to send to our system notifs.subscription_ready = function() {} notifs.set_params = function(status) { var subscription = this.sub_object; this.subscription.ip_referer = ""; $.getJSON("https://api.ipify.org?format=jsonp&callback=?",function(json) { notifs.subscription.ip_referer = json.ip; }); //console.log(subscription); var json_sub; var sub; //console.log(subscription); //console.log(typeof subscription); if(typeof subscription !== 'undefined'){ json_sub = JSON.stringify(subscription); } //console.log(json_sub); //console.log(typeof json_sub); if(typeof json_sub === 'string' && typeof json_sub !== 'undefined'){ sub = JSON.parse(json_sub); }else if(typeof json_sub === 'object' && typeof json_sub !== 'undefined'){ sub = json_sub; } //console.log(sub); //console.log(typeof sub); if(typeof sub.keys === 'undefined' || typeof sub.keys.p256dh === 'undefined' || typeof sub.keys.auth === 'undefined'){ sub = JSON.parse(subscription.toJSON()); } var endpoint = sub.endpoint; //console.log(sub); // Chrome 42 + 43 will not have the subscriptionId attached to the endpoint. if (navigator.browserInfo.browser == 'Chrome' && (navigator.browserInfo.version == '42' || navigator.browserInfo.version == '43')) { if (subscription.subscriptionId && subscription.endpoint.indexOf(subscription.subscriptionId) === -1) { // Handle version 42 where you have separate subId and Endpoint endpoint = subscription.endpoint + '/' + subscription.subscriptionId; } } var endpointSections = endpoint.split('/'); var subscriptionId = endpointSections[endpointSections.length - 1]; endpoint = endpoint.replace(subscriptionId, ''); var date_data = new Date; this.subscription.endpoint = endpoint; this.subscription.sub_id = subscriptionId this.subscription.browser = navigator.browserInfo.browser; this.subscription.version = navigator.browserInfo.version; this.subscription.referer = window.location.href; this.subscription.origin = window.location.origin; this.subscription.time = date_data.getTime(); this.subscription.status = status; this.subscription.p256dh = sub.keys.p256dh; this.subscription.auth = sub.keys.auth; this.subscription.gmt_offset = date_data.toString().match(/([A-Z]+[\+-][0-9]+)/)[1]; this.subscription.timezone = date_data.toString().match(/\(([A-Za-z\s].*)\)/)[1]; this.subscription.userAgent = navigator.userAgent; if(Utils.global_settings.device_detect_loaded == false){ Utils.append_device_file(); this.set_params(status); return; } this.subscription.alternate_device = ""; this.subscription.form_factor = ""; this.subscription.is_mobile = ""; if(typeof window.WURFL == 'object'){ this.subscription.alternate_device = WURFL.complete_device_name; this.subscription.form_factor = WURFL.form_factor; this.subscription.is_mobile = WURFL.is_mobile; } if(typeof this.subscription.user_id != 'undefined' && this.subscription.user_id != null && typeof this.subscription.user_id == 'number' && this.subscription.user_id > 0){ //user_id has been set already so do nothing }else{ //get the user id from realclear_user cookie var user_id = readCookie('realclear_user'); //console.log('USER ID: '+user_id); if(user_id && user_id != null && typeof user_id == 'string' && user_id.length > 0){ //console.log('user_id good'); this.subscription.user_id = parseInt(user_id); }else{ //console.log('user_id bad'); this.subscription.user_id = 0; } } notifs.subscription_ready(); } //this puts the html into the page. //Checks if on the landing page for subscriptions //else appends the pop up to the body of the page notifs.form = function() { //check if were on static, which is the body class for the pages system if ($('body').hasClass('static')) { //append content only after this javascript file itself. If not found then nothing is appended. var scripts = document.getElementsByTagName('script'); var regex = /.*notifications\.([^/]+\.)?js/; //looks for investigations.js in script tags for (var i = 0; i < scripts.length; i++) { //loops through all script tags in page var this_script = scripts[i]; if (this_script.src.match(regex)) { if(notifs.landing_page == false){//so content is only loaded in once $(this_script).after(''); notifs.landing_page = true; //temporary to get landing page working on defense if(notifs.subscription.site == 'defense'){ notifs.notifs_work = true; notifs.valid_os = true; notifs.valid_browser = true; } if (notifs.notifs_work == true) { $(this_script).after(notifs.landing_page_content()); notifs.form_html_inserted = true; notifs.set_form_values(); } else { notifs.check_ready = true; console.log('ready_to_be_checked ::: 2'); notifs.ready_to_be_checked(); $(this_script).after(notifs.landing_page_content()); notifs.form_html_inserted = true; $('#notif_cb').prop('disabled', true); $('.nt_form').show(); if ( notifs.valid_os == false && notifs.valid_browser == false ) { notifs.show_response('Sorry, notifications do not work on your browser and operating system. Notifications work on Chrome, Firefox or Opera browsers and on Windows, MacOS, Android and Linux.', 'error'); } else if (notifs.valid_browser == false) { notifs.show_response('Sorry, notifications do not work on your browser. Notifications work on Chrome, Firefox or Opera.', 'error'); } else if (notifs.valid_os == false) { notifs.show_response('Sorry, notifications do not work on your operating system. Notifications work on Windows, MacOS, Android and Linux.', 'error'); } } } } } if (notifs.landing_page == false && notifs.notifs_work == true) { $( notifs.sign_up_pop_up() ).appendTo('body'); notifs.form_html_inserted = true; notifs.set_form_values(); } } else if(notifs.notifs_work == true){ $( notifs.sign_up_pop_up() ).appendTo('body'); notifs.form_html_inserted = true; notifs.set_form_values(); } if(notifs.subscription.site != 'politics'){ $('#polling_alerts_li').hide(); } } //sets the status and values of the check boxes in the sign up pages //also sets event listeners to the checkboxes and closing pop up notifs.set_form_values = function() { if (this.denied == false) { if (this.enabled == true ) { $('#notif_cb').prop('checked', true); this.show_response('You are already subscribed. See below the type of notifications you\'re subscribed to.', 'success'); if(this.new_subscription == true || this.landing_page == true){ this.get_segments(); } } $(document).on('click', '.notif_action', function(event) { var value = event.target.value; if (value != 'notif') { var want = 0; if (event.target.checked == true) { want = 1; } notifs.set_segment(value, want); } else { if (event.target.checked == true) { $('#action_spinnner').show(); notifs.register(); } else { $('#action_spinnner').show(); notifs.unregister(); } } }); if(this.landing_page == true){ $('.nt_form').show(); } notifs.check_ready = true; console.log('ready_to_be_checked ::: 3'); console.log('notifs.enabled: '+notifs.enabled); notifs.ready_to_be_checked(); } else { this.show_response('Notifications are blocked. Change browser settings to ask or allow and try again.', 'error'); $('#notif_cb').prop('disabled', true); if(this.landing_page == true){ $('.nt_form').show(); } notifs.check_ready = true; console.log('ready_to_be_checked ::: 4'); notifs.ready_to_be_checked(); } $(document).on('click', '.close_notifications_pop_up', function(){ $('#overlay_notif_pop_up').hide(); }); } //gets the current subscription segment types for a specific user from our system notifs.get_segments = function() { fetch('https://util.realclearpolitics.com/web_notifications/segments.php?get=1', { method: 'post', body: JSON.stringify({ 'sub_id': this.subscription.sub_id }) }).then(function(response) { return response.json(); }).then(function(json) { notifs.options = json; notifs.options_ready(); for (var i in json) { if (parseInt(json[i]) == 1) { $('#' + i + '_cb').prop('checked', true); } else { $('#' + i + '_cb').prop('checked', false); } } $('.nt_list').show(); $('.nt_form').show(); }); } //sets a current segment to on or off notifs.set_segment = function(segment, want) { fetch('https://util.realclearpolitics.com/web_notifications/segments.php?set=1', { method: 'post', body: JSON.stringify({ 'sub_id': this.subscription.sub_id, 'segment': segment, 'want': want }) }).then(function(response) { return response.json(); }).then(function(json) { notifs.options = json; if (want == 1) { notifs.show_response('Notification type added.', 'success'); } else { notifs.show_response('Notification type removed.', 'success'); } }). catch (function(e) { notifs.show_response('Error submitting your change. Error: ' + e, 'error'); }); } //function to display responses of things to users notifs.show_response = function(str, type) { var el = $('#notif_response'); el.removeClass(); if (typeof type !== 'undefined') { el.addClass(type); el.attr('style', 'opacity:1;'); } el.attr('data-next', str); if (parseInt(el.css('opacity')) != 0) { el.fadeOut(250, function() { $(this).html($(this).attr('data-next')); $(this).fadeIn(250); }); } else { el.html(str); el.attr('style', 'opacity:1;'); } } //landing page content notifs.landing_page_content = function() { if(typeof this.site_params == 'undefined'){ this.set_site_params(); } var html = ""; html += '\ \


'; return html; } //pop up content notifs.sign_up_pop_up = function(){ return '\ \ '; } //check boxes used for both landing page and pop up notifs.check_boxes = function() { return '\
 
\ \
    \
  • \ \
  • \
  • \ \
  • \
  • \ \
  • \
  • \ \
  • \
'; } //overlay to show if user is on "ask" status of notifications notifs.overlay = function(){ return '\ '; } notifs.check_ready = false; notifs.ready_to_be_checked = function(){} //notifications entry point //checks whether notifications works //if they don't work then check for ad code or ad block //if they work, check the notification permision status //if granted then try to resubscribe user, insert html to DOM and check for ad code and ad blocks //if on "ask" then insert html to DOM for subscribing //if denied then append html to DOM and in case user tries to subscribe let them know how to enable notifications notifs.check_notif_status = function() { //checks if notifications work on the current browser and OS this.check_if_notifs_work(); //check if referred by a newsletter email link and if so set yearly cookie warning_widget.check_for_newsletter_referer(); //if so, go here //console.log('ad block check final: '+Utils.global_settings.realclear_ad_block_check); if (this.notifs_work == true) { //A. A. Temporary fix to enable resubscribe users if (Notification.permission == 'granted') { this.new_subscription = false; console.log('Notifications check registration'); //appends manifest file for notifications to head this.append_manifest_file(); this.check_registration(); }else{ if( $('body').hasClass('static') ){ notifs.form(); } } //inserts inline sign up widget inline_widget.insert_widget_into_page(); return; //appends manifest file for notifications to head this.append_manifest_file(); //inserts inline sign up widget inline_widget.insert_widget_into_page(); if(typeof Utils.global_settings.realclear_ad_block_check !== 'undefined' && Utils.global_settings.realclear_ad_block_check === true){ var warning_underlay = readCookie('warning_underlay'); if(!warning_underlay){ createCookie('warning_underlay', 'temp', 6, true); warning_widget.warning_template(); } notifs.form(); console.log(notifs.enabled); notifs.check_ready = true; console.log('ready_to_be_checked ::: 1'); notifs.ready_to_be_checked(); }else if (Notification.permission == 'granted') { this.new_subscription = false; //console.log('re register'); this.check_registration(); //check for ad code here // else check for newsletter cookie, if not present display newsletter sign up var warning_underlay = readCookie('warning_underlay'); if(!warning_underlay){ var warning_newsletter_underlay = readCookie('warning_newsletter_underlay'); if(!warning_newsletter_underlay){ createCookie('warning_underlay', 'temp', 12, true); warning_widget.set_newslettter_sign_up(); } } console.log(notifs.enabled); } else if (Notification.permission == 'default' || Notification.permission == 'denied') { //console.log('register'); if(Notification.permission == 'denied'){ this.denied = true; this.new_subscription = false; } var warning_underlay = readCookie('warning_underlay'); if(!warning_underlay){ var warning_notif_underlay = readCookie('warning_notif_underlay'); var warning_newsletter_underlay = readCookie('warning_newsletter_underlay'); if(!warning_notif_underlay){ createCookie('warning_underlay', 'temp', 11, true); warning_widget.set_notifications_sign_up(); }else if(!warning_newsletter_underlay){ createCookie('warning_underlay', 'temp', 11, true); warning_widget.set_newslettter_sign_up(); } } notifs.form(); } //if not so, go here } else { //inserts inline sign up widget inline_widget.insert_widget_into_page(); if(this.subscription.site == 'politics' || this.subscription.site == 'markets'){ return; } //check for ad code here if(typeof Utils.global_settings.realclear_ad_block_check !== 'undefined' && Utils.global_settings.realclear_ad_block_check === true){ var warning_underlay = readCookie('warning_underlay'); if(!warning_underlay){ createCookie('warning_underlay', 'temp', 6, true); warning_widget.warning_template(); } }else{ var warning_underlay = readCookie('warning_underlay'); if(!warning_underlay){ var warning_newsletter_underlay = readCookie('warning_newsletter_underlay'); if(!warning_newsletter_underlay){ createCookie('warning_underlay', 'temp', 12, true); warning_widget.set_newslettter_sign_up(); } } } if( $('body').hasClass('static') ){ notifs.form(); } } } //run notifications entry point when DOM ready //also run inline check for inline widget $(document).ready(function(){ warning_widget.interval_id = 0; if(notifs.subscription.site === 'politics'){ //console.log('checking ad block'); warning_widget.interval_id = window.setInterval(function(){ //console.info('Interval Ran. Ad_Block_Ready: '+warning_widget.ad_block_ready_for_check+' isAdBlockActive: '+Utils.global_settings.realclear_ad_block_check); //console.info('(**********************************************************************************************************)'); if(warning_widget.ad_block_ready_for_check === true){ //console.log('ad block check done'); clearInterval( warning_widget.interval_id ); notifs.check_notif_status(); } },250); }else{ warning_widget.check_ad_block_status(); /*setTimeout(function(){ notifs.check_notif_status(); },2000);*/ } }); //////////////////////////////////////////////////////////////////////////////// // TEMPSHOW LIBRARY //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /* Tempshow js notification library * v1.0 (c) 2018 RealClear */ window.Tempshow = function() { this.default = { width: '300px', // any css width unit horizontal: 'right', // left, center, right vertical: 'top', // top, center, bottom type: 'info', // warning, info, success, fail, or custom seconds: 10, // default seconds until removed msg: '', // message string }; this.remove_timeouts = []; this.template = '
' + '
{{msg}}
' + '
X
' + '
'; this.generate_id = function() { return Math.floor(Math.random() * Math.floor(9999999999)); }; this.create = function(new_options) { var html = this.template; // Apply options var options = this.default; for (var property in new_options) { if (new_options.hasOwnProperty(property)) { options[property] = new_options[property]; } } html = html.replace('{{msg}}', options.msg); html = html.replace('{{type}}', options['type']); html = html.replace('{{horizontal}}', options.horizontal); html = html.replace('{{vertical}}', options.vertical); html = html.replace('{{width}}', options['width']); var notif_id = this.generate_id(); html = html.replace('{{notif_id}}', notif_id); // Add new notification document.body.insertAdjacentHTML('beforeend', html); // Add click removal var exit_btn = document.querySelector('#tempshow_notif_'+notif_id+' .exit'); this.addEvent(exit_btn, 'click', function() { parent.remove_existing(notif_id); }.bind(parent = this, notif_id)); // Start removal timeout this.remove_timeouts.push(window.setTimeout(function() { parent.remove_existing(notif_id); }.bind(parent = this, notif_id), options.seconds * 1000)); }; this.remove_existing = function(notif_id) { // If 'animations' available in browser, do animation then remove at end of animation // If not available, just remove it right away var existing = document.querySelector('#tempshow_notif_'+notif_id); if(existing !== null) { if(this.isAnimationSupported()) { if( !this.hasClass(existing, 'remove') ) { transitionEndEventNames.forEach( function(evt) { existing.addEventListener(evt, function() { existing.parentNode.removeChild(existing); }.bind(existing), false); }.bind(existing)); this.addClass(existing, 'remove'); } } else { existing.parentNode.removeChild(existing); } } }; // UTILITY this.addClass = function(el, className) { if (el.classList) el.classList.add(className); else if (!hasClass(el, className)) el.className += ' ' + className; }; this.hasClass = function(el, className) { return el.classList ? el.classList.contains(className) : new RegExp('\\b'+ className+'\\b').test(el.className); }; var transitionEndEventNames = [ 'animationend', 'webkitAnimationEnd', 'oAnimationEnd', 'MSAnimationEnd' ]; this.isAnimationSupported = function() { var thisBody = document.body || document.documentElement, thisStyle = thisBody.style, support = thisStyle.animation !== undefined || thisStyle.WebkitAnimation !== undefined || thisStyle.MozAnimation !== undefined || thisStyle.MsAnimation !== undefined || thisStyle.OAnimation !== undefined; return support; }; this.addEvent = function(el, type, handler) { if (el.attachEvent) el.attachEvent('on'+type, handler); else el.addEventListener(type, handler); }; }; //////////////////////////////////////////////////////////////////////////////// // EVOLOK LIBRARY ////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// if(SITE_INFO['evolok_enabled']) { /** * @license ev-em.min.js v3.2.10 * (c) 2015-2017 Evolok, Inc. http://www.evolok.com/ * * License: MIT */ window.EV=window.EV||{},function(o){"use strict";function t(){var e="Unknown";return navigator.userAgent.indexOf("MSIE")!=-1?e="MSIE":navigator.userAgent.indexOf("Firefox")!=-1?e="Firefox":navigator.userAgent.indexOf("Opera")!=-1?e="Opera":navigator.userAgent.indexOf("Chrome")!=-1?e="Chrome":navigator.userAgent.indexOf("Safari")!=-1&&(e="Safari"),e}function n(){void 0===v&&void 0===p||""===v&&""===p||(void 0!==v&&""!==v&&r("ev_sid")!=v&&(i("ev_sid",v,10),c("ev_sid",v,0,"localStorage"),m=m+"&ev_sid="+v),void 0!==p&&""!==p&&r("ev_did")!=p&&(i("ev_did",p,10),c("ev_did",p,0,"localStorage"),m=m+"&ev_did="+p))}function r(e){var o,t="; "+document.cookie,n=t.split("; "+e+"=");return 2==n.length?(o=n.pop().split(";").shift(),o=o.replace(/["'()]/g,"")):""}function i(e,o,t){if(!f.sidCookieDomain)throw new Error("Please specify sidCookieDomain in the config!",!0);var n=new Date;t=1460,n.setDate(n.getDate()+t),document.cookie=e+"="+escape(o)+(null===t?"":";expires="+n.toUTCString())+";path=/; domain="+f.sidCookieDomain,console.log(e+"="+escape(o)+(null===t?"":";expires="+n.toUTCString())+";path=/; domain="+f.sidCookieDomain)}function a(e){return""!==r(e)&&"undefined"!==r(e)?r(e):void 0}function s(e){return""!==l(e,"localStorage")&&"undefined"!==l(e,"localStorage")?l(e,"localStorage"):void 0}function d(){if(!f)throw"Evolok Metering library is not initialised!"}function l(e,o){var t=document.cookie.indexOf(e+"=");return"localStorage"==o?"undefined"!=typeof localStorage?localStorage.getItem(e):document.cookie.length>0&&t!==-1?getCookieSubstring(t,e):"":"sessionStorage"==o?"undefined"!=typeof sessionStorage?(console.log(sessionStorage.getItem(e)),sessionStorage.getItem(e)):(t=document.cookie.indexOf(e+"="),document.cookie.length>0&&t!==-1?getCookieSubstring(t,e):""):void 0}function c(e,o,t,n){var r=new Date;"localStorage"==n&&(r.setDate(r.getDate()+t),"undefined"!=typeof localStorage?localStorage.setItem(e,o):document.cookie=e+"="+escape(o)+(null===t?"":";expires="+r.toUTCString())),"sessionStorage"==n&&(r.setDate(r.getDate()+t),"undefined"!=typeof sessionStorage?sessionStorage.setItem(e,o):document.cookie=e+"="+escape(o)+(null===t?"":";expires="+r.toUTCString()))}function u(e){var o="";e=JSON.parse(e);for(var t in e)""!==o&&(o+="&"),o+=t+"="+encodeURIComponent(e[t]);return o}function g(e,o){d();var t=f.url;if(!t)throw new Error("Evolok Metering host url is not configured!");return t+="/"===t.charAt(t.length-1)&&"/"===e.charAt(0)?e.substring(1,e.length):e,t=o?t+"?"+o:t}var f,v,p,m,S;o.Em={init:function(e){if(!e.hasOwnProperty("url"))throw"Configuration must specify the url property!";f=e},authorize:function(e,t,n){o.Em.assert(e,"Parameters should not be empty!"),o.Em.assert(t,"Success callback should not be empty!"),o.Em.assert(n,"Error callback should not be empty!");var d=u(e),w="",h="",_="";m=d,a("ev_sid")?(h="&ev_sid="+r("ev_sid"),c("ev_sid",r("ev_sid"),0,"localStorage")):s("ev_sid")&&(f.hasOwnProperty("meterHD")?f.meterHD===!0&&(i("ev_sid",l("ev_sid","localStorage"),10),h="&ev_sid="+l("ev_sid","localStorage"),S=f.meterHD):i("ev_sid",l("ev_sid","localStorage"),10)),a("ev_did")?(_="&ev_did="+r("ev_did"),c("ev_did",r("ev_did"),0,"localStorage")):s("ev_did")&&(f.hasOwnProperty("meterHD")?f.meterHD===!0&&(i("ev_did",l("ev_did","localStorage"),10),_="&ev_did="+l("ev_did","localStorage")):i("ev_did",l("ev_did","localStorage"),10)),""!==r("ev_ss")&&(w+="&ev_ss="+r("ev_ss")),d=d+w+h+_;var y=g("/authorize/json",d),E=new XMLHttpRequest;E.open("GET",y,!0),E.withCredentials=!0,E.onload=function(){function e(e){var o;"function"==typeof CustomEvent?o=new CustomEvent("ev.ad.authorize",{detail:e}):(o=document.createEvent("CustomEvent"),o.initCustomEvent("ev.ad.authorize",!1,!1,e)),window.dispatchEvent(o)}if(E.status>=200&&E.status<400){var o=JSON.parse(E.responseText);e(o),window.addEventListener("ev.widgets.paywall.load",function(){e(o)}),window.addEventListener("ev.widgets.notifier.load",function(){e(o)}),o.hasOwnProperty("sessionKeys")&&o.sessionKeys.hasOwnProperty("ev_sid")&&(v=o.sessionKeys.ev_sid),o.hasOwnProperty("sessionKeys")&&o.sessionKeys.hasOwnProperty("ev_did")&&(p=o.sessionKeys.ev_did),t(o)}else n&&n(E.status,E.responseText)},E.onerror=function(e){e?n(e):n(0,"unknown connection error")},E.send()},pretty_print:function(e){var t=/^( *)("[\w]+": )?("[^"]*"|[\w.+-]*)?([,[{])?$/gm,n=JSON.stringify(e,null,3).replace(/&/g,"&").replace(/\\"/g,""").replace(//g,">").replace(t,o.Em.replacer);return n="
"+n+"
"},replacer:function(e,o,t,n,r){var i="",a="",s="",d=o||"";return t&&(d=d+i+t.replace(/[": ]/g,"")+": "),n&&(d=d+('"'==n[0]?s:a)+n+""),d+(r||"")},get_cookie_local_storage:function(e){if("undefined"!=typeof localStorage)return localStorage.getItem(e);var o=document.cookie.indexOf(e+"=");return document.cookie.length>0&&o!==-1?getCookieSubstring(o,e):""},set_cookie_local_storage:function(e,o,t){var n=new Date;n.setDate(n.getDate()+t),"undefined"!=typeof localStorage?(alert("This place has local storage!"),localStorage.setItem(e,o)):document.cookie=e+"="+escape(o)+(null===t?"":";expires="+n.toUTCString())},segment:function(t,n,r){o.Em.assert(t,"Parameters should not be empty!"),o.Em.assert(n,"Success callback should not be empty!"),o.Em.assert(r,"Error callback should not be empty!");var i=u(t),a=g("/segment",i),s=new XMLHttpRequest;s.open("GET",a,!0),s.withCredentials=!0,s.onload=function(){if(s.status>=200&&s.status<400){var e=JSON.parse(s.responseText);n(e)}else r&&r(s.status,s.responseText)},s.onerror=function(){e?r(e):r(0,"unknown connection error")},s.send()},call_VerifyCookiesforSafari:function(){n()},get_Browser_Name:function(){var e="Unknown";return navigator.userAgent.indexOf("MSIE")!=-1?e="MSIE":navigator.userAgent.indexOf("Firefox")!=-1?e="Firefox":navigator.userAgent.indexOf("Opera")!=-1?e="Opera":navigator.userAgent.indexOf("Chrome")!=-1?e="Chrome":navigator.userAgent.indexOf("Safari")!=-1&&(e="Safari"),e},assert:function(e,o){if(!e){if(o=o||"Assertion failed","undefined"!=typeof Error)throw new Error(o);throw o}},getUrl:function(){return f.url}},"Safari"==t()?setTimeout(function(){n()},4e3):setTimeout(function(){n()},4e3)}(window.EV),function(){if(!window.EV.Em)throw new Error("Couldn't find the Evolok Metering library in the browser context!")}(); } //////////////////////////////////////////////////////////////////////////////// // EVOLOK NOTIFIERS //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /* * Module: Evolok Init Scripts - Notifiers/Modals * * Launch: 06.07.18 * */ if( typeof send_notifier_event != 'function' ){ //send ga events for all users => anonymous/logged in => upon accepting cookies/policies function send_notifier_event(data) { // EXAMPLE INPUT: /* { 'ge_action' : 'The What', 'ge_category' : 'High Level - Event Name', 'ge_label' : 'Descriptor/Values being tracked' 'ge_index' : INT/index/counter => would allow you to track which element out of many/locations 'ge_noninteraction' : Boolean => If empty/false(default) it would go again daily numbers/bounce rates("Intentional or NOT") } */ //Wrap event tracking call to prevent premature termination of this function. try{ _gaq.push(['_trackEvent', data['ge_category'], data['ge_action'], data['ge_label'], data['ge_index'], data['ge_noninteraction']]); //console.log('trackevent: '+data['ge_category']+' - '+data['ge_action']+' - '+data['ge_label']+' - '+data['ge_index']+' - '+data['ge_noninteraction']); } catch(err) {} } } $(document).ready(function(){ $(document).on('click', '.jQ_allow', function(){ $(".adblk-todo-wrapper").css({"display" : "block"}); }); $(document).on('click', '.jQ_close', function(){ $(".adblk-todo-wrapper").css({"display" : "none"}); }); $(document).on('click', '.jQ_buy', function(){ location.assign("//" + document.domain + "/subscriptions/index.html"); }); if(typeof window.EV !== 'undefined') { if(typeof EV.Event !== 'undefined'){ EV.Event.on("ev.notifier.opened", function(){ //Javascript functionality //console.log("::: AD WIDGET VISIBLE :::"); //run until bootstrap modal, "notifier", is visible - get heights, recalculate, reset modal position for all devices /*get_ev_modal_ht = setInterval(function(){ var notifier_ht = $(".modal-content").height(); var notifier_half_ht = (notifier_ht / 2); if( $("body.ev-modals").length > 0 ){ var vp_ht = $(window).height(); var vp = (vp_ht / 2); var modal_pos = (vp - notifier_half_ht); var modal_pos_reset = (modal_pos-20); $("body.ev-modals .modal").css({"top" : modal_pos_reset+"px"}); } clearInterval(get_ev_modal_ht); }, 300);*/ var notifier_segment; get_notifier_segment = setInterval(function(){ if( $(".offer-wrapper").length > 0 ){ notifier_segment = $(".offer-wrapper").data("segments"); check_send_ga_loaded = setInterval(function(){ if( typeof send_notifier_event == 'function' ){ var onload_notifier_data = { 'ge_action' : 'AD Widget - Notifier Viewed - ' + 'Segment: ' + notifier_segment, 'ge_category' : 'EV Subscriptions Notifier', 'ge_label' : 'Viewed URL: ' + window.location.href, 'ge_index' : null, 'ge_noninteraction' : true }; send_notifier_event(onload_notifier_data); createCookie('notifierSegment',notifier_segment,'365'); clearInterval(check_send_ga_loaded); } //if func() exists check }, 250); //2.5 Second Intervals clearInterval(get_notifier_segment); } }, 500); }); } } /* ADBLOCK AD WIDGET LOGIC */ $(document).on('focus', '#email', function(){ $(this).parents('.adb-clear-input form').addClass('focused'); //$(".agree_container label, .agree_container input").show('fast'); //$(".adb_agree_container label, .adb_agree_container input").css({ "display" : "inline !important" }); $(".adb_agree_container").css({ "display" : "inline-block" }); }); $(document).on('blur', '#email', function(){ if( $(this).val() == "" ){ $(this).parents('.adb-clear-input form').removeClass('focused'); } //$(".agree_container label, .agree_container input").hide('fast'); }); $(document).on('submit', '.adb-news-form', function(ev){ //$(".adb-news-form").submit(function(ev){ ev.preventDefault(); ev.stopPropagation(); if( !$('#adb-agree').is(':checked') ) { //I Agree MUST be checked alert("Please make sure I Agree is checked and your email address is entered."); return; // Don't allow form submission unless TOS checked } if( $("#email").val() == "" ){ //Email Cannot be Blank - JS Validation alert("Please Enter Email Address and Try Again."); return; //keeps form from submitting with empty value, hitting API, and failing } var user_email = $("#email").val(); //alert(email_address); var user_site = document.domain; user_site = user_site.replace("www1.", ""); user_site = user_site.replace("www.", ""); console.log("User LOC: ", user_site); rcmg_api_call('auto_signup_adblock_notifier', { user_email : user_email, site : user_site, loc : 'adblock-user-notifier-signup-' + SITE_INFO['name'] }, function(response) { //console.log("Response - no fail or succeed", response); if (response.data.mc_result == 'approved') { createCookie('two_weeks_adfree', '1', '14'); //valid for 2 weeks $(".adb-clear-input").last().html('
Thank you! You may now browse our site, Ad-Free, for the next 2 weeks!
'); } else { $(".adb-clear-input").last().html('
Oh No! Our records indicate you have previously or are currently signed up for this newsletter. You are not currently eligible for this offer.
'); } }); }); if(typeof window.EV !== 'undefined') { if(typeof EV.Event !== 'undefined'){ EV.Event.on("ev.notifier.opened", function(){ //Javascript functionality //console.log("::: AD WIDGET VISIBLE :::"); $(".back-to-top").css({ "z-index" : "0" }); get_modal_counts = setInterval(function(){ if( $(".offer-wrapper").length > 0 ){ var cur_count = parseInt($(".current-posts").html()); var total_count = $(".total-posts").html(); if( typeof total_count != "undefined" ){ var nLimit = parseInt(total_count.replace("*", "")); } if( cur_count >= nLimit ){ $(".current-posts").html(nLimit); get_ev_modal_ht = setInterval(function(){ var notifier_ht = $(".modal-content").height(); var notifier_half_ht = (notifier_ht / 2); if( $("body.ev-modals").length > 0 ){ var vp_ht = $(window).height(); var vp = (vp_ht / 2); var modal_pos = (vp - notifier_half_ht); var modal_pos_reset = (modal_pos-20); $("body.ev-modals .modal").css({"top" : modal_pos_reset+"px"}); /*$(document).mouseup(function(e) { var container = $(".modal"); //console.info("THIS IS HAPPENING:::: "); // if the target of the click isn't the container nor a descendant of the container if (!container.is(e.target) && container.has(e.target).length === 0) { //container.hide(); EV.Event.publish('ev.notifier.close'); $(".ev-modals .modal-backdrop").hide(); $(".adb-overlay").remove(); } });*/ } clearInterval(get_ev_modal_ht); }, 300); $("body").prepend('
'); $(".modal-header-markets .close").hide(); $(".adblk-todo span a").last().hide(); }else{ get_ev_modal_ht = setInterval(function(){ var notifier_ht = $(".modal-content").height(); var notifier_half_ht = (notifier_ht / 2); if( $("body.ev-modals").length > 0 ){ var vp_ht = $(window).height(); var vp = (vp_ht / 2); var modal_pos = (vp - notifier_half_ht); var modal_pos_reset = (modal_pos-20); $("body.ev-modals .modal").css({"top" : modal_pos_reset+"px"}); $("body.ev-modals .modal").css({ "width" : "100% !important", "height" : "100% !important" }); $(document).mouseup(function(e) { var container = $(".modal"); //console.info("THIS IS HAPPENING:::: "); // if the target of the click isn't the container nor a descendant of the container if (!container.is(e.target) && container.has(e.target).length === 0) { //container.hide(); EV.Event.publish('ev.notifier.close'); $(".ev-modals .modal-backdrop").hide(); } }); } clearInterval(get_ev_modal_ht); }, 300); } //end else } clearInterval(get_modal_counts); }, 300); }); } } //var cookieValue = document.cookie.replace(/(?:(?:^|.*;\s*)notifierSegment\s*\=\s*([^;]*).*$)|^.*$/, "$1"); }); //////////////////////////////////////////////////////////////////////////////// // COOKIE CONSENT LIBRARY ////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// if( fire_gdpr_consent ) { (function(cc) { // stop from running again, if accidently included more than once. if (cc.hasInitialised) return; var util = { // http://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex escapeRegExp: function(str) { return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&'); }, hasClass: function(element, selector) { var s = ' '; return element.nodeType === 1 && (s + element.className + s).replace(/[\n\t]/g, s).indexOf(s + selector + s) >= 0; }, addClass: function(element, className) { element.className += ' ' + className; }, removeClass: function(element, className) { var regex = new RegExp('\\b' + this.escapeRegExp(className) + '\\b'); element.className = element.className.replace(regex, ''); }, interpolateString: function(str, callback) { var marker = /{{([a-z][a-z0-9\-_]*)}}/ig; return str.replace(marker, function(matches) { return callback(arguments[1]) || ''; }) }, getCookie: function(name) { var value = '; ' + document.cookie; var parts = value.split('; ' + name + '='); return parts.length != 2 ? undefined : parts.pop().split(';').shift(); }, setCookie: function(name, value, expiryDays, domain, path) { var exdate = new Date(); exdate.setDate(exdate.getDate() + (expiryDays || 365)); var cookie = [ name + '=' + value, 'expires=' + exdate.toUTCString(), 'path=' + (path || '/') ]; if (domain) { cookie.push('domain=' + domain); } document.cookie = cookie.join(';'); }, // only used for extending the initial options deepExtend: function(target, source) { for (var prop in source) { if (source.hasOwnProperty(prop)) { if (prop in target && this.isPlainObject(target[prop]) && this.isPlainObject(source[prop])) { this.deepExtend(target[prop], source[prop]); } else { target[prop] = source[prop]; } } } return target; }, // only used for throttling the 'mousemove' event (used for animating the revoke button when `animateRevokable` is true) throttle: function(callback, limit) { var wait = false; return function() { if (!wait) { callback.apply(this, arguments); wait = true; setTimeout(function() { wait = false; }, limit); } } }, // only used for hashing json objects (used for hash mapping palette objects, used when custom colours are passed through JavaScript) hash: function(str) { var hash = 0, i, chr, len; if (str.length === 0) return hash; for (i = 0, len = str.length; i < len; ++i) { chr = str.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; } return hash; }, normaliseHex: function(hex) { if (hex[0] == '#') { hex = hex.substr(1); } if (hex.length == 3) { hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2]; } return hex; }, // used to get text colors if not set getContrast: function(hex) { hex = this.normaliseHex(hex); var r = parseInt(hex.substr(0, 2), 16); var g = parseInt(hex.substr(2, 2), 16); var b = parseInt(hex.substr(4, 2), 16); var yiq = ((r * 299) + (g * 587) + (b * 114)) / 1000; return (yiq >= 128) ? '#000' : '#fff'; }, // used to change color on highlight getLuminance: function(hex) { var num = parseInt(this.normaliseHex(hex), 16), amt = 38, R = (num >> 16) + amt, B = (num >> 8 & 0x00FF) + amt, G = (num & 0x0000FF) + amt; var newColour = (0x1000000 + (R<255?R<1?0:R:255)*0x10000 + (B<255?B<1?0:B:255)*0x100 + (G<255?G<1?0:G:255)).toString(16).slice(1); return '#'+newColour; }, isMobile: function() { return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent); }, isPlainObject: function(obj) { // The code "typeof obj === 'object' && obj !== null" allows Array objects return typeof obj === 'object' && obj !== null && obj.constructor == Object; }, }; // valid cookie values cc.status = { deny: 'deny', allow: 'allow', dismiss: 'dismiss' }; // detects the `transitionend` event name cc.transitionEnd = (function() { var el = document.createElement('div'); var trans = { t: "transitionend", OT: "oTransitionEnd", msT: "MSTransitionEnd", MozT: "transitionend", WebkitT: "webkitTransitionEnd", }; for (var prefix in trans) { if (trans.hasOwnProperty(prefix) && typeof el.style[prefix + 'ransition'] != 'undefined') { return trans[prefix]; } } return ''; }()); cc.hasTransition = !!cc.transitionEnd; // array of valid regexp escaped statuses var __allowedStatuses = Object.keys(cc.status).map(util.escapeRegExp); // contains references to the custom
'; }else if( location == 'simple_left' ){ //new widget - without images - bottom left column mixi_id = 92584; target = 'ul#most-read-box'; fark_target = 'ul#most-read-box'; insertHere = 'after'; widget = '
From our Partners
'; widget += '
'; widget += ''; // Hides the 'Recent News' Title Header. }else if( location == 'middle' ){ //Article Permalinks(Standard) Middle Column mixi_id = 92313; target = 'div.alpha'; fark_target = 'div.alpha'; insertHere = 'append'; widget = '
'; }else{ //loc == right/default mixi_id = 91801; target = 'div.beta'; if( SITE_INFO['name'] != "politics" ){ //All Sites EXCEPT RCP Right Column(article pages only) fark_target = 'div.beta'; insertHere = 'append'; }else{ fark_target = 'div.beta .widget_slot:eq(3)'; insertHere = 'after'; } widget = '
From our Partners
'; widget += '
'; } if($(target).length) { if( insertHere == 'append' ){ $(fark_target).append( widget ); }else{ $(fark_target).after( widget ); } var sc = document.createElement('script'); sc.type = 'text/javascript'; sc.async = true; sc.src = '//mixi.media/data/js/'+mixi_id+'.js'; sc.charset = 'utf-8'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(sc, s); } } $(document).ready(function(){ if(SITE_INFO['name'] == 'politics'){ if( $('body').hasClass('article') || $('body').hasClass('video') || $('body').hasClass('home') || $('body').hasClass('polls') || $('body').hasClass('polls') ){ dynamic_ads.fark_widget('right'); dynamic_ads.fark_widget('simple_left'); } } else if( (SITE_INFO['name'] == 'markets' || SITE_INFO['name'] == 'history') && $('body').hasClass('home') ){ dynamic_ads.fark_widget('right'); } else if( (SITE_INFO['name'] == 'defense' || SITE_INFO['name'] == 'world' || SITE_INFO['name'] == 'science') && $('body').hasClass('home') ){ dynamic_ads.fark_widget('left'); }else if( (SITE_INFO['name'] == 'defense' || SITE_INFO['name'] == 'world' || SITE_INFO['name'] == 'science' || SITE_INFO['name'] == 'markets' || SITE_INFO['name'] == 'history') && $('body').hasClass('article') ){ $(".newsletter-signup-container2").last().hide(); $(".newsletter-widget").css({ "margin-bottom" : "20px" }); dynamic_ads.fark_widget('middle'); dynamic_ads.fark_widget('right'); } }); //////////////////////////////////////////////////////////////////////////////// // FLOATING LEADERBOARD //////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //M.B. ADDED 12.5.17 -- FLOATING LEADERBOARD AD/RIGHTRAIL AD_BOX_TOP //A.A. REWORKED AND CLEANED UP 11.15.18 /* floating leaderboard ad && floating right rail ad box top */ //if( $('body.article').length > 0 ){ //only article pages -- might need to kill /articles and long-format pages??? //console.log('floater func enabled.......'); //when doc is ready then check body class - if checks true do following... $(document).ready(function(){ var settings = {}; leaderboardActions(leaderboardSettings(settings)); }); //end doc ready var leaderboardSettings = function(options){ var checkIfArticle = function(){ if( $('body.article').length > 0 && $('div.beta div').first().hasClass('RC-AD-BOX-TOP') ){ return true; } return false; } var checkIfPolls = function(){ //Setting this as false permanently to turn off on polls per Ivan - A.A. 03-12-2019 return false; if( $('body.polls').length > 0 || $('body.maps').length > 0 || $('body.live_results').length>0 ){ return true; } } options = options || {}; var settings = { fixed_class: 'fixed-leaderboard', leaderboard_cookie: 'rc-ad_rc-ad-top-banner_fixed-leaderboard_close-ad', hide_class: 'hide', top_pos_class: 'top', tynt_check: '.tynt-ad-fence', top_banner_ad_el: $('.RC-AD-TOP-BANNER'), container_top: $('#container').offset().top, container_width: $('#container').width(), alpha_left: $('.alpha').length ? $('.alpha').offset().left : 0, alpha_width: $('.alpha').length ? $('.alpha').width() : 0, article: checkIfArticle(), polls: checkIfPolls(), on_article: { reset: 1600, }, on_polls: { reset: 800, }, hooks: [ 'rightColumnStickyOnScroll', 'backToTopIcon' ], scroll_hooks: [], }; $.extend(true, settings, options); return settings; }; var leaderboardActions = function(set){ var pos_settings = {}; if(set.article == true){ pos_settings = set.on_article; }else if(set.polls == true){ pos_settings = set.on_polls; //if not valid page exit early }else { return; } //if not at least 1180 pixels wide exit early var winWidth = $(window).width(); if( winWidth <= 1180 ){ return; } var timeout = null; var reset = pos_settings.reset+set.container_top; var container_top = set.container_top; var cookie = set.leaderboard_cookie; $(window).scroll(function (event) { clearTimeout(timeout); timeout = setTimeout(function() { if(!readCookie(cookie)){ var topPos = $(this).scrollTop(); var position = ( ( $(window).width() - $('#container').width() ) / 2) + $('.beta').width() + 90; //if top pass the container top reset the ad to the top of the page if(topPos <= container_top){ //remove all classes to reset ad to the top of the page to orinal position $(set.top_banner_ad_el).removeClass(set.fixed_class) .removeClass(set.top_pos_class) .removeClass(set.hide_class) .css({'right': 'initial'}); //if passed the container top position and below reset then fix the ad }else if(topPos > container_top && topPos < reset){ $(set.top_banner_ad_el).removeClass(set.hide_class); //fix add to top if not already done so if( !$(set.top_banner_ad_el).hasClass(set.fixed_class) ){ $(set.top_banner_ad_el).addClass(set.fixed_class); //.css({'right' : position+'px'}); //if tynt ad on page then fix to top if( $(set.tynt_check).length > 0 && !$(set.top_banner_ad_el).hasClass(set.top_pos_class) ){ $(set.top_banner_ad_el).addClass(set.top_pos_class); } } //Using current jquery structure to adjust ad position based to screen size if(winWidth > 1179 && winWidth < 1281 && $("body.article").length > 0) { $(set.top_banner_ad_el).css({'right' : 439+'px', 'margin-right' : '7px'}); }else if(winWidth > 1279 && $("body.article").length > 0) { $(set.top_banner_ad_el).css({'right' : 'auto', 'margin-right' : '41px'}); }else if(winWidth > 1279 && winWidth < 1300 && $("body.article").length > 0) { $(set.top_banner_ad_el).css({'right' : 451+'px'}); }else{ $(set.top_banner_ad_el).css({'right' : position+'px'}); } //$(set.top_banner_ad_el).css({'right' : position+'px'}); //if passed the reset position then hide it } else if(topPos >= reset){ $(set.top_banner_ad_el).addClass(set.hide_class); } } if(set.scroll_hooks.length > 0){ //call other functions dynamically that are hook into the on scroll event for (var i = 0; i < set.scroll_hooks.length; i++) { window[set.scroll_hooks[i]](); } } }, 10); }).scroll(); if(set.hooks.length > 0){ //call other functions dynamically that are hook into the on scroll event for (var i = 0; i < set.hooks.length; i++) { window[set.hooks[i]](); } } } var rightColumnStickyOnScroll = function(){ if( SITE_INFO['name'] != "markets" ){ //if standard article OR polls page - all verticals - float rightrail ad-box-top ad on scroll if( ( $('body.article').length && $('div.beta div').first().hasClass('RC-AD-BOX-TOP') ) || ( $('body.polls').length ) || ( $('body.maps').length ) || ( $('body.live_results').length ) ){ /** * A.A. code to make the right column sticky and then scrollable */ var scroll_distance = 1500; if($('body.polls').length || $('body.maps').length) { scroll_distance = 800; } var sticky_base_class = 'sticky-right-col'; $('.beta').wrapInner("
"); var sticky_el = '.'+sticky_base_class; var beta_top_st = $('.beta').offset().top; $(window).on('scroll', function(event){ var w_top = $(this).scrollTop(); if( w_top < beta_top_st ){ $(sticky_el).removeClass('scroll'); $(sticky_el).css('margin-top', '0px'); }else if( w_top > beta_top_st && w_top < (beta_top_st + scroll_distance) ){ $(sticky_el).addClass('scroll'); $(sticky_el).css('margin-top', '0px'); $(sticky_el).removeClass('stop'); }else if( w_top > (beta_top_st + scroll_distance) ){ $(sticky_el).addClass('stop'); $(sticky_el).css('margin-top', scroll_distance+'px'); } }); } } } var backToTopIcon = function(){ //BACK TO TOP if($('body').hasClass('article')){ //this will only get executed only and only if the body has a class of article it $('body').append('
'); backToTop = function(){ var scrollTrigger = 300; var scrollTop = $(window).scrollTop(); if(scrollTop > scrollTrigger){ $('.back-to-top').addClass('show'); } else{ $('.back-to-top').removeClass('show'); } } backToTop(); $(window).on('scroll',function(){ backToTop(); }) $('.back-to-top').on('click', function(e){ e.preventDefault(); $('html, body'). animate({ scrollTop:0 }, 700); }); } } //JQUERY FUNCTION TO CHECK IF ITEM IS WITHIN THE WINDOW VIEWPORT, VISIBLE $.fn.inViewport = function() { //get the passed item's postion var elementTop = $(this).offset().top; var elementBottom = elementTop + $(this).outerHeight(); //get the viewports positions var viewportTop = $(window).scrollTop(); var viewportBottom = viewportTop + $(window).height(); //will return true if item is within viewport, else will return false return elementBottom >= viewportTop && elementTop <= viewportBottom; }; //RETURNS TRUE OR FALSE IF WINDOW SIZE IS TABLET $.fn.isTablet = function(){ var width = $(window).width(); return width >= 768 && width <= 1024; } //RETURNS TRUE OR FALSE IF WINDOW SIZE IS MOBILE $.fn.isMobile = function(){ return $(window).width() < 768; } // Another floating ads class... may be redundant? ///////////////////////////// window.floatingAds = function(p_enabledAds, p_banner, p_box_top, p_banner_big, p_mobile_box_top){ //add the sitename to the body tag to target css on differences between sites if( SITE_INFO['name'] && !$('body').hasClass(SITE_INFO['name']) ){ $('body').addClass(SITE_INFO['name']); } // possible to pass these as false to turn off ad transitions var enabledAds = { banner: true, box_top: true, big_banner: true, mobile_box_top: true, }; p_enabledAds = p_enabledAds || {}; $.extend(true, enabledAds, p_enabledAds); var banner = { tag: '.RC-AD-TOP-BANNER', cookie: 'rc-ad_rc-ad-top-banner_sticky-banner_close-ad', triggerPoint: 10,//point at which ad will become fixed hidePoint: 900,//point at which ad will slide up and hide sticky: 'sticky-banner', //class causes the banner to stick to the top slideUp: 'banner-slide-up', //class causese the sticky banner to slide up has_tynt: 'has-tynt-ad', tynt_class: '.tynt-ad-fence', adHidden: false, //flag for big banner to know when to show up }; p_banner = p_banner || {}; $.extend(true, banner, p_banner); var box_top = { init: false,//after initial setting up of the DOM, this is true tag: '.RC-AD-BOX-TOP', beta: '.beta-container .beta', beta_top: 0,//will trigger fixPos class once the beta top position is scrolled trigger: 600,//how long to make the beta column to be fixed, then it will be absolute positioned adHeight: 0,//needed to so some calculations fixPos: 'fix-box-top',//added to beta column to make it fixed so it scrolls with the user absPos: 'abs-box-top',//added to beta column after fixed to make it absolute positioned, not used anymore relPos: 'rel-box-top',//added to beta column after fixed to make it relative positioned }; p_box_top = p_box_top || {}; $.extend(true, box_top, p_box_top); var rightColPadding = 34; if( $('#container').width() == 1280 ){ rightColPadding = 134; } var banner_big = { init: false,//set to true when initial DOM setup is done adWrapper: 'banner-big-wrapper',//wraps banner add with div with this class adContainer: '.top-bannerx',//the ad container div ad: '.RC-AD-TOP-BANNER-BIG',//the ad div element class // these two are calculated on the fly but set with innitial to // do the math before the ad is loaded in yet adHeight: 90, adWidth: 970, // this the selector and top position of it // where the big banner will be hidden hideEl: '#hpstreams', hidePoint: 0, hasCloser: false, rightColPadding: rightColPadding, }; p_banner_big = p_banner_big || {}; $.extend(true, banner_big, p_banner_big); var mobile_box_top = { init: false, tag: '.RC-AD-BOX-TOP', wrapperTag: 'top-ad-wrapper-mobile', containerTag: 'top-ad-container-mobile', adDiv: 'top-ad-div', adEl: null, adHeight: 0, adWidth: 0, adBottom: 0, hidePoint: 500, }; p_mobile_box_top = p_mobile_box_top || {}; $.extend(true, mobile_box_top, p_mobile_box_top); return { pos:{ top: 0, width: 0, gamma_left: 0, gamma_right: 0, gamma_width: 0, alpha_left: 0, alpha_width: 0, alpha_right: 0, }, enabledAds: enabledAds, ads:{ banner: banner, box_top: box_top, banner_big: banner_big, mobile_box_top: mobile_box_top, }, timeoutID:0, /** * ENTRY POINT TO START LISTENER AND AD SETTINGS */ init: function(){ this.updateScrollValues(); if(this.enabledAds.box_top == true){ this.initBoxTop(); } if(this.enabledAds.big_banner == true){ this.initBigBanner(); } if(this.enabledAds.mobile_box_top == true){ this.initMobileBoxTop(); } this.setListeners(); }, /** * SETS WINDOW LISTENERS FOR SCROLL */ setListeners: function(){ $( window ).scroll(function(event){ this.scrollBack(event); }.bind(this)); $(window).scroll(); }, /** * THE SCROLL EVENT TRIGGERS THIS FUNCTION * IT HAS A TIMEOUT TO MAKE PERFORMANCE AS BEST AS POSSIBLE */ scrollBack: function(event){ clearTimeout(this.timeoutID); this.timeoutID = setTimeout(function(){ this.updateScrollValues(event); this.parseAdsPositions(); }.bind(this), 10); }, /** * AFTER TIME OUT IN scrollBack() EXPIRES THIS IS TRIGGERED * UPDATES DIMENSIONS USED BY ALL AD POSITIONING CALCULATIONS */ updateScrollValues: function(event){ this.pos.top = window.pageYOffset; this.pos.width = window.innerWidth; if( $('.gamma').length > 0 ){ this.pos.gamma_left = $('.gamma').offset().left; this.pos.gamma_width = $('.gamma').width(); this.pos.gamma_right = this.pos.gamma_left + this.pos.gamma_width; } if( $('.alpha').length > 0 ){ this.pos.alpha_left = $('.alpha').offset().left; this.pos.alpha_width = $('.alpha').width(); this.pos.alpha_right = this.pos.alpha_left + this.pos.alpha_width; } if(this.pos.width >= 768 && this.enabledAds.box_top == true){ this.ads.box_top.adHeight = $('.beta '+this.ads.box_top.tag+' > div').height(); } if(this.pos.width >= 1300 && this.enabledAds.big_banner == true){ // this.ads.banner_big.adHeight = $(this.ads.banner_big.ad+' > div').height() || 90; this.ads.banner_big.adHeight = $(this.ads.banner_big.ad+' > div:nth-child(2)').height() || 90; this.ads.banner_big.adWidth = $(this.ads.banner_big.ad+' > div:nth-child(2) ').width() || 970; this.ads.banner_big.hidePoint = $(this.ads.banner_big.hideEl).offset().top + 200; } if(this.pos.width < 768 && this.enabledAds.mobile_box_top == true ){ if(!this.ads.mobile_box_top.adEl || this.ads.mobile_box_top.adEl == null){ this.ads.mobile_box_top.adEl = $('div.alpha div'+this.ads.mobile_box_top.tag); } this.ads.mobile_box_top.adHeight = $(this.ads.mobile_box_top.adEl).height(); this.ads.mobile_box_top.adWidth = $(this.ads.mobile_box_top.adEl).width(); } }, /** * AFTER EVERY CALL TO UPDATE SCROLL VALUES THIS IS TRIGGERED * RUNS THE FUNCTIONS TO UPDATE THE AD POSITIONING */ parseAdsPositions: function(){ if(this.pos.width >= 768 && this.enabledAds.box_top == true){ this.parseBoxTop(); } if(this.pos.width >= 768 && this.enabledAds.banner == true){ this.parseBannerAd(); } if(this.pos.width >= 1300 && this.enabledAds.big_banner == true){ this.parseBigBanner(); } if(this.pos.width < 768 && this.enabledAds.mobile_box_top == true){ this.parseMobileBoxTop(); } }, /** * POSIONS LOCATION OF THE LEADERBOARD BANNER AD */ parseBannerAd: function(){ if(readCookie(this.ads.banner.cookie)){ return; } var triggerPoint = this.ads.banner.triggerPoint; var tag = this.ads.banner.tag; var sticky = this.ads.banner.sticky; var slideUp = this.ads.banner.slideUp; var hidePoint = this.ads.banner.hidePoint; var has_tynt = this.ads.banner.has_tynt; var tynt_class = this.ads.banner.tynt_class; var pos = this.pos; //if tynt add class that allows the add to move to the top of the page if( $(tynt_class).length > 0 && !$(tag).hasClass(has_tynt) ){ $(tag).addClass(has_tynt); } if( pos.top < triggerPoint ){ $(tag).css({'left': 'auto'}); $(tag).css({'margin-left': 'auto'}); if( $(tag).hasClass(sticky) ){ $(tag).toggleClass(sticky); } if( $(tag).hasClass(slideUp) ){ $(tag).toggleClass(slideUp); } }else if( pos.width >= 768 && ( pos.top > triggerPoint && pos.top < hidePoint ) ){ var mid_positon = (pos.alpha_width + pos.gamma_width - 688) / 2; //console.log(mid_positon); $(tag).css({'left': this.pos.gamma_left+'px'}); $(tag).css({'margin-left': mid_positon+'px'}); if( !$(tag).hasClass(sticky) ){ $(tag).toggleClass(sticky); } if( $(tag).hasClass(slideUp) ){ $(tag).toggleClass(slideUp); $('li.top-left').addClass('skyscraper-ad'); $('li.top-right').addClass('skyscraper-ad'); $('.skyscraper-ad').css({'transform': 'translateY(0px)'}); this.ads.banner.adHidden = false; } }else if( pos.width >= 768 && pos.top >= hidePoint ){ if( !$(tag).hasClass(slideUp) ){ $(tag).toggleClass(slideUp); $('li.top-left').addClass('skyscraper-ad'); $('li.top-right').addClass('skyscraper-ad'); $('.skyscraper-ad').css({'transform': 'translateY(-650px)'}); this.ads.banner.adHidden = true; } } }, /** * BOX TOP AD ON RIGHT COL NEEDS INITIAL SETUP * THIS TRIGGERS THE CODE NEEDED TO MAKE THE RIGHT COLUMN POSITIONING WORK */ initBoxTop: function(){ if( this.ads.box_top.init == false && this.pos.width >= 768 ) { var beta = this.ads.box_top.beta; $(beta).addClass('clearfix'); this.ads.box_top.beta_top = $(beta).offset().top; this.ads.box_top.init = true; } }, /** * ONCE INIT FOR BOX TOP RUNS THIS WILL UPDATE THE RIGHT COLUMN POSITIONING */ parseBoxTop: function(){ if(this.pos.width >= 768 && this.ads.box_top.init == true){ var theAd = this.ads.box_top.tag; var beta = this.ads.box_top.beta; var beta_top = this.ads.box_top.beta_top; var trigger = this.ads.box_top.trigger; var adHeight = this.ads.box_top.adHeight; var fixPos = this.ads.box_top.fixPos; // var absPos = this.ads.box_top.absPos; var relPos = this.ads.box_top.relPos; var triggerPoint = beta_top + trigger; var currentPoint = this.pos.top; //console.log(currentPoint+' < '+triggerPoint); if(currentPoint < beta_top){ $(beta).removeClass(fixPos); }else if( currentPoint >= beta_top ){ $(beta).addClass(fixPos); if(currentPoint < triggerPoint){ $(beta).removeClass(relPos).css({'margin-top': 'initial'}); }else{ $(beta).addClass(relPos).css({'margin-top': trigger+'px'}); } } } }, /** * BIG BANNER NEEDS INITIAL SETUP TO BECOME FIXED AT BOTTOM OF PAGE */ initBigBanner: function(){ if(this.pos.width >= 1025){ var banner_big = this.ads.banner_big; var adContainer = banner_big.adContainer; var adWrapper = banner_big.adWrapper; var adHeight = banner_big.adHeight; var ad = banner_big.ad; $(adContainer).wrapAll('
'); $('.'+adWrapper).addClass('clearfix'); $(ad).css({'transform': 'translateY('+adHeight+'px)'}); //on clicking the corner X, slide the ad out and then display none so it doesn't appear again $('.'+adWrapper).on('click', '.banner-big-close', function(){ $(ad).css({'transform': 'translateY(600px)'}); createCookie('big_banner_close', 'Clicked on big banner ad custom close x', 1); setTimeout(function(){ $('.'+adWrapper).css({'display': 'none'}); }, 250); }); // // Allow the code above to remove the image from the masthead // // But don't show the ad if the cookie exists var cookie = readCookie('big_banner_close'); if(cookie){ this.ads.banner_big.init = false; $(this.ads.banner_big.ad).hide(); console.log('Big banner cookie found: '+cookie); return; }else{ this.ads.banner_big.init = true; } } }, /** * AFTER INIT FOR BIG BANNER THIS WILL UPDATE THE POSITIONING OF IT */ parseBigBanner: function(){ if(this.enabledAds.big_banner === true && this.ads.banner_big.init === true){ var adHeight = this.ads.banner_big.adHeight; var alpha_left = this.pos.alpha_left + this.ads.banner_big.rightColPadding; var adWrapper = '.'+this.ads.banner_big.adWrapper; var adContainer = this.ads.banner_big.adContainer; var ad = this.ads.banner_big.ad; var hasCloser = this.ads.banner_big.hasCloser; //if the banner ad is disabled, check where it would normally be triggered //and update the adHidden value before checking if the big banner should show up if(this.enabledAds.banner == false){ if(this.pos.top >= this.ads.banner.hidePoint){ this.ads.banner.adHidden = true; }else{ this.ads.banner.adHidden = false; } } //hide big banner if banner leaderboard is shown if(this.ads.banner.adHidden == false){ $(ad).css({'transform': 'translateY('+parseInt(adHeight+30)+'px)', 'visibility': 0}); $(adWrapper).css({'visibility': 'collapse'}); $(adContainer).css({'visibility': 'collapse'}); //show/hide big banner if leaderboard is hidden }else if(this.ads.banner.adHidden == true){ var top = this.pos.top; var hidePoint = this.ads.banner_big.hidePoint; var currentPoint = top + window.innerHeight; //show big banner if(currentPoint < hidePoint){ if(hasCloser == false){ setTimeout(function(){ $(ad).prepend(''); }, 2000); this.ads.banner_big.hasCloser = true; } $(ad).css({'transform': 'translateY(0px)','visibility': 'inherit', 'visibility': 'initial'}); $(adContainer).css({'visibility': 'inherit', 'visibility': 'initial'}); $(adWrapper).css({'right': alpha_left+'px','visibility': 'inherit', 'visibility': 'initial'}); //hide big banner further down the page after hide point is passed }else{ $(ad).css({'transform': 'translateY('+parseInt(adHeight+30)+'px)', 'visibility': 'collapse'}); $(adWrapper).css({'visibility': 'collapse'}); $(adContainer).css({'visibility': 'collapse'}); } } } }, /** * MOBILE BOX TOP AD NEEDS INITIAL SETUP TO BE FIXED AT BOTTOM OF SCREEN */ initMobileBoxTop: function(){ if(this.ads.mobile_box_top.init == false && this.pos.width < 768){ var cookie = readCookie('mobile_box_top'); if(cookie){ console.log('Mobile box top cookie found: '+cookie); $('.date-menu img').css({'padding-top': '20px'}); return; } $('.date-menu img').css({'padding-top': '10px !important'}); if(!this.ads.mobile_box_top.adEl || this.ads.mobile_box_top.adEl == null){ this.ads.mobile_box_top.adEl = $('div.alpha div'+this.ads.mobile_box_top.tag); } var adHeight = this.ads.mobile_box_top.adHeight; var adWidth = this.ads.mobile_box_top.adWidth; if(!adHeight || adHeight == 0){ this.updateScrollValues(); adHeight = this.ads.mobile_box_top.adHeight; adWidth = this.ads.mobile_box_top.adWidth; } console.log('adHeight: '+adHeight); console.log('adWidth: '+adWidth); var theAd = this.ads.mobile_box_top.tag; var wrapperTag = this.ads.mobile_box_top.wrapperTag; var containerTag = this.ads.mobile_box_top.containerTag; var adDiv = this.ads.mobile_box_top.adDiv; console.log(this.ads.mobile_box_top.adEl); $(this.ads.mobile_box_top.adEl).appendTo("body"); $(this.ads.mobile_box_top.adEl).wrapAll('
'); $(this.ads.mobile_box_top.adEl).wrapAll('
'); $(this.ads.mobile_box_top.adEl).wrapAll('
'); console.log('wrappers'); $('.'+wrapperTag).addClass('clearfix'); $('.'+containerTag).addClass('clearfix'); $('.'+adDiv).addClass('clearfix'); $('.'+adDiv).prepend('
'); var margin_left = (this.pos.width - adWidth) / 2; $(this.ads.mobile_box_top.adEl).css({'margin-left': margin_left+'px'}); this.updateScrollValues(); this.ads.mobile_box_top.init = true; this.parseMobileBoxTop(); //on clicking the corner X, slide the ad out and then display none so it doesn't appear again $('.'+wrapperTag).on('click', '.mobile-box-top-close', function(){ console.log('clicked'); $('.'+adDiv).css({'transform': 'translateY(300px)'}); createCookie('mobile_box_top', 'clicked on mobile ad close x', 1); setTimeout(function(){ $('.'+wrapperTag).css({'display': 'none'}); }, 250); }); } }, /** * AFTER INIT FOR MOBILE BOX TOP THIS WILL REPOSITION IT */ parseMobileBoxTop: function(){ if(this.ads.mobile_box_top.init == true){ var adHeight = this.ads.mobile_box_top.adHeight; var adWidth = this.ads.mobile_box_top.adWidth; var hidePoint = this.ads.mobile_box_top.hidePoint; var adDiv = this.ads.mobile_box_top.adDiv; var wrapperTag = this.ads.mobile_box_top.wrapperTag; if(!adHeight || adHeight == 0){ this.updateScrollValues(); adHeight = this.ads.mobile_box_top.adHeight; } var margin_left = (this.pos.width - adWidth) / 2; $(this.ads.mobile_box_top.adEl).css({'margin-left': margin_left+'px'}); if(this.pos.top < hidePoint){ $(wrapperTag).css({'visibility': 'inherit', 'visibility': 'initial'}); $('.'+adDiv).css({'transform': 'translateY(0px)', 'visibility': 'inherit', 'visibility': 'initial'}); }else{ $(wrapperTag).css({'visibility': 'collapse'}); $('.'+adDiv).css({'transform': 'translateY(300px)', 'visibility': 'collapse'}); } } }, }; } //////////////////////////////////////////////////////////////////////////////// // ADS FUNCTIONS /////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// function init_network_ads() { if( SITE_INFO['disable_all_ads'] ) { return; } var gpt_library = { src: '//www.googletagservices.com/tag/js/gpt.js' }; if( LAZY_ADS_ENABLED) { init_lazy_ads(); if( typeof window.lazySizes === 'undefined' ) { // Lazysizes library allows us to detect when an element is in view if(SITE_INFO['name'] == 'politics') { rcmg_top_scripts.push({ src: '/3rd_party/lazysizes/lazysizes.min.js' }); } else { rcmg_top_scripts.push({ src: '/asset/3rd_party/lazysizes/lazysizes.min.js' }); } } } if( !PREBIDDING_ENABLED ) { gpt_library['onload'] = 'ads_ready()'; rcmg_top_scripts.push(gpt_library); } else { rcmg_top_scripts.push(gpt_library); // This can disable prebid for testing? /*var pbjs = { que: [function() { pbjs.requestBids = function() {}; }] };*/ // fscomscore (what is this for?) rcmg_top_scripts.push({ src: '//a.pub.network/core/fscomscore.js', 'data-cfasync': false, }); // Prebid library (supplied by Publir?) rcmg_top_scripts.push({ src: SITE_INFO['prebid_src'], onload: 'ads_ready()', }); } } function loadAds() { /*console.log('all_ads_disabled: '+(typeof all_ads_disabled)); console.log('evolok_init_finished: '+evolok_init_finished); console.log('evolok_do_ads: '+evolok_do_ads); console.log('evolok_block_ads: '+evolok_block_ads); console.log('allow_ad_render: '+allow_ad_render); console.log('network_ads_loaded: '+network_ads_loaded);*/ if(typeof all_ads_disabled !== 'undefined' && all_ads_disabled === true) { return; } if(evolok_init_finished) { if(!evolok_do_ads && !evolok_block_ads) { // Just skip and wait for next function call for a status change return; } else if(evolok_block_ads) { return; } // Otherwise go ahead and do ads } if(!allow_ad_render) { return; } if(network_ads_loaded) { return; } network_ads_loaded = true; // Track how many page hits by users in their two-week adfree trial if( readCookie('two_weeks_adfree') ){ check_send_ga_loaded = setInterval(function(){ if( typeof send_notifier_event == 'function' ){ var onload_adfree_user_data = { 'ge_action' : 'Page Load No Ads', 'ge_category' : 'Two Weeks Ad-Free Promo', 'ge_label' : 'Adblock User Subscribed to Newsletter', 'ge_index' : null, 'ge_noninteraction' : true }; send_notifier_event(onload_adfree_user_data); clearInterval(check_send_ga_loaded); } //if func() exists check }, 250); //2.5 Second Intervals return false; } // TRIGGER HOMEPAGE FLOATING ADS CODE if( $("body").hasClass("home") ){ if( SITE_INFO['name'] == 'politics' ){ var isMobile = $().isMobile(); if(!(isMobile)){ //ONLY DESKTOP/TABLET we float ads var adOpts = {}; if( $('body').hasClass('with-distroscale') ){ adOpts.banner = false; } adOpts.box_top = false; window.floatAds = new window.floatingAds(adOpts); window.floatAds.init(); } }else if(SITE_INFO['name'] == 'defense' || SITE_INFO['name'] == 'policy' || SITE_INFO['name'] == 'science'){ window.floatAds = new window.floatingAds({mobile_box_top: false}); window.floatAds.init(); } } if( LAZY_ADS_ENABLED ) { start_lazy_ads(); } else { normal_ads_load(); } } function ads_ready() { allow_ad_render = true; loadAds(); } function init_lazy_ads() { window.lazySizesConfig = window.lazySizesConfig || {}; window.lazySizesConfig.lazyClass = 'RC-AD'; // instead of default 'lazyload' window.lazySizesConfig.loadMode = 2; // 1 - only load visible elements, 2 - loads "very near" window.lazySizesConfig.expand = 300; // expands the calculated visual viewport area in all directions, so that elements can be loaded before they become visible window.lazySizesConfig.loadHidden = false; // should delay loading of fixed ads until they appear window.lazySizesConfig.init = false; // Do not initialize on load. Init manually when ready. } function start_lazy_ads() { // Show all ads that are marked with class .RC-AD-SHOW-NOW instead of .RC-AD var show_now_elements = document.querySelectorAll('.RC-AD-SHOW-NOW'); for (i=0; i < show_now_elements.length; i++) { var show_now = show_now_elements[i]; for (var ad_slot in ads_info) { if (ads_info.hasOwnProperty(ad_slot)) { if( !ads_info[ad_slot]['loaded'] && hasClass(show_now, ads_info[ad_slot]['class']) && isVisible(show_now) ) { lazy_ad_list.push(ad_slot); // adds ad to list of ads to render (if ready) ads_info[ad_slot]['loaded'] = true; } } } } // We push ad slots to a list. This is because the above-the-fold ads may be // visible to lazyload library before our publir prebid is ready document.addEventListener('lazybeforeunveil', function(e) { for (var ad_slot in ads_info) { if (ads_info.hasOwnProperty(ad_slot)) { if( !ads_info[ad_slot]['loaded'] && hasClass(e.target, ads_info[ad_slot]['class']) && isVisible(e.target) && !hasClass(e.target, '.RC-AD-SHOW-NOW') ) { console.log('ad pushed into ad render list'); // Record of all ad slots that have been visible to user lazy_ad_list.push(ad_slot); // adds ad to list of ads to render (if ready) ads_info[ad_slot]['loaded'] = true; break; } } } }); window.lazySizes.init(); // Initializes lazysizes manually right now var lazy_ad_interval = window.setInterval(function() { //console.log('lazy check... length: '+lazy_ad_list.length); if( lazy_ad_list.length == 0 || !allow_ad_render ) { return; } // Find first ad_slot that is actually visible on screen and load // In theory this shouldn't be neccessary... not sure why lazysizes is getting false positives sometimes var target_ad_i = lazy_ad_list.length - 1; var match_found = false; for (var i = 0; i < lazy_ad_list.length; i++) { var ad_elem = firstVisibleElement('.'+ads_info[lazy_ad_list[i]]['class']); // first visible element //if( ad_elem == null || !isVisibleOnScreen(ad_elem) ) { // must be visible on screen if( ad_elem == null ) { // must have match continue; } else { target_ad_i = i; match_found = true; } } if( !match_found ) { return; // Don't do unless truly visible on screen } // Removes and returns ad name from stack that has been accumulating var temp_ad_slots = lazy_ad_list.splice(target_ad_i, 1); var ad_slot = temp_ad_slots[0]; if(ad_slot){ googletag.cmd.push(function () { init_googletag(); //// Create and serve prebid ad rcmg_load_ad(ad_slot, 'lazy'); }); } }, 50); // Checks every 50 milliseconds } function rcmg_load_ad(ad_slot, load_type) { if(typeof load_type === 'undefined') { load_type = 'normal'; }// Get only first visible element that matches var ad_elem = firstVisibleElement('.'+ads_info[ad_slot]['class']); // first visible element //var ad_elem = document.querySelector('.'+ads_info[ad_slot]['class']); // default element is just first matching class if(ad_elem == null) { console.log('no container found for: '+ads_info[ad_slot]['class']); return; // no ad container found } /*var matches = document.querySelectorAll('.'+ads_info[ad_slot]['class']); for (var i = 0; i < matches.length; ++i) { if(isVisible(matches[i])) { ad_elem = matches[i]; break; } }*/ // If ad has been closed recently, do not load if( readCookie(ad_close_cookie_name(ad_elem)) ) { return; } // If investingchannel override, and on relevant site, put script tag in and return if( SITE_INFO['name'] == 'markets' && typeof ads_info[ad_slot]['ic_override'] !== 'undefined' && ads_info[ad_slot]['ic_override'].length > 2 ) { var s = document.createElement("script"); s.type = "text/javascript"; s.src = ads_info[ad_slot]['ic_override']; s.charset = "utf-8" ad_elem.appendChild(s); return; } var new_slot = googletag.defineSlot(ads_info[ad_slot]['name'], ads_info[ad_slot]['sizes'], ad_slot).addService(googletag.pubads()); console.log(ad_elem); //console.log(pbjs.adUnits); //ad_elem.innerHTML = "
"; // Use this method to append... so we don't overwrite any close button var new_ad_div = document.createElement('div'); new_ad_div.id = ad_slot; ad_elem.appendChild(new_ad_div); googletag.display(ad_slot); console.log(ad_elem.innerHTML); if(load_type == 'lazy') { if(PREBIDDING_ENABLED) { console.log('refreshing prebid ad'); /* pbjs.que.push(function() { pbjs.setTargetingForGPTAsync(); googletag.pubads().refresh([ new_slot ]); });*/ pbjs.que.push(function() { pbjs.requestBids({ timeout: PREBID_TIMEOUT, //set by publir adUnitCodes: [ad_slot], bidsBackHandler: function() { pbjs.setTargetingForGPTAsync([ad_slot]); googletag.pubads().refresh([new_slot]); } }); }); } else { console.log('loading lazy ad no prebid'); if(SITE_INFO['name'] != 'markets') { googletag.pubads().refresh([ new_slot ]); } } } setAdCloser(ad_elem); } // Global requirements: ads_info, googletag function normal_ads_load() { console.log('normal_ads_load()'); // Load ads normally googletag.cmd.push(function () { init_googletag(); //try { amznads.setTargetingForGPTAsync('amznslots');} catch(e) { /*ignore*/} //googletag.pubads().collapseEmptyDivs(true); //googletag.pubads().refresh(); for (var ad_slot in ads_info) { if (ads_info.hasOwnProperty(ad_slot)) { rcmg_load_ad(ad_slot); } } if(!PREBIDDING_ENABLED) { googletag.pubads().refresh(); } else { pbjs.que.push(function() { pbjs.requestBids({ timeout: PREBID_TIMEOUT, //set by publir bidsBackHandler: function() { pbjs.setTargetingForGPTAsync(); googletag.pubads().refresh(); } }); }); } }); } // Requirements: must be called within a gogoletag.cmd.push(function() {}) block function init_googletag() { googletag.pubads().setTargeting("SiteDomain", SITE_INFO['name']); googletag.pubads().setTargeting("SitePage", SITE_PAGE); googletag.pubads().setTargeting("Tags", GA_TAG); //googletag.pubads().enableSingleRequest(); googletag.pubads().disableInitialLoad(); googletag.pubads().collapseEmptyDivs(true); googletag.enableServices(); } // Ad Closing ////////////////////////////////////////////////////////////////// function setAdCloser(el){ //Check if the Ad should be closed if(!shouldAdHaveCloser(el)) { return; } setTimeout(function(){ $el = $(el); var closer = '
×
'; $el.css({'position': 'relative', 'display' : 'block'}).append(closer); //alert('here'); $el.find('.close-the-ad').click(function() { // $(this).parent().parent().hide(); // $(this).closest('.RC-AD').hide(); // on closing ad, create a cookie based on the classes of the element // the cookie is to be used by anyone else needing to check for this //var ad_element = $(this).closest('.RC-AD'); var ad_element = $(this).parent(); var cookie_name = ad_close_cookie_name(ad_element); createCookie(cookie_name, $(ad_element).prop('nodeName')+'_'+cookie_name, 1); $(ad_element).hide(); }); }, 1000); } function ad_close_cookie_name(ad_element) { return Utils.make_slug($(ad_element).attr('class')+'_close-ad'); } //Check if ad Exist 11/15/2018 function shouldAdHaveCloser(el){ for (var ad_slot in ads_info) { if (ads_info.hasOwnProperty(ad_slot)) { // Don't bother with check if no closable_pages set if( ads_info[ad_slot]['closeable_pages'].length == 0) { return; } // Go through each ad unit for(var i = 0; i < ads_info[ad_slot]['closeable_pages'].length; i++) { // Make sure body element is within this ad unit's closable pages if($('body').hasClass(ads_info[ad_slot]['closeable_pages'][i])) { // Make sure ad element has this ad class if( $(el).hasClass(ads_info[ad_slot]['class']) ) { return true; } } } } } return false; } // Special Ad Vendors ////////////////////////////////////////////////////////// function loadGotChosen(){ if(typeof all_ads_disabled !== 'undefined' && all_ads_disabled === true) { return; } if(evolok_init_finished) { if(!evolok_do_ads) { // Just skip and wait for next function call for a status change return; } // Otherwise go ahead and do ads } $has_comments = $('#comments-container').length; $is_polls = $('body.polls').length; if($has_comments > 0 || $is_polls > 0){ if(!$('#gotChosen').length ){ gotChosenWidget(); } } } function gotChosenWidget(){ if($('body').hasClass('polls')){ $('div.alpha').append('
'); }else{ $('#comments-container, #fb-comments-container').after('
Advertisement
'); } (function(e,t,n,r,i,s,o){e["GotChosenObject"]=i;e[i]=e[i]||function() {(e[i].q=e[i].q||[]).push(arguments)},e[i].l=1*new Date;s=t.createElement(n),o=t.getElementsByTagName(n) [0];s.async=1;s.src=r;o.parentNode.insertBefore(s,o)}) (window,document,"script","https://www.gotchosen.com/thirdparty/gc.js","gc"); gc("webcurtain", SITE_INFO['gotchosen_id'] , { widgets: { autoinstall: [ { type: 'carousel-multi', selector: '#gotChosen', insertion: 'into' } ] } }); } function loadZergOrRev() { if(typeof all_ads_disabled !== 'undefined' && all_ads_disabled === true) { return; } if(evolok_init_finished) { if(!evolok_do_ads) { // Just skip and wait for next function call for a status change return; } // Otherwise go ahead and do ads } //if( $("#revContentWidget").length>0 ){ //IF WE HAVE A REVC_ID AND WE'RE ON AN ARTICLE PAGE var isarticle = $('body.article').length; var ispoll = $('body.polls').length; var isSponsoredPage = $('body.sp_content').length; //if sponsored page do not want any ads/ad widgets if(SITE_INFO['revc_id']!="" && isSponsoredPage==0 && (isarticle>0 || ispoll>0)){ //if NOT hiding 3rd party ads then load rev/zerg ads if( $(".data-no-ads").length == 0 ){ if(SITE_INFO['zerg_id']==''){ //loadRevContentWidgets(); }else{ //use zerg if we have it loadZergWidgets(); } } } } function loadZergWidgets(){ //REV CONTENT BELOW MAIN SECTION $f = $('div.alpha'); $f.append("
"); //(function() { var zergnet = document.createElement('script'); zergnet.type = 'text/javascript'; zergnet.async = true; zergnet.src = (document.location.protocol == "https:" ? "https:" : "http:") + '//www.zergnet.com/zerg.js?id='+SITE_INFO['zerg_id']; var znscr = document.getElementsByTagName('script')[0]; znscr.parentNode.insertBefore(zergnet, znscr); //})(); } function loadRevContentWidgets(){ //REV CONTENT BELOW ARTICLE //$f = $('#revContentWidget'); $f = $('div.alpha'); //$f.after("
"); $f.append("
"); var referer=""; try{ if(referer=document.referrer,"undefined"==typeof referer) throw"undefined" }catch(exception){ referer=document.location.href,(""==referer||"undefined"==typeof referer)&&(referer=document.URL) } referer=referer.substr(0,700); var rcel = document.createElement("script"); rcel.id = 'rc_' + Math.floor(Math.random() * 1000); rcel.type = 'text/javascript'; rcel.src = "https://trends.revcontent.com/serve.js.php?w="+SITE_INFO['revc_w']+"&t="+rcel.id+"&c="+(new Date()).getTime()+"&width="+(window.outerWidth || document.documentElement.clientWidth)+"&referer="+referer; rcel.async = true; if( $('body.article.long').length==0 ){ var rcds = document.getElementById(SITE_INFO['revc_id']); rcds.appendChild(rcel); } if(SITE_INFO['revc_id_side']!=''){ //LOAD SIDEBAR WIDGET IF WE HAVE CODE //REV CONTENT SIDEBAR $('div.beta').append("
"); var referer=""; try{ if(referer=document.referrer,"undefined"==typeof referer) throw"undefined" }catch(exception){ referer=document.location.href,(""==referer||"undefined"==typeof referer)&&(referer=document.URL) } referer=referer.substr(0,700); var rcel = document.createElement("script"); rcel.id = 'rc_' + Math.floor(Math.random() * 1000); rcel.type = 'text/javascript'; rcel.src = "https://trends.revcontent.com/serve.js.php?w="+SITE_INFO['revc_w_side']+"&t="+rcel.id+"&c="+(new Date()).getTime()+"&width="+(window.outerWidth || document.documentElement.clientWidth)+"&referer="+referer; rcel.async = true; if( $('body.article.long').length==0 ){ var rcds = document.getElementById(SITE_INFO['revc_id_side']); rcds.appendChild(rcel); } } } function markets_investingchannel() { if(typeof all_ads_disabled !== 'undefined' && all_ads_disabled === true) { return; } if(evolok_init_finished) { if(!evolok_do_ads) { // Just skip and wait for next function call for a status change return; } // Otherwise go ahead and do ads } if( readCookie('two_weeks_adfree') ){ return false; } if(SITE_INFO['name'] == 'markets') { var invc_bylineAd = ""; var invc_lcAd = ""; var invc_bannerAd = ""; if( $(".sharepoint-wrapper").length>0 ){ $(".article-auth").css({ "margin-bottom" : "45px" }); } //Dynamically load in Inv. Channel Ads // disabled 1/6/2019 ROWLAND //$('.article-auth').after( invc_bylineAd ); //$('.invc-lc-ad').append( invc_lcAd ); //$('.invc-header-ad').append( invc_bannerAd ); } } function taboolaWidget(pos){ //pos comes from articles.js if( typeof pos === "undefined" ){ pos = 0; }else{ pos = pos; } var module = $("#taboolaWidget").attr('data-module'); var type = $("#taboolaWidget").attr('data-type'); //3 Types: full -> thumb -> text window._taboola = window._taboola || []; if( module == 'video' ){ _taboola.push({video: 'auto'}); }else if(module=='home'){ _taboola.push({home:'auto'}); }else if(module=='polls'){ _taboola.push({category:'auto'}); }else{ _taboola.push({article: 'auto'}); } !function (e, f, u) { e.async = 1; e.src = u; f.parentNode.insertBefore(e, f); }(document.createElement('script'), document.getElementsByTagName('script')[0], '//cdn.taboola.com/libtrc/realclearpolitics/loader.js'); if( type == 'full' ){ //both thumb and text link versions - 2 box elements //THUMBS if( pos == 0 ){ $('#taboolaWidget').after("
"); window._taboola = window._taboola || []; _taboola.push({mode : 'autosized-generated-2r', container : 'taboola-bottom-main-column', placement : 'bottom-main-column'}); //TEXT $('#taboola-bottom-main-column').after("
"); window._taboola = window._taboola || []; _taboola.push({mode:'text-links-2c', container:'taboola-text-2-columns-mix', placement:'text-2-columns', target_type:'mix'}); }else{ //infinite scroll triggered - increment position and push... push it real good $('#taboolaWidget_'+pos+'').after("
"); window._taboola = window._taboola || []; _taboola.push({mode : 'autosized-generated-2r', container : 'taboola-bottom-main-column_'+pos+'', placement : 'bottom-main-column'}); //TEXT $('#taboola-bottom-main-column_'+pos+'').after("
"); window._taboola = window._taboola || []; _taboola.push({mode:'text-links-2c', container:'taboola-text-2-columns-mix', placement:'text-2-columns', target_type:'mix'}); } }else if( type == 'thumb' ){ // thumb w/ link version - 1 element //THUMBS if( pos == 0 ){ $('#taboolaWidget').after("
"); window._taboola = window._taboola || []; _taboola.push({mode : 'autosized-generated-2r', container : 'taboola-bottom-main-column', placement : 'bottom-main-column'}); }else{ $('#taboolaWidget_'+pos+'').after("
"); window._taboola = window._taboola || []; _taboola.push({mode : 'autosized-generated-2r', container : 'taboola-bottom-main-column_'+pos+'', placement : 'bottom-main-column'}); } }else if( type == 'text' ){ //text link version - 1 box element //TEXT if( pos == 0 ){ $('#taboolaWidget').after("
"); $('#taboola-bottom-main-column').after("
"); window._taboola = window._taboola || []; _taboola.push({mode:'text-links-2c', container:'taboola-text-2-columns-mix', placement:'text-2-columns', target_type:'mix'}); }else{ $('#taboolaWidget_'+pos+'').after("
"); $('#taboola-bottom-main-column').after("
"); window._taboola = window._taboola || []; _taboola.push({mode:'text-links-2c', container:'taboola-text-2-columns-mix', placement:'text-2-columns', target_type:'mix'}); } }else if(type == 'home_left_rail'){ //HOMEPAGE LEFT RAIL $('#taboolaWidget').after("
"); window._taboola = window._taboola || []; _taboola.push({mode:'thumbnails-lr', container:'taboola-left-rail-thumbnails', placement:'Left Rail Thumbnails', target_type:'mix'}); }else if(type == 'polls'){ //POLLS PAGES - LEFT SIDE - BOTTOM $('#taboolaWidget').after("
"); window._taboola = window._taboola || []; _taboola.push({mode:'thumbnails-a', container:'taboola-below-main-column-thumbnails', placement:'Below Main Column Thumbnails', target_type:'mix'}); } _taboola.push({flush:true}); }//end articles taboola //LOAD INFINITY POP-UNDER // No need to have evolok manage this until politics ready function loadInfinityAds(){ setTimeout(function(){ //console.log('infinity: '); //console.log(enable_infinity_ads); if(SITE_INFO['name']=='politics'){ //console.log('infinity ran'); if(!(navigator.userAgent.match(/(iPhone|iPod|iPad)/i))){ var cur_body_class = document.body.getAttribute('class').split(/\s+/); //grab body class //ONLY ON SPECIFIC SECTIONS if(cur_body_class[0]=='polls' || cur_body_class[0]=='video' || cur_body_class[0]=='article' || cur_body_class=='home'){ (function(s,o,l,v,e,d){if(s[o]==null&&s[l+e]){s[o]="loading";s[l+e](d,l=function(){s[o]="complete";s[v+e](d,l,!1)},!1)}})(document,"readyState","add","remove","EventListener","DOMContentLoaded");(function(){var s=document.createElement("script");s.type="text/javascript";s.async=true;s.src="//cdn.engine.4dsply.com/Scripts/infinity.js.aspx?guid=9483dc51-8a49-444d-92b3-54b3f3d6a32b";s.id="infinity";s.setAttribute("data-guid","9483dc51-8a49-444d-92b3-54b3f3d6a32b");s.setAttribute("data-version","async");var e=document.getElementsByTagName('script')[0];e.parentNode.insertBefore(s,e)})(); } } } },500); //wait half second to make sure survey wasn't triggered } //////////////////////////////////////////////////////////////////////////////// // SOCIAL FUNCTIONS //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// function loadSocialTools(){ var any_print_button = false; //IF SOCIAL TOOLS CONTAINER EXIST if($('div#fb-root').length<1) { $('body').append('
'); //Add the fb-root if it doesn't exist already. } // ---------------------------- //BUILD SOCIAL TOOLS ON ALL CONTAINER INSTANCES AND APPEND $(".socialBar .toolset").each(function(index){ if($(this).is('.has-tools')) { return; //quit this function if the current item already has social tools. //this function will append the .has-tools class to $(this) at the end. } var sbIndex = index; //alert(sbIndex); var socialBar = $(this).parent(); var socialBarParent = socialBar.parent(); //grandparent to socialBar var feedName = socialBarParent.attr("data-feed-name"); if( feedName == "" || typeof feedName === 'undefined' ){ //we have a discrepency in html markup different on targeting the elements for sharing tools for twitter feedName = socialBar.attr('data-src-title'); if(feedName == "" || typeof feedName === 'undefined'){ feedName = $(document).find("title").text(); } } var feedCaption = socialBarParent.attr("data-feed-caption"); if( feedCaption == "" || typeof feedCaption === 'undefined' ){ feedCaption = $(document).find("description").text(); } //var feedDescription = socialBarParent.attr("data-feed-description"); var feedDesc = $(".pull-quote .description").text(); var feedAuth = socialBar.attr("data-src-author");//Articles if(feedAuth == "" || typeof feedAuth === 'undefined'){ //this will get the author from the Articles permalink pages feedAuth = $(".auth-author").text(); } var feedDescription = feedDesc; if(feedAuth != '' || typeof feedAuth === 'undefined' && feedDesc != ''){ feedDescription = feedDesc +' - By '+feedAuth; } if( feedDescription == "" || typeof feedDescription === 'undefined' ){ feedDescription = $(document).find("description").text(); } var feedLink = socialBarParent.attr("data-feed-link"); if( feedLink == "" || typeof feedLink === 'undefined' ){ feedLink = window.location.href; } //var feedLink = window.location.href; var feedPhoto = socialBarParent.attr("data-feed-photo"); if( feedPhoto == "" || typeof feedPhoto === 'undefined' ){ feedPhoto = $('meta[property="og:image"]').attr('content'); } var shareStyle = socialBar.attr('data-style'); var shareDialog = socialBar.attr('data-dialog'); var toolset = $(this); //parent toolset element //GRABS REFERRAL URL var ref_url = socialBar.attr('data-src-url'); if(!ref_url){ //IF 'ref' non-existent pull current page url ref_url = window.location.href; } /** * E.M * Multipage data url * It will only exist if ther is a multi-page article */ //if it is a multipage article if($('.multipage_article').length > 0){ //var new_location = $(this).attr('data-url'); ref_url = $('.multipage_article').attr('data-url'); } //GRABS REFERRAL TITLE var ref_title = socialBar.attr('data-src-title'); if(!ref_title){ //IF 'title' non-existent pull current page meta-title ref_title = $(document).find("title").text(); } //Replace requires a new variable name for each replace you do or it will not work var new_ref_title = ref_title; var refTitleClean = new_ref_title.replace("'",""); var rtNoEm = refTitleClean.replace("",""); var refTitle = rtNoEm.replace("", ""); //console.log('NEW Title: ' + refTitle); var red_btn_html = ' submit to reddit '; // Print Button var include_print = false; var print_icon_html = ''; if(typeof socialBar.attr("data-print") !== 'undefined' && socialBar.attr("data-print") != '') { include_print = true; any_print_button = true; print_icon_html = ""; } //CUSTOM TWITTER TEXT FOR FEED TYPE SHARE DIALOGS feed_temp = feedName.split('|'); feedName = feed_temp[0]; if(feedName.includes('Articles ')){ feedName = refTitle; } var twt_share_text = feedName + ' - ' + feedDescription; var new_twt_share_text = fixedEncodeURIComponent( feedName + " - " + feedDescription); if( shareStyle == "short" ){ if( shareDialog == "feed" ){ //APPEND TWITTER SHARE refTitle = refTitle.replace("039", ""); refTitle = refTitle.replace("'", ""); share_url = 'https://twitter.com/share?url='+encodeURIComponent(ref_url)+'&text='+ new_twt_share_text +'&related='+SITE_INFO['twitter_related']; //share_url = share_url.replace("039", ""); //share_url = share_url.replace("'", ""); //console.log(share_url); toolset.append(""); feedName = feedName.replace("'", ""); toolset.append(""); //APPEND FACEBOOK SHARE //share_url = 'https://www.facebook.com/sharer/sharer.php?u='+ref_url; //toolset.append(""); }else{ //APPEND TWITTER SHARE refTitle = refTitle.replace("039", ""); refTitle = refTitle.replace("'", ""); feed_temp = refTitle.split('|'); refTitle = feed_temp[0]; share_url = 'https://twitter.com/share?url='+encodeURIComponent(ref_url)+'&text='+ encodeURIComponent(refTitle) +'&related='+SITE_INFO['twitter_related']; //share_url = share_url.replace("039", ""); //share_url = share_url.replace("'", ""); //console.log('Share URL: ' + share_url); toolset.append(""); //APPEND FACEBOOK SHARE share_url = 'https://www.facebook.com/sharer/sharer.php?u='+ref_url; toolset.append(""); } //Linked In global share url - used in short style sharing or when clicking the plus/more button menu var lin_share_url = 'https://www.linkedin.com/shareArticle?mini=true&url='+encodeURIComponent(ref_url)+'&title='+encodeURIComponent(refTitle)+'&summary='+encodeURIComponent(refTitle)+'&source='+SITE_INFO['site_title']; //Google Plus global share url - used in short style sharing when sharing is inside plus/more button menu var gp_share_url = 'https://plus.google.com/share?url='+ref_url; //APPEND MORE DRAWER //style=\"display:none;\" toolset.append("" + "" + "
" + "
" + " " + "" + red_btn_html + "" + "" //+ "
" //+ "" //+ "
Email Link to Friends
" //+ "
" //+ rctools_genSendEmailsForm(ref_url) //+ "
" //+ "
" + "
" + print_icon_html + "
" + "
" + "
" + "
"); } //end short bar else if( shareStyle == "full" ){ if( shareDialog == "feed" ){ //APPEND TWITTER SHARE twt_share_text = twt_share_text.replace("039", ""); twt_share_text = twt_share_text.replace("'", ""); share_url = 'https://twitter.com/share?url='+encodeURIComponent(ref_url)+'&text='+ encodeURIComponent(twt_share_text) +'&related='+SITE_INFO['twitter_related']; //share_url = share_url.replace("039", ""); //share_url = share_url.replace("'", ""); //console.log(share_url); toolset.append(""); //APPEND FACEBOOK SHARE feedName = feedName.replace("'", ""); toolset.append(""); //APPEND FACEBOOK SHARE //share_url = 'https://www.facebook.com/sharer/sharer.php?u='+ref_url; //toolset.append(""); }else{ //APPEND TWITTER SHARE refTitle = refTitle.replace("039", ""); refTitle = refTitle.replace("'", ""); share_url = 'https://twitter.com/share?url='+encodeURIComponent(ref_url)+'&text='+ encodeURIComponent(refTitle) +'&related='+SITE_INFO['twitter_related']; //share_url = share_url.replace("039", ""); //share_url = share_url.replace("'", ""); //console.log(share_url); toolset.append(""); //APPEND FACEBOOK SHARE share_url = 'https://www.facebook.com/sharer/sharer.php?u='+ref_url; toolset.append(""); } //APPEND LINKEDIN share_url = 'https://www.linkedin.com/shareArticle?mini=true&url='+encodeURIComponent(ref_url)+'&title='+encodeURIComponent(refTitle)+'&summary='+encodeURIComponent(refTitle)+'&source='+SITE_INFO['site_title']; toolset.append(""); //APPEND GOOGLE+ share_url = 'https://plus.google.com/share?url='+ref_url; toolset.append(""); //APPEND EMAIL MARKUP //style=\"display:none;\" toolset.append("" + "" //+ "
" //+ "" //+ "
Email Link to Friends
" //+ "
" //+ rctools_genSendEmailsForm(ref_url) //+ "
" //+ "
" + print_icon_html + "
"); } //end full bar else if( shareStyle == "site" ){ //APPEND TWITTER SHARE site_url = SITE_INFO['global_site_url']; share_url = 'https://twitter.com/share?url='+encodeURIComponent(site_url); //share_url = share_url.replace("039", ""); //share_url = share_url.replace("'", ""); //console.log(share_url); toolset.append(""); //APPEND FACEBOOK SHARE share_url = 'https://www.facebook.com/sharer/sharer.php?u='+site_url; toolset.append(""); //APPEND LINKEDIN share_url = 'https://www.linkedin.com/shareArticle?mini=true&url='+encodeURIComponent(site_url)+'&source='+SITE_INFO['site_title']; toolset.append(""); //APPEND GOOGLE+ share_url = 'https://plus.google.com/share?url='+site_url; toolset.append(""); } else if( shareStyle == "mobile" ){ //APPEND TWITTER SHARE share_url = 'https://twitter.com/share?url='+encodeURIComponent(ref_url)+'&text='+ encodeURIComponent(refTitle) +'&related='+SITE_INFO['twitter_related']; //share_url = share_url.replace("039", ""); //share_url = share_url.replace("'", ""); //console.log(share_url); toolset.append(""); //APPEND FACEBOOK SHARE share_url = 'https://www.facebook.com/sharer/sharer.php?u='+ref_url; toolset.append(""); //APPEND SMS BUTTON sms_body = ref_url; //var isIOS8 = function() { var deviceAgent = navigator.userAgent.toLowerCase(); var isIOS = false; var sms_body_switch; if(/ipad|ipod|iphone/i.test(navigator.userAgent)) { //if ios //return /(iphone|ipod|ipad).* os 8_/.test(deviceAgent); var isIOS = true; if(isIOS){ if( /(iphone|ipod|ipad).* os 8_/.test(deviceAgent) ){ sms_body_switch = '&'; }else if( /(iphone|ipod|ipad).* os 7_/.test(deviceAgent) ){ sms_body_switch = ';'; }else{ sms_body_switch = '?'; } } }else{ //if anything BUT iOS sms_body_switch = '?'; } //alert(sms_body_switch); toolset.append(""); //APPEND EMAIL MARKUP //style=\"display:none;\" toolset.append("" + "" //+ "
" //+ "" //+ "
Email Link to Friends
" //+ "
" //+ rctools_genSendEmailsForm(ref_url) //+ "
" //+ "
" + "
"); }//end site bar $(this).addClass('has-tools'); }); if(any_print_button) { if($(".socialBar .print_icon").length) { $(".socialBar .print_icon").unbind('click'); $(".socialBar .print_icon").click(function() { window.print(); }); } } }//end socialTools function //fixex to include encode properly function fixedEncodeURIComponent(str) { return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { return '%' + c.charCodeAt(0).toString(16); }); } function shareOnFacebook(feedName, feedCaption, feedDescription, feedLink, feedPhoto){ var ogImg = $('meta[property="og:image"]').attr('content'); if( feedPhoto == "" ){ if( ogImg != "" ){ feedPhoto = ogImg; }else{ feedPhoto = feedPhoto = document.domain+'/asset/img/og-default.png'; } } FB.ui({ method: 'feed', name: feedName, link: feedLink, caption:feedCaption, picture: feedPhoto, description: feedDescription }, function(response) { if(response && response.post_id){} else{} }); } function initSocialDrawer(){ //ICON BUTTONS WITH DRAWERS CLICK -- SHOW DRAWER $(".jqDrawer").click(function(){ if($(this).parent().children(".toolset_drawer").is(':hidden')){ $(".socialBar .left .more-wrapper .toolset_drawer").hide(); //we must hide all other first $(this).parent().children(".toolset_drawer").show(200); //SHOW ONE YOU CLICKED ON //$(this).parent().find(".toolset_drawer .fieldset").css({ "opacity" : "1" }); //set visibility of form //rctools_initEmailControls($(this).parent(),ref_title); //init controls }else{ $(this).parent().children(".toolset_drawer").hide(200); } }); } function initEmailDrawer(){ //ICON BUTTONS WITH DRAWERS CLICK -- SHOW DRAWER ref_title = $(document).find("title").text(); var new_ref_title = ref_title.replace("'",""); var refTitle = new_ref_title.replace("'",""); } //BUILDS SOCIAL BUTTONS function rctools_genSocialToolsDropDown(share_url,share_title){ var output = ""; output += "
" + "" + "
" //+ "" + "
" + "
" + "" + "
" + "
" + "
"; return output; } //BUILDS EMAIL FORM function rctools_genSendEmailsForm(share_url){ var output = "
" + "
" + "

" + "
" + "Your Name:
" + "
" + "Your E-mail:
" + "
" + "
" + "Friend\'s E-mail(s):
" + "" + "
+
" + "
" + "Message:(optional)
" + "
" + "" + "
Close
" + "
" + "
"; return output; } //SOCIAL OPEN WINDOW function rctools_openShareWindow(name,url,width){ w = typeof w !== 'undefined' ? width : 550; var sTop = window.screen.height/2-(218); var sLeft = window.screen.width/2-(313); window.open(url,name,"height=450, width="+w+", top="+sTop+", left="+sLeft+", toolbar=0, location=0, menubar=0, directories=0, scrollbars=0"); } function rctools_initEmailControls(parent,title){ //*CURRENT* EMAIL CONTAINER TARGET ELEMENT var emailBox = parent.find('.toolset_drawer .send-btn-form'); //SET TRIGGER FOR + ICON var gindex = 1; emailBox.find(".addEmailBtn").click(function(){ gindex++; rctools_addField(gindex,emailBox); emailBox.find('[data-index="' + (gindex).toString() + '"]').focus(); }); //SET TRIGGER TO ADD NEW FIELDS WHEN HITTING RETURN AND COMMA emailBox.on('keydown', 'input', function (event) { if (event.which == 13 || event.which == 188) { event.preventDefault(); var $this = $(event.target); var index = parseFloat($this.attr('data-index')); $('[data-index="' + (index + 1).toString() + '"]').focus(); if(index >=1){ gindex++; rctools_addField(gindex,emailBox) emailBox.find('[data-index="' + (gindex).toString() + '"]').focus(); } } }); emailBox.find("#sendBtn").unbind("click").click(function(e){ var emailForm = $(this).parent().parent(); e.preventDefault(); //emailBox.append("

orale guey

"); //var title = $("title").html(); emailForm.find(".emailLoader").show(); emailForm.find(".fieldset").css({ "opacity" : "0.3" }); //get site name via url var getUrl = document.domain; //strip params off url to get raw site name var url = getUrl.replace(".com",""); var site = url.replace("www.",""); var siteName = site.replace("www1.",""); //Get the data-feed-url from the div.hover-social, or fall back on window.location.href var pageLink = parent.parent().parent().parent().attr('data-feed-url') || window.location.href; //Get the data-feed-name from the div.hover-social, or fall back on title passed in to the function title = parent.parent().parent().parent().attr('data-feed-name') || title; var name = emailForm.find("#senderName").val(); var sEmail = emailForm.find("#senderEmail").val(); var recEmail = emailForm.find("#recpEmail").val(); var msg = emailForm.find("#optMessage").val(); var send = true; if( name == "" ){ //alert ('Please Add Name'); emailForm.find("#msgBox").html("Please Add Name"); emailForm.find("#msgBox").show().delay(3000).fadeOut(); emailForm.find(".emailLoader").hide(); emailForm.find(".fieldset").css({ "opacity" : "1" }); send = false; } if( sEmail == "" ){ //alert('Please Enter Email'); emailForm.find("#msgBox").html("Please Enter Email"); emailForm.find("#msgBox").show().delay(3000).fadeOut(); emailForm.find(".emailLoader").hide(); emailForm.find(".fieldset").css({ "opacity" : "1" }); send = false; } if( recEmail == "" ){ //alert('Please Enter Recipients Email'); emailForm.find("#msgBox").html("Please Enter Recipients Email"); emailForm.find("#msgBox").show().delay(3000).fadeOut(); emailForm.find(".emailLoader").hide(); emailForm.find(".fieldset").css({ "opacity" : "1" }); send = false; } if( msg != "" ){ if (emailForm.find('#optMessage').val().match(/<(\w+)((?:\s+\w+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)>/) || emailForm.find('#optMessage').val().match(/http/i) || emailForm.find('#optMessage').val().match(/www./i)) { //alert('msg has html'); emailForm.find('#msgBox').html("NO Links or HTML allowed. Please re-enter Message."); emailForm.find("#msgBox").show().delay(3000).fadeOut(); emailForm.find(".emailLoader").hide(); emailForm.find(".fieldset").css({ "opacity" : "1" }); var msg = emailForm.find("#optMessage").val(""); send = false; } } //var emailArray = new Array('idelgado@rcp.com','delgado.ivan@gmail.com', 'mb@rcp.com'); var emailArray = new Array(); emailForm.find("#addEmailForm input").each(function(i){ var emails = $(this).val(); emailArray.push(emails); }); emailArray.push(recEmail); //append first field //if(send == true){ if(rctools_verifyEmail(sEmail) && rctools_verifyEmail(emailArray)){ var sEmailLen = sEmail.length; var recEmailLen = recEmail.length; if(sEmailLen <= 200 && recEmailLen <= 200){ if(send == true || send == "true"){ $.getJSON(window.location.protocol+"//util.realclearpolitics.com/email/app/sendemail.php?jsoncallback=?",{ name:name, sEmail:sEmail, recEmail:recEmail, msg:msg, siteName:siteName, pageLink:pageLink, emailArray:emailArray, title:title }, function(data) { $.each(data, function(key,val){ if(key == "response"){ if(val == 1){ emailForm.find(".emailLoader").hide(); var name = $(".fieldset #senderName").val(""); var sEmail = $(".fieldset #senderEmail").val(""); var recEmail = $(".fieldset #recpEmail").val(""); var msg = $(".fieldset #optMessage").val(""); emailBox.find("#msgBox").html("Your email has been sent."); emailBox.find("#msgBox").show().delay(4000).fadeOut(); //$('.toolset_drawer').delay(5000).hide(200); }else if(val == 2){ //alert('Please wait one minute before sending another email to a friend'); emailForm.find("#msgBox").html("Please wait one minute before sending another email to a friend"); emailForm.find("#msgBox").show().delay(3000).fadeOut(); emailForm.find(".emailLoader").hide(); emailForm.find(".fieldset").css({ "opacity" : "1" }); }else if(val == 3){ emailForm.find("#msgBox").html("Error: Email did not send. Please Contact Us for support."); emailForm.find("#msgBox").show().delay(9000).fadeOut(); emailForm.find(".emailLoader").hide(); emailForm.find(".fieldset").css({ "opacity" : "0" }); //parent.find('.toolset_drawer').delay(5000).hide(200); }else{ //alert('Error: Please try again'); $("#msgBox").html("Error: Please try again"); $("#msgBox").show().delay(3000).fadeOut(); emailForm.find(".emailLoader").hide(); emailForm.find(".fieldset").css({ "opacity" : "1" }); } } }); }); } //end if send is true - no errors }else{ //alert('Email is too long. Please try again.'); emailForm.find("#msgBox").html("Email is too long. Please try again."); emailForm.find("#msgBox").show().delay(3000).fadeOut(); emailForm.find(".emailLoader").hide(); emailForm.find(".fieldset").css({ "opacity" : "1" }); } }else{ //alert('Invalid Email. Please correct and try again'); emailForm.find("#msgBox").html("Invalid Email. Please correct and try again."); emailForm.find("#msgBox").show().delay(3000).fadeOut(); emailForm.find(".emailLoader").hide(); emailForm.find(".fieldset").css({ "opacity" : "1" }); } //} //end if send - no errors }); //end send to friend handler } //SENDMAIL HELPER FUNCS function rctools_addField(gindex,box){ var addEmailInput = '
'; box.find("#addEmailForm").append(addEmailInput); } function rctools_verifyEmail(email) { // Validate an email address, or an array of addresses. var emailReg = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,20}$/; if(email.constructor === Array) { for(var i=0; i 0 && $('body.polls').length == 0) { $.ajax({ dataType: 'json', url: window.location.href.substring(0, window.location.href.lastIndexOf('.') ) + '.json', success: function(data) { console.log(data); var pageviews = 0; var pageviews_text = ''; if(data.hasOwnProperty('today_pageviews')) { pageviews += parseInt(data['today_pageviews']); } if(data.hasOwnProperty('total_pageviews')) { pageviews += parseInt(data['total_pageviews']); } if(pageviews < 1) { $pv.hide(); $('.socialBar-divide').hide(); } else { pageviews_text = social_number_format(pageviews); } $pv.html(pageviews_text + ' Views'); }, timeout: 2000, error: function(jqXHR, textStatus, errorThrown) { $pv.hide(); $('.socialBar-divide').hide(); } }); } else { $('.socialBar-divide').hide(); } }*/ function social_number_format(num) { if(num < 1000) { return num; } else if(num < 10000) { return (Math.floor(num/100) / 10) + 'k'; } else if(num < 1000000) { return Math.floor(num/1000) + 'k'; } else if(num < 10000000) { return (Math.floor(num/100000) / 10) + 'M'; } else if(num < 1000000000) { return Math.floor(num/1000000) + 'M'; } else { return (Math.floor(num/100000000) / 10) + 'B'; // It could happen } } /*function populateShares(){ $(".socialBar").each(function() { if($(this).parent().find('.socialBar-shares').length > 0 || $(this).parent().parent().next('.socialBar-bottom-counts').length > 0 || $(this).parent().parent().next('.socialBar-top-counts').length > 0 || $(this).parent().parent().next('.socialBar-mobile-counts').length > 0 ) { //console.log('length: '+$(this).parent().find('.socialBar-shares').length); //console.log('length: '+$(this).parent().parent().next('.socialBar-bottom-counts').length); populateSharesSingle($(this)); } }); } function populateSharesSingle(container){ var shareUrl = ''; if( typeof container.attr("data-src-url") !=="undefined" ){ shareUrl = container.attr("data-src-url"); }else{ shareUrl = window.location.href; } //console.log("This Here URL... " + shareUrl); $.ajax({ url: 'https://graph.facebook.com/?id='+shareUrl, dataType: 'jsonp', ref: container, success: function(data){ var ref = this.ref; // New data structure, post 8/19/2016 var share = data.share; //console.log(share); var shareCount = 0; if( typeof share !== 'undefined') { // case where no shares available yet shareCount = share.share_count; if( shareCount == '' || shareCount == 'undefined' || shareCount == undefined ){ shareCount = 0; }else{ shareCount = shareCount; } } ref.fbDone=true; ref.fbShares = shareCount; socialDone(ref); }, timeout: 4000, error: function(jqXHR, textStatus, errorThrown) { this.ref.fbDone=true; this.ref.fbShares = 0; socialDone(this.ref); } }); $.ajax({ url: 'https://www.linkedin.com/countserv/count/share?url='+shareUrl+'&callback=myCallback&format=jsonp', ref: container, dataType: "jsonp", jsonpCallback: "myCallback", success: function (data) { var ref = this.ref; $(data).each(function(i,k){ var linCount = k.count; ref.linDone=true; ref.linkedCount = linCount; socialDone(ref); }); }, timeout: 4000, error: function(jqXHR, textStatus, errorThrown) { this.ref.linDone=true; this.ref.linkedCount = 0; socialDone(this.ref); } }); }*/ function socialDone(c){ //M.B. updated 9.8.16 - removing twitter from totals as they do not offer counts anymore if( c.fbDone == true && c.linDone == true ){ //if( c.fbDone == true && c.twtDone == true && c.linDone == true ){ //console.log('successful c:'); //console.log(c); //total shared count from all 3 social networks //console.log('fb: '+c.fbShares + ', twt: ' + c.twtCount + ', li: ' + c.linkedCount); //M.B. UPDATED 9.8.16 - NO MORE TWITTER var totalSharesCount = c.fbShares + c.linkedCount; //var totalSharesCount = c.fbShares + c.twtCount + c.linkedCount; //formatted version of the total share count - 12,365 total == 12.3k var totalCount = nFormatter(totalSharesCount); if( totalSharesCount > 49 ){ //$(".socialBar-shares").html(totalCount + ' Shares'); //$(".socialBar-divide").css({"display" : "inline-block"}); //$(".socialBar-shares").css({"display" : "inline-block"}); c.parent().find(".socialBar-shares").each(function() { $(this).html(totalCount + ' Shares'); $(this).css({"display" : "inline-block"}); if($(this).parent().find('.socialBar-clicks').is(':visible')) { $(this).parent().find('.socialBar-divide').css({"display" : "inline-block"}); } }); c.parent().parent().next('.socialBar-bottom-counts').find('.socialBar-shares').each(function() { $(this).html(totalCount + ' Shares'); $(this).css({"display" : "inline-block"}); if($(this).parent().find('.socialBar-clicks').is(':visible')) { $(this).parent().find('.socialBar-divide').css({"display" : "inline-block"}); } }); }else{ //$(".socialBar-shares").html(totalCount + ' Shares'); //$(".socialBar-divide").css({"display" : "none"}); //$(".socialBar-shares").css({"display" : "none"}); c.parent().find(".socialBar-shares").each(function() { $(this).html(totalCount + ' Shares'); $(this).css({"display" : "none"}); $(this).parent().find('.socialBar-divide').css({"display" : "none"}); }); } } } //function to format numeric results - 12,654 == 12.6k etc,... function nFormatter(num) { if (num >= 1000000000) { return (num / 1000000000).toFixed(1).replace(/\.0$/, '') + 'B'; } if (num >= 1000000) { return (num / 1000000).toFixed(1).replace(/\.0$/, '') + 'M'; } if (num >= 1000) { return (num / 1000).toFixed(1).replace(/\.0$/, '') + 'k'; } return num; } //GET SOCIAL NETWORK SHARE COUNTS function getFbShareCount(){ var shareUrl = window.location.href; $.ajax({ url: 'https://graph.facebook.com/?id='+shareUrl, success: function(data){ $(data).each(function(i,k){ //alert(k.shares); var fbShares = k.shares; if( fbShares == '' || fbShares == 'undefined' || fbShares == undefined ){ fbShares = 0; }else{ fbShares = fbShares; $(".fb_icon .bubble").css({ "display" : "block" }); } $(".fb_icon .bubble").html(fbShares); }); } }); } function getTweetCount(){ var shareUrl = window.location.href; $.ajax({ url: 'https://urls.api.twitter.com/1/urls/count.json?url='+shareUrl, dataType: "jsonp", success: function (data) { $(data).each(function(i,k){ //alert(k.shares); var twtCount = k.count; if( twtCount == '' ){ twtCount = 0; }else{ twtCount = twtCount; $(".tweet_icon .bubble").css({ "display" : "block" }); } $(".tweet_icon .bubble").html(twtCount); }); } }); } function getLinkedCount(){ var shareUrl = window.location.href; $.ajax({ url: 'https://www.linkedin.com/countserv/count/share?url='+shareUrl+'&callback=myCallback&format=jsonp', dataType: "jsonp", jsonpCallback: "myCallback", success: function (data) { $(data).each(function(i,k){ //alert(k.shares); var linkedCount = k.count; if( linkedCount == '' ){ linkedCount = 0; }else{ linkedCount = linkedCount; $(".lnkdin_icon .bubble").css({ "display" : "block" }); } $(".lnkdin_icon .bubble").html(linkedCount); }); } }); } //SET UP FACEBOOK COMMENTS/ADMINS ELEMENTS - MUST GO BEFORE EXECUTION OF FACEBOOK SDK /*function load_fbcomments() { var comments_container = document.getElementById("fb-comments-container"); if(comments_container != null ) { var div_fb_comments = document.createElement("div"); div_fb_comments.setAttribute("class","fb-comments"); div_fb_comments.setAttribute("data-href", window.location.hostname+window.location.pathname); div_fb_comments.setAttribute("data-numposts", "20"); div_fb_comments.setAttribute("data-colorscheme", "light"); div_fb_comments.setAttribute("data-width", "100%"); comments_container.appendChild(div_fb_comments); } //END SET UP FACEBOOK ELEMENTS } function load_fb_sdk() { window.fbAsyncInit = function() { // init the FB JS SDK FB.init({ appId : FB_app_id, // App ID from the app dashboard status : true, // Check Facebook Login status xfbml : true // Look for social plugins on the page }); // channelUrl : '//WWW.YOUR_DOMAIN.COM/channel.html', // Channel file for x-domain comms // Additional initialization code such as adding Event Listeners goes here }; // Load the SDK asynchronously (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 = "//connect.facebook.net/en_US/all.js"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); }*/ //////////////////////////////////////////////////////////////////////////////// // UTILITY FUNCTIONS /////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// function hasClass(el, className) { return el.classList ? el.classList.contains(className) : new RegExp('\\b'+ className+'\\b').test(el.className); } function isVisible(el) { return !!( el.offsetWidth || el.offsetHeight || el.getClientRects().length ); } function isVisibleOnScreen(elm) { var rect = elm.getBoundingClientRect(); var doc = document.documentElement; var viewHeight = Math.max(doc.clientHeight, window.innerHeight); // console log if true /*if(!(rect.bottom < 0 || rect.top >= viewHeight || (rect.height == 0 && rect.width == 0))) { console.log('-----------------------------------------'); console.log(elm); console.log('rect.bottom: '+rect.bottom); console.log('rect.top: '+rect.top); console.log('topScroll: '+viewHeight); console.log('-----------------------------------------'); }*/ return !(rect.bottom < 0 || rect.top >= viewHeight || (rect.height == 0 && rect.width == 0)); } function firstVisibleElement(str) { var results = Array.prototype.slice.call(document.querySelectorAll(str)) .filter(function (item,index) { if( isVisible(item) ) { return true; } else { return false; } }); if(results && results.length) { return results[0]; } else { return null; } } function readCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null; } function createCookie(name,value,days, expire_in_hours ) { if (days) { //allows us to set cookie expirations based on hours rather than days if(typeof expire_in_hours !== 'undefined' && expire_in_hours == true){ var date = new Date(); date.setTime(date.getTime()+(days*60*60*1000)); var expires = "; expires="+date.toGMTString(); }else{ var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); var expires = "; expires="+date.toGMTString(); } } else var expires = ""; document.cookie = name+"="+value+expires+"; path=/; domain=."+getDomain()+""; } function eraseCookie(name) { createCookie(name,"",-1); } //handler to fire script from script function loadscript(script_url, target_id, callback, attr_obj) { var elem = document.getElementById(target_id); var script = document.createElement('script'); script.type = 'text/javascript'; script.src = script_url; if(typeof attr_obj != 'undefined') { for(var k in attr_obj) { script[k] = attr_obj[k]; script.attributes[k] = attr_obj[k]; script.setAttribute(k, attr_obj[k]); } } if(callback != null) { script.onreadystatechange = callback; script.onload = callback; } elem.appendChild(script); } function getDocHeight() { var D = document; return Math.max( D.body.scrollHeight, D.documentElement.scrollHeight, D.body.offsetHeight, D.documentElement.offsetHeight, D.body.clientHeight, D.documentElement.clientHeight ); } //used with createcookie function to match domain function getDomain(){ var path = window.location.host; if(path.substr(0,3)=='www'){ var per=path.indexOf('.') per=per+1; path=path.substr(per); } return path; } //gets querystring variable value function getQueryVariable(variable) { var query = window.location.search.substring(1); var vars = query.split("&"); for (var i=0;i 2) { href = event.target.href; } else { href = event.target.parentNode.href; } } //Build the params to go to click tracking. var url = window.location.protocol+'//util.realclearpolitics.com/trackclicks/trackclick.php?'; url += 'site='+this.site+'&'; if(typeof(entry_id) != 'undefined') url += 'entry_id='+entry_id+'&'; if(typeof(atxt) != 'undefined') url += 'atxt='+atxt+'&'; if(typeof(site_module) != 'undefined') url += 'site_module='+site_module+'&'; url += 'entry_url='+href+'&'; if(typeof(section) != 'undefined') url += 'section='+section; if(parseInt(permanent) == 1) url += '&perm='+'1'+'&position='+position+'&partner_title='+partner_title; try{ var tclick = this.ajax(url); console.log(tclick); } catch(err) { console.log("Track failed: "+err.message); } finally { if(event.ctrlKey || event.metaKey) { //If right-click or control click return true; } else { target = event.target.target; if(typeof target !== "undefined" && target !== false && target == '_blank'){ window.open(href); }else{ window.setTimeout('document.location = "' + href + '"', 100); //Go to hyperlink return false; } } } } }; //**End Click Tracking**/ //////////////////////////////////////////////////////////////////////////////// // SCRIPT LOADING FUNCTIONS //////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /* NAME: loadScriptsDynamicSync INPUT: arr_of_scripts (array of objects) RETURNS: - SIDE EFFECT: writes script tags in order to trigger synchronous execution By writing a script tag directly to the page we are able to trigger a dynamic synchronous execution of a js file. arr_of_scripts must be an array of objects that at least have a property of 'src' equal to some valid javascript url. We also allow any additional attributes to be specified. */ function loadScriptsDynamicSync(arr_of_scripts) { for(var i = 0; i < arr_of_scripts.length; i++) { var extra_attr = ''; for(var key in arr_of_scripts[i]) { if(arr_of_scripts[i].hasOwnProperty(key)) { if(key != 'src') { extra_attr += ' '+key+'="'+arr_of_scripts[i][key]+'" '; } } } document.write('\x3Cscript type="text/javascript" src="'+arr_of_scripts[i]['src']+'" '+extra_attr+'>\x3C/script>'); } } // This should only be called once per pageload, before any of the loaded scripts are needed function loadTopScripts() { if(typeof rcmg_top_scripts !== 'undefined') { loadScriptsDynamicSync(rcmg_top_scripts); } } //////////////////////////////////////////////////////////////////////////////// // WIDGETS FUNCTIONS /////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// function load_widget(widget_id, w_container) { if(typeof w_container[0].loaded_dropdown_widgets === 'undefined') { w_container[0].loaded_dropdown_widgets = ''; } w_container.addClass('overlay'); var now_time = new Date().getTime(); now_time = Math.floor(now_time / 100000); // Changes every 100 seconds $.get( '/widget/'+widget_id+'.json?no_cache='+now_time, function(widget_data) { w_container.attr('data-widget-type', widget_data['type']); w_container.attr('data-widget-title', widget_data['title']); if(widget_data['type'] == 'feed') { if(widget_data['feed_info']['feed_type'] == 'json') { if(typeof widget_data['feed_info']['jsonp_callback'] !== 'undefined') { // Is JSONP $.ajax({ crossDomain: true, url: widget_data['feed_info']['feed_url']+'?no_cache='+now_time, dataType: 'jsonp', jsonp: 'callback', jsonpCallback: widget_data['feed_info']['jsonp_callback'], container_ref: w_container, success : function(feed_data) { feed_loaded(widget_data, feed_data, this.container_ref); this.container_ref.removeClass('overlay'); } }); } else { // Is JSON /*$.getJSON(widget_data['feed_info']['feed_url'], function(feed_data) { feed_loaded(widget_data, feed_data, w_container); w_container.removeClass('overlay'); });*/ $.ajax({ dataType: 'json', url: widget_data['feed_info']['feed_url']+'?no_cache='+now_time, container_ref: w_container, success: function(feed_data) { feed_loaded(widget_data, feed_data, this.container_ref); this.container_ref.removeClass('overlay'); } }); } } else if(widget_data['feed_info']['feed_type'] == 'rss') { // Is XML $.ajax({ type: 'GET', url: widget_data['feed_info']['feed_url']+'?no_cache='+now_time, dataType: 'xml', container_ref: w_container, success : function(feed_xml) { feed_loaded(widget_data, feed_xml, this.container_ref); this.container_ref.removeClass('overlay'); } }); } } else if(widget_data['type'] == 'story_stream') { story_stream_loaded(widget_data, w_container); w_container.removeClass('overlay'); } else if(widget_data['type'] == 'race') { // JSONP historical data $.ajax({ crossDomain: true, url: 'https://www.realclearpolitics.com/epolls/json/'+widget_data['race_id']+'_historical.js?no_cache='+now_time, dataType: 'jsonp', jsonp: 'callback', jsonpCallback: 'return_json', container_ref: w_container, success : function(historical_data) { // Get candidates JSON $.ajax({ dataType: 'json', url: '/poll/race/'+widget_data['race_id']+'/candidates.json?no_cache='+now_time, container_ref: this.container_ref, success: function(candidates_data) { $.ajax({ dataType: 'json', url: '/poll/race/'+widget_data['race_id']+'/polling_data.json?no_cache='+now_time, container_ref: this.container_ref, success: function(polling_data) { var race_title = polling_data['moduleInfo']['title']; race_loaded(widget_data, historical_data, candidates_data, this.container_ref, race_title); this.container_ref.removeClass('overlay'); } }); } }); // Get candidates json // $.getJSON('/poll/race/'+widget_data['race_id']+'/candidates.json?no_cache='+now_time, function(candidates_data) // { // // Get polling data json just for race title // $.getJSON('/poll/race/'+widget_data['race_id']+'/polling_data.json?no_cache='+now_time, function(polling_data) // { // var race_title = polling_data['moduleInfo']['title']; // race_loaded(widget_data, historical_data, candidates_data, this.container_ref, race_title); // this.container_ref.removeClass('overlay'); // }); // }); } }); } else if(widget_data['type'] == 'rcp_averages') { var race_id_arr = widget_data['race_ids'].replace(/ /g, '').split(','); rcp_avg_w_total = race_id_arr.length; for(var i = 0; i < race_id_arr.length; i++) { $.ajax({ dataType: 'json', url: '//www.realclearpolitics.com/poll/race/'+race_id_arr[i]+'/historical_data.json?no_cache='+now_time, container_ref: w_container, i_ref: i, success : function(historical_data) { rcp_avg_w_data[this.i_ref] = historical_data; rcp_avg_w_loaded(widget_data, this.container_ref); } }); } } else if(widget_data['type'] == 'head_to_head') { head_to_head_loaded(widget_data, w_container); w_container.removeClass('overlay'); } else if(widget_data['type'] == 'latest_polls') { // Get json latest polls feed $.ajax({ dataType: 'json', url: widget_data['feed_info']['feed_url'], container_ref: w_container, success: function(latest_polls_data) { latest_polls_loaded(widget_data, latest_polls_data, this.container_ref); this.container_ref.removeClass('overlay'); } }); } else if(widget_data['type'] == 'custom') { custom_widget_loaded(widget_data, w_container); w_container.removeClass('overlay'); } },'json'); } function rcp_avg_w_loaded(widget_data, w_container) { for(var i = 0; i < rcp_avg_w_total; i++) { if(typeof rcp_avg_w_data[i] === 'undefined') { return; } } w_container.removeClass('overlay'); console.log('rcp_avg_w_data'); console.log(rcp_avg_w_data); // Load dropdown widgets if new, else keep old dropdown info if(w_container[0].loaded_dropdown_widgets.length == 0) { if(widget_data['dropdown_widgets'].length > 0) { w_container[0].loaded_dropdown_widgets = widget_data['dropdown_widgets']; // Add self to list (will be hidden later) w_container[0].loaded_dropdown_widgets.unshift({ 'id' : widget_data['id'], 'title' : widget_data['title'], 'dropdown_title' : widget_data['dropdown_title'], 'color' : widget_data['color'] }); } else { w_container[0].loaded_dropdown_widgets = 'none'; } } w_container[0].current_item_num = 0; var subtitle = ''; var hide_dropdown = 'style="display:none;"'; if(widget_data['dropdown_title'].length > 0 && widget_data['dropdown_widgets'].length > 0) { subtitle = 'Select Poll'; hide_dropdown = ''; } var widget_html = ''; widget_html += '
'; widget_html += '
Story Stream Icon '+widget_data['title']+'
'; widget_html += '
'; widget_html += '
'+subtitle+'
'; if(w_container[0].loaded_dropdown_widgets != 'none') { widget_html += ''; } widget_html += ''; widget_html += '
'; if(w_container[0].loaded_dropdown_widgets != 'none') { widget_html += '
    '; for(var key_d in w_container[0].loaded_dropdown_widgets) { var d_title = ''; if(typeof w_container[0].loaded_dropdown_widgets[key_d]['dropdown_title'] !== 'undefined' && w_container[0].loaded_dropdown_widgets[key_d]['dropdown_title'] !== null && w_container[0].loaded_dropdown_widgets[key_d]['dropdown_title'].length > 0) { d_title = w_container[0].loaded_dropdown_widgets[key_d]['dropdown_title']; } else { d_title = w_container[0].loaded_dropdown_widgets[key_d]['title']; } var d_color = ''; var d_background_color = 'data-bcolor=""'; if(w_container[0].loaded_dropdown_widgets[key_d]['color'] != '') { d_color = 'style="color:'+w_container[0].loaded_dropdown_widgets[key_d]['color']+';"'; d_background_color = 'data-bcolor="'+w_container[0].loaded_dropdown_widgets[key_d]['color']+'"'; } widget_html += ''; } widget_html += '
'; } widget_html += '
'; widget_html += '
'; widget_html += '
'; var max_height_style = ''; if(widget_data['max_height'] > 0) { max_height_style = 'style="max-height: '+widget_data['max_height']+'px;"'; } widget_html += ''; w_container.html(widget_html); bottom_fade(w_container); widget_link_events(w_container); } function custom_widget_loaded(widget_data, w_container) { // Load dropdown widgets if new, else keep old dropdown info if(w_container[0].loaded_dropdown_widgets.length == 0) { if(widget_data['dropdown_widgets'].length > 0) { w_container[0].loaded_dropdown_widgets = widget_data['dropdown_widgets']; // Add self to list (will be hidden later) w_container[0].loaded_dropdown_widgets.unshift({ 'id' : widget_data['id'], 'title' : widget_data['title'], 'dropdown_title' : widget_data['dropdown_title'], 'color' : widget_data['color'] }); } else { w_container[0].loaded_dropdown_widgets = 'none'; } } var new_dropdown_color = ''; var subtitle_color = ''; if(w_container[0].loaded_dropdown_widgets == 'none') { new_dropdown_color = 'style="background:none;"'; } else if(widget_data['text_color'] == '#000000') { subtitle_color = 'style="color:'+widget_data['text_color']+';"'; //new_dropdown_color = 'style="background-image:url(/asset/img/grey-bg-chev.png)"'; } var subtitle = ''; if(widget_data['dropdown_title'].length > 0) { subtitle = ''+widget_data['dropdown_title']+''; } var widget_html = ''; widget_html += '
'; widget_html += '
'+widget_data['title']+'
'; if(w_container[0].loaded_dropdown_widgets != 'none') { widget_html += '
'; widget_html += '
'+subtitle+'
'; if(w_container[0].loaded_dropdown_widgets != 'none') { widget_html += ''; } widget_html += ''; widget_html += '
'; if(w_container[0].loaded_dropdown_widgets != 'none') { widget_html += '
    '; for(var key_d in w_container[0].loaded_dropdown_widgets) { var d_title = ''; if(typeof w_container[0].loaded_dropdown_widgets[key_d]['dropdown_title'] !== 'undefined' && w_container[0].loaded_dropdown_widgets[key_d]['dropdown_title'] !== null && w_container[0].loaded_dropdown_widgets[key_d]['dropdown_title'].length > 0) { d_title = w_container[0].loaded_dropdown_widgets[key_d]['dropdown_title']; } else { d_title = w_container[0].loaded_dropdown_widgets[key_d]['title']; } var d_color = ''; var d_background_color = 'data-bcolor=""'; if(typeof w_container[0].loaded_dropdown_widgets[key_d]['color'] !== 'undefined' && w_container[0].loaded_dropdown_widgets[key_d]['color'] != '') { d_color = 'style="color:'+w_container[0].loaded_dropdown_widgets[key_d]['color']+';"'; d_background_color = 'data-bcolor="'+w_container[0].loaded_dropdown_widgets[key_d]['color']+'"'; } widget_html += ''; } widget_html += '
'; } widget_html += '
'; widget_html += '
'; } widget_html += '
'; widget_html += ''; w_container.html(widget_html); recommendedSitesMenu(w_container); recommendedSitesMenuHover(); recommendedSitesMenuItems(w_container); widget_link_events(w_container); if(parseInt(widget_data['id']) == 41 && SITE_INFO['name'] == 'world') { // Countries widget loadCountriesMenu(); } if(parseInt(widget_data['id']) == 45 && SITE_INFO['name'] == 'energy') { // States widget loadStatesMenu(); } } function head_to_head_loaded(widget_data, w_container) { // Load dropdown widgets if new, else keep old dropdown info if(w_container[0].loaded_dropdown_widgets.length == 0) { if(widget_data['dropdown_widgets'].length > 0) { w_container[0].loaded_dropdown_widgets = widget_data['dropdown_widgets']; // Add self to list (will be hidden later) w_container[0].loaded_dropdown_widgets.unshift({ 'id' : widget_data['id'], 'title' : widget_data['title'], 'dropdown_title' : widget_data['dropdown_title'], 'color' : widget_data['color'] }); } else { w_container[0].loaded_dropdown_widgets = 'none'; } } var new_dropdown_color = ''; var subtitle_color = ''; if(w_container[0].loaded_dropdown_widgets == 'none') { new_dropdown_color = 'style="background:none;"'; } else if(widget_data['text_color'] == '#000000') { subtitle_color = 'style="color:'+widget_data['text_color']+';"'; //new_dropdown_color = 'style="background-image:url(/asset/img/grey-bg-chev.png)"'; } var subtitle = ''; if(widget_data['dropdown_title'].length > 0) { subtitle = ''+widget_data['dropdown_title']+''; } var widget_html = ''; widget_html += '
'; widget_html += '
Flag Icon'+widget_data['title']+'
'; widget_html += '
'; widget_html += '
'+subtitle+'
'; if(w_container[0].loaded_dropdown_widgets != 'none') { widget_html += ''; } widget_html += ''; widget_html += '
'; if(w_container[0].loaded_dropdown_widgets != 'none') { widget_html += '
    '; for(var key_d in w_container[0].loaded_dropdown_widgets) { var d_title = ''; if(typeof w_container[0].loaded_dropdown_widgets[key_d]['dropdown_title'] !== 'undefined' && w_container[0].loaded_dropdown_widgets[key_d]['dropdown_title'] !== null && w_container[0].loaded_dropdown_widgets[key_d]['dropdown_title'].length > 0) { d_title = w_container[0].loaded_dropdown_widgets[key_d]['dropdown_title']; } else { d_title = w_container[0].loaded_dropdown_widgets[key_d]['title']; } var d_color = ''; var d_background_color = 'data-bcolor=""'; if(typeof w_container[0].loaded_dropdown_widgets[key_d]['color'] !== 'undefined' && w_container[0].loaded_dropdown_widgets[key_d]['color'] != '') { d_color = 'style="color:'+w_container[0].loaded_dropdown_widgets[key_d]['color']+';"'; d_background_color = 'data-bcolor="'+w_container[0].loaded_dropdown_widgets[key_d]['color']+'"'; } widget_html += ''; } widget_html += '
'; } widget_html += '
'; widget_html += '
'; widget_html += '
'; widget_html += '
'; widget_html += ''; widget_html += '
'; widget_html += '
'; if(widget_data['dropdown_races'].length > 0) { widget_html += '
    '; for(var key_d in widget_data['dropdown_races']) { var d_title = widget_data['dropdown_races'][key_d]['title']; var d_id = widget_data['dropdown_races'][key_d]['id']; widget_html += ''; } widget_html += '
'; } widget_html += ''; w_container.html(widget_html); get_head_to_head_body(widget_data, w_container); head_to_head_menu_init(); race_dropdown_items_init(widget_data, w_container); recommendedSitesMenu(w_container); recommendedSitesMenuHover(); recommendedSitesMenuItems(w_container); widget_link_events(w_container); } function head_to_head_menu_init(){ $('.head_to_head_candidates .menu').click(function(){ $(this).parent().parent().find('.head_to_head_race_dropdown').toggle(); }); } // Race dropdown menu items click function race_dropdown_items_init(widget_data, w_container) { $('.head_to_head_race_dropdown ul li span').click( { widget_data_ref:widget_data, container_ref:w_container }, function(event) { get_head_to_head_body(event.data.widget_data_ref, event.data.container_ref, $(this).attr('data-id')); //$('.head_to_head_race_dropdown').toggle(); $(this).parent().parent().parent().toggle(); }); } function get_head_to_head_body(widget_data, w_container, new_race_id) { // JSON polling data var now_time = new Date().getTime(); now_time = Math.floor(now_time / 100000); // Changes every 100 seconds var target_id = 0; if(typeof new_race_id === 'undefined') { target_id = widget_data['dropdown_races'][0]['id']; } else { target_id = new_race_id; } $.getJSON('/poll/race/'+target_id+'/polling_data.json?no_cache='+now_time, function(polling_data) { var body_html = ''; if(polling_data['poll'][0]['pollster'] == 'rcp_average') { body_html += '
'; body_html += '
'; for(var i = 0; i < polling_data['poll'][0]['candidate'].length; i++) { if(i > 1) { break; } if(i > 0) { body_html += '
'; } var aff = affiliation_to_abbr(polling_data['poll'][0]['candidate'][i]['affiliation'], polling_data['poll'][0]['candidate'][i]['name']); var c_image_source = ''; if(is_approve_candidate(polling_data['poll'][0]['candidate'][i]['name'])) { c_image_source = '/asset/img/approve.png'; } else if(is_disapprove_candidate(polling_data['poll'][0]['candidate'][i]['name'])) { c_image_source = '/asset/img/against.png'; } else { c_image_source = window.location.protocol+'//www.realclearpolitics.com/epolls/images/'+polling_data['poll'][0]['candidate'][i]['id']+'.jpg'; } body_html += '
'+polling_data['poll'][0]['candidate'][i]['name']+'
'; } body_html += '
'; body_html += '
'; for(var i = 0; i < polling_data['poll'][0]['candidate'].length; i++) { if(i > 1) { break; } var aff = affiliation_to_abbr(polling_data['poll'][0]['candidate'][i]['affiliation'], polling_data['poll'][0]['candidate'][i]['name']); var score = polling_data['poll'][0]['candidate'][i]['value']; body_html += '
'+score+'%
'; } body_html += '
'; body_html += '
'; // Find sum of top two candidate scores (for calculating bar width) var score_sum = 0; for(var i = 0; i < polling_data['poll'][0]['candidate'].length; i++) { if(i > 1) { break; } score_sum += parseFloat(polling_data['poll'][0]['candidate'][i]['value']); } for(var i = 0; i < polling_data['poll'][0]['candidate'].length; i++) { if(i > 1) { break; } var aff = affiliation_to_abbr(polling_data['poll'][0]['candidate'][i]['affiliation'], polling_data['poll'][0]['candidate'][i]['name']); var bar_width = ( Math.floor(parseFloat(polling_data['poll'][0]['candidate'][i]['value'])) / score_sum ) * 268; body_html += '
'; } body_html += '
'; body_html += '
'; body_html += '
'; // Also write dropdown title custom to show candidate 1 v candidate 2 w_container.find('.head_to_head_candidates .names').html(''+polling_data['poll'][0]['candidate'][0]['name']+' v '+polling_data['poll'][0]['candidate'][1]['name']+''); } w_container.find('.head_to_head_body').html(body_html); }); } function affiliation_to_abbr(aff, name) { if(aff.toLowerCase() == 'democrat') { return 'dem'; } else if(aff.toLowerCase() == 'republican') { return 'gop'; } else if(aff.toLowerCase() == 'independent') { return 'ind'; } else if(name.toLowerCase() == 'approve' || name.toLowerCase() == 'right direction' || name.toLowerCase() == 'favorable' || name.toLowerCase() == 'support') { return 'approve'; } else if(name.toLowerCase() == 'disapprove' || name.toLowerCase() == 'wrong track' || name.toLowerCase() == 'unfavorable' || name.toLowerCase() == 'oppose') { return 'disapprove'; } else { if(name.toLowerCase() == 'approve' || name.toLowerCase() == 'right direction' || name.toLowerCase() == 'favorable' || name.toLowerCase() == 'support') { return 'approve'; } else if(name.toLowerCase() == 'disapprove' || name.toLowerCase() == 'wrong track' || name.toLowerCase() == 'unfavorable' || name.toLowerCase() == 'oppose') { return 'disapprove'; } else { return 'other'; } } } function is_approve_candidate(name) { if(name.toLowerCase() == 'approve' || name.toLowerCase() == 'right direction' || name.toLowerCase() == 'favorable' || name.toLowerCase() == 'support') { return true; } return false; } function is_disapprove_candidate(name) { if(name.toLowerCase() == 'disapprove' || name.toLowerCase() == 'wrong track' || name.toLowerCase() == 'unfavorable' || name.toLowerCase() == 'oppose') { return true; } return false; } function race_loaded(widget_data, historical_data, candidates_data, w_container, race_title) { // Load dropdown widgets if new, else keep old dropdown info if(w_container[0].loaded_dropdown_widgets.length == 0) { if(widget_data['dropdown_widgets'].length > 0) { w_container[0].loaded_dropdown_widgets = widget_data['dropdown_widgets']; // Add self to list (will be hidden later) w_container[0].loaded_dropdown_widgets.unshift({ 'id' : widget_data['id'], 'title' : widget_data['title'], 'dropdown_title' : widget_data['dropdown_title'], 'color' : widget_data['color'] }); } else { w_container[0].loaded_dropdown_widgets = 'none'; } } w_container[0].current_item_num = 0; var subtitle = ''; var hide_dropdown = 'style="display:none;"'; if(widget_data['dropdown_title'].length > 0 && widget_data['dropdown_widgets'].length > 0) { subtitle = 'Select Poll'; hide_dropdown = ''; } var widget_html = ''; widget_html += '
'; widget_html += '
Story Stream Icon '+widget_data['title']+'
'; widget_html += '
'; widget_html += '
'+subtitle+'
'; if(w_container[0].loaded_dropdown_widgets != 'none') { widget_html += ''; } widget_html += ''; widget_html += '
'; if(w_container[0].loaded_dropdown_widgets != 'none') { widget_html += '
    '; for(var key_d in w_container[0].loaded_dropdown_widgets) { var d_title = ''; if(typeof w_container[0].loaded_dropdown_widgets[key_d]['dropdown_title'] !== 'undefined' && w_container[0].loaded_dropdown_widgets[key_d]['dropdown_title'] !== null && w_container[0].loaded_dropdown_widgets[key_d]['dropdown_title'].length > 0) { d_title = w_container[0].loaded_dropdown_widgets[key_d]['dropdown_title']; } else { d_title = w_container[0].loaded_dropdown_widgets[key_d]['title']; } var d_color = ''; var d_background_color = 'data-bcolor=""'; if(w_container[0].loaded_dropdown_widgets[key_d]['color'] != '') { d_color = 'style="color:'+w_container[0].loaded_dropdown_widgets[key_d]['color']+';"'; d_background_color = 'data-bcolor="'+w_container[0].loaded_dropdown_widgets[key_d]['color']+'"'; } widget_html += ''; } widget_html += '
'; } widget_html += '
'; widget_html += '
'; widget_html += '
'; var max_height_style = ''; if(widget_data['max_height'] > 0) { max_height_style = 'style="max-height: '+widget_data['max_height']+'px;"'; } widget_html += ''; widget_html += ''; w_container.html(widget_html); bottom_fade(w_container); race_date_arrows(widget_data, historical_data, candidates_data, w_container, race_title); widget_link_events(w_container); } function race_date_arrows(widget_data, historical_data, candidates_data, w_container, race_title) { w_container.find('.race_nav .left_arrow').click( { widget_data_ref: widget_data, historical_data_ref: historical_data, candidates_data_ref: candidates_data, container_ref: w_container, race_title_ref: race_title }, function(event) { event.data.container_ref[0].current_item_num += 1; var body_html = get_race_widget_body(event.data.widget_data_ref, event.data.historical_data_ref, event.data.candidates_data_ref, event.data.container_ref, event.data.race_title_ref); event.data.container_ref.find('.rec-link-body').html(body_html); race_date_arrows(event.data.widget_data_ref, event.data.historical_data_ref, event.data.candidates_data_ref, event.data.container_ref, event.data.race_title_ref); }); w_container.find('.race_nav .right_arrow').click( { widget_data_ref: widget_data, historical_data_ref: historical_data, candidates_data_ref: candidates_data, container_ref: w_container, race_title_ref: race_title }, function(event) { if(event.data.container_ref[0].current_item_num > 0) { event.data.container_ref[0].current_item_num -= 1; var body_html = get_race_widget_body(event.data.widget_data_ref, event.data.historical_data_ref, event.data.candidates_data_ref, event.data.container_ref, event.data.race_title_ref); event.data.container_ref.find('.rec-link-body').html(body_html); race_date_arrows(event.data.widget_data_ref, event.data.historical_data_ref, event.data.candidates_data_ref, event.data.container_ref, event.data.race_title_ref); } }); } function get_race_widget_body(widget_data, historical_data, candidates_data, w_container, race_title) { var body_html = ''; //console.log(w_container[0].current_item_num); body_html += '
'+race_title+'
'; body_html += '
'; var rcp_avg_date = new Date(historical_data['poll']['rcp_avg'][w_container[0].current_item_num]['date']); var month_num_to_text = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ]; var rcp_avg_display_date = month_num_to_text[rcp_avg_date.getMonth()]+' '+rcp_avg_date.getDate()+', '+rcp_avg_date.getFullYear(); body_html += '
<
'; body_html += '
>
'; body_html += '
'+rcp_avg_display_date+'
'; body_html += '
'; var ul_classes = 'race'; if(widget_data['max_height'] > 0) { ul_classes += ' scroll'; } body_html += '
    '; var race_data = historical_data['poll']['rcp_avg'][w_container[0].current_item_num]; for(var i=0; i= widget_data['item_limit']) { break; } if(race_data['candidate'][i]['value'] == null || race_data['candidate'][i]['value'] == '') { continue; } body_html += '
  • '; var c_color = ''; var c_b_color = ''; if(race_data['candidate'][i]['color'].length > 0) { c_color = 'color:'+race_data['candidate'][i]['color']+';'; c_b_color = 'background-color:'+race_data['candidate'][i]['color']+';'; } var c_image = ''; for(var j=0; j'; } } } body_html += '
    '; body_html += '
    '+c_image+'
    '+race_data['candidate'][i]['name']+'
    '; body_html += '
    '+race_data['candidate'][i]['value']+'%
    '; body_html += '
  • '; } body_html += '
'; if(widget_data['max_height'] > 0) { body_html += '
'; } return body_html; } function story_stream_loaded(widget_data, w_container) { // Load dropdown widgets if new, else keep old dropdown info if(w_container[0].loaded_dropdown_widgets.length == 0) { if(widget_data['dropdown_widgets'].length > 0) { w_container[0].loaded_dropdown_widgets = widget_data['dropdown_widgets']; // Add self to list (will be hidden later) w_container[0].loaded_dropdown_widgets.unshift({ 'id' : widget_data['id'], 'title' : widget_data['title'], 'dropdown_title' : widget_data['dropdown_title'], 'color' : widget_data['color'] }); } else { w_container[0].loaded_dropdown_widgets = 'none'; } } var w_color = ''; if(widget_data['color'] != '') { w_color = 'style="background:'+widget_data['color']+';"'; } var new_dropdown_color = ''; var subtitle_color = ''; if(w_container[0].loaded_dropdown_widgets == 'none') { new_dropdown_color = 'style="background:none;"'; } else if(widget_data['text_color'] == '#000000') { subtitle_color = 'style="color:'+widget_data['text_color']+';"'; //new_dropdown_color = 'style="background-image:url(/asset/img/grey-bg-chev.png)"'; } var subtitle = ''; if(widget_data['dropdown_title'].length > 0) { subtitle = ''+widget_data['dropdown_title']+''; } var widget_html = ''; widget_html += '
'; widget_html += '
Story Stream Icon '+widget_data['title']+'
'; widget_html += '
'; widget_html += '
'+subtitle+'
'; if(w_container[0].loaded_dropdown_widgets != 'none') { widget_html += ''; } widget_html += ''; widget_html += '
'; if(w_container[0].loaded_dropdown_widgets != 'none') { widget_html += '
    '; for(var key_d in w_container[0].loaded_dropdown_widgets) { var d_title = ''; if(typeof w_container[0].loaded_dropdown_widgets[key_d]['dropdown_title'] !== 'undefined' && w_container[0].loaded_dropdown_widgets[key_d]['dropdown_title'] !== null && w_container[0].loaded_dropdown_widgets[key_d]['dropdown_title'].length > 0) { d_title = w_container[0].loaded_dropdown_widgets[key_d]['dropdown_title']; } else { d_title = w_container[0].loaded_dropdown_widgets[key_d]['title']; } var d_color = ''; var d_background_color = 'data-bcolor=""'; if(w_container[0].loaded_dropdown_widgets[key_d]['color'] != '') { d_color = 'style="color:'+w_container[0].loaded_dropdown_widgets[key_d]['color']+';"'; d_background_color = 'data-bcolor="'+w_container[0].loaded_dropdown_widgets[key_d]['color']+'"'; } widget_html += ''; } widget_html += '
'; } widget_html += '
'; widget_html += '
'; widget_html += '
'; var max_height_style = ''; if(widget_data['max_height'] > 0) { max_height_style = 'style="max-height: '+widget_data['max_height']+'px;"'; } widget_html += ''; widget_html += ''; w_container.html(widget_html); bottom_fade(w_container); $w_ss.push($.extend(true, {}, $StoryStream)); // Clone $StoryStream object // By pushing a clone into an array, we are able to have multiple storystream // objects on a page at once, each with their own infinite scroll $w_ss[$w_ss.length - 1].topic = widget_data['topic']; $w_ss[$w_ss.length - 1].container = w_container.find('.items'); $w_ss[$w_ss.length - 1].print_type = 'widget'; $w_ss[$w_ss.length - 1].limit = widget_data['item_limit']; $w_ss[$w_ss.length - 1].ss_index = $w_ss.length - 1; $w_ss[$w_ss.length - 1].finished_callback = function() { update_date_displays(); var $target = this.container.parent(); $target.attr('data-ss-index', this.ss_index); $target.scroll(function() { var ss_i = parseInt($(this).attr('data-ss-index')); if($(this).scrollTop() + $(this).height() + 20 >= $(this)[0].scrollHeight && $w_ss[ss_i].scroll_continue_done == true) { $w_ss[ss_i].scroll_continue_done = false; $w_ss[ss_i].continue_stream(); } }); } $w_ss[$w_ss.length - 1].continue_stream(); recommendedSitesMenu(w_container); recommendedSitesMenuHover(); recommendedSitesMenuItems(w_container); widget_link_events(w_container); } function latest_polls_loaded(widget_data, latest_polls_data, w_container) { // Load dropdown widgets if new, else keep old dropdown info if(w_container[0].loaded_dropdown_widgets.length == 0) { if(widget_data['dropdown_widgets'].length > 0) { w_container[0].loaded_dropdown_widgets = widget_data['dropdown_widgets']; // Add self to list (will be hidden later) w_container[0].loaded_dropdown_widgets.unshift({ 'id' : widget_data['id'], 'title' : widget_data['title'], 'dropdown_title' : widget_data['dropdown_title'], 'color' : widget_data['color'] }); } else { w_container[0].loaded_dropdown_widgets = 'none'; } } var new_dropdown_color = ''; var subtitle_color = ''; if(w_container[0].loaded_dropdown_widgets == 'none') { new_dropdown_color = 'style="background:none;"'; } else if(widget_data['text_color'] == '#000000') { subtitle_color = 'style="color:'+widget_data['text_color']+';"'; //new_dropdown_color = 'style="background-image:url(/asset/img/grey-bg-chev.png)"'; } var subtitle = ''; if(widget_data['dropdown_title'].length > 0 && widget_data['dropdown_widgets'].length > 0) { subtitle = ''+widget_data['dropdown_title']+''; } var title_icon = ''; if(widget_data['show_stream_icon'] == 1) { title_icon = 'Story Stream Icon'; } var widget_html = ''; widget_html += '
'; widget_html += '
'+title_icon+widget_data['title']+'
'; widget_html += '
'; widget_html += '
'+subtitle+'
'; if(w_container[0].loaded_dropdown_widgets != 'none') { widget_html += ''; } widget_html += ''; widget_html += '
'; if(w_container[0].loaded_dropdown_widgets != 'none') { widget_html += '
    '; for(var key_d in w_container[0].loaded_dropdown_widgets) { var d_title = ''; if(typeof w_container[0].loaded_dropdown_widgets[key_d]['dropdown_title'] !== 'undefined' && w_container[0].loaded_dropdown_widgets[key_d]['dropdown_title'] !== null && w_container[0].loaded_dropdown_widgets[key_d]['dropdown_title'].length > 0) { d_title = w_container[0].loaded_dropdown_widgets[key_d]['dropdown_title']; } else { d_title = w_container[0].loaded_dropdown_widgets[key_d]['title']; } var d_color = ''; var d_background_color = 'data-bcolor=""'; /*if(w_container[0].loaded_dropdown_widgets[key_d]['color'] != '') { d_color = 'style="color:'+w_container[0].loaded_dropdown_widgets[key_d]['color']+';"'; d_background_color = 'data-bcolor="'+w_container[0].loaded_dropdown_widgets[key_d]['color']+'"'; }*/ widget_html += ''; } widget_html += '
'; } widget_html += '
'; widget_html += '
'; widget_html += '
'; var max_height_style = ''; if(widget_data['max_height'] > 0) { max_height_style = 'style="max-height: '+widget_data['max_height']+'px;"'; } widget_html += ''; if(widget_data['footer_text'] != '') { widget_html += ''; } w_container.html(widget_html); bottom_fade(w_container); recommendedSitesMenu(w_container); recommendedSitesMenuHover(); recommendedSitesMenuItems(w_container); widget_link_events(w_container); } function feed_loaded(widget_data, feed_data, w_container) { // Convert feed data to standard format var feed_standard = []; if($.isXMLDoc(feed_data)) { // Is XML $(feed_data).find('item').each(function(index) { var image_url = ''; if( widget_data['feed_info']['image'] == 'media:thumbnail' ) { // The comma is needed for chrome to work image_url = $(this).find('media\\:thumbnail, thumbnail').attr('url'); } else if( widget_data['feed_info']['image'] == 'media:content' ) { // The comma is needed for chrome to work image_url = $(this).find('media\\:content, content').attr('url'); } else { image_url = $(this).find(widget_data['feed_info']['image']).html(); } feed_item = { 'byline' : $(this).find(widget_data['feed_info']['byline']).html(), 'title' : $(this).find(widget_data['feed_info']['title_path']).html(), 'category' : $(this).find(widget_data['feed_info']['category']).html(), 'image' : image_url, 'show_image' : $(this).find(widget_data['feed_info']['show_image']).html(), 'link' : $(this).find(widget_data['feed_info']['link']).html(), }; feed_standard.push(feed_item); }); } else { // Is object (from json feed) for( var key1 in feed_data ) { if(key1 == widget_data['feed_info']['container']) { if(typeof feed_data[key1][widget_data['feed_info']['byline']] !== 'undefined' || typeof feed_data[key1][widget_data['feed_info']['title_path']] !== 'undefined') { feed_item = { 'byline' : feed_data[key1][widget_data['feed_info']['byline']], 'title': feed_data[key1][widget_data['feed_info']['title_path']], 'category' : feed_data[key1][widget_data['feed_info']['category']], 'image' : feed_data[key1][widget_data['feed_info']['image']], 'show_image' : feed_data[key1][widget_data['feed_info']['show_image']], 'link' : feed_data[key1][widget_data['feed_info']['link']] }; if(widget_data['show_category_color']) { feed_item['category_color'] = feed_data[key1][widget_data['feed_info']['category_color']]; } if(widget_data['feed_info']['show_image'] != '') { feed_item['show_image'] = feed_data[key1][widget_data['feed_info']['show_image']]; } if(typeof feed_data[key1]['sponsored'] !== 'undefined') { feed_item['sponsored'] = feed_data[key1]['sponsored']; } feed_standard.push(feed_item); } else { for( var key2 in feed_data[key1] ) { if(typeof feed_data[key1][key2][widget_data['feed_info']['byline']] !== 'undefined' || typeof feed_data[key1][key2][widget_data['feed_info']['title_path']] !== 'undefined') { feed_item = { 'byline' : feed_data[key1][key2][widget_data['feed_info']['byline']], 'title': feed_data[key1][key2][widget_data['feed_info']['title_path']], 'category' : feed_data[key1][key2][widget_data['feed_info']['category']], 'image' : feed_data[key1][key2][widget_data['feed_info']['image']], 'link' : feed_data[key1][key2][widget_data['feed_info']['link']] }; if(widget_data['show_category_color']) { feed_item['category_color'] = feed_data[key1][key2][widget_data['feed_info']['category_color']]; } if(widget_data['feed_info']['show_image'] != '') { feed_item['show_image'] = feed_data[key1][key2][widget_data['feed_info']['show_image']]; } if(typeof feed_data[key1][key2]['sponsored'] !== 'undefined') { feed_item['sponsored'] = feed_data[key1][key2]['sponsored']; } feed_standard.push(feed_item); } else { for( var key3 in feed_data[key1][key2] ) { if(typeof feed_data[key1][key2][key3][widget_data['feed_info']['byline']] !== 'undefined' || typeof feed_data[key1][key2][key3][widget_data['feed_info']['title_path']] !== 'undefined') { feed_item = { 'byline' : feed_data[key1][key2][key3][widget_data['feed_info']['byline']], 'title': feed_data[key1][key2][key3][widget_data['feed_info']['title_path']], 'category' : feed_data[key1][key2][key3][widget_data['feed_info']['category']], 'image' : feed_data[key1][key2][key3][widget_data['feed_info']['image']], 'link' : feed_data[key1][key2][key3][widget_data['feed_info']['link']] }; if(widget_data['show_category_color']) { feed_item['category_color'] = feed_data[key1][key2][key3][widget_data['feed_info']['category_color']]; } if(widget_data['feed_info']['show_image'] != '') { feed_item['show_image'] = feed_data[key1][key2][key3][widget_data['feed_info']['show_image']]; } if(typeof feed_data[key1][key2][key3]['sponsored'] !== 'undefined') { feed_item['sponsored'] = feed_data[key1][key2][key3]['sponsored']; } feed_standard.push(feed_item); } } } } } } } } for( var key_feed in feed_standard) { // If category is numeric, convert to our standard categories var cat = feed_standard[key_feed]['category']; if($.isNumeric(cat)) { cat = category_id_to_name(cat); } feed_standard[key_feed]['category'] = cat; } // Load dropdown widgets if new, else keep old dropdown info if(w_container[0].loaded_dropdown_widgets.length == 0) { if(widget_data['dropdown_widgets'].length > 0) { w_container[0].loaded_dropdown_widgets = widget_data['dropdown_widgets']; // Add self to list (will be hidden later) w_container[0].loaded_dropdown_widgets.unshift({ 'id' : widget_data['id'], 'title' : widget_data['title'], 'dropdown_title' : widget_data['dropdown_title'], 'color' : widget_data['color'] }); } else { w_container[0].loaded_dropdown_widgets = 'none'; } } var w_color = ''; if(widget_data['color'] != '') { w_color = 'style="background-color:'+widget_data['color']+';"'; } if(widget_data['background_image'] !== null && widget_data['background_image'] !== '') { w_color = 'style="padding-left: 26px; background-image:url('+widget_data['background_image']+');"'; } var new_dropdown_color = ''; var subtitle_color = ''; if(w_container[0].loaded_dropdown_widgets == 'none') { new_dropdown_color = 'style="background:none;"'; } else if(widget_data['text_color'] == '#000000') { subtitle_color = 'style="color:'+widget_data['text_color']+';"'; //new_dropdown_color = 'style="background-image:url(/asset/img/grey-bg-chev.png)"'; } var subtitle = ''; if(widget_data['dropdown_title'] !== null && widget_data['dropdown_title'].length > 0) { subtitle = ''+widget_data['dropdown_title']+''; } var title_icon = ''; if(widget_data['show_stream_icon'] == 1) { title_icon = 'Story Stream Icon'; } var widget_html = ''; //console.log(widget_data['title']); widget_html += '
'; widget_html += '
'+title_icon+widget_data['title']+'
'; widget_html += '
'; widget_html += '
'+subtitle+'
'; if(w_container[0].loaded_dropdown_widgets != 'none') { widget_html += ''; } widget_html += ''; widget_html += '
'; if(w_container[0].loaded_dropdown_widgets != 'none') { widget_html += '
    '; for(var key_d in w_container[0].loaded_dropdown_widgets) { var d_title = ''; if(typeof w_container[0].loaded_dropdown_widgets[key_d]['dropdown_title'] !== 'undefined' && w_container[0].loaded_dropdown_widgets[key_d]['dropdown_title'] !== null && w_container[0].loaded_dropdown_widgets[key_d]['dropdown_title'].length > 0) { d_title = w_container[0].loaded_dropdown_widgets[key_d]['dropdown_title']; } else { d_title = w_container[0].loaded_dropdown_widgets[key_d]['title']; } var d_color = ''; var d_background_color = 'data-bcolor=""'; if(w_container[0].loaded_dropdown_widgets[key_d]['color'] != '') { d_color = 'style="color:'+w_container[0].loaded_dropdown_widgets[key_d]['color']+';"'; d_background_color = 'data-bcolor="'+w_container[0].loaded_dropdown_widgets[key_d]['color']+'"'; } widget_html += ''; } widget_html += '
'; } widget_html += '
'; widget_html += '
'; widget_html += '
'; var max_height_style = ''; if(widget_data['max_height'] > 0) { max_height_style = 'style="max-height: '+widget_data['max_height']+'px;"'; } widget_html += ''; if(widget_data['footer_text'] !== null && widget_data['footer_text'].length > 0) { widget_html += ''; } w_container.html(widget_html); bottom_fade(w_container); recommendedSitesMenu(w_container); recommendedSitesMenuHover(); recommendedSitesMenuItems(w_container); widget_link_events(w_container); /*setTimeout(function(){ $(w_container).show(); }, 250);*/ } function bottom_fade(w_container) { w_container.find('.rec-link-body').scroll(function() { $(this).find('.white-overlay').css('bottom', $(this).scrollTop() * -1); }); } // Event when link in body of system widget is clicked function widget_link_events(w_container) { w_container.find('.rec-link-body a').click( { container_ref: w_container }, function(event) { //Get the href value. Will use at the end to go to link target. event = event || window.event; var href = $(this).closest('a').attr('href'); //Build the params to go to event tracking /*var ge_action = 'Section Redesign: ' + $('body').attr('class').split(' ')[0]; // Section: var ge_category = 'System Widget: ' + event.data.container_ref.attr('data-widget-type') + ': ' + event.data.container_ref.attr('data-widget-title'); // System Widgets: var ge_label = 'Link';*/ var ge_action = 'Click: Link'; var ge_category = 'System Widget Interaction'; var ge_label = event.data.container_ref.attr('data-widget-title')+': '+$('body').attr('class').split(' ')[0]; //Wrap event tracking call to prevent premature termination of this function. try{ _gaq.push(['_trackEvent', ge_category, ge_action, ge_label]); console.log('trackevent: '+ge_category+' '+ge_action+' '+ge_label); } catch(err) {} if(event.ctrlKey || event.metaKey) { //If right-click or control click return true; } else { window.setTimeout('document.location = "' + href + '"', 100); //Go to hyperlink return false; } }); } // Menu items click function recommendedSitesMenuItems(w_container) { w_container.find('.rec-site-list ul li span').click( { container_ref: w_container }, function(event) { /*var ge_action = 'Section Redesign: ' + $('body').attr('class').split(' ')[0]; // Section: var ge_category = 'System Widget: ' + event.data.container_ref.attr('data-widget-type') + ': ' + event.data.container_ref.attr('data-widget-title'); // System Widgets: var ge_label = 'Menu: ' + $(this).html();*/ var ge_action = 'Click: Menu'; var ge_category = 'System Widget Interaction'; var ge_label = event.data.container_ref.attr('data-widget-title')+': '+$('body').attr('class').split(' ')[0]; console.log('trackevent: '+ge_category+' '+ge_action+' '+ge_label); _gaq.push(['_trackEvent', ge_category, ge_action, ge_label]); load_widget($(this).attr('data-id'), event.data.container_ref); }); } //other sites menu - recommended widget drop down menu function recommendedSitesMenu(w_container){ //console.log('recommendedSitesMenu'); w_container.find('.rec-site .menu').click( { container_ref: w_container }, function(event){ event.data.container_ref.find('.rec-site-tab').toggle(); event.data.container_ref.find('.rec-site-list').toggle(); }); } //open sitesMenu hover handler - changes color of pointer triangle at top of menu to match hovered site // Now also handles color of li->a background function recommendedSitesMenuHover() { $('.rec-site-list ul li span').hover(function(){ var bg = $(this).attr('data-bcolor'); if(bg.length > 0) { $(this).css('color', '#ffffff'); } $(this).css('background-color', bg); $(this).parent().parent().parent().parent().find('.rec-site-tab').css( { "border-bottom" : "10px solid " + bg } ); }, function(){ var bg = $(this).attr('data-bcolor'); var new_color = ''; if(bg.length > 0) { new_color = bg; } $(this).css('color', new_color); $(this).css('background-color', ''); //$('.verticals-tab').css( { "border-bottom" : "10px solid #EBEBEB" } ); $(this).parent().parent().parent().parent().find('.rec-site-tab').css( { "border-bottom" : "10px solid #EBEBEB" } ); }); } function category_id_to_name(cat_id) { if(cat_id == '0') { return 'none'; } else if(cat_id == '1') { return 'article'; } else if(cat_id == '2') { return 'video'; } else if(cat_id == '3') { return 'list'; } else if(cat_id == '4') { return 'poll'; } else if(cat_id == '5') { return 'podcast'; }else if(cat_id == '6'){ return 'quiz'; }else if(cat_id == '7'){ return 'tag'; } } function update_date_displays() { $('.item_date').each(function() { var today_date = new Date(); //var today_date = new Date(1435536200000); var item_date = new Date(parseInt($(this).attr('data-ms'))); var elapsed_ms = today_date.getTime() - item_date.getTime(); var elapsed_seconds = elapsed_ms / 1000; var elapsed_minutes = elapsed_ms / 60000; var elapsed_hours = elapsed_minutes / 60; var elapsed_hours_exact = Math.floor(elapsed_hours); var elapsed_minutes_exact = Math.floor(elapsed_minutes); var elapsed_seconds_exact = Math.floor(elapsed_seconds); var display_date = ''; if(elapsed_hours >= 24) { display_date = item_date.toDateString(); } else if(elapsed_hours >= 1) { display_date = elapsed_hours_exact+' hours ago'; } else if(elapsed_minutes >= 1) { display_date = elapsed_minutes_exact+' min ago'; } else if(elapsed_seconds >= 1) { display_date = elapsed_seconds_exact+' sec ago'; } else { display_date = 'now'; } $(this).html(display_date); }) } //////////////////////////////////////////////////////////////////////////////// // EVOLOK FUNCTIONS //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// function evolok_init() { //if main evo library is ready if(typeof window.EV !== 'undefined' && !evolok_init_finished) { adblock_exists_check = window.setInterval(function(){ if( warning_widget.ad_block_ready_for_check == true || warning_widget.ad_block_ready_for_check == "true" ){ console.log('Console: USING ADBLOCK::: ' + Utils.global_settings.realclear_ad_block_check); continue_ev_init(Utils.global_settings.realclear_ad_block_check); clearInterval(adblock_exists_check); } }, 1000); //global param indicating libraries are ready evolok_init_finished = true; } else { //console.log('ev undefined or init already called'); loadAds(); } } function continue_ev_init(adBlockEnabled){ var evp = {}; if(typeof window.ev_params !== 'undefined') { evp = window.ev_params; } console.log("inline ev params:::: "); console.log(evp); var id_timestamp = Math.floor(Date.now() / 1000 / 60); ev_article_id = id_timestamp; var wevp = {"articleId":ev_article_id,"site":SITE_INFO['name'],"adblock":adBlockEnabled}; var all_params = Object.assign(wevp, evp); console.log("ALL PARAMS:::: "); console.log(all_params); window.evolok_params = JSON.stringify(all_params); var ev_init_url = "//rcp.evolok.net/acd/api/3.0"; var cookieDomain = "realclear"+SITE_INFO['name']+".com"; if(Utils.get_query_param('evo_test') == 'true') { ev_init_url = "//rcp.uat.evolok.net/acd/api/3.0"; } EV.Em.init({ sidCookieDomain: document.domain, url: ev_init_url }); EV.Em.authorize(window.evolok_params, evolok_metering_success, evolok_metering_error); } function evolok_metering_success(response) { console.log('evolok success response:'); console.log(response); if(response.result == 'ALLOW_ACCESS' && response.loggedOut == false && typeof response.ruleProperties !== 'undefined' && response.ruleProperties.ADFREE == 'true') { evolok_block_ads = true; createCookie('evaf','1','365'); // This means ads have shown, at least some inline ones that depend on cookie // So it's best to refresh // checks if we can read a cookie, means cookies are enabled // m.b. added 9.27 - typeof check for ad free sites - master loads after invchnl_rcmg.js file causing false positive if( ( typeof inline_ads_status !== 'undefined' && inline_ads_status == 'shown' ) && readCookie('evaf') ) { location.reload(); return; } // We now know that ads will not be loaded, and there is no need for a refresh. // So we can display the tempshow notifications if(typeof Tempshow !== 'undefined') { var tempshow = new Tempshow; // 15 sec every time tempshow.create({ msg: 'RCMG Ad-Free', seconds: 15 }); if(readCookie('purchase_thanks_hp_modal') != '1') { // permanent just once tempshow.create({ msg: 'Thank you for your support!
Enjoy your ad-free experience.', type: 'subscribe_thanks', seconds: 20, vertical: 'center', horizontal: 'center', width: '500px' }); createCookie('purchase_thanks_hp_modal','1','365'); } } } else { eraseCookie('evaf'); refresh_if_af_from_cookie(); evolok_do_ads = true; } loadAds(); loadGotChosen(); distroscale_init(); markets_investingchannel(); if(typeof load_spot_recirculation == 'function') {load_spot_recirculation(); } if(typeof load_investingchannel_88x31 == 'function') {load_investingchannel_88x31(); } if(typeof load_investingchannel_300 == 'function') {load_investingchannel_300(); } //load loadLockerdome everywhere else except for science if(typeof loadLockerdome == 'function') { loadLockerdome(); } spot_right_rail_init(); } function evolok_metering_error(response) { console.log('evolok metering error'); //console.log(response); eraseCookie('evaf'); refresh_if_af_from_cookie(); evolok_do_ads = true; loadAds(); loadGotChosen(); distroscale_init(); markets_investingchannel(); if(typeof load_spot_recirculation == 'function') {load_spot_recirculation(); } if(typeof load_investingchannel_88x31 == 'function') {load_investingchannel_88x31(); } if(typeof load_investingchannel_300 == 'function') {load_investingchannel_300(); } //load loadLockerdome everywhere else except for science if(typeof loadLockerdome == 'function') { loadLockerdome(); } spot_right_rail_init(); } function refresh_if_af_from_cookie() { if( ( typeof inline_ads_status !== 'undefined' && inline_ads_status == 'skipped' )) { location.reload(); } } // The following functions are for checking if the user has purchased // Done after filling in fn/ln/email form on subscription page function evolok_post_init_check() { EV.Em.authorize('{"site":"'+SITE_INFO['name']+'"}', evolok_post_init_metering_success, evolok_post_init_metering_error); } function evolok_post_init_metering_success(response) { if(response.result == 'ALLOW_ACCESS' && response.loggedOut == false && typeof response.ruleProperties !== 'undefined' && response.ruleProperties.ADFREE == 'true') { evolok_already_purchased(); } } function evolok_post_init_metering_error(response) { console.log('Error with post-init authorize call'); //console.log(response); } function evolok_already_purchased(){} // overwrite where needed as a callback //////////////////////////////////////////////////////////////////////////////// // DISTROSCALE FUNCTIONS /////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //DISTROSCALE VIDEO WIDGET function distroscale_init(){ // Disable for resolutions less than 1024 if($(window).outerWidth() < 1024) { return; } if(typeof all_ads_disabled !== 'undefined' && all_ads_disabled === true) { return; } if(evolok_init_finished) { if(!evolok_do_ads) { // Just skip and wait for next function call for a status change return; } // Otherwise go ahead and do ads } var allowedSites = [ "science", "policy", "politics" ]; if( $.inArray(SITE_INFO['name'], allowedSites) > -1 ){ var launch_distro = false; // Launch on policy & science homepages if(SITE_INFO['name']=="policy" && $("body.home").length>0) { $dstro = $('div.beta div.distro_spot'); $dstro.append("
"); launch_distro = true; } else if(SITE_INFO['name']=="science" && $("body.home").length>0) { $dstro = $('div.beta div.distro_spot'); $dstro.append("
"); launch_distro = true; } else if( ($("body.distro_test").length>0 || $("body.article").length>0 || $("body.polls").length>0 || $("body.maps").length>0 || $("body.live_results").length>0 ) && $(".data-no-ads").length == 0 ){ //|| $('body.video-landing').length > 0 || $('body.video-perma').length > 0 if(SITE_INFO['name']!="politics"){ if( $("body.distro_test").length>0 ) { $dstro = $('div.beta div.distro_spot'); } else { $dstro = $('div.beta .RC-AD-BOX-TOP:first-child'); } $dstro.append("
"); }else{ if( $("body.distro_test").length>0 || $("body.video-landing").length>0 || $("body.video-perma").length>0 ) { $dstro = $('div.beta div.distro_spot'); } else { $dstro = $('div.beta div:nth-child(1)'); } $dstro_html = "
"; if($("body.polls").length>0 || $("body.maps").length>0 || $("body.live_results").length>0 ) { $dstro.before($dstro_html); } else { $dstro.after($dstro_html); } } launch_distro = true; } if(launch_distro) { var distroscale = document.createElement('script'); distroscale.type = 'text/javascript'; distroscale.async = true; distroscale.src = (document.location.protocol == "https:" ? "https:" : "http:") + '//c.jsrdn.com/s/cs.js?p=22663'; var dstrox = document.getElementsByTagName('script')[0]; dstrox.parentNode.insertBefore(distroscale, dstrox); } } } //////////////////////////////////////////////////////////////////////////////// // SPOT.IM FUNCTIONS /////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //SPOT.IM DOC READY -- NEEDED TO CALL OUT EACH TEMPLATE AND APPEND SPOT.IM WIDGET TO RIGHT RAIL WHEN ELEMENTS ARE ALL LOADED - ONLY RCP!!! function spot_right_rail_init() { if(typeof all_ads_disabled !== 'undefined' && all_ads_disabled === true) { return; } if(evolok_init_finished) { // Evolok is initiated if(!evolok_do_ads) { console.log('skip and wait for next function call'); // Just skip and wait for next function call for a status change return; } console.log('go ahead and do spot right rail'); // Otherwise go ahead and do ads } var allowedSites = [ "defense", "markets", "world", "science", "history", "policy", "religion", "energy", "investigations", "health", "eduction", "books" ,"politics" ]; if( $.inArray(SITE_INFO['name'], allowedSites) > -1 ){ var widget_loc = ''; var widget_order = ''; if( $("body.video").length>0 || $("body.entry").length>0 || $("body.author").length>0 || $("body.cartoon").length>0 || $("body.search").length>0 || $("body.story-stream").length>0 ){ //Check, Re-Check if elements exist until they do then append spot widget to right rail widget_loc = 'Other'; widget_order = 'before'; isITNLoaded(widget_loc, widget_order); }else if( $("body.home").length>0 ){ //&& $("body").hasClass("spot-home") //Check, Re-Check if elements exist until they do then append spot widget to right rail widget_loc = 'homepage'; widget_order = 'before'; isITNLoaded(widget_loc, widget_order); }else if( $("body.article").length>0 ){ widget_loc = 'articles'; widget_order = 'after'; isITNLoaded(widget_loc, widget_order); }else if( $("body.polls").length>0 || $("body.live_results").length>0 ){ widget_order = 'before'; isITNLoaded(".widget_slot:eq(3)", widget_order); } } } //SPOT.IM -- makes sure elements are loaded on page and then, depending on template, appends spot.im widget to right rail function isITNLoaded(widget_loc, widget_order) { var target_el = ''; if(widget_loc == "Other"){ target_el = '.widget_slot:eq(2)'; }else if(widget_loc == "homepage"){ //var target_el = '[data-widget-title="Latest Polls"]'; var target_column = '.beta'; if(document.body.clientWidth < 768){ // smaller than ipad portrait target_column = '.alpha'; } target_el = target_column + ' .spot-box'; //Added empty div to index template - Only page we needed additional markup }else if( widget_loc=='articles' ){ target_el = '.widget_slot:eq(2)'; }else{ //else make widget_loc the target_el for custom places target_el = widget_loc; } if ( $(target_el).length>0 && !$(target_el).is("[data-no-ads]") ) { //console.log("ITN Loaded, Append SPOT.IM...."); //temporary solution if(SITE_INFO['name'] == 'politics') { if(widget_order == "before"){ //console.log('WIDGET LOC: ' + widget_loc); if(widget_loc == "homepage"){ //console.log('TARGET EL INSIDE IS HOMEPAGE CHECK: ' + target_el); $(target_el).append('
Popular in the Community
'); var social_side_rail = document.createElement("script"); social_side_rail.type = "text/javascript"; social_side_rail.src = "https://mc-siderail.spot.im/spot/" + SITE_INFO['spot_production_id']; social_side_rail.async = true; social_side_rail.setAttribute("data-spotim-script", "siderail"); //$(social_side_rail).appendTo("body"); $(target_el).append(social_side_rail); //newsletter is being removed in another function in master on 2 other sites so we didn't need this here just added rcp to the other function... //$(".newsletter-widget").last().remove(); //$(".newsletter-signup-container2").last().remove(); }else{ $(target_el).before('
Popular in the Community
'); var social_side_rail = document.createElement("script"); social_side_rail.type = "text/javascript"; social_side_rail.src = "https://mc-siderail.spot.im/spot/" + SITE_INFO['spot_production_id']; social_side_rail.async = true; social_side_rail.setAttribute("data-spotim-script", "siderail"); //$(social_side_rail).appendTo("body"); $(target_el).after(social_side_rail); } }else{ $(target_el).after('
Popular in the Community
'); var social_side_rail = document.createElement("script"); social_side_rail.type = "text/javascript"; social_side_rail.src = "https://mc-siderail.spot.im/spot/" + SITE_INFO['spot_production_id']; social_side_rail.async = true; social_side_rail.setAttribute("data-spotim-script", "siderail"); //$(social_side_rail).appendTo("body"); $(target_el).after(social_side_rail); } } else { if(widget_order == "before"){ //console.log('WIDGET LOC: ' + widget_loc); if(widget_loc == "homepage"){ //console.log('TARGET EL INSIDE IS HOMEPAGE CHECK: ' + target_el); $(target_el).append('
Popular in the Community
'); var social_side_rail = document.createElement("script"); social_side_rail.type = "text/javascript"; social_side_rail.src = "https://recirculation.spot.im/spot/" + SITE_INFO['spot_production_id'] + "/siderail"; social_side_rail.async = true; social_side_rail.setAttribute("data-spotim-script", "recirculation"); //$(social_side_rail).appendTo("body"); $(target_el).append(social_side_rail); //newsletter is being removed in another function in master on 2 other sites so we didn't need this here just added rcp to the other function... //$(".newsletter-widget").last().remove(); //$(".newsletter-signup-container2").last().remove(); }else{ $(target_el).before('
Popular in the Community
'); var social_side_rail = document.createElement("script"); social_side_rail.type = "text/javascript"; social_side_rail.src = "https://recirculation.spot.im/spot/" + SITE_INFO['spot_production_id'] + "/siderail"; social_side_rail.async = true; social_side_rail.setAttribute("data-spotim-script", "recirculation"); //$(social_side_rail).appendTo("body"); $(target_el).after(social_side_rail); } }else{ $(target_el).after('
Popular in the Community
'); var social_side_rail = document.createElement("script"); social_side_rail.type = "text/javascript"; social_side_rail.src = "https://recirculation.spot.im/spot/" + SITE_INFO['spot_production_id'] + "/siderail"; social_side_rail.async = true; social_side_rail.setAttribute("data-spotim-script", "recirculation"); //$(social_side_rail).appendTo("body"); $(target_el).after(social_side_rail); } } } else { //check in 500 ms setTimeout('isITNLoaded()', 500); } } //////////////////////////////////////////////////////////////////////////////// // STORY STREAM FUNCTIONS ////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /**TEMPORARY FIX Allows us to change the stream page for sponsors and custom ads on page. 10.03.16 A.A. - Added time outs for each section of this to make sure that the content is updated either on first try or on second try from timeouts because of a race between this and story-stream.js to update the header of the story streams page. **/ function init_story_stream_related() { if( SITE_PAGE == 'story-stream' && SITE_INFO['story_stream_related'] == true ) { console.log("story"); var sp_url = decodeURIComponent(window.location.href).toLowerCase(); var sp_topic_match = sp_url.match(/topic=(\w+)/); if(typeof sp_topic_match != 'undefined' && sp_topic_match.length > 0){ var sp_topic = sp_topic_match.length >1 ? sp_topic_match[1] : "election_2016"; var meta_url = "/topic/"+sp_topic.substring(0, 1)+"/"+sp_topic+"/tag_meta.json"; $.ajax({ dataType: 'json', url: meta_url, success: function(data) { var output = ''; if(typeof data.tag_assigned_tags !== 'undefined' && data.tag_assigned_tags.length > 0){ $(document).ready(function(){ //overwrites the original height of the parent div to adjust to the new elements added $(data.tag_assigned_tags).each(function(){ var safe_link = this.name.toLowerCase().replace(/ /g, '_').replace(/\W+/g, ""); //output += '
  • '+ this.name +'
  • '; output += '
  • '; output += '
    '; output += '' + this.name + ''; output += '
    '; //end of content-wrapper output += '
  • '; //end item }); story_stream_related_tags_html = ''; //adds the description to the header $('.tag-description').append(data.tag_description); $('.related_tags').append('
    '); $('.related_tags').append(''); $('.related_tags ul.related-tags-side-widget').append(output); if($('.alpha_related_tags').length) { $('.alpha_related_tags').append(output); } }); } if(parseInt(data.sponsored) == 1){ if(data.sponsor_ads != null || data.sponsor_ads != "" || data.sponsor_ads != undefined){ $("#jsSite").attr("data-gaTag", data.sponsor_ads); GA_TAG = $("#jsSite").attr("data-gaTag"); } //overwrites the ba $('#sponsored_heading').html(''); setTimeout(function(){ $('#sponsored_heading').html(''); //console.log("delayed css"); }, 300); $('.stream-details div.icon').html(''); setTimeout(function(){ $('.stream-details div.icon').html(''); //console.log("delayed icon"); }, 300); $(document).ready(function(){ var html = ""; html += "
    "+data.sponsor_text+"
    "; if(data.sponsor_link != null || data.sponsor_link != "" || data.sponsor_link != undefined){ html += ""; } html += "
    "; if(data.sponsor_link !== null || data.sponsor_link !== "" || data.sponsor_link !== undefined){ html += "
    "; } $('#sponsored_heading').append(html); }); setTimeout(function(){ $('#sponsored_heading').append(html); //console.log("delayed append"); }, 400); //console.log("Sponsored On"); }else if(data.tag_image_loc !== '' || data.tag_image_loc !== null){ //console.log(data); $(document).ready(function(){ $('.stream-header').css({ 'background-color' : '#000', 'height' : '300px' }); $('.stream-header .photo').css({ 'background' : 'url('+data.tag_image_loc+') no-repeat #000', 'background-color' : '#000', 'opacity': '0.6', 'background-size' : 'cover', 'height': '300px', 'background-position-y' : '50%', }); //$('.tag-description').append(data.tag_description); $('.tag-description').css({ 'color' : '#fff', }); }); /* setTimeout(function(){ $('.stream-header').css({ 'background-color' : '#000', }); if(data.tag_image_loc !== '' || data.tag_image_loc !== null){ $('.stream-header .photo').css({ 'background' : 'url('+data.tag_image_loc+') no-repeat #000', 'background-color' : '#000', 'opacity': '0.6', 'background-size' : 'cover', 'height': '250px', 'background-position-y' : '50%', }); } //$('.tag-description').append(data.tag_description); $('.tag-description').css({ 'color' : '#fff', }); }, 500); */ } else{ $(document).ready(function(){ $('.photo').css({ 'background-color' : '#000', 'height' : '250px', }); }); /*setTimeout(function(){ $('.photo').css('background', '#000'); //console.log("delayed else"); }, 500);*/ //console.log("Sponsored Off"); } }, error: function(jqXHR, textStatus, errorThrown){ $('.photo').css('background', '#000'); setTimeout(function(){ $('.photo').css('background', '#000'); //console.log("delayed error"); }, 500); }, statusCode: { 404: function() { //console.log( "sponsor json not found" ); $('.photo').css('background', '#000'); setTimeout(function(){ $('.photo').css('background', '#000'); //console.log("delayed 404"); }, 500); }, 403:function() { //console.log( "sponsor json forbiden" ); $('.photo').css('background', '#000'); setTimeout(function(){ $('.photo').css('background', '#000'); //console.log("delayed 403"); }, 500); } } }); }else{ console.log('no topic for story stream'); } } } function storyStreamClick(e){ /* This code figures out the targets (span click or hovered) location Compares it to the alpha location wrapper div and figures out the top and left position that overlay story stream should appear at */ var ele_text = $(e.target).text(); $(e.target).html(ele_text+''); $(".story-stream-hover-wrapper").hide(); //var ele_url = ele_text.toLowerCase(); //ele_url = ele_url.replace(/ /g, '_').replace(/\W+/g, ""); //use the same basename making process equal to cms side var ele_url = Utils.make_slug(ele_text); $(".story-stream-hover-wrapper .title-wrapper .title").html('' + ele_text + ''); populateStreamTag(ele_url, e, 'click'); } function storyStreamHover(e){ /* This code figures out the targets (span click or hovered) location Compares it to the alpha location wrapper div and figures out the top and left position that overlay story stream should appear at */ var ele_text = $(e.target).text(); $(e.target).html(ele_text+''); $(".story-stream-hover-wrapper").hide(); //var ele_url = ele_text.toLowerCase(); //ele_url = ele_url.replace(/ /g, '_').replace(/\W+/g, ""); //use the same basename making process equal to cms side var ele_url = Utils.make_slug(ele_text); $(".story-stream-hover-wrapper .title-wrapper .title").html('' + ele_text + ''); populateStreamTag(ele_url, e, 'hover'); //keeps stream info box open when hovered over - desktop $( ".story-stream-hover-wrapper" ).hover( function() { $( this ).show(); }, function() { $( this ).hide(); } ); } //populate story stream popups for any template that uses them function populateStreamTag(tag, e, ga_action){ var ss = $.extend(true, {}, $StoryStream); ss.topic = tag; //Set the limit in StoryStream object. This is the number of stories that will appear at a time. ss.limit = 12; //Set which DOM element is the content container ss.container = $(".story-stream-hover-wrapper"); ss.event = e; ss.ga_action = ga_action; ss.loop_limit = 5; ss.pushed_to_html = 0; ss.fail_limit = 10; ss.stories_added = []; ss.html = ""; ss.current_article = $('.article-title h1').text(); //Override the print_stories function. //This is so the markup for this page gets generated on continue_stream(), // instead of the default markup ss.print_stories = function(stories_array) { stream_tags[tag] = ''; var urlArray = []; for(var i=0; i= this.loop_limit){ break; } if(urlArray.indexOf(stories_array[i].content_url) != -1 || this.current_article == this.clear_html_entities(stories_array[i].heading1.replace(/\\/g, "")) ){ continue; } //end urlArray check urlArray.push(stories_array[i].content_url); this.stories_added.push([stories_array[i].content_url, stories_array[i].heading1]); this.pushed_to_html = this.pushed_to_html + 1; } //end if type check } //end for loop if(this.pushed_to_html >= this.loop_limit){ this.is_finished = true; this.build_up_html(); reposition_story_stream_widget(this.event, this.ga_action, true); } } //end print stories ss.clear_html_entities = function(text){ var txt = document.createElement("textarea"); txt.innerHTML = text; return txt.value; } ss.build_up_html = function(){ if(this.stories_added.length > 0){ this.html = ""; var limiter = 5; if(this.stories_added.length < 5){ limiter = this.stories_added.length; } for(var i = 0; i < limiter; i++){ this.html += '
  • '+this.stories_added[i][1].replace(/\\/g, "")+'
  • '; } $(".story-stream-hover-wrapper .recent-link ul").html(this.html); }else{ $(".story-stream-hover-wrapper .recent-link ul").html("No Posts Available"); } } ss.finished_callback = function(){ if(this.fail_count >= this.fail_limit){ this.is_finished = true; this.build_up_html(); reposition_story_stream_widget(this.event, this.ga_action, false); } } //init stream - build links ss.continue_stream(); } function reposition_story_stream_widget(e, ga_action, completed){ $('.ss_loader').remove(); var ele = $(e.target.parentNode); var target_offset = $(e.target).offset(); var target_width = $(e.target).width(); var target_height = $(e.target).height(); var target_left = target_offset.left; var target_top = target_offset.top; var scrollTop = $(window).scrollTop(), elementOffset = ele.offset().top, distance = (elementOffset - scrollTop); var windowWidth = $(window).outerWidth(); var height = $(".story-stream-hover-wrapper").height(); var alpha_offset = $('.alpha').offset(); var hoverLeft; var hoverTop; hoverTop = target_top - alpha_offset.top - (target_height/2); if( windowWidth > 768 ){ hoverLeft = target_left - alpha_offset.left - (target_width/2) - 20; if(hoverLeft < -42){ hoverLeft = -42; } $( ".mobile-close-btn" ).hide(); }else{ hoverLeft = "0px"; if( distance > height ){ hoverTop = hoverTop + 40; } $( ".mobile-close-btn" ).show(); } var appear_on_top = false; if( distance <= height ){ //show below placeholder hoverTop = hoverTop - 10; $(".story-stream-hover-wrapper").css({ position: "absolute", top: hoverTop, left: hoverLeft }).show(); $( ".story-stream-hover-tab-up" ).show(); $( ".story-stream-hover-tab-down" ).hide(); appear_on_top = false; }else{ //show above placeholder hoverTop = hoverTop - 401; $(".story-stream-hover-wrapper").css({ position: "absolute", top: hoverTop, left: hoverLeft }).show(); $( ".story-stream-hover-tab-down" ).show(); $( ".story-stream-hover-tab-up" ).hide(); appear_on_top = true; } if(ga_action == 'click'){ $( ".mobile-close-btn" ).show(); }else{ $( ".mobile-close-btn" ).hide(); } $( ".mobile-close-btn" ).click(function(){ $( ".story-stream-hover-wrapper" ).hide(); }); var position_data = { target_top:target_top - alpha_offset.top - (target_height/2)-210, appear_on_top: appear_on_top } if(position_data.appear_on_top){ var wrapper_height = $(".story-stream-hover-wrapper").height(); if(parseInt(wrapper_height) < 350){ var difference = 350 - wrapper_height; var current_top_pos = parseFloat($(".story-stream-hover-wrapper").css('top')); var new_top_pos = current_top_pos + difference; if(parseInt(new_top_pos) <= parseInt(position_data.target_top) ){ $(".story-stream-hover-wrapper").css('top', new_top_pos+'px'); }else{ $(".story-stream-hover-wrapper").css('top', (position_data.target_top-20)+'px'); } } } var bc = $('body').attr('class'); var data = { 'ge_action' : ga_action, 'ge_category' : 'System Widget Interaction', 'ge_label' : 'Inline Story Stream : '+bc }; try{ _gaq.push(['_trackEvent', data['ge_category'], data['ge_action'], data['ge_label']]); } catch(err) {} } //////////////////////////////////////////////////////////////////////////////// // HOMEPAGE FUNCTIONS ////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //homepage navigation touch/click handlers function homeNavClick(e){ var ele = $(e.target.parentNode); var menu = ele.find("ul"); $( menu ).toggle(); } //homepage navigation mouse event handlers function mainNavHover(){ var over_submenu = false; /*$('.main-nav-bar ul.hoverMenu').hover( function(){ over_submenu = true; }, function(){ over_submenu = false; } );*/ $(".main-nav-bar .hoverli").hover( function () { // $('ul.hoverMenu').slideDown('medium'); $(this).find('ul.hoverMenu').show(); }, function () { //$('ul.hoverMenu').slideUp('medium'); //setTimeout(function(){ // if(!over_submenu) { //$('.main-nav-bar ul.hoverMenu').hide(); //} //}, 20); $(this).find('ul.hoverMenu').hide(); } ); } function viewSwitcher(){ $( ".grid_hp" ).click(function(){ $('.list_view_default').hide(); $( ".grid-view" ).css({ "display" : "block" }); $( ".list-view" ).css({ "display" : "none" }); $( ".list-style .grid_hp" ).addClass("active"); $( ".list-style .list_hp" ).removeClass("active"); var data = { 'ge_action' : 'Grid View', 'ge_category' : 'Section: Homepage', 'ge_label' : 'Click' }; send_ga_event(data); // Ask if this should be default if( SITE_INFO['name'] != "investigations" ){ $('.grid_view_default .yes').click(function() { createCookie('grid_view_default','1','365'); $('.grid_view_default').hide(); var grid_data = { 'ge_action' : 'Grid View', 'ge_category' : 'Section: Homepage', 'ge_label' : 'Set Grid Cookie: Yes' }; send_ga_event(grid_data); }); $('.grid_view_default .no').click(function() { createCookie('grid_view_default','0','365'); $('.grid_view_default').hide(); var grid_data = { 'ge_action' : 'Grid View', 'ge_category' : 'Section: Homepage', 'ge_label' : 'Set Grid Cookie: No' }; send_ga_event(grid_data); }); if(readCookie('grid_view_default') != '1') { $('.grid_view_default').show(); } } }); $( ".list_hp" ).click(function(){ $('.grid_view_default').hide(); $( ".list-view" ).css({ "display" : "block" }); $( ".grid-view" ).css({ "display" : "none" }); $( ".list-style .list_hp" ).addClass("active"); $( ".list-style .grid_hp" ).removeClass("active"); var data = { 'ge_action' : 'List View', 'ge_category' : 'Section: Homepage', 'ge_label' : 'Click' }; send_ga_event(data); // Ask if this should be default if( SITE_INFO['name'] != "investigations" ){ $('.list_view_default .yes').click(function() { createCookie('grid_view_default','0','365'); $('.list_view_default').hide(); var list_data = { 'ge_action' : 'List View', 'ge_category' : 'Section: Homepage', 'ge_label' : 'Set List View Cookie: Yes' }; send_ga_event(list_data); }); $('.list_view_default .no').click(function() { createCookie('grid_view_default','1','365'); $('.list_view_default').hide(); var list_data = { 'ge_action' : 'List View', 'ge_category' : 'Section: Homepage', 'ge_label' : 'Set List View Cookie: No' }; send_ga_event(list_data); }); if(readCookie('grid_view_default') != '0') { $('.list_view_default').show(); } } }); // Read cookie to determine if grid is default, if so, click if(readCookie('grid_view_default') == '1') { $( ".grid_hp" ).trigger('click'); } } //////////////////////////////////////////////////////////////////////////////// // CONGRESSIONAL BILL TRACKER FUNCTIONS //////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// function cbtSearch(){ $( "#cbt-searchBox" ).keypress(function(e) { //e.preventDefault(); if(e.which == 13) { searchText = ($(this).val()); window.location = window.location.protocol+'//dyn.realclearpolitics.com/congressional_bill_tracker/search/' + searchText + ''; $(this).val(''); } }); } function toggleCBTsearch(){ $( ".cbt-widget .filter" ).click(function(){ $( ".cbt-widget .search #cbt-searchBox" ).toggle(); $( ".cbt-widget .search #form_state_select" ).toggle(); $( ".cbt-widget .search .select" ).toggle(); }); } //////////////////////////////////////////////////////////////////////////////// // COMMENTS FUNCTIONS ////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// function showComments(){ $('.comments-count .show').click(function(){ $(this).parent().parent().find("#comments-container").show(); $(".comments-count .show").hide(); $(".comments-count .hide").show(); clearInterval(rcp_page_refresh_interval); //CLEARS THE REFRESH INTERVAL SET ON rcp.js }); } function hideComments(){ $('.comments-count .hide').click(function(){ $(this).parent().parent().find("#comments-container").hide(); $(".comments-count .hide").hide(); $(".comments-count .show").show(); }); } function showHideComments(){ $('.comments-wrapper .comments-label').click(function(){ $(this).parent().parent().find("#comments-container").toggle(); $(".comments-count .hide").toggle(); $(".comments-count .show").toggle(); clearInterval(rcp_page_refresh_interval); //CLEARS THE REFRESH INTERVAL SET ON rcp.js }); } //////////////////////////////////////////////////////////////////////////////// // HP RECENTS FUNCTIONS //////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// function recentItemsSlider() { var $container = $('.hp-recents-container'); if($container.length > 0) { $.getJSON(SITE_INFO['global_site_url']+'/include/home-recents-scroller-data.js?callback=?'); } } // This function serves as the callback for /include/home-recents-scroller-data.js function callback_recent_scroller(data) { var $container = $('.hp-recents-container'); // Populate with items from data var output = ''; var counter = 1; output += ''; //output += ' '; $container.children("#entries").html(output); var grid_size = get_grid_size_recents(); $container.children("#entries").flexslider({ animation: "slide", slideshowSpeed: 15000, controlNav: false, itemWidth: 210, minItems: grid_size, maxItems: grid_size }); $(window).resize(throttle_resize_recents); } var resize_timeout_recents; function throttle_resize_recents() { window.clearTimeout(resize_timeout_recents); resize_timeout_recents = setTimeout(window_resize_recents, 70); } function window_resize_recents() { //DESTROY FLEXSLIDER IF EXISTS var flexslider = $('.hp-recents-container #entries').data('flexslider'); if(flexslider != undefined) { flexslider.destroy(); var grid_size = get_grid_size_recents(); $('.hp-recents-container #entries').flexslider({ animation: "slide", slideshowSpeed: 5000, controlNav: false, itemWidth: 200, minItems: grid_size, maxItems: grid_size }); } } function get_grid_size_recents() { var w_width = window.innerWidth; if(w_width < 480) { return 1; } else if(w_width < 760) { return 2; } else if(w_width < 860) { return 3; } else if(w_width < 1080) { return 4; } else { return 5; } } //////////////////////////////////////////////////////////////////////////////// // OTHER FUNCTIONS ///////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// function click_outside_menus() { $(document).click(function(event) { // Hide main dropdown menu on system widgets if( !$(event.target).closest('.rec-site .rec-site-list').length && !$(event.target).closest('.rec-site .menu').length ) { $('.rec-site .rec-site-list').each(function() { if( $(this).is(':visible') ) { $(this).hide(); $(this).parent().find('.rec-site-tab').hide(); } }); } // Hide secondary dropdown menu on head-to-head system widget if( !$(event.target).closest('.head_to_head_candidates .menu').length && !$(event.target).closest('.head_to_head_race_dropdown').length ) { $('.head_to_head_race_dropdown').each(function() { if( $(this).is(':visible') ) { $(this).hide(); } }); } // Hide quick links / advanced filter if( !$(event.target).closest('.polls_header_dropdown').length && $(event.target).attr('src') != '/asset/img/grey-bg-chev.png' ) { var $ql_c = $('.polls_header_dropdown .quick_links_content'); var $f_c = $('.polls_header_dropdown .filter_content'); $('.polls_header_dropdown .open .quick_links_title').removeClass('active'); $('.polls_header_dropdown .open .filter_title').removeClass('active'); $('.polls_header_dropdown .open .arrow').html('Arrow'); if( $ql_c.is(':visible') ) { $ql_c.slideToggle(); } else if( $f_c.is(':visible') ) { $f_c.slideToggle(); } } if( !$(event.target).closest('.polls_header_2_dropdown').length && $(event.target).attr('src') != '/asset/img/grey-bg-chev.png' ) { var $ql_c = $('.polls_header_2_dropdown .quick_links_content'); var $f_c = $('.polls_header_2_dropdown .filter_content'); $('.polls_header_2_dropdown .open .quick_links_title').removeClass('active'); $('.polls_header_2_dropdown .open .filter_title').removeClass('active'); $('.polls_header_2_dropdown .open .arrow').html('Arrow'); if( $ql_c.is(':visible') ) { $ql_c.slideToggle(); } else if( $f_c.is(':visible') ) { $f_c.slideToggle(); } } // verticals menu masthead inner pages if( !$(event.target).closest('.verticals-menu').length && !$(event.target).closest('.verticals-site-list').length ) { if( $('.verticals-tab').is(':visible') ) { $('.verticals-tab').hide(); $('.verticals-site-list').hide(); } } // social bar Menu if( !$(event.target).closest('.jqDrawer').length && !$(event.target).closest('.toolset_drawer').length && !$(event.target).closest('.email_icon').length ) { if( $('.toolset_drawer').is(':visible') ) { $('.toolset_drawer').hide(200); } } // homepage date dropdown if( !$(event.target).closest('.date-menu').length ) { if( $('.date-menu .menu').is(':visible') ) { $('.date-menu .menu').hide(); $('.date-menu .menu-marker').hide(); } } }); } function displayStaff(){ $('.menu .title').click(function(){ var team = $( this ).parent().find(".author-wrapper"); $( team ).toggle(); $( this ).parent().toggleClass( "active" ); }); } function postScroller (){ var scrollerWidth = 0; //get width - per post item var postWidth = $( ".scroller .post" ).outerWidth(); var postLimit = 6; var totalPosts = ''; $( ".scroller .post" ).each(function(index) { scrollerWidth += parseInt($(this).outerWidth(), 10); totalPosts = index+1; }); $( ".scroller" ).css({ "width" : scrollerWidth }); $('.scroller-wrapper .right').click(function() { //alert(postWidth); postLimit += 1; if( postLimit != totalPosts ){ $('.scroller').animate({left: '-=' + postWidth + 'px'}, 'fast'); } }); $('.scroller-wrapper .left').click(function() { //alert(postWidth); postLimit -= 1; if( postLimit > 6 ){ $('.scroller').animate({left: '+=' + postWidth + 'px'}, 'fast'); } }); } function dateMenu(){ $( ".date-menu" ).click(function(){ $( ".date-menu .menu-marker" ).toggle(); $( ".date-menu .menu" ).toggle(); dateMenuVisible = true; }); } function send_ga_event(data) { // EXAMPLE INPUT: /* { 'ge_action' : 'List View', 'ge_category' : 'Homepage: Grid/List', 'ge_label' : 'Click' } */ //Wrap event tracking call to prevent premature termination of this function. try{ _gaq.push(['_trackEvent', data['ge_category'], data['ge_action'], data['ge_label']]); console.log('trackevent: '+data['ge_category']+' '+data['ge_action']+' '+data['ge_label']); } catch(err) {} } function customSelectBox(){ // Iterate over each select element $('#form_state_select').each(function () { // Cache the number of options var $this = $(this), numberOfOptions = $(this).children('option').length; // Hides the select element $this.addClass('s-hidden'); // Wrap the select element in a div $this.wrap('
    '); // Insert a styled div to sit over the top of the hidden select element $this.after('
    '); // Cache the styled div var $styledSelect = $this.next('div.styledSelect'); // Show the first select option in the styled div $styledSelect.text($this.children('option').eq(0).text()); // Insert an unordered list after the styled div and also cache the list var $list = $('
      ', { 'class': 'options' }).insertAfter($styledSelect); // Insert a list item into the unordered list for each select option for (var i = 0; i < numberOfOptions; i++) { $('
    • ', { text: $this.children('option').eq(i).text(), rel: $this.children('option').eq(i).val() }).appendTo($list); } // Cache the list items var $listItems = $list.children('li'); // Show the unordered list when the styled div is clicked (also hides it if the div is clicked again) $styledSelect.click(function (e) { e.stopPropagation(); $('div.styledSelect.active').each(function () { $(this).removeClass('active').next('ul.options').hide(); }); $(this).toggleClass('active').next('ul.options').toggle(); }); // Hides the unordered list when a list item is clicked and updates the styled div to show the selected list item // Updates the select element to have the value of the equivalent option $listItems.click(function (e) { e.stopPropagation(); $styledSelect.text($(this).text()).removeClass('active'); $this.val($(this).attr('rel')); $list.hide(); /* alert($this.val());*/ //Uncomment this for demonstration! window.location = window.location.protocol+'//dyn.realclearpolitics.com/congressional_bill_tracker/state/' + $this.val() + ''; }); // Hides the unordered list when clicking outside of it $(document).click(function () { $styledSelect.removeClass('active'); $list.hide(); }); }); } function sitesMenu(){ $('.verticals-menu').click(function(){ //if( $( '.more-nav' ).is( ' :visible' ) ){ // $('.more-nav').hide(); //} $('.verticals-tab').toggle(); $('.verticals-site-list').toggle(); }); } //open sitesMenu hover handler - changes color of pointer triangle at top of menu to match hovered site function sitesMenuHover(){ $('.verticals-site-list ul li a').mouseenter(function(){ if($(this).is(':hover')){ var bg = $(this).css('background-color'); var parent = $(this).parent().parent().parent().parent(); $('.verticals-tab').css( { "border-bottom" : "10px solid " + bg } ); } }); $('.verticals-site-list ul li a').mouseleave(function(){ if($(this).not(':hover')){ $('.verticals-tab').css( { "border-bottom" : "10px solid #EBEBEB" } ); } }); } //open sitesMenu hover handler - changes color of pointer triangle at top of menu to match hovered site function recommendedSitesMenuHover(){ $('.rec-site-list ul li a').mouseenter(function(){ if($(this).is(':hover')){ var bg = $(this).css('background-color'); var parent = $(this).parent().parent().parent().parent(); $('.rec-site-tab').css( { "border-bottom" : "10px solid " + bg } ); } }); $('.verticals-site-list ul li a').mouseleave(function(){ if($(this).not(':hover')){ $('.verticals-tab').css( { "border-bottom" : "10px solid #EBEBEB" } ); } }); } //more link drop menu - contains all sections of website function sectionsMenu(){ $( ".site-nav-more" ).on({ mouseenter: function(e) { //HIDES OTHER DROPDOWNS if( $( '.verticals-menu' ).is( ' :visible' ) ){ $('.verticals-tab').hide(); $('.verticals-site-list').hide(); } $(this).find('.sections-tab').show(); $(this).find('.primary').show(); }, mouseleave: function(e){ $(this).find('.sections-tab').hide(); $(this).find('.primary').hide(); }/*, click: function(e) { //HIDES OTHER DROPDOWNS if( $( '.verticals-menu' ).is( ' :visible' ) ){ $('.verticals-tab').hide(); $('.verticals-site-list').hide(); } $(this).find('.sections-tab').toggle(); $(this).find('.primary').toggle(); }*/ }); $('li.site-nav-more .jQ-section-menu').click(function(e){ //alert(e.target+'-'+this); if(e.target != this) return; // only continue if the target itself has been clicked, this is so child submenu clicks will work //alert('got here'); //HIDES OTHER DROPDOWNS if( $( '.verticals-menu' ).is( ' :visible' ) ){ $('.verticals-tab').hide(); $('.verticals-site-list').hide(); } $(this).parent().find('.sections-tab').toggle(); $(this).parent().find('.primary').toggle(); }); /* $(".site-nav-more").hover( function () { //HIDES OTHER DROPDOWNS if( $( '.verticals-menu' ).is( ' :visible' ) ){ $('.verticals-tab').hide(); $('.verticals-site-list').hide(); } $(this).find('.sections-tab').show(); $(this).find('.primary').show(); }, function () { $(this).find('.sections-tab').hide(); $(this).find('.primary').hide(); } ); */ } //inner sections menu handler - opens sub-sections for modules like Polls, Elections 2016, Etc... function sectionsInnerMenu(){ $('.site-nav-more ul.primary li a').click(function(){ //alert('test'); if( $(this).not('.static') ){ $(this).parent().find('.inner').toggle(); } /*if( $(this).is('.static') ){ $('.more-nav').toggle(); var url = $(this).attr('href'); location.href = url; }*/ }); } function progressBar(){ var getMax = function(){ return $(document).height() - $(window).height(); } var getValue = function(){ return $(window).scrollTop(); } //alert( 'getMax: ' + getMax() + ' -- ' + 'getVal: ' + getValue() ); if ('max' in document.createElement('progress')) { // Browser supports progress element var progressBar = $('progress'); var top = $('#progress-bar').offset().top; // Set the Max attr for the first time progressBar.attr({ max: getMax() }); $(document).on('scroll', function(){ // On scroll only Value attr needs to be calculated progressBar.attr({ value: getValue() }); var y = $(this).scrollTop(); if( y > top ){ // $('#progress-bar').addClass('fixed'); $('.progress-bar').addClass('fixed'); $(".progress-bar").css({ "position" : "fixed" }); }else{ //$('#progress-bar').removeClass('fixed'); //$('.progress-bar').addClass('fixed'); } }); $(window).resize(function(){ // On resize, both Max/Value attr needs to be calculated progressBar.attr({ max: getMax(), value: getValue() }); }); } else { //no browser support => older browsers and < IE10 var progressBar = $('.progress-bar'), max = getMax(), value, width; var getWidth = function() { // Calculate width in percentage value = getValue(); width = (value/max) * 100; width = width + '%'; return width; } var setWidth = function(){ progressBar.css({ width: getWidth() }); } $(document).on('scroll', setWidth); $(window).on('resize', function(){ // Need to reset the Max attr max = getMax(); setWidth(); }); } } function onResize(){ //viewport has resize //on viewport resize $(window).resize(function(){ //certain inline styles are applied onScroll in specific viewport sizes so we clear them here $('#masthead-container').attr('style',''); }); } function onScroll(){ //show/hide masthead on scrolling down/up var didScroll; var lastScrollTop = 0; var delta = 5; var firedNewsletterPromo = 0; //INIT NEWSLETTER FIRED-TRIGGER var firedNotificationsPromo = 0; //INIT NOTIFICATIONS FIRED-TRIGGER if($('body.home').length>0){ var navbarHeight = $("#masthead-container").outerHeight(); }else{ var navbarHeight = $("#masthead-wrapper").outerHeight(); } // on scroll, let the interval function know the user has scrolled $(window).scroll(function(event){ didScroll = true; }); // run hasScrolled() and reset didScroll status setInterval(function() { if (didScroll) { hasScrolled(); didScroll = false; } }, 250); function hasScrolled() { var st = $(this).scrollTop(); var mastHeight = $("#masthead-wrapper").css("height"); var mastheadContainerHeight = $("#masthead-container").css("height"); var windowWidth = $(window).outerWidth(); //notifications checks var n_browser = navigator.browserInfo.browser; var n_os = navigator.osInfo.os; var pop_up_notif = false; var notificationsPopCookie = readCookie('notificationsScrollPop'); if(notif_browser(n_browser) && notif_os(n_os) && SITE_INFO['name'] == "politics" && (!$("body").hasClass("home") && !$("body").hasClass("welcome")) && !notificationsPopCookie){ pop_up_notif = true; }else if(notif_browser(n_browser) && notif_os(n_os) && SITE_INFO['name'] == "politics" && $('#notif_banner_content').is(':visible')){ notif_banner_enabled = true; } else if($('#large_notif_content').is(':visible') || SITE_INFO['name'] != 'politics'){ notif_banner_enabled = false; } if(notif_banner_enabled == false){ $('#large_notif_content').slideUp(); $('#container').css('padding-top', '0px'); $('#masthead-container').css('margin-top', 'inherit'); $('.flex-viewport').css('margin-top', 'inherit'); if(SITE_INFO['name'] == "politics" && notif_banner_enabled == true){ switch_to_banner(windowWidth); } } //end notifications checks //if(Math.abs(lastScrollTop-st) <= delta) return; // If current position > last position AND scrolled past navbar... //console.log(st+' > '+navbarHeight); //if (st > lastScrollTop && st > navbarHeight){ EM: Original if (st > lastScrollTop && st > 1){ //checks viewport vertical scroll percentage scrollPercentage = getScrollPercent(); //IF SCROLLED PAST 50% AND WE HAVE NOT FIRED YET /*ORIGINAL CODE TO ONLY FIRE loadNewsletterPromo(); if(scrollPercentage>35 && firedNewsletterPromo==0){ //load newsletter promo //alert('scroll-percentage: '+scrollPercentage); firedNewsletterPromo=1; //SET FIRE TRIGGER OFF loadNewsletterPromo(); }*/ //M.B. SEE CHANGE LOG ON TOP FILE... /*if(scrollPercentage>25 && firedNotificationsPromo==0){ //load notifications promo //alert('scroll-percentage: '+scrollPercentage); firedNotificationsPromo=1; //SET FIRE TRIGGER OFF // Make sure OS is Mac, Windows, Android or Linux // Make sure browser is chrome or firefox //if(pop_up_notif){ //loadNotificationsPromo(); //}else{ var newsPopCookie = readCookie('newsletterScrollPop'); if(!newsPopCookie && SITE_INFO['name'] != 'politics'){ loadNewsletterPromo(); } //} }*/ // Scroll Down if( (windowWidth < 1180 && $( 'body.home' ).length) || !$( 'body.home' ).length ){ $("#masthead-wrapper").removeClass("nav-down").addClass("nav-up"); } $("#masthead-wrapper").css({ "box-shadow" : "none" }); /*if( windowWidth < 768 && st>navbarHeight){ $("#masthead-container").removeClass("nav-down").addClass("nav-up").css("position","fixed"); }*/ if( windowWidth < 768 ){ $("#masthead-container").removeClass("nav-down").addClass("nav-up").css("position","fixed"); } $("#masthead-container").css({ "box-shadow" : "none" }); $(".progress-bar").css({ "position" : "relative", "top" : "8px" }); if( mastHeight == "54px" ){ $("progress").css({ "position" : "relative", "top" : "-11px" }); } if( mastHeight == "166px" && windowWidth <= 1280 ){ $("progress").css({ "position" : "relative", "top" : "-14px" }); } if( windowWidth >= 768 || windowWidth <= 1024 ){ $(".progress-bar").css({ "position" : "fixed", "top" : "0" }); } if(notif_banner_enabled){ $('#masthead-container').css('margin-top', '35px'); $('.flex-viewport').css('margin-top', '35px'); //to push the menu down on inner pages if(!$("body").hasClass("home") && $('#large_notif_wrapper').is(':visible')){ $('#large_notif_wrapper').css('top', '0'); $('#masthead-wrapper').css('top', '35px'); $('#container').css('padding-top', '45px'); if($('#masthead-wrapper').hasClass('nav-down')){ if(windowWidth < 768){ $('.progress-bar').css('top', '89px'); }else{ $('.progress-bar').css('top', '110px'); } }else{ $('.progress-bar').css('top', '35px'); } } }else{ $('#masthead-container').css('margin-top', 'inherit'); $('.flex-viewport').css('margin-top', 'inherit'); $('#masthead-wrapper').css('top', '0'); $('#container').css('padding-top', '10px'); } } else { // Scroll Up // If did not scroll past the document (possible on mac)... if(st + $(window).height() < $(document).height()) { if( (windowWidth < 1180 && $( 'body.home' ).length) || !$( 'body.home' ).length ){ $("#masthead-wrapper").removeClass("nav-up").addClass("nav-down"); } /*if( windowWidth < 1024 ){ $("#masthead-container").removeClass("nav-up").addClass("nav-down"); if( st= 768){ $(".progress-bar").css({ "position" : "fixed", "top" : "73px" }); } if( windowWidth < 768){ if( SITE_INFO['name'] == "investigations" ){ $(".progress-bar").css({ "position" : "fixed", "top" : "42px" }); }else{ $(".progress-bar").css({ "position" : "fixed", "top" : "54px" }); } } if(notif_banner_enabled){ $('#masthead-container').css('margin-top', '35px'); $('.flex-viewport').css('margin-top', '35px'); //to push the menu down on inner pages if(!$("body").hasClass("home") && $('#large_notif_wrapper').is(':visible')){ $('#large_notif_wrapper').css('top', '0'); $('#masthead-wrapper').css('top', '35px'); $('#container').css('padding-top', '45px'); if($('#masthead-wrapper').hasClass('nav-down')){ if(windowWidth < 768){ $('.progress-bar').css('top', '89px'); }else{ $('.progress-bar').css('top', '110px'); } }else{ $('.progress-bar').css('top', '35px'); } } }else{ $('#masthead-container').css('margin-top', 'inherit'); $('.flex-viewport').css('margin-top', 'inherit'); $('#masthead-wrapper').css('top', '0'); $('#container').css('padding-top', '10px'); } //alert( mastHeight ); if( mastHeight == "54px" ){ $("#masthead-wrapper").css({ "box-shadow" : "none" }); $("progress").css({ "position" : "relative", "top" : "-16px" }); }else{ $("#masthead-wrapper").css({ "box-shadow" : "0px 8px 5px -5px "+SITE_INFO['site_color'] }); } if( mastheadContainerHeight == "54px" ){ $("#masthead-container").css({ "box-shadow" : "none" }); $("progress").css({ "position" : "relative", "top" : "-16px" }); } } if(st < 135){ //height of masthead-wrapper + pageheader div - clears shadow smoothly $("#masthead-wrapper").css({ "box-shadow" : "none" }); } } lastScrollTop = st; } } function getScrollPercent() { var h = document.documentElement, b = document.body, st = 'scrollTop', sh = 'scrollHeight'; return h[st]||b[st] / ((h[sh]||b[sh]) - h.clientHeight) * 100; } function notif_browser(browser){ if(browser == 'Firefox' || browser == 'Chrome' || browser == 'Opera'){ return true; }else{ return false; } } function notif_os(OS){ if(OS == 'Linux' || OS == 'Mac OS X' || OS == 'Mac OS' || OS.charAt(0) == 'W' || OS == 'Android'){ return true; }else{ return false; } } function shareSelected(){ var savedText = null; // Variable to save the text function saveSelection() { if (window.getSelection) { var sel = window.getSelection(); if (sel.getRangeAt && sel.rangeCount) { return sel.getRangeAt(0); } } else if (document.selection && document.selection.createRange) { return document.selection.createRange(); } return null; } function restoreSelection(range) { if (range) { if (window.getSelection) { var sel = window.getSelection(); sel.removeAllRanges(); sel.addRange(range); } else if (ddocument.selection && range.select) { range.select(); } } } var btnWrap = document.getElementById('share-button'), btnShare = btnWrap.children[0]; document.onmouseup = function(e) { savedText = saveSelection(); // Save selection on mouse-up //alert(savedText); setTimeout(function() { var isEmpty = savedText.toString().length === 0; // Check selection text length // set sharing button position //if( savedText.toString().length > 45 ){ btnWrap.style.top = (isEmpty ? -9999 : e.pageY) + 'px'; btnWrap.style.left = (isEmpty ? -9999 : e.pageX) + 'px'; //} }, 10); }; btnShare.onmousedown = function(e) { if (!savedText) return; //window.open('http://firefox.com/'); window.open('https://twitter.com/intent/tweet?text=' + savedText, 'shareWindow', 'width=300,height=150,top=50,left=50'); // Insert the selected text into sharing URL restoreSelection(savedText); // select back the old selected text // hide if we are done setTimeout(function() { btnWrap.style.top = '-9999px'; btnWrap.style.left = '-9999px'; }, 1000); return false; }; } function showMobileSearch(){ $( ".site-search-mobile" ).click(function(){ $( ".site-search.mobile" ).toggle(); $( ".site-search-mobile" ).hide(); }); } function goToByScroll(id){ // Reove "link" from the ID id = id.replace("link", ""); var offset; var navPointer; function getNav(){ navPointer = $("#masthead-container").attr("class"); if( navPointer === "nav-down" ){ //scrolling down if( id === "top" ){ offset = 30; }else{ offset = 50; } }else if( navPointer === "nav-up" ){ if( id === "top" ){ offset = 174; }else{ offset = 104; } }else{ offset = 0; } } //the use of timeout gets more accurate value of offset to use - allows scrolling to wind down before calculating setTimeout(getNav(), 4000); //set offset to control scroll stop point - home page only if( $("body.home").length > 0 ){ // Scroll $('html,body').animate({ scrollTop: $("#"+id).offset().top-offset}, 'slow'); }else{ // Scroll $('html,body').animate({ scrollTop: $("#"+id).offset().top}, 'slow'); } } //SITE SEARCH function siteSearch(){ if( $('body.home').length>0 ){ $( ".home-search #searchBox" ).keypress(function(e) { if(e.which == 13) { e.stopPropagation(); e.preventDefault(); searchText = ($(this).val()); searchText = searchText.replace(" ", "+"); window.location = SITE_INFO['global_site_url']+'/search/?q=' + searchText + ''; $(this).val(''); return false; } }); }else{ $( "#searchBox" ).keypress(function(e) { if(e.which == 13) { e.stopPropagation(); e.preventDefault(); searchText = ($(this).val()); searchText = searchText.replace(" ", "+"); window.location = SITE_INFO['global_site_url']+'/search/?q=' + searchText + ''; $(this).val(''); return false; } }); } } function convertImgUrl(url, target) { //Changes image url to an alternate resolution image var a = document.createElement('a'); //If 'target' argument has no value or is zero, the new url will not have _N_ at the end (where N is a number). var new_res = typeof target === 'undefined' || target == 0 ? '' : '_'+target+'_'; a.href = url; if(a.pathname.match(/\/(\d+)_([12345])_.(jpg|png|gif)/g)) { url = window.location.protocol+'//' + a.hostname + a.pathname.replace(/_[12345]_/g, new_res); } a.remove(); return url; } function upgradeImagesByDisplaySize() { var images = document.getElementsByTagName('img'); for(var i=0; i= 400px images[i].src = alt_src.value; } } }