(function ($, template, JSON, Class, Cookie) { this.COGNATIVEX = this.COGNATIVEX || {}; function widgetFactoryClass(widgetRenderInstance, result){ // reset the impression flag widgetRenderInstance.isWidgetImpressionSent = false; // if no result then simply stop if(!(result && result.data)) return; // define main vars this.widgetposts = []; this.widgetdata = { 'id' : result.id, 'timestamp_server' : result.timestamp, 'timestamp_client' : new Date().getTime(), 'logic' : result.logic, 'sdk_version' : window.COGNATIVEX.sdk_version, 'version' : result.version || "", 'posts' : this.widgetposts, 'key' : result.key }; // save a reference of the class instance const objRef = this; ///////////////////////////// // define the helper methods ///////////////////////////// // Set widgets prerequisites this.processWidgetData = function () { // process data COGNATIVEX.$.each(result.data, function (index, val) { // get a reference of the value const value = val; // gather the post data const post = { id: value.postid, r: value.rank, i: value.index, l: value.logic, v: result.version }; // push posts of widgets objRef.widgetposts.push(post); if( typeof COGNATIVEX.infinite_view_triggered !== "undefined" && COGNATIVEX.infinite_page !== -1 && COGNATIVEX.infinite_view_triggered.indexOf(COGNATIVEX.infinite_page) == -1 && COGNATIVEX.current_post['url'] != result.data[0]['url'] ){ COGNATIVEX.infinite_view_triggered.push(COGNATIVEX.infinite_page); COGNATIVEX.current_post = { url : result.data[0]['url'] , postid : result.data[0]['postid'] }; } objRef.widgetposts.push(post); // re-format the date to print in the widget in a representable way if (typeof result.data[index]['publisheddate'] != 'undefined') { const date = new Date(result.data[index]['publisheddate']); var day = date.getDate(), month = (date.getMonth() + 1), year = date.getFullYear(); result.data[index]['publisheddate'] = day + '.' + month + '.' + year; var monthNames = ["كانون الثاني", "فبراير", "مارس", "أبريل", "أيار", "حزيران", "تموز", "آب", "أيلول", "تشرين الأول", "تشرين الثاني", "كانون الاول" ]; result.data[index]['arabicdate'] = day + " " + monthNames[month] + " " + year; } // re-format the title to cut it after x number of chars in key of `display_title` if (typeof result.data[index]['title'] != 'undefined') { result.data[index]['display_title'] = result.data[index]['title']; if (result.data[index]['title'].length > 50) { result.data[index]['display_title'] = result.data[index]['title'].substring(0, 46) + '..'; } } // attach the following event listeners. let action_types = ['link', 'expand', 'popup', 'close']; value.event_attach = {}; for (let i in action_types){ let event = 'widget_click'; // default value unless the event is a close event. click_event = ''; if(action_types[i] == 'close') event = 'widget_close'; switch (action_types[i]){ case 'link': let postWithType = post; postWithType['action_type'] = action_types[i]; // link const extra = encodeURIComponent(JSON.stringify(postWithType)); break; default: let eventData = objRef.widgetdata; eventData['action_type'] = action_types[i]; // ex. expand, popup even close break; } // add the click events value.event_attach[action_types[i]] = click_event; } }); widgetRenderInstance.isWidgetImpressionSent = true; // set flag that impression has been sent } // Set widgets prerequisites this.setWidgetsDefaults = function () { switch(result.widget_layout.type ){ default: break; case 'recommendation-infinite': if (typeof COGNATIVEX.infinite_page == 'undefined') { COGNATIVEX.infinite_page = -1; COGNATIVEX.infinite_view_triggered = []; COGNATIVEX.infinite_posts = result.posts_url; } result.page = COGNATIVEX.infinite_page; break; } } // Sets the layout of the widget this.widgetLayout = function () { const widgetdiv = document.getElementById(widgetRenderInstance.container); if(! widgetdiv) return; if(objRef.widgetposts.length == 0) { widgetdiv.style.display = "none"; return; } widgetdiv.style.display = "block"; // set a container div for the widget let widgetDom = "
"; // check if there is some css to inject if (typeof result.widget_layout.css !== 'undefined' && result.widget_layout.css !== '') { if ((result.widget_layout.type == 'recommendation-infinite' && COGNATIVEX.infinite_page == -1) || result.widget_layout.type != 'recommendation-infinite') { widgetDom += ""; } } // get the dom of the tpl from the json widgetDom += template(template.decode(result.widget_layout.template), result); // end the template div widgetDom += "
"; // Appending all of that to the dom widgetdiv.className += ' cognativex-widget-' + result.widget_layout.type ; widgetdiv.innerHTML = widgetdiv.innerHTML + widgetDom; // check if there is some js to inject if (typeof result.widget_layout.js != 'undefined' && result.widget_layout.js != '') { widgetRenderInstance.runScript(result.widget_layout.js); } //track the view event of the widget seen widgetRenderInstance.findEltsVisible(widgetRenderInstance.container, result, function (post_id) { switch(result.widget_layout.type ){ default: if(typeof post_id !== "undefined" && result.widget_layout.type == 'recommendation-feed'){ objRef.widgetdata['posts'] = [post_id]; } break; case 'recommendation-infinite': // set the current post for the infinite scroll COGNATIVEX.current_post = { url : result.data[0].url, postid : result.data[0].postid }; break; } }); } // Do the necessary after the dom existance this.initWidgetScripts = function () { switch (result.widget_layout.type ) { default: break; case 'recommendation-infinite': // attach the scroll event one time if (typeof COGNATIVEX.infinite_page != 'undefined') { COGNATIVEX.$(window).scroll(function () { // we have set the scroll to be max 3 loads if ((COGNATIVEX.infinite_page < COGNATIVEX.infinite_posts.length) && ((Math.floor(COGNATIVEX.$(window).scrollTop() + COGNATIVEX.$(window).height() ) +5) >= Math.floor(COGNATIVEX.$(document).height()))) { COGNATIVEX.$('.cognativex-load-more').last().show(); COGNATIVEX.infinite_page = COGNATIVEX.infinite_page + 1; // we have index 0 loaded so load 1 setTimeout(function () { // load content; that is 0 is the default loaded // note that we set some time out so that we can see the loader for few widgetRenderInstance.load_content(COGNATIVEX.infinite_page , widgetRenderInstance.container, widgetRenderInstance.templateid); }, 100); } }); } break; case 'recommendation-popup1': case 'recommendation-popup2': // hide popups by default. COGNATIVEX.$('.cognativex-widget-' + result.widget_layout.type ).show(); break; } // this is general to all widgets once found a video then add the following style once. if (COGNATIVEX.$('.cognativex-type-main-image-container-video').length && !COGNATIVEX.$('.cognativex-vid-styling').length) { COGNATIVEX.$('.cognativex-widget').first().before(''); } } this.run = function (){ this.processWidgetData(); this.setWidgetsDefaults(); this.widgetLayout(); this.initWidgetScripts(); } } function WidgetRenderClass(widgetId) { // set the key of the widget in use this.key = ''; this.widget_id = widgetId; // initialize some default values. this.isWidgetImpressionSent = false; this.viewedWidgets = []; this.viewedFeedPosts = {}; // get the main containers and templates ids this.container = "cognativex-widget-" + this.widget_id; this.templateid = "cognativex-template-" + this.widget_id; this.init = function () { // Make an ajax to load widget info. const xhttp = new XMLHttpRequest(); // on ready state call helper function const objRef = this; xhttp.onreadystatechange = function () { objRef.afterAjax(this, objRef.container, objRef.templateid); }; // double check configs and widgets are set if (!COGNATIVEX.config || !COGNATIVEX.config.settings || !COGNATIVEX.config.settings["widget"]) { return; } if (!COGNATIVEX.config.appdomain || !COGNATIVEX.config.appkey) { console.error("appdomain and appkey are empty"); return; } // temperoray set for the file for each widget needed. const widgetSidebar1 = "widget-sidebar1.json", widgetSidebar2 = "widget-sidebar2.json", widgetSidebar3 = "widget-sidebar3.json", widgetBanner1 = "widget-banner1.json", widgetBanner2 = "widget-banner2.json", widgetBottom1 = "widget-bottom1.json", widgetBottom2 = "widget-bottom2.json", widgetReadmore1 = "widget-readmore1.json", widgetReadmore2 = "widget-readmore2.json", widgetFeeds1 = "widget-feeds1.json", widgetInfiniteScroll1 = "infinteSamples/widget-infinite-scroll1.json", widgetPopup1 = "widget-popup1.json", widgetPopup2 = "widget-popup2.json"; const path = "./src/data/"; let widgetUrl = path; switch (this.widget_id) { case '5650687863029760': case '56506878630297600': widgetUrl += widgetSidebar2; break; case '5650687863029761': case '56506878630297610': widgetUrl += widgetBanner1; break; case '5650687863029762': case '56506878630297620': widgetUrl += widgetBottom1; break; case '5650687863029763': case '56506878630297630': widgetUrl += widgetReadmore1; break; case '5650687863029764': case '56506878630297640': widgetUrl += widgetPopup1; break; case '5650687863029765': case '56506878630297650': widgetUrl += widgetBottom2; break; case '5650687863029766': case '56506878630297660': widgetUrl += widgetFeeds1; break; case '5650687863029767': case '56506878630297670': case '5733704819277824': case '57337048192778240': widgetUrl += widgetSidebar1; break; case '5650687863029768': case '56506878630297680': widgetUrl += widgetSidebar3; break; case '5650687863029769': case '56506878630297690': widgetUrl += widgetReadmore2; break; case '5650687863029770': case '56506878630297700': case '5749071943827456': case '57490719438274560': widgetUrl += widgetInfiniteScroll1; break; case '5650687863029771': case '56506878630297710': widgetUrl += widgetPopup2; break; case '5650687863029772': case '56506878630297720': widgetUrl += widgetBanner2; break; } xhttp.open("GET", widgetUrl, true); xhttp.send(); } this.inViewPort = function (el) { // use el in Jquery ex . COGNATIVEX.$('selector') if (typeof el !== 'undefined') { if (typeof el[0] !== 'undefined') { if (typeof el[0].getBoundingClientRect !== 'undefined') { var rect = el[0].getBoundingClientRect(); return rect.bottom > 0 && rect.right > 0 && rect.left < (window.innerWidth || document.documentElement.clientWidth) && rect.top < (window.innerHeight || document.documentElement.clientHeight); } } } return false; } this.findEltsVisible = function (eltStr, result, callback) { const objRef = this; COGNATIVEX.$(window).scroll(function () { switch(result.widget_layout.type ){ case 'recommendation-feed': // send post ids if (COGNATIVEX.$('#' + eltStr).length) { if(typeof objRef.viewedFeedPosts['#' + eltStr] == "undefined") objRef.viewedFeedPosts['#' + eltStr] = []; // prepare init for array of posts // sure we have an array to push into it COGNATIVEX.$('.cognativex-feeds1-link').each(function(){ if(objRef.inViewPort(COGNATIVEX.$(this)) && objRef.viewedFeedPosts['#' + eltStr].indexOf(COGNATIVEX.$(this).attr('post_id')) == -1){ // if in view port and post id in view port isnt in array then push it to array to not see it again and send it to callback. objRef.viewedFeedPosts['#' + eltStr].push(COGNATIVEX.$(this).attr('post_id')); if(typeof callback !== 'function') { console.error('Callback must be a function'); return; } (callback(COGNATIVEX.$(this).attr('post_id'))); } }); } break; default: if (objRef.inViewPort(COGNATIVEX.$('#' + eltStr)) && objRef.viewedWidgets.indexOf(eltStr) == -1) { objRef.viewedWidgets.push(eltStr); if(typeof callback !== 'function') { console.error('Callback must be a function'); return; } (callback()); } break; } }); } this.runScript = function (str) { /******** // Helper function: // this function expects a string supposedly js syntax code and executes it. ********/ const s = document.createElement('script'); s.type = 'text/javascript'; s.innerHTML = str; // re-insert the script tag so it executes. document.head.appendChild(s); } this.afterAjax = function (self, container, templateid) { /******** // Helper function: // this function is only used to set what needs to be done after ajax is complete // consists of main data structuring and other widgets functionality ********/ if (self.readyState === 4 && self.status === 200) { new widgetFactoryClass(this, JSON.parse(self.responseText)).run(); } } this.load_content = function (myPage, container, templateid) { /******** // Helper function: // this function is only used for the infinite scroll case where we need to always do an ajax request to get other articles per page scroll ********/ // cognativex-load-more const xhttp = new XMLHttpRequest(); const objRef = this; xhttp.onreadystatechange = function () { const self = this; COGNATIVEX.$('.cognativex-load-more').last().hide(); objRef.afterAjax(self, container, templateid); }; if(typeof COGNATIVEX.infinite_posts[myPage] == "undefined") { COGNATIVEX.$('.cognativex-load-more').last().hide(); return;} xhttp.open("GET", COGNATIVEX.infinite_posts[myPage]['url'], true); xhttp.send(); } } this.COGNATIVEX.renderWidget = function (widgetid) { new WidgetRenderClass(widgetid).init(); }; })(COGNATIVEX.jQuery, COGNATIVEX.template, COGNATIVEX.JSON, COGNATIVEX.Class, COGNATIVEX.Cookies);