/* Minification failed. Returning unminified contents. (2358,6): run-time error JS1004: Expected ';' (2360,35): run-time error JS1004: Expected ';' (2362,26): run-time error JS1004: Expected ';' (3469,25-33): run-time error JS1006: Expected ')': function (3469,36): run-time error JS1004: Expected ';' (3472,25): run-time error JS1004: Expected ';' (4055,2-3): run-time error JS1195: Expected expression: ) */ /* Copyright 2013 - SmartAdmin Template * This script is part of an item on wrapbootstrap.com * https://wrapbootstrap.com/user/myorange * * * * * For more information please contact info@myorange.ca * * */ $.sound_path = "/themes/new/content/sound/"; $.sound_on = true; // turn off sound if you are having issues with Safari. jQuery(document).ready(function () { // Plugins placing $("body").append("
"); $("body").append("
"); }); //Closing Rutine for Loadings function SmartUnLoading() { $(".divMessageBox").fadeOut(300, function () { $(this).remove(); }); $(".LoadingBoxContainer").fadeOut(300, function () { $(this).remove(); }); } // Messagebox var ExistMsg = 0, SmartMSGboxCount = 0, PrevTop = 0; $.SmartMessageBox = function (settings, callback) { var SmartMSG, Content; settings = $.extend({ title: "", content: "", NormalButton: undefined, ActiveButton: undefined, buttons: undefined, input: undefined, inputValue: undefined, placeholder: "", options: undefined }, settings); var PlaySound = 0; PlaySound = 1; //Messagebox Sound // SmallBox Sound if (isIE8orlower() == 0) { var audioElement = document.createElement('audio'); audioElement.setAttribute('src', $.sound_path + 'messagebox.mp3'); //$.get(); audioElement.addEventListener("load", function () { audioElement.play(); }, true); audioElement.pause(); audioElement.play(); } SmartMSGboxCount = SmartMSGboxCount + 1; if (ExistMsg == 0) { ExistMsg = 1; SmartMSG = "
"; $("body").append(SmartMSG); if (isIE8orlower() == 1) { $("#MsgBoxBack").addClass("MessageIE"); } } var InputType = ""; var HasInput = 0; if (settings.input != undefined) { HasInput = 1; settings.input = settings.input.toLowerCase(); switch (settings.input) { case "text": settings.inputValue = $.type(settings.inputValue) === 'string' ? settings.inputValue.replace(/'/g, "'") : settings.inputValue; InputType = "

"; break; case "password": InputType = "

"; break; case "select": if (settings.options == undefined) { alert("For this type of input, the options parameter is required."); } else { InputType = "" } break; default: alert("That type of input is not handled yet"); } } Content = "
"; Content += "
"; Content += "" + settings.title + ""; Content += "

" + settings.content + "

"; Content += InputType; Content += "
"; if (settings.buttons == undefined) { settings.buttons = "[Accept]"; } settings.buttons = $.trim(settings.buttons); settings.buttons = settings.buttons.split(''); var Name = ""; var NumBottons = 0; if (settings.NormalButton == undefined) { settings.NormalButton = "#232323"; } if (settings.ActiveButton == undefined) { settings.ActiveButton = "#ed145b"; } for (var i = 0; i <= settings.buttons.length - 1; i++) { if (settings.buttons[i] == "[") { Name = ""; } else { if (settings.buttons[i] == "]") { NumBottons = NumBottons + 1; Name = ""; Content += Name; } else { Name += settings.buttons[i]; } } }; Content += "
"; //MessageBoxButtonSection Content += "
"; //MessageBoxMiddle Content += "
"; //MessageBoxContainer // alert(SmartMSGboxCount); if (SmartMSGboxCount > 1) { $(".MessageBoxContainer").hide(); $(".MessageBoxContainer").css("z-index", 99999); } $(".divMessageBox").append(Content); // Focus if (HasInput == 1) { $("#txt" + SmartMSGboxCount).focus(); } $('.botTempo').hover(function () { var ThisID = $(this).attr('id'); // alert(ThisID); // $("#"+ThisID).css("background-color", settings.ActiveButton); }, function () { var ThisID = $(this).attr('id'); //$("#"+ThisID).css("background-color", settings.NormalButton); }); // Callback and button Pressed $(".botTempo").click(function () { // Closing Method var ThisID = $(this).attr('id'); var MsgBoxID = ThisID.substr(ThisID.indexOf("-") + 1); var Press = $.trim($(this).text()); if (HasInput == 1) { if (typeof callback == "function") { var IDNumber = MsgBoxID.replace("Msg", ""); var Value = $("#txt" + IDNumber).val(); if (callback) callback(Press, Value); } } else { if (typeof callback == "function") { if (callback) callback(Press); } } $("#" + MsgBoxID).addClass("animated fadeOut fast"); SmartMSGboxCount = SmartMSGboxCount - 1; if (SmartMSGboxCount == 0) { $("#MsgBoxBack").removeClass("fadeIn").addClass("fadeOut").delay(300).queue(function () { ExistMsg = 0; $(this).remove(); }); } }); } // BigBox var BigBoxes = 0; $.bigBox = function (settings, callback) { var boxBig, content; settings = $.extend({ title: "", content: "", icon: undefined, number: undefined, color: undefined, sound: $.sound_on, timeout: undefined, colortime: 1500, colors: undefined }, settings); // bigbox Sound if (settings.sound === true) { if (isIE8orlower() == 0) { var audioElement = document.createElement('audio'); if (navigator.userAgent.match('Firefox/')) audioElement.setAttribute('src', $.sound_path + 'bigbox.ogg'); else audioElement.setAttribute('src', $.sound_path + 'bigbox.mp3'); //$.get(); audioElement.addEventListener("load", function () { audioElement.play(); }, true); audioElement.pause(); audioElement.play(); } } BigBoxes = BigBoxes + 1; boxBig = "
"; boxBig += "" + settings.title + ""; boxBig += "

" + settings.content + "

"; boxBig += "
"; if (settings.icon == undefined) { settings.icon = "fa fa-cloud"; } boxBig += ""; boxBig += "
"; boxBig += "
"; if (settings.number != undefined) { boxBig += settings.number; } boxBig += "
"; boxBig += "
"; // stacking method $("#divbigBoxes").append(boxBig); if (settings.color == undefined) { settings.color = "#004d60"; } $("#bigBox" + BigBoxes).css("background-color", settings.color); $("#divMiniIcons").append("
"); //Click Mini Icon $("#miniIcon" + BigBoxes).bind('click', function () { var FrontBox = $(this).attr('id'); var FrontBigBox = FrontBox.replace("miniIcon", "bigBox"); var FronBigBoxColor = FrontBox.replace("miniIcon", "bigBoxColor"); $(".cajita").each(function (index) { var BackBox = $(this).attr('id'); var BigBoxID = BackBox.replace("miniIcon", "bigBox"); $("#" + BigBoxID).css("z-index", 9998); }); $("#" + FrontBigBox).css("z-index", 9999); $("#" + FronBigBoxColor).removeClass("animated fadeIn").delay(1).queue(function () { $(this).show(); $(this).addClass("animated fadeIn"); $(this).clearQueue(); }); }); var ThisBigBoxCloseCross = $("#botClose" + BigBoxes); var ThisBigBox = $("#bigBox" + BigBoxes); var ThisMiniIcon = $("#miniIcon" + BigBoxes); // Color Functionality var ColorTimeInterval; if (settings.colors != undefined && settings.colors.length > 0) { ThisBigBoxCloseCross.attr("colorcount", "0"); ColorTimeInterval = setInterval(function () { var ColorIndex = ThisBigBoxCloseCross.attr("colorcount"); ThisBigBoxCloseCross.animate({ backgroundColor: settings.colors[ColorIndex].color, }); ThisBigBox.animate({ backgroundColor: settings.colors[ColorIndex].color, }); ThisMiniIcon.animate({ backgroundColor: settings.colors[ColorIndex].color, }); if (ColorIndex < settings.colors.length - 1) { ThisBigBoxCloseCross.attr("colorcount", ((ColorIndex * 1) + 1)); } else { ThisBigBoxCloseCross.attr("colorcount", 0); } }, settings.colortime); } //Close Cross ThisBigBoxCloseCross.bind('click', function () { clearInterval(ColorTimeInterval); if (typeof callback == "function") { if (callback) callback(); } var FrontBox = $(this).attr('id'); var FrontBigBox = FrontBox.replace("botClose", "bigBox"); var miniIcon = FrontBox.replace("botClose", "miniIcon"); $("#" + FrontBigBox).removeClass("fadeIn fast"); $("#" + FrontBigBox).addClass("fadeOut fast").delay(300).queue(function () { $(this).clearQueue(); $(this).remove(); }); $("#" + miniIcon).removeClass("fadeIn fast"); $("#" + miniIcon).addClass("fadeOut fast").delay(300).queue(function () { $(this).clearQueue(); $(this).remove(); }); }); if (settings.timeout != undefined) { var TimedID = BigBoxes; setTimeout(function () { clearInterval(ColorTimeInterval); $("#bigBox" + TimedID).removeClass("fadeIn fast"); $("#bigBox" + TimedID).addClass("fadeOut fast").delay(300).queue(function () { $(this).clearQueue(); $(this).remove(); }); $("#miniIcon" + TimedID).removeClass("fadeIn fast"); $("#miniIcon" + TimedID).addClass("fadeOut fast").delay(300).queue(function () { $(this).clearQueue(); $(this).remove(); }); }, settings.timeout); } } // .BigBox // Small Notification var SmallBoxes = 0, SmallCount = 0, SmallBoxesAnchos = 0; $.smallBox = function (settings, callback) { var BoxSmall, content; settings = $.extend({ title: "", content: "", icon: undefined, iconSmall: undefined, sound: $.sound_on, color: undefined, timeout: undefined, colortime: 1500, colors: undefined }, settings); // SmallBox Sound if (settings.sound === true) { if (isIE8orlower() == 0) { var audioElement = document.createElement('audio'); if (navigator.userAgent.match('Firefox/')) audioElement.setAttribute('src', $.sound_path + 'smallbox.ogg'); else audioElement.setAttribute('src', $.sound_path + 'smallbox.mp3'); //$.get(); audioElement.addEventListener("load", function () { audioElement.play(); }, true); audioElement.pause(); audioElement.play(); } } SmallBoxes = SmallBoxes + 1; BoxSmall = "" var IconSection = "", CurrentIDSmallbox = "smallbox" + SmallBoxes; if (settings.iconSmall == undefined) { IconSection = "
"; } else { IconSection = "
"; } if (settings.icon == undefined) { BoxSmall = "
" + settings.title + "

" + settings.content + "

" + IconSection + "
"; } else { BoxSmall = "
" + settings.title + "

" + settings.content + "

" + IconSection + "
"; } if (SmallBoxes == 1) { $("#divSmallBoxes").append(BoxSmall); SmallBoxesAnchos = $("#smallbox" + SmallBoxes).height() + 40; } else { var SmartExist = $(".SmallBox").size(); if (SmartExist == 0) { $("#divSmallBoxes").append(BoxSmall); SmallBoxesAnchos = $("#smallbox" + SmallBoxes).height() + 40; } else { $("#divSmallBoxes").append(BoxSmall); $("#smallbox" + SmallBoxes).css("top", SmallBoxesAnchos); SmallBoxesAnchos = SmallBoxesAnchos + $("#smallbox" + SmallBoxes).height() + 20; $(".SmallBox").each(function (index) { if (index == 0) { $(this).css("top", 20); heightPrev = $(this).height() + 40; SmallBoxesAnchos = $(this).height() + 40; } else { $(this).css("top", heightPrev); heightPrev = heightPrev + $(this).height() + 20; SmallBoxesAnchos = SmallBoxesAnchos + $(this).height() + 20; } }); } } var ThisSmallBox = $("#smallbox" + SmallBoxes); // IE fix // if($.browser.msie) { // // alert($("#"+CurrentIDSmallbox).css("height")); // } if (settings.color == undefined) { ThisSmallBox.css("background-color", "#004d60"); } else { ThisSmallBox.css("background-color", settings.color); } var ColorTimeInterval; if (settings.colors != undefined && settings.colors.length > 0) { ThisSmallBox.attr("colorcount", "0"); ColorTimeInterval = setInterval(function () { var ColorIndex = ThisSmallBox.attr("colorcount"); ThisSmallBox.animate({ backgroundColor: settings.colors[ColorIndex].color, }); if (ColorIndex < settings.colors.length - 1) { ThisSmallBox.attr("colorcount", ((ColorIndex * 1) + 1)); } else { ThisSmallBox.attr("colorcount", 0); } }, settings.colortime); } if (settings.timeout != undefined) { setTimeout(function () { clearInterval(ColorTimeInterval); var ThisHeight = $(this).height() + 20; var ID = CurrentIDSmallbox; var ThisTop = $("#" + CurrentIDSmallbox).css('top'); // SmallBoxesAnchos = SmallBoxesAnchos - ThisHeight; // $("#"+CurrentIDSmallbox).remove(); if ($("#" + CurrentIDSmallbox + ":hover").length != 0) { //Mouse Over the element $("#" + CurrentIDSmallbox).on("mouseleave", function () { SmallBoxesAnchos = SmallBoxesAnchos - ThisHeight; $("#" + CurrentIDSmallbox).remove(); if (typeof callback == "function") { if (callback) callback(); } var Primero = 1; var heightPrev = 0; $(".SmallBox").each(function (index) { if (index == 0) { $(this).animate({ top: 20 }, 300); heightPrev = $(this).height() + 40; SmallBoxesAnchos = $(this).height() + 40; } else { $(this).animate({ top: heightPrev }, 350); heightPrev = heightPrev + $(this).height() + 20; SmallBoxesAnchos = SmallBoxesAnchos + $(this).height() + 20; } }); }); } else { clearInterval(ColorTimeInterval); SmallBoxesAnchos = SmallBoxesAnchos - ThisHeight; if (typeof callback == "function") { if (callback) callback(); } $("#" + CurrentIDSmallbox).removeClass().addClass("SmallBox").animate({ opacity: 0 }, 300, function () { $(this).remove(); var Primero = 1; var heightPrev = 0; $(".SmallBox").each(function (index) { if (index == 0) { $(this).animate({ top: 20 }, 300); heightPrev = $(this).height() + 40; SmallBoxesAnchos = $(this).height() + 40; } else { $(this).animate({ top: heightPrev }); heightPrev = heightPrev + $(this).height() + 20; SmallBoxesAnchos = SmallBoxesAnchos + $(this).height() + 20; } }); }) } }, settings.timeout); } // Click Closing $("#smallbox" + SmallBoxes).bind('click', function () { clearInterval(ColorTimeInterval); if (typeof callback == "function") { if (callback) callback(); } var ThisHeight = $(this).height() + 20; var ID = $(this).attr('id'); var ThisTop = $(this).css('top'); SmallBoxesAnchos = SmallBoxesAnchos - ThisHeight; $(this).removeClass().addClass("SmallBox").animate({ opacity: 0 }, 300, function () { $(this).remove(); var Primero = 1; var heightPrev = 0; $(".SmallBox").each(function (index) { if (index == 0) { $(this).animate({ top: 20, }, 300); heightPrev = $(this).height() + 40; SmallBoxesAnchos = $(this).height() + 40; } else { $(this).animate({ top: heightPrev }, 350); heightPrev = heightPrev + $(this).height() + 20; SmallBoxesAnchos = SmallBoxesAnchos + $(this).height() + 20; } }); }) }); } // .Small Notification // Sounds function getInternetExplorerVersion() { var rv = -1; // Return value assumes failure. if (navigator.appName == 'Microsoft Internet Explorer') { var ua = navigator.userAgent; var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})"); if (re.exec(ua) != null) rv = parseFloat(RegExp.$1); } return rv; } function checkVersion() { var msg = "You're not using Windows Internet Explorer."; var ver = getInternetExplorerVersion(); if (ver > -1) { if (ver >= 8.0) msg = "You're using a recent copy of Windows Internet Explorer." else msg = "You should upgrade your copy of Windows Internet Explorer."; } alert(msg); } function isIE8orlower() { var msg = "0"; var ver = getInternetExplorerVersion(); if (ver > -1) { if (ver >= 9.0) msg = 0 else msg = 1; } return msg; // alert(msg); }; var CE21Forum = { "hubName": "forumHub", "groupKey": function (forumSetttingId, parentEventTimeid) { if (parentEventTimeid && parentEventTimeid > 0) { return "forumProduct-" + padLeft(parentEventTimeid, 6); } else { return "forum-" + padLeft(forumSetttingId, 6); } }, "connectGroup": function (forumSetttingId, parentEventTimeid) { if ($.connection.hub.state != $.signalR.connectionState.connected) return; if (CE21SignalR.getHub(this.hubName) && forumSetttingId) { CE21SignalR.getHub(this.hubName).connectGroup(this.groupKey(forumSetttingId, parentEventTimeid)); } }, "connectAll": function () { if ($.connection.hub.state != $.signalR.connectionState.connected) return; $('.ForumWidgetMain').each(function () { var forumSettingId = $(this).attr('data-forumSettingId'); var parentEventTimeid = $(this).attr('data-mainparenteventtimeid'); if (forumSettingId) { CE21Forum.connectGroup(forumSettingId, parentEventTimeid); } }); }, "bindListner": function () { var self = this; CE21SignalR.on(this.hubName, "receiveAction", function (Jdict) { if (Jdict) { var value = JSON.parse(Jdict); var data = value.Data; self.triggerActions(value.Action, data); } }); }, "sendAction": function (forumSetttingId, data) { if (CE21SignalR.getHub(this.hubName) && forumSetttingId) { CE21SignalR.getHub(this.hubName).sendAction(this.groupKey(forumSetttingId, data.Data.parentEventTimeid), JSON.stringify(data)); } }, "sendCustomerProfile": function (data) { if (CE21SignalR.isConnected() && CE21SignalR.getHub(this.hubName)) { $('.ForumWidgetMain').each(function () { var forumSettingId = $(this).attr('data-forumSettingId'); var parentEventTimeid = $(this).attr('data-mainparenteventtimeid'); if (forumSettingId) { data.Data.forumSettingId = forumSettingId; data.Data.parentEventTimeid = parentEventTimeid; CE21Forum.sendAction(forumSettingId, data); } }); } }, "triggerActions": function (action, data) { switch (action) { case "newforum": getNewProductForums(data.forumSettingId, data.productForumId, data.parentEventTimeid); break; case "deleteforumData": deleteProductForums(data.productForumId, data.parentProductForumId, data.forumSettingId); break; case "changeProfile": replaceParticipantProfile(data.customerId, data.seoFilename); break; case "changeUserName": changeForumProfileName(data.customerId, data.userName); break; default: break; } }, "sendCustomerName": function (data) { if (CE21SignalR.isConnected() && CE21SignalR.getHub(this.hubName)) { $('.ForumWidgetMain').each(function () { var forumSettingId = $(this).attr('data-forumSettingId'); var parentEventTimeid = $(this).attr('data-mainparenteventtimeid'); if (forumSettingId) { data.Data.forumSettingId = forumSettingId; data.Data.parentEventTimeid = parentEventTimeid; CE21Forum.sendAction(forumSettingId, data); } }); } }, }; ; Util = (function () { if (typeof Util != 'undefined') return Util; var utilObj = new function () { var self = this; self.ConvertToUtc = function (d) { var hour = 7 - ((new Date().getTimezoneOffset()) / 60); //hardcoded 7 to mark as pacific var date = new Date(d); var modifiedDate = date.getTime(); modifiedDate += (hour * 60 * 60 * 1000); date.setTime(modifiedDate); return date; }; self.ConvertToUserTimeZone = function (d) { var a = d.split(' '); var b = a[0].split('-'); var c = a[1].split(':'); var hour = 7 - ((new Date().getTimezoneOffset()) / 60); var date = new Date(b[0], b[1] - 1, b[2], c[0], c[1], c[2]) var modifiedDate = date.getTime(); modifiedDate += (-1 * hour * 60 * 60 * 1000); date.setTime(modifiedDate); return date; }; self.stringToHex = function (str) { var hex = ''; for (var i = 0; i < str.length; i++) { hex += '' + str.charCodeAt(i).toString(16); } return hex; }; self.padZero = function (num, size) { var paddedstring = '00000000000000000000000000' + num; return paddedstring.substr(paddedstring.length - size); }; self.ConvertTo24HourTime = function (inputDate) { var h = inputDate.getHours(); var m = inputDate.getMinutes(); if (h < 10) h = '0' + h; if (m < 10) m = '0' + m; return h + ':' + m; }; self.Inherit = function () { for (var i = 1; i < arguments.length; i++) { } }; self.GetQueryStringParam = function (paramName) { var pairs = location.search.slice(1).split('&'); var result = {}; for (var idx = 0; idx < pairs.length; idx++) { var pair = pairs[idx].split('='); if (!!pair[0]) result[pair[0]] = decodeURIComponent(pair[1] || ''); } if (paramName != null) result = result[paramName]; return result; }; self.ConvertLocalToUTC = function (d) { var localTimeZoneOffesetInMillseconds = d.getTimezoneOffset() * 60 * 1000, localDateTimeInMilliseconds = Date.UTC(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours(), d.getMinutes(), d.getSeconds(), d.getMilliseconds()), localUTCDateTimeInMilliseconds = localDateTimeInMilliseconds + localTimeZoneOffesetInMillseconds * 2; //localDateTime = d.getTime(), d.setTime(localUTCDateTimeInMilliseconds); return d; }; self.ConvertUTCToLocal = function (d) { var localTimeZoneOffesetInMillseconds = d.getTimezoneOffset() * 60 * 1000, localDateTime = d.getTime(), localDateTimeInMilliseconds = localDateTime - localTimeZoneOffesetInMillseconds; d.setTime(localDateTimeInMilliseconds); return d; }; self.getCurrentDateTime = function () { return self.getDateTimeString(new Date()); }; self.getDateTimeString = function (d) { if (!d) return ""; var dateString = self.getDateString(d, "{YYYY}-{MM}-{DD}"); var timeString = self.getTimeString(d); return dateString + " " + timeString; }; self.getDateString = function (d, formatStr) { if (!d) return ""; var year = d.getFullYear(); var month = self.getZeroPaddedString((d.getMonth() + 1), 2); var date = self.getZeroPaddedString(d.getDate(), 2); //var dateString = year + "-" + month + "-" + date; var dateString = self.format(formatStr, { YYYY: year, MM: month, DD: date, YY: (year % 100) }); return dateString; }; self.getTimeString = function (d) { if (!d) return ""; var hour = self.getZeroPaddedString(d.getHours(), 2); var minutes = self.getZeroPaddedString(d.getMinutes(), 2); var seconds = self.getZeroPaddedString(d.getSeconds(), 2); var timeString = hour + ":" + minutes + ":" + seconds; return timeString; }; self.getDaysCount = function (dt) { var currentDT = new Date(), delta, days, hours, minutes, srcDt; if (!dt) { return self.getDateTimeString(); } else { srcDt = dt; dt = self.ConvertUTCToLocal(new Date(dt));//new Date(dt); if (dt == 'Invalid Date') { return srcDt }; } // get total seconds between the times delta = Math.abs(currentDT - dt) / 1000; // calculate (and subtract) whole days days = Math.floor(delta / 86400); delta -= days * 86400; // calculate (and subtract) whole hours hours = Math.floor(delta / 3600) % 24; delta -= hours * 3600; // calculate (and subtract) whole minutes minutes = Math.floor(delta / 60) % 60; delta -= minutes * 60; return days + " Days " + hours + " Hours " + minutes + " Minutes"; }; self.getMinsAndSecFromSec = function (sec) { if (sec) { var m = 0, s = 0; if (sec >= 60) { m = Math.floor(sec / 60); s = sec - (m * 60); } else { s = sec; } return { minutes: m, seconds: s }; } return null; }; self.getZeroPaddedString = function (num, padToLength) { num = num.toString(); var zerosToPad = (padToLength - num.length); for (var i = 0; i < zerosToPad; i++) num = '0' + num; return num; }; self.makeNativeArray = function (arrObj) { if (null == arrObj || arrObj.length == null) return null; var arr = []; for (var i = 0; i < arrObj.length; i++) { arr.push(arrObj[i]) }; return arr; }; self.getErrorObj = function (error) { return { message: error.message, name: error.name, fileName: error.fileName, lineNumber: error.lineNumber, columnNumber: error.columnNumber, description: error.description, number: error.number, stack: error.stack }; }; self.getPropertyByString = function (o, s) { s = s.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties s = s.replace(/^\./, ''); // strip a leading dot var a = s.split('.'); while (a.length) { var n = a.shift(); if (o && n in o) { if (o[n] && (typeof o[n]) == 'function') o = o[n](); else o = o[n]; } else if (o instanceof Array && isNaN(parseInt(n))) { var temp = []; for (var i = 0; i < o.length; i++) { if (o[i][n]) temp.push(o[i][n]); } if (temp.length > 0) o = temp else return; } else { return; } } return o; } self.getCurrentDateForService = function () { var d = new Date(); var year = d.getFullYear(); var month = self.getZeroPaddedString((d.getMonth() + 1), 2); var date = self.getZeroPaddedString(d.getDate(), 2); var dateString = month + "/" + date + "/" + year; return dateString; }; self.sortFunction = function (field, dir) { var sortFuncStr = 'function (item1, item2) {'; sortFuncStr += 'var returnVal = 0, sortItem1, sortItem2;'; if (dir == 'desc') { sortFuncStr += 'sortItem1 = item1.' + field + ';'; sortFuncStr += 'sortItem2 = item2.' + field + ';'; } else if (dir == 'asc') { sortFuncStr += 'sortItem1 = item2.' + field + ';'; sortFuncStr += 'sortItem2 = item1.' + field + ';'; } sortFuncStr += 'return (sortItem2 > sortItem1 ? 1 : (sortItem2 < sortItem1 ? -1 : 0)); // to handle both string and integer.'; sortFuncStr += '}'; return GetFunction(sortFuncStr); }; function GetFunction(funcStr) { //Get the name of the argument. We know there is a single argument //in the worker function, between the first '(' and the first ')'. var argName = funcStr.substring(funcStr.indexOf("(") + 1, funcStr.indexOf(")")); //Now get the function body - between the first '{' and the last '}'. funcStr = funcStr.substring(funcStr.indexOf("{") + 1, funcStr.lastIndexOf("}")); //Construct the new Function return new Function(argName, funcStr); }; self.NumericOnly = function (event) { var key = window.event ? event.keyCode : event.which; if (event.keyCode == 8 || event.keyCode == 37 || event.keyCode == 39) { return true; } else if (key < 48 || key > 57) { return false; } else return true; }; self.isSessionStorageSupported = function () { try { return window.sessionStorage && typeof (window.sessionStorage) != undefined; } catch (e) { return false; } } self.isLocalStorageSupported = function () { try { return window.localStorage && typeof (window.localStorage) != undefined; } catch (e) { return false; } } self.stripHtml = function(html) { try { // Create a new div element var temporalDivElement = document.createElement("div"); // Set the HTML content with the providen temporalDivElement.innerHTML = html; // Retrieve the text property of the element (cross-browser support) return temporalDivElement.textContent || temporalDivElement.innerText || ""; } catch (e) { return html } } self.hexToRGB = function(h) { let r = 0, g = 0, b = 0; // 3 digits if (h.length == 4) { r = "0x" + h[1] + h[1]; g = "0x" + h[2] + h[2]; b = "0x" + h[3] + h[3]; // 6 digits } else if (h.length == 7) { r = "0x" + h[1] + h[2]; g = "0x" + h[3] + h[4]; b = "0x" + h[5] + h[6]; } return "rgb(" + +r + ", " + +g + ", " + +b + ")"; } if (Object.freeze) Object.freeze(self); }; return utilObj; })(); if (Array.prototype.diff == undefined) { Array.prototype.diff = function (a) { return this.filter(function (i) { return a.indexOf(i) < 0; }); } } if (Array.prototype.unique == undefined) { Array.prototype.unique = function (b) { var a = this.concat(b); for (var i = 0; i < a.length; ++i) { for (var j = i + 1; j < a.length; ++j) { if (a[i] === a[j]) a.splice(j--, 1); } } return a; } } if (Number.prototype.between == undefined) { Number.prototype.between = function (a, b) { var min = Math.min.apply(Math, [a, b]), max = Math.max.apply(Math, [a, b]); return this >= min && this <= max; }; } //helper ; (function () { Helper = new function () { //self reference var self = this; //private field //public field //subscriptions //private methods //none //public methods }; })(); //common helper ; (function () { Helper.Common = new function () { //self reference var self = this; //private field //public field //subscriptions //private methods //none //public methods self.HtmlEncode = function (value) { return $('
').text(value).html(); }; self.HtmlDecode = function (value) { return $('
').html(value).text(); }; self.UrlEncode = function (url) { return encodeURIComponent(url); }; self.UrlDecode = function (url) { return decodeURIComponent(url); }; self.QueryParamFromUri = function (url, name) { var startindex = url.indexOf('?'); var endindex = url.length; url = url.substring(startindex, endindex); name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]"); var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"), results = regex.exec(url); return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " ")); }; self.HashParamFromUri = function (url, index) { var result = null; var urlArray = url.split('#'); if (urlArray.length > index) return urlArray[index]; else return null; }; self.Linkify = function (content, _target) { return content.replace(/(https?:\/\/[^\s]+)(\.?\b)/gi, '$1$2'); }; self.ReplaceAll = function (str, o, n) { if (str) { var strLength = str.length; for (var i = 0; i < strLength; i++) { if (str.indexOf(o) !== -1) { str = str.replace(o, n); } else { i = strLength; } } } return str; }; self.GetUserTimeZone = function () { return /\((.*)\)/.exec(new Date().toString())[1]; }; self.IsDayLightSaving = function () { return (new Date()).getTimezoneOffset() < Math.max((new Date((new Date()).getFullYear(), 0, 1)).getTimezoneOffset(), (new Date((new Date()).getFullYear(), 6, 1)).getTimezoneOffset()); }; self.GetUserTimeZoneOffset = function () { return (new Date()).getTimezoneOffset(); }; self.FormatToISOAndGetLocaDateTime = function (d) { if (!d) return new Date(new Date().toISOString()); return new Date(new Date(d).toISOString()) }; self.CreateCookie = function (name, value, days) { if (days) { 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=/"; }; self.ReadCookie = function (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; }; self.EraseCookie = function (name) { self.CreateCookie(name, "", -1); }; self.GenerateKey = function (length, characterSet) { characterSet = characterSet || 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+='; var key = ''; for (var i = 0; i < length; i++) { var randomPoz = Math.floor(Math.random() * characterSet.length); key += characterSet.substring(randomPoz, randomPoz + 1); } return key; }; self.JSON2XML = function (o, tab) { var toXml = function (v, name, ind) { var xml = ""; if (v instanceof Array) { for (var i = 0, n = v.length; i < n; i++) xml += ind + toXml(v[i], name, ind + "\t") + "\n"; } else if (typeof (v) == "object") { var hasChild = false; xml += ind + "<" + name; for (var m in v) { if (m.charAt(0) == "@") xml += " " + m.substr(1) + "=\"" + v[m].toString() + "\""; else hasChild = true; } xml += hasChild ? ">" : "/>"; if (hasChild) { for (var m in v) { if (m == "#text") xml += v[m]; else if (m == "#cdata") xml += ""; else if (m.charAt(0) != "@") xml += toXml(v[m], m, ind + "\t"); } xml += (xml.charAt(xml.length - 1) == "\n" ? ind : "") + ""; } } else { xml += ind + "<" + name + ">" + v.toString() + ""; } return xml; }, xml = ""; for (var m in o) xml += toXml(o[m], m, ""); return tab ? xml.replace(/\t/g, tab) : xml.replace(/\t|\n/g, ""); }; self.copyToClipBoard = function (text, element) { if (!text) return; var textArea = document.createElement("textarea"); // Place in top-left corner of screen regardless of scroll position. textArea.style.position = 'fixed'; textArea.style.top = 0; textArea.style.left = 0; // Ensure it has a small width and height. Setting to 1px / 1em // doesn't work as this gives a negative w/h on some browsers. textArea.style.width = '1em'; textArea.style.height = '1em'; // We don't need padding, reducing the size if it does flash render. textArea.style.padding = 0; // Clean up any borders. textArea.style.border = 'none'; textArea.style.outline = 'none'; textArea.style.boxShadow = 'none'; // Avoid flash of white box if rendered for any reason. textArea.style.background = 'transparent'; textArea.value = text; document.body.appendChild(textArea); textArea.select(); try { var successful = document.execCommand('copy'); if (successful) { if (typeof (element) !== "undefined" && element) { setTooltip('Copied!', element); hideTooltip(element); } } } catch (err) { if (typeof (element) !== "undefined" && element) { setTooltip('Failed!', element); hideTooltip(element); } } document.body.removeChild(textArea); } function setTooltip(message, element) { $(element).tooltip('hide') .attr('data-original-title', message) .tooltip('show'); } function hideTooltip(element) { setTimeout(function () { $(element).attr('data-original-title', '').tooltip("destroy"); }, 1000); } }; })(); //logger helper ; (function () { Helper.VIDEOJS = new function () { //self reference var self = this; self.CLOSED_CAPTIONS_TEXT = "Closed Captions / Subtitles"; //public methods self.removeAllRemoteTextTrack = function (player) { if (!player) return; var xtracks = player.remoteTextTracks(), breakTrackLoop = false; while (xtracks && xtracks.length > 0 && !breakTrackLoop) { try { player.removeRemoteTextTrack(xtracks[0]); } catch (e) { console.log('Exception when remove text track', e); breakTrackLoop = true; } } }; //public methods self.prepareMediaURL = function (source) { if (!source) return ""; return source.replace("http://", "https://"); }; self.getType = function (source) { var t = "video/mp4"; if (source && source.indexOf("m3u8") > -1) t = "application/x-mpegurl"; if (source && source.indexOf(".mp3") > -1) t = "audio/mpeg"; if (source && source.indexOf(".m4a") > -1) t = null; return t; }; self.compareVideoSources = function (source, compareSource) { return self.prepareMediaURL(compareSource) == self.prepareMediaURL(source); }; self.addRemoteTextTrack = function (player, track) { if (!player || !track) return; player.addRemoteTextTrack(track); }; self.getCurrentState = function (player) { if (player) { if (!player.paused()) return "PLAYING"; if (player.paused()) return "PAUSED"; if (player.seeking() && player.bufferedPercent() > 0) return "BUFFERING"; if (player.readyState() > 1) return "IDLE"; } return undefined; }; self.saveVidPlayerSettings = function (player) { if (!player) return; var vidPlayerSettings = { volume: player.volume(), muted: player.muted() }; try { if (Util.isSessionStorageSupported()) { sessionStorage.setItem('vidPlayerSettings', JSON.stringify(vidPlayerSettings)); } else { window.sessionStorage = { 'vidPlayerSettings': vidPlayerSettings }; } } catch (e) { } } self.setVidPlayerSettings = function (player) { if (!player) return; var vidPlayerSettings = {}; if (Util.isSessionStorageSupported()) { vidPlayerSettings = JSON.parse(sessionStorage.getItem('vidPlayerSettings')) || { volume: 1.0, muted: false }; } else { try { vidPlayerSettings = window.sessionStorage.vidPlayerSettings || { }; } catch (e) { } } player.volume(vidPlayerSettings.volume || 1.0); player.muted(vidPlayerSettings.muted || false); } self.disposePlayer = function (player) { if (!player) return; try { if (player.player_) { player.dispose(); } else { player.reset(); } } catch (e) { } } /*showing - the text track is visible and updating and firing events disabled - the track track isn't visible and isn't firing events hidden - the track track isn't visible but it is firing events.*/ self.saveCCSettings = function (player) { if (!player) return; try { if (!Helper.Viewer.isUnauthenticatedUser() && this.hasRemoteTextTrack(player) && Util.isLocalStorageSupported()) { var ccSettings; if (player.cache_ && player.cache_.selectedLanguage) { var settings = player.cache_.selectedLanguage; ccSettings = { language: settings.language || 'en', mode: settings.enabled ? 'showing' : 'disabled' } } else { var activeTrack = this.getActiveRemoteTextTrack(player) || { language: 'en', mode: 'disabled' }; ccSettings = { language: activeTrack.language, mode: activeTrack.mode } } localStorage.setItem(this.getCCLocalStorageKey(), JSON.stringify(ccSettings)); } } catch (e) { } } self.getCCSettings = function (player) { if (!player) return; var defaultCCSettings = { language: 'en', mode: 'disabled' } try { if (Util.isLocalStorageSupported()) { return JSON.parse(localStorage.getItem(this.getCCLocalStorageKey())) || defaultCCSettings; } } catch (e) { return defaultCCSettings; } } self.hasRemoteTextTrack = function (player) { if (!player || player.remoteTextTracks().length == 0 || !player.remoteTextTracks()[0].src) return false; var src = player.remoteTextTracks()[0].src || ''; return src !== ''; } self.getActiveRemoteTextTrack = function (player) { if (!player || !this.hasRemoteTextTrack(player)) return null; for (var i = 0; i < player.remoteTextTracks().length; i++) { var track = player.remoteTextTracks()[i]; if (track && track.mode == "showing") return track; } return null; } self.setActiveRemoteTextTrack = function (player, ccSettings) { if (!player || !this.hasRemoteTextTrack(player)) return; if (!ccSettings) ccSettings = this.getCCSettings(player); for (var i = 0; i < player.remoteTextTracks().length; i++) { var track = player.remoteTextTracks()[i]; if (track && track.language == ccSettings.language) { track.mode = ccSettings.mode; return; } } if (player.remoteTextTracks()[0]) player.remoteTextTracks()[0].mode = ccSettings.mode; } self.getCCLocalStorageKey = function () { return 'CCSettings-' + Helper.Viewer.getCustomerId(); } }; })(); //interval helper ; (function () { Helper.Interval = new function () { //self reference var self = this; self.keys = {}; //public methods self.set = function (key, func, seconds) { if (!seconds) seconds = 0; if (self.keys[key]) clearInterval(self.keys[key]); self.keys[key] = setInterval(func, seconds * 1000); }; //public methods self.clear = function (key) { if (self.keys[key]) clearInterval(self.keys[key]); }; }; Helper.TimeOut = new function () { //self reference var self = this; self.keys = {}; //public methods self.set = function (key, func, seconds) { if (!seconds) seconds = 0; if (self.keys[key]) clearTimeout(self.keys[key]); self.keys[key] = setTimeout(func, seconds * 1000); }; //public methods self.clear = function (key) { if (self.keys[key]) clearTimeout(self.keys[key]); }; }; })(); //VTT helper ; (function () { Helper.WebVTT = new function () { //self reference var self = this; self.doCaptions = function (caption, callback) { if (typeof (WebVTT) !== "function") return; var cues = []; var regions = []; var parser = new window.WebVTT.Parser(window, window.vttjs, window.WebVTT.StringDecoder()); //var parser = new WebVTT.Parser(window, WebVTT.StringDecoder()); parser.oncue = function (cue) { cues.push(cue); }; parser.onregion = function (region) { regions.push(region); } parser.onparsingerror = function (error) { console.log(error); } parser.parse(caption); parser.flush(); if (callback) { callback(cues); } }; self.getCaptions = function (captionURL, callback) { $.get(captionURL, function (res) { self.doCaptions(res, callback); }); }; }; })(); //Viewer helper ; (function () { Helper.Viewer = new function () { //self reference var self = this; self.getCustomerId = function () { return typeof (u) === 'string' ? Number(u) : 0; }; self.isUnauthenticatedUser = function () { return this.getCustomerId() <= 0; } }; })(); //Timer helper ; (function () { Helper.Timer = new function () { //self reference var self = this; if (typeof (timeInfo) !== "undefined" && timeInfo) self.offset = timeInfo.local - (timeInfo.server == "Invalid Date" ? timeInfo.serverNew : timeInfo.server); else self.offset = 0; self.curServerTime = function () { return new Date(new Date().getTime() - self.offset); }; self.diff = function (val1) { return (val1 - self.curServerTime()) / 1000; }; self.readableDiff = function (val1) { return self.toDDHHMM(self.diff(val1)); }; self.getDiffInObject = function (val1) { var sec_num = parseInt(self.diff(val1), 10), // don't forget the second param hours = Math.floor(sec_num / 3600), days = Math.floor(hours / 24), minutes = Math.floor((sec_num - (hours * 3600)) / 60), seconds = sec_num - (hours * 3600) - (minutes * 60); if (days > 0) { hours -= (days * 24); } return { "seconds": seconds, "minutes": minutes, "hours": hours, "days": days } }; self.toTwoDigit = function (value) { if (value.toString().length === 1) { value = "0" + value; } return value; }; self.toDDHHMM = function (val1) { var sec_num = parseInt(val1, 10), // don't forget the second param hours = Math.floor(sec_num / 3600), days = Math.floor(hours / 24), minutes = Math.floor((sec_num - (hours * 3600)) / 60), seconds = sec_num - (hours * 3600) - (minutes * 60); var time = ''; if (days > 0) { hours = Math.floor(hours - (days * 24)), //time = days + ' day(s) ' + hours + ' hr '; time = days + ' day(s) '; if (hours > 0) { time += hours + ' hr '} } else { time = hours + ' hr ' + minutes + ' min ' + seconds + ' secs'; } return time; }; }; })();; var AttendanceConfirmation = function (seminar) { var self = this; self.seminar = seminar; self.interval = null; self.attendanceRequirements = self.seminar.AttendanceRequirements || []; self.currentAttendance = null; self.isPauseVideo = !(self.seminar.IsPauseVideo || false); // IsPauseVideo means "Do not pause video when popups display" self.attendanceContainer = $('#AttendanceConfirmationPopup'); self.IsBrowserFocus = true; self.IsBrowserFocusOnAttendenceShow = true; self.popupTimer = 0; self.popupTimerInterval = null; self.anyActivePopup = false; self.anyActiveDelayPopup = false; //@Method: Initialize attendance requirments and set inteval self.init = function () { self.currentAttendance = null; if (self.interval) { clearInterval(self.interval); } if (!self.attendanceRequirements || self.attendanceRequirements.length == 0) { return; } //Apply sort for attendance requirments based on relative time self.attendanceRequirements = self.attendanceRequirements.sort(function (a, b) { return a.RelativeTime - b.RelativeTime }); self.interval = setInterval(self.checkAttendance, 1 * 1000); self.checkPopupFailedAttendance(); }; //@Method: Check the attendance requirments every 1 sec and open popup if matched self.checkAttendance = function () { if (!self.attendanceRequirements || self.attendanceRequirements.length == 0) { return; } var relativeTime = Math.round(curRelativeTime / 1000); // Set active popup as false current attendance time is still up after 8 min; if (self.anyActivePopup == true && self.anyActiveDelayPopup == false && self.currentAttendance && (relativeTime - self.currentAttendance.RelativeTime) >= 480) { self.anyActivePopup = false; } jQuery.each(self.attendanceRequirements, function (idx, a) { if (self.currentAttendance != a && a.Status == 0 && !a.IsComplete && self.anyActivePopup == false && relativeTime.between(a.RelativeTime, a.RelativeTime + 10)) { console.log('relativeTime', relativeTime); console.log('a.relativeTime', a.RelativeTime); if (self.seminar.TotalMissedCount > self.seminar.AllowedMissedCount) { self.showPopUpAfterAttendaceFailed(); } else { self.currentAttendance = a; self.showAttendanceConfirmationPopup(); } } }); //Process attendance requirment if missed somehow - It will process after 5 minute if (self.seminar.AllowedMissedCount >= self.seminar.TotalMissedCount && !self.currentAttendance && self.anyActivePopup == false && $.magnificPopup && $.magnificPopup.instance && !$.magnificPopup.instance.isOpen) { var pendingAttendance = $.grep(self.attendanceRequirements, function (a) { return self.currentAttendance != a && a.Status == 0 && !a.IsComplete && (a.RelativeTime + 300) < relativeTime; })[0]; if (pendingAttendance) { console.log('Executed Missed Attendance'); console.log(pendingAttendance); self.currentAttendance = pendingAttendance; self.anyActiveDelayPopup = true; self.showAttendanceConfirmationPopup(); } } }; // check any popup missed and not restrat the segment or seminar. Display FailedPopup dialog //#11407: Manager > Attendance Confirmation Additional Tweaks Needed self.checkPopupFailedAttendance = function() { if (!self.attendanceRequirements || self.attendanceRequirements.length == 0) { return; } if (self.seminar.TotalMissedCount > self.seminar.AllowedMissedCount && (self.checkAllowAttempt() || self.checkShowLimitPopUp())) { //check curRelativeTime exist or not if (!curRelativeTime) { setTimeout(function () { self.checkPopupFailedAttendance(); }, 5 * 1000); return; } var misedAttendances = $.grep(self.attendanceRequirements, function (a) { return a.Status == 1 && a.IsComplete; //&& (a.RelativeTime) < relativeTime + 80 }); if (!misedAttendances) return; var lastMissedAttendance = misedAttendances.sort(function (a, b) { return b.RelativeTime - a.RelativeTime; })[0]; if (lastMissedAttendance && self.checkAllowAttempt()) { self.currentAttendance = lastMissedAttendance; self.displayAttemptPopup(); } else if (self.checkShowLimitPopUp()) {// 11407 Manager > Attendance Confirmation Additional Tweaks Needed - Show Popup for Continue without credits on viewer startup. //Get the list if Continue without credits buttons was pressed or not. var isResumeWithoutCreditDone = $.grep(self.attendanceRequirements, function (a) { return a.RestartButtonType == 3 && a.IsComplete; }); if (isResumeWithoutCreditDone.length == 0) { self.currentAttendance = lastMissedAttendance; self.limitExceededPopup(); } } } }; //@Method: display attendance confirmation popup self.showAttendanceConfirmationPopup = function () { if (!self.currentAttendance) { return null; } $.magnificPopup.close(); self.anyActivePopup = true; $(".PopUp-Attendance-TimeOut").html('Confirm Attendance'); //If Question popup if (self.currentAttendance.PopupType == 2) { $('.questionPopUp').show(); $('.simplePopUp').hide(); //Set QuestionName in label $('.qustionLabel').html(self.currentAttendance.QuestionName); $('#QuestionAnswer').attr("required", "required"); } else { //Simple pop up $('.questionPopUp').hide(); $('.simplePopUp').show(); } if (vidPlayer && self.isPauseVideo) { vidPlayer.pause(); } if (vidPlayer && vidPlayer.isFullscreen()) { vidPlayer.exitFullscreen(); } self.IsBrowserFocusOnAttendenceShow = self.IsBrowserFocus; //Open magnific popup self.openMagnificPopup({ items: { src: '#attendancePopup' }, callbacks: { afterClose: self.markAsMissedPopup, open: self.setPopupTimer //Init Poup timer } }); }; //@Method: set the popup timer self.setPopupTimer = function () { self.clearPopupTimer(); if (self.currentAttendance.PopupDisplayTime > 0) { var popTimeOut = self.getPopUpDisplayMinute(self.currentAttendance.PopupDisplayTime); self.popupTimerInterval = setInterval(function () { //Close the popup and mark as missed if (self.currentAttendance != null && self.popupTimer >= self.currentAttendance.PopupDisplayTime) { //Close pop up $.magnificPopup.close(); clearInterval(self.popupTimerInterval); } if (!$('#QuestionAnswer').hasClass('focused')) { self.popupTimer += 1; //Start :This Part is for display timer in button text Mantis task:#7292 var timeoutButtonClass = ".PopUp-Attendance-TimeOut"; var part = popTimeOut.toString().split('.'); if (part.length == 2 && part[1] == '00') { popTimeOut = popTimeOut - 0.40; } popTimeOut = Number(popTimeOut - 0.01).toFixed(2); $(timeoutButtonClass).html('Confirm Attendance ' + popTimeOut.replace(".", ":")); if (popTimeOut == 0.00) { $(timeoutButtonClass).html('Confirm Attendance'); } } }, 1000); } } //@Method: Clear popup interval and reset timer self.clearPopupTimer = function () { self.popupTimer = 0; if (self.popupTimerInterval) { clearInterval(self.popupTimerInterval); } } self.getPopUpDisplayMinute = function (seconds) { var s = seconds % 60; s = s < 10 ? "0" + s : s; var m = Math.floor(seconds / 60) % 60; m = m < 10 ? "0" + m : m; var h = Math.floor(seconds / 60 / 60); var time = m + "." + s return time; } self.submitAttendancePopup = function () { var isValid = $(this).valid(); var browserstatus = "OutFoucus"; if (self.IsBrowserFocusOnAttendenceShow != self.IsBrowserFocus) { browserstatus = "PartiallyInFocus" } else if (self.IsBrowserFocus == true) { browserstatus = "InFocus"; } if (isValid) { $('#frmattendancePopup').find('button[type="submit"]').prop('disabled', true); $.ajax({ type: 'POST', url: '/ShowTimeWidget/SaveAttendance', data: { 'status': 2, 'registrantAttendanceId': self.currentAttendance.RegistrantAttendanceId, 'currentAttempt': self.seminar.CurrentAttempt, 'programRegistrantId': ProgramRegistrantId, 'browserStatus': browserstatus }, success: function (missedPopupCount) { self.currentAttendance.Status = 2; self.resetAttendanceRequirement(); RefreshCertificate(); if (missedPopupCount) { self.seminar.TotalMissedCount = missedPopupCount; } }, error: function (jqXHR, textStatus, errorThrown) { self.resetAttendanceRequirement(); RefreshCertificate(); } }); } return false; } $('#frmattendancePopup').submit(self.submitAttendancePopup); //@Method: Reset Popup value and close popup self.resetAttendanceRequirement = function () { self.anyActivePopup = false; self.anyActiveDelayPopup = false; $.magnificPopup.close(); if (self.currentAttendance) { if (self.currentAttendance.Status != 0) { self.currentAttendance.IsComplete = true; } self.currentAttendance = null; } if (vidPlayer) { vidPlayer.play(); } $('#frmattendancePopup').find('button[type="submit"]').prop('disabled', false); $('#frmattendancePopup').find('input[type="text"]').val(''); $('#frmattendancePopup').find('input[type="text"]').closest('.form-group').removeClass('has-error'); } //@Method: Handle for missed popup self.markAsMissedPopup = function () { var fnCallback = function () { if (self.checkAllowAttempt()) { self.displayAttemptPopup(); } //else if (!self.checkContinueViewing() && !self.seminar.IsAllowAttempts) { // //Open magnific popup // self.openMagnificPopup({ // items: { // src: '#attendanceNotificationPopup' // }, // enableEscapeKey: true, // showCloseBtn: true, // callbacks: { // afterClose: self.restartLastSection // } // }); //} else if (self.checkShowLimitPopUp()) { self.limitExceededPopup(); } else { self.resetAttendanceRequirement(); } }; if (self.currentAttendance && self.currentAttendance.Status != 2) { // self.seminar.TotalMissedCount = (self.seminar.TotalMissedCount || 0) + 1; //Update Status In Db self.saveAttendanceForMissed(fnCallback); } } //@Method: Save missed attendanace popup self.saveAttendanceForMissed = function (callback) { var browserstatus = "OutFoucus"; if (self.IsBrowserFocusOnAttendenceShow != self.IsBrowserFocus) { browserstatus = "PartiallyInFocus"; } else if (self.IsBrowserFocus == true) { browserstatus = "InFocus"; } $.ajax({ type: 'POST', url: '/ShowTimeWidget/SaveAttendance', data: { 'status': 1, 'registrantAttendanceId': self.currentAttendance.RegistrantAttendanceId, 'currentAttempt': self.seminar.CurrentAttempt, 'programRegistrantId': ProgramRegistrantId, 'browserStatus': browserstatus }, success: function (missedPopupCount) { self.currentAttendance.Status = 1; RefreshCertificate(); if (missedPopupCount) { self.seminar.TotalMissedCount = missedPopupCount; } }, error: function (jqXHR, textStatus, errorThrown) { RefreshCertificate(); } }).always(callback); } //@Method: Check allow attempt self.checkAllowAttempt = function () { if (self.seminar.IsAllowAttempts && self.seminar.NoOfAttempts && self.seminar.NoOfAttempts > 0 && (self.seminar.NoOfAttempts + 1) > self.seminar.CurrentAttempt && self.seminar.TotalMissedCount > self.seminar.AllowedMissedCount) { return true; } else { return false; } } //@Method: Check continue viewing self.checkContinueViewing = function () { return self.seminar.IsContinueViewing && seminar.IsContinueViewing == true; } //@Method: Display limit popup self.checkShowLimitPopUp = function () { if (self.seminar.TotalMissedCount > self.seminar.AllowedMissedCount && seminar.CurrentAttempt >= (seminar.NoOfAttempts + 1)) { return true; } else { return false; } } //@Method: Open Inline magnific popup self.openMagnificPopup = function (options) { var op = { type: 'inline', closeOnBgClick: false, enableEscapeKey: false, showCloseBtn: false, }; op = $.extend(op, options || {}) $.magnificPopup.open(op); } //@Method: Restart Seminar self.restartSeminar = function () { $(this).html('  Processing...').attr('disabled', true); if (vidPlayer) { vidPlayer.pause(); } self.InsertRestartButtonEvent(self.currentAttendance.RegistrantAttendanceId, 'RestartVideo'); $.ajax({ type: 'POST', url: '/ShowTimeWidget/DeleteAttendance', data: { 'programRegistrantId': ProgramRegistrantId }, success: function (data) { if (data.isDeleted) { if (tableSasTrackingUri) { tableSasTrackingUri = null; } $('#divProgress').show(); //Reload the viewer location.reload(); } }, error: function (jqXHR, textStatus, errorThrown) { self.resetAttendanceRequirement(); } }); }; $("body").on("click", "#btnRestartSeminar,#btnRestartSeminarHistory", self.restartSeminar); //@Method: Restart Last Section self.restartLastSection = function () { $(this).html('  Processing...').attr('disabled', true); if (vidPlayer) { vidPlayer.pause(); } self.InsertRestartButtonEvent(self.currentAttendance.RegistrantAttendanceId, 'RestartSection'); $.ajax({ type: 'POST', url: '/ShowTimeWidget/GetLastAttendentTime', data: { 'programRegistrantId': ProgramRegistrantId }, success: function (data) { if (tableSasTrackingUri) { tableSasTrackingUri = null; } $('#divProgress').show(); //Reload the viewer location.reload(); }, error: function (jqXHR, textStatus, errorThrown) { self.resetAttendanceRequirement(); } }); }; $("body").on("click", "#btnRestartFromLastAttendance", self.restartLastSection); //when continue button click when attempt popup is open $("body").on("click", "#btnContinueSeminar,#btnContinueSeminarLimit,#btnContinueSeminarAttemp", function () { $("#CertificationWidget").html(''); if ($(this).attr('id') == "btnContinueSeminarLimit") { self.InsertRestartButtonEvent(self.currentAttendance.RegistrantAttendanceId, 'ResumeWithoutCredit'); } RefreshCertificate(); self.resetAttendanceRequirement(); self.seminar.IsContinueViewing = true; }); $("body").on("click", "#btnQuitSeminar", function () { window.open('', '_parent', ''); window.close(); }); //#7293 Viewer > Attendance Confirmation > Stop clock when entering answer var focusTimer = null; $("body").on("keypress", "#QuestionAnswer", function () { console.log("You pressed a key inside the input field"); $(this).addClass('focused'); clearTimeout(focusTimer); focusTimer = setTimeout(function () { $('#QuestionAnswer').removeClass('focused'); }, 2000) }); //@Method: Display Attmpt popup - It will call if any attempt avilable self.displayAttemptPopup = function () { if (self.checkAllowAttempt()) { if (vidPlayer) { vidPlayer.pause(); } if (vidPlayer && vidPlayer.isFullscreen()) { vidPlayer.exitFullscreen(); } // check restart from begining or from last confirm popup time var popupSrc = "#attendanceAttemptPopup"; if (self.seminar.RestartVideoType == 1) { popupSrc = "#attendanceAttemptPopupToLastConfirm"; } //Open magnific popup self.openMagnificPopup({ items: { src: popupSrc }, callbacks: { afterClose: self.resetAttendanceRequirement } }); } } //@Method: Show Limit exceeded popup self.limitExceededPopup = function () { if (vidPlayer) { vidPlayer.pause(); } //Open magnific popup self.openMagnificPopup({ items: { src: '#attendanceAttemptLimitPopup' }, callbacks: { afterClose: function () { RefreshCertificate(); self.resetAttendanceRequirement(); self.seminar.IsContinueViewing = true; self.anyActivePopup = false; } } }); } //@Method: Open the popup before attendance popup open - It will call if attendance is failed self.showPopUpAfterAttendaceFailed = function () { if (self.checkAllowAttempt()) { self.anyActivePopup = true; self.displayAttemptPopup(); } else if (self.checkShowLimitPopUp() && !self.checkContinueViewing()) { self.anyActivePopup = true; self.limitExceededPopup(); } } self.init(); //#11493 - Attendance Confirmation > Record when Restart and Resume buttons are clicked self.InsertRestartButtonEvent = function (registrantAttendanceId, restartButtonType) { $.post('/ShowTimeWidget/UpdateRestartButtonType', { registrantAttendanceId: registrantAttendanceId, restartButtonType: restartButtonType }); }; }; var oldIE = false; var toggleBtn1 = document.getElementById("slide-toggle"); var toggleBtn2 = document.getElementById("video-toggle"); var toggleBtn3 = document.getElementById("video-resize"); var toggleBtn0 = document.getElementById("default-view"); var toggleBtnState = document.getElementById("info-toggle-btn"); var mainViewColumn = $('#mainView .column:first'); var maxWidgetHeight = $(window).height() - 250; var maxWidgetHeightInteractive = $(window).height() / 2 - 250; var demoSlides = []; var demoStartTime = 0; var IsAudioOnly = false; var IsBrowserFocus = true; var IsBrowserFocusOnAttendenceShow = true; var IsBrowserFocusOnParticipationCodeShow = true; var ATTENDANCE_REQUIREMENT = null; var isOverideLastTrackTime = false; var SYNC_VIEWER = null; var ViewerSettings = {}; var allSlideTimes = []; var ViewerAnalyticsId = 0; var chatRoomId = 0; var isUnloadPage = false; var sidePanelShowAll = false; var testVideoUrl = ""; //used in media.js and media_oss.js Helper.Interval.set("VIEWER_VALIDATEBROWSERCUSTOMER", validateBrowserCustomer, 60); async function getTestVideoUrl() { try { const testVideoUrl = await fetch("/showtimewidget/gettestvideourl"); if (!testVideoUrl.ok) throw new Error("Failed to retrieve data"); const url = await testVideoUrl.json(); return url; } catch (err) { console.log("could not retrieve test video url from /showtimewidget/gettestvideourl"); return ""; } } //parameter name get function function getParameterByName(name) { name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]"); var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"), results = regex.exec(location.search); return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " ")); } //add data-activeTab attribute in body function addActiveTabAttr() { var id = $("#navlist li.active a").attr("data-href"); $("body").attr("data-activeTab", id); } // #region toggle video and slide function toggleVideoSlide(elementId, isVideo, isVideoResize) { $(elementId).closest('li').toggleClass('active'); $('.resizebutton > p > button').each(function () { var id = '#' + $(this).attr('id'); if (elementId != id) { $(this).closest('li').removeClass('active'); } }); if (!anyResizeMethodActive()) { $(toggleBtn0).closest('li').addClass('active'); } defaultView(true); VideoWidgetPIP(); SlideWidgetPIP(); toggleBtn3ToggleVideoSlide(); if (isVideoResize == false) { $(window).resize(); } } // #endregion toggle video and slide // #region toggle video and slide Interactive function toggleVideoSlideInteractive(elementId, isVideo) { if ($(elementId).hasClass("btn-primary")) { $(elementId).removeClass("btn-primary").addClass("btn-default"); if (isVideo) { $("#slideView").removeClass("col-md-6").addClass("col-md-12"); //$("#media-container_wrapper,div#media-container").css({ "height": "0" }, { "opacity": "0" }).addClass('hideVideo'); $("#main-panel").hide().addClass('hideVideo'); $("#playlist_panel").css({ "height": "0" }, { "opacity": "0" }); $("#slidescreen img").width('95%'); $("#slide-toggle-interactive").attr('disabled', 'disabled'); } else { $("#slidescreen").hide(); $("#mediaView").removeClass("col-md-6").addClass("col-md-12"); $("#video-toggle-interactive").attr('disabled', 'disabled'); } } else { $(elementId).removeClass("btn-default").addClass("btn-primary"); if (isVideo) { //$("#media-container_wrapper,div#media-container").css({ "height": "auto" }, { "opacity": "" }).removeClass('hideVideo'); $("#main-panel").show().removeClass('hideVideo'); $("#playlist_panel").css({ "height": "auto" }, { "opacity": "" }); if ($("#slidescreen").css("display") == "none" || $("#slidescreen img").attr("src") === undefined) { if (seminar != null && seminar.Slides !== undefined && seminar.Slides != null && seminar.Slides.length > 0) { if ($(toggleBtnState).hasClass("glyphicon-chevron-right")) { $("#mediaView").removeClass("col-md-6").addClass("col-md-12"); $("#slideView").removeClass("col-md-6").addClass("col-md-12"); } else { $("#mediaView").removeClass("col-md-12").addClass("col-md-6"); $("#slideView").removeClass("col-md-12").addClass("col-md-6"); } } else { $("#mediaView").removeClass("col-md-6").addClass("col-md-12"); $("#slideView").removeClass("col-md-6").addClass("col-md-12"); } } else { if ($(toggleBtnState).hasClass("glyphicon-chevron-right")) { $("#mediaView").removeClass("col-md-6").addClass("col-md-12"); $("#slideView").removeClass("col-md-6").addClass("col-md-12"); } else { $("#mediaView").removeClass("col-md-12").addClass("col-md-6"); $("#slideView").removeClass("col-md-12").addClass("col-md-6"); } } $("#slide-toggle-interactive").removeAttr('disabled'); } else { $("#slidescreen").show(); if ($(toggleBtnState).hasClass("glyphicon-chevron-right")) { $("#mediaView").removeClass("col-md-6").addClass("col-md-12"); $("#slideView").removeClass("col-md-6").addClass("col-md-12"); } else { $("#mediaView").removeClass("col-md-12").addClass("col-md-6"); $("#slideView").removeClass("col-md-12").addClass("col-md-6"); } $("#video-toggle-interactive").removeAttr('disabled'); } } $(window).resize(); } function toggleVideoSlideInteractive1(elementId, isVideo) { if ($(elementId).hasClass("btn-primary")) { $(elementId).removeClass("btn-primary").addClass("btn-default"); if (isVideo) { $("#slideView").removeClass("col-md-6").addClass("col-md-12"); //$("#media-container_wrapper,div#media-container").css({ "height": "0" }, { "opacity": "0" }).addClass('hideVideo'); $("#main-panel").hide().addClass('hideVideo'); $("#playlist_panel").css({ "height": "0" }, { "opacity": "0" }); $("#slidescreen img").width('100%'); $("#slidescreen img").css("height", maxWidgetHeight); $("#slide-toggle-interactive1").attr('disabled', 'disabled'); } else { $("#slidescreen").hide(); $("#mediaView").removeClass("col-md-6").addClass("col-md-12"); //$("#media-container_wrapper,div#media-container").css("height", maxWidgetHeight); $("#main-panel").show().css("height", maxWidgetHeight); $("#video-toggle-interactive1").attr('disabled', 'disabled'); } } else { $(elementId).removeClass("btn-default").addClass("btn-primary"); if (isVideo) { //$("#media-container_wrapper,div#media-container").css({ "height": "auto" }, { "opacity": "" }).removeClass('hideVideo'); $("#main-panel").show().removeClass('hideVideo'); $("#playlist_panel").css({ "height": "auto" }, { "opacity": "" }); if ($("#slidescreen").css("display") == "none" || $("#slidescreen img").attr("src") === undefined) { if (seminar != null && seminar.Slides !== undefined && seminar.Slides != null && seminar.Slides.length > 0) { if ($(toggleBtnState).hasClass("glyphicon-chevron-left")) { $("#mediaView").removeClass("col-md-6").addClass("col-md-12"); $("#slideView").removeClass("col-md-6").addClass("col-md-12"); //$("#media-container_wrapper,div#media-container").css("height", "auto").removeClass('hideVideo'); $("#main-panel").show().removeClass('hideVideo'); $("#slidescreen img").css("height", "auto"); } else { $("#mediaView").removeClass("col-md-12").addClass("col-md-6"); $("#slideView").removeClass("col-md-12").addClass("col-md-6"); $("#slidescreen img").css("height", "auto"); //$("#media-container_wrapper,div#media-container").css("height", "auto").removeClass('hideVideo'); $("#main-panel").show().removeClass('hideVideo'); } } else { $("#mediaView").removeClass("col-md-6").addClass("col-md-12"); $("#slideView").removeClass("col-md-6").addClass("col-md-12"); $("#slidescreen img").css("height", "auto"); //$("#media-container_wrapper,div#media-container").css("height", "auto").removeClass('hideVideo'); $("#main-panel").show().removeClass('hideVideo'); $("#main-panel").css("height", ""); } } else { if ($(toggleBtnState).hasClass("glyphicon-chevron-left")) { $("#mediaView").removeClass("col-md-6").addClass("col-md-12"); $("#slideView").removeClass("col-md-6").addClass("col-md-12"); } else { $("#mediaView").removeClass("col-md-12").addClass("col-md-6"); $("#slideView").removeClass("col-md-12").addClass("col-md-6"); } } $("#slide-toggle-interactive1").removeAttr('disabled'); } else { $("#slidescreen").show(); if ($(toggleBtnState).hasClass("glyphicon-chevron-left")) { $("#mediaView").removeClass("col-md-6").addClass("col-md-12"); $("#slideView").removeClass("col-md-6").addClass("col-md-12"); } else { $("#mediaView").removeClass("col-md-12").addClass("col-md-6"); $("#slideView").removeClass("col-md-12").addClass("col-md-6"); } $("#video-toggle-interactive1").removeAttr('disabled'); } } $(window).resize(); } // #endregion toggle video and slide // #region Twitter var twitterTimeout; var productTweets = [], lastTweetSyncTime, isTwitterLoad = true; function iniTwitter() { isTwitterLoad = true; //setupTwitterScroll(); //getTweets(); Helper.Interval.set("VIEWER_TWITTER", getTweets, 10); if (productTweets.length > 0) { if (isTwitterLoad) { setupTwitterScroll(); isTwitterLoad = false; } } } function setupTwitterScroll() { $(".twitterTicker").bootstrapNews({ newsPerPage: 5, autoplay: (Number(seminar.TwittRotateDuration) == -1 ? false : true), pauseOnHover: true, direction: 'up', newsTickerInterval: Number(seminar.TwittRotateDuration) * 1000 }); } function getTweets() { if (seminar != undefined && seminar != null) { if (!lastTweetSyncTime) { //lastTweetSyncTime = seminar.StrStartTimeUtc; //lastTweetSyncTime = moment(lastTweetSyncTime).add(-1, 'hours').format(); lastTweetSyncTime = null; } else { //lastTweetSyncTime = new Date(new Date() + ' UTC'); //lastTweetSyncTime = //moment(new Date()).format(); //moment(lastTweetSyncTime).format(); lastTweetSyncTime = moment(new Date()).format(); } //moment(lastTweetSyncTime).utc() $.ajax({ type: 'GET', url: '/ShowtimeWidget/GetTweets', dataType: 'json', data: { 'productId': s, 'eventTimeId': e, 'lastSyncUtcTime': lastTweetSyncTime }, global: false, success: function (tweets) { lastTweetSyncTime = seminar.StrStartTimeUtc; lastTweetSyncTime = moment(lastTweetSyncTime).format(); if (tweets !== undefined && tweets != null) { if (tweets.tweetList !== undefined && tweets.tweetList != null && tweets.tweetList.length > 0) { var countTweet = productTweets.length; productTweets.push.apply(productTweets, tweets.tweetList); if (productTweets.length > countTweet && !$("#TwitterWidget").is(":visible")) { $(".baseTwitterWidget").text("new"); } bindTweets(); //var tweetHtml = ""; //$.each(productTweets, function (index, element) { // tweetHtml = tweetHtml + "
  • " + // "
    " + "
    " + // "
    " + element.TweetText + "
    " + // "
    " + element.TweetTime + "
    " + // "
  • "; //}); //$(".twitterTicker").html(tweetHtml); if (isTwitterLoad) { setupTwitterScroll(); isTwitterLoad = false; } //$("#spnTwitterHashTag").text(" - " + productTweets[productTweets.length - 1].TwitterHashTag); } if (tweets.twitterHashTag !== undefined && tweets.twitterHashTag != null) { $("#spnTwitterHashTag").text(" - #" + tweets.twitterHashTag); } } //if (seminar.TwitterHashTag !== undefined && seminar.TwitterHashTag != null && seminar.TwitterHashTag.length > 0) { // if (productTweets == undefined || productTweets == null || productTweets.length == 0) { // $(".twitterTicker").html("
  • "); // $(".twitterTicker").css({ 'height': 'auto' }); // } //} //$(".baseTwitterWidget").text(productTweets.length); }, error: function (jqXHR, textStatus, errorThrown) { console.log("error: getTweets"); } }); if (seminar.TwitterHashTag !== undefined && seminar.TwitterHashTag != null && seminar.TwitterHashTag.length > 0) { if (productTweets == undefined || productTweets == null || productTweets.length == 0) { $(".twitterTicker").html("
  • "); $(".twitterTicker").css({ 'height': 'auto' }); } } } } function bindTweets() { if (productTweets.length > 0) { var tweetHtml = ""; $.each(productTweets, function (index, element) { tweetHtml = tweetHtml + "
  • " + "
    " + "
    " + "
    " + element.TweetText + "
    " + "
    " + element.TweetTime + "
    " + "
  • "; }); $(".twitterTicker").html(tweetHtml); //if (isTwitterLoad) { // setupTwitterScroll(); // isTwitterLoad = false; //} //$("#spnTwitterHashTag").text(" - " + productTweets[productTweets.length - 1].TwitterHashTag); //if (seminar.TwitterHashTag !== undefined && seminar.TwitterHashTag != null && seminar.TwitterHashTag.length > 0) { // if (productTweets == undefined || productTweets == null || productTweets.length == 0) { // $(".twitterTicker").html("
  • "); // $(".twitterTicker").css({ 'height': 'auto' }); // } //} $(".countTwitterWidget").text(productTweets.length); } if (seminar.TwitterHashTag !== undefined && seminar.TwitterHashTag != null && seminar.TwitterHashTag.length > 0) { if (productTweets == undefined || productTweets == null || productTweets.length == 0) { $(".twitterTicker").html("
  • "); $(".twitterTicker").css({ 'height': 'auto' }); } } } // #endregion Twitter // #region Notes function setNotesCount() { if ($("#hdnNoteCount")) { $(".baseNotesWidget").text($("#hdnNoteCount").val()); } } // #endregion Notes // #region Slides function getAllSlideTimes() { if (!seminar.Slides || seminar.Slides.length == 0) { allSlideTimes = []; return; } $.each(seminar.Slides, function (index, slide) { if (!slide.SlideTimes || slide.SlideTimes.length == 0) return; $.each(slide.SlideTimes, function (index, slideTime) { if (slideTime.ProductTime) allSlideTimes.push(slideTime.ProductTime); }); }); } // set slide badge function setSlideCount(slideCount) { $(".baseSlideThumbsWidget").text(slideCount); } function syncSlides() { if ($("#btnSyncSlide").length > 0 && $(".SlideThumbsWidget a img").hasClass("preview")) { if ($(".SlideThumbsWidget a img.preview").parent().attr("data-slideid") == $(".SlideThumbsWidget a img.selected").parent().attr("data-slideid")) { $("#btnSyncSlide").attr("data-issync", true) autoScrollSlide(); } else { $("#btnSyncSlide").attr("data-issync", false) } } else { if ($("#btnSyncSlide").length > 0 && $(".SlideThumbsWidget a img").hasClass("selected")) { $("#btnSyncSlide").attr("data-issync", true) autoScrollSlide(); } else { $("#btnSyncSlide").attr("data-issync", false) } } applySlideScreenStatus(); } function autoScrollSlide() { var container = $("#info-panel-content"); var scrollTo = $("#SlideThumbsWidget img.selected"); if (scrollTo.offset() !== undefined) { container.scrollTop( scrollTo.offset().top - container.offset().top + container.scrollTop() ); } //12919: Viewer > Bottom end of Scrollbar partially hidden / Feedback Widget - don't overlay on scroll bar area setTimeout(function () { setFeedbackWidgetButtonOffset(); }, 200); } // #endregion Slides // #region Materials var materialsTimeout; var materialsCount = 0; function iniMaterials() { // Helper.Interval.set("VIEWER_MATERIALS", getMetarials, 2 * 60); } function getMetarials() { if ($("a[data-href='MaterialWidget']").length > 0) { var pageWidgetId = $("a[data-href='MaterialWidget']").attr("data-pagewidgetid"); LoadHtml("MaterialWidget", "", pageWidgetId, true); } } function setMaterialsCount() { // set Materials Count if ($("#hdnMaterialsCount").length > 0 && $(".baseMaterialWidget").length > 0) { $(".baseMaterialWidget").text($("#hdnMaterialsCount").val()); if (materialsCount > 0 && Number($("#hdnMaterialsCount").val()) > materialsCount && !$("#MaterialWidget").is(':visible')) { $(".baseMaterialWidget").text("New"); } materialsCount = Number($("#hdnMaterialsCount").val()); } } // #endregion Materials // #region chat function initializeChat() { CE21Chat.initAll(); } // This optional function html-encodes messages for display in the page. function htmlEncode(value) { var encodedValue = $('
    ').text(value).html(); return encodedValue; } function getChats() { $.ajax({ cache: false, type: "GET", datatype: "json", data: { "productId": s, "eventTimeId": e }, url: "/showtimewidget/getseminarchats", success: function (chats) { if (chats !== undefined && chats != null && chats.length > 0) { $("#chatDiscussion").html(""); $.each(chats, function (i, oChat) { var htmlChatBody = "
  • " + "Avatar" + "" + "
    " + "
    " + " " + oChat.FirstName + " " + "" + oChat.ChatDateTime + "" + "
    " + "

    " + oChat.Message + "

    " + "
    " + "
  • "; $("#chatDiscussion").append(htmlChatBody); }); if ($("#chatDivScroll").length > 0) { $("#chatDivScroll").scrollTop($('#chatDivScroll')[0].scrollHeight); } } }, error: function (jqXHR, textStatus, errorThrown) { console.log("error: getChats"); } }); } //// email Chat //function emailChats() { // if (seminar != null && seminar.Customer != null && seminar.Customer.Email != null && seminar.Customer.Email.length > 0) { // $.ajax({ // type: 'POST', // url: '/ShowtimeWidget/EmailChats', // dataType: 'json', // data: { // 'productId': s, 'eventTimeId': e, 'email': seminar.Customer.Email // }, // success: function (data) { // if (data !== undefined && data != null && data.length > 0) { // //$("#chatEmailMessage label").text(data); // //$("#chatEmailMessage").show(); // //setTimeout(function () { // // $("#chatEmailMessage label").text(""); // // $("#chatEmailMessage").hide(); // //}, 10000); // alert(data); // } // }, // error: function (jqXHR, textStatus, errorThrown) { // console.log("error: emailChats"); // } // }); // } //} // #endregion chat // #region Video Segments function iniVideoSegment() { if (seminar.MediaClips != null && seminar.MediaClips.length > 0) { var strHtml = ""; $.each(seminar.MediaClips, function (index, objMediaClip) { if (objMediaClip.IsPreSeminar) return; //seminar.MediaClips[0].Media.Label strHtml = strHtml + "
    " + "
    " + "
    " + "" + "
    " + "
    " + "View" + "
    " + "
    " + "

    " + (objMediaClip.SegmentDescription != undefined && objMediaClip.SegmentDescription != null && objMediaClip.SegmentDescription != '' ? objMediaClip.SegmentDescription : '') + "

    " + "
    " + "
    " + "
    " + "
    " + "
    " + "
    " + "
    " + "
    " + "
    " + "
    " + "
    "; }); $("#divVideoSegment").html(strHtml); } } function setCurrVideoSegment() { if (curMediaClip !== undefined && curMediaClip != null) { // set button active if ($("#divVideoSegment a[data-mediaClipId='" + curMediaClip.MediaClipId + "']").length > 0) { $("#divVideoSegment a").removeClass("btn-success"); $("#divVideoSegment a").addClass("btn-default"); $("#divVideoSegment a[data-mediaClipId='" + curMediaClip.MediaClipId + "']").removeClass("btn-default").addClass("btn-success"); } // set progress bar active if ($("#divVideoSegment div.progress-bar[data-mediaClipId='" + curMediaClip.MediaClipId + "']").length > 0) { $("#divVideoSegment div.progress-bar").removeClass("active"); $("#divVideoSegment div.progress-bar[data-mediaClipId='" + curMediaClip.MediaClipId + "']").addClass("active"); } // no segment for pre seminar medias if (curMediaClip.IsPreSeminar) { $("#divVideoSegment div.progress-bar").removeClass("active"); $("#divVideoSegment a").removeClass("btn-success"); $("#divVideoSegment a").addClass("btn-default"); } } } // #endregion Video Segments function HideShowNavList(divid, targetPageWidgetId) { $("#navlist a").each(function () { var id = $(this).attr("data-href"); var pageWidgetId = $(this).attr("data-pagewidgetid"); var actionName = $(this).attr("data-actionName"); var navSelector = '#' + id; var isTargetNode = (divid == id); if (id == "HTMLWidget") { navSelector += "[data-id='" + pageWidgetId + "']"; isTargetNode = (divid == id && pageWidgetId == targetPageWidgetId); } if (isTargetNode == false) { if (!sidePanelShowAll) { $(navSelector).hide(); } $(this).parent().removeClass("active"); } else if (isTargetNode) { $(navSelector).show(); $(this).parent().addClass("active"); if (divid == "QuestionsWidget") { iniQuestions(); } if (divid == "MaterialWidget") { setMaterialsCount(); iniMaterials(); } if (divid == "SlideThumbsWidget") { autoScrollSlide(); } if (divid == "CertificationWidget") { hideCertAlertIcon(); } if (divid == "ForumWidget") { $(".baseForumWidget").text(""); } if (divid == "TwitterWidget") { $(".baseTwitterWidget").text(""); } if (actionName != "CustomDataNewTab") { LoadHtml(divid, $(this).attr("data-text"), $(this).attr("data-PageWidgetID"), false); } document.title = $(this).attr("data-text") + ' | ' + PageTitle; } }); } var questionResponceInterVal, questionResponceEmail; function LoadHtml(ActionName, title, PageWidgetID, isForceCall) { // $("title").html(title + " | " + PageTitle); addActiveTabAttr(); if (ActionName == "eventlog" || ActionName == "videoSegment" || ActionName == "transcript") { return false; } var selectorName = "#" + ActionName; if (ActionName == "HTMLWidget") { selectorName += "[data-id='" + PageWidgetID + "']"; } var isArchive = seminar != undefined && seminar != null && seminar.IsArchive; if (ActionName == "SupportWidget") { isForceCall = true; } var divs = $(selectorName).find("." + ActionName); if (divs.length == 0 || isForceCall) { // #0018272 if (IsSnapshotPreview && isSnapshotWidget(ActionName)) { manageSnapshotPreviewWidgets(ActionName); return false; } if (ActionName == "CertificationWidget") { RefreshCertificate(); } else { $("#divProgress").show(); var actionUrl = "/showtimewidget/" + ActionName.toLowerCase() + "?PageWidgetID=" + PageWidgetID + "&SeminarId=" + Number(s) + "&TimeId=" + Number(e) + "&CustomerId=" + u + "&ProgramRegistrantId=" + ProgramRegistrantId + "&IsArchive=" + isArchive + "&pageId=" + showTimePageId; if (ActionName == "ForumWidget") { actionUrl += "&parentSeminarId=" + ps + "&parentTimeId=" + pe; } else if (ActionName == "ChatWidget") { actionUrl = "/chat/index?roomEntityId=" + pe + "&roomEntityType=EventTime&chatTenantId=" + pt; } $(selectorName).load(actionUrl, function () { setTimeout(function () { scrollOnSpecificDiv(selectorName); }, 100); //Intialize Magnific if (ActionName == "SlideThumbsWidget") { if ((Number(seminar.SeminarTypeId) == 4 || Number(seminar.SeminarTypeId) == 3)) { if (curSlideId <= 0) { ZoomSlides(); initSlides(); } } else { initSlides(); if (curSlideId <= 0) { ZoomSlides(); } } if (seminar != null && seminar.Slides !== undefined && seminar.Slides != null && seminar.Slides.length > 0) { setSlideCount(seminar.Slides.length); } autoScrollSlide(); } if ($.validator != undefined && $.validator.unobtrusive != undefined) { $.validator.unobtrusive.parse("form"); } if (ActionName == "TwitterWidget") { bindTweets(); iniTwitter(); } if (ActionName == "NotesWidget") { setNotesCount(); ManageNotes('GetItem'); } if (ActionName == "QuestionsWidget") { setQuestionCount(); //questionResponceEmail = $('#ProductResponseEmail').val(); //if (questionResponceEmail != undefined && questionResponceEmail == '') { // Helper.Interval.set("VIEWER_QUESTIONRESPONCE", function () { // var Wquestion = $('#navlist').find('a[data-href="QuestionsWidget"]'); // LoadHtml("QuestionsWidget", $(Wquestion).attr("data-text"), $(Wquestion).attr("data-PageWidgetID"), true); // }, 60); //} else if (questionResponceInterVal) { // clearInterval(questionResponceInterVal); //} } if (ActionName == "MaterialWidget") { setMaterialsCount(); } if (ActionName == "SegmentsWidget") { iniVideoSegment(); setCurrVideoSegment(); } if (ActionName == "ChatWidget") { if ($("#navlist li.active").css('display') === "none" && $("#navlist li.active a").attr("data-href") === "ChatWidget") { $(selectorName).hide(); } initializeChat(); if (localStorage.getItem('loc-pressentertosend') != null) { $("#chkChatEnter").prop('checked', localStorage.getItem('loc-pressentertosend')); } } if (ActionName == "PollingResultWidget") { getPollingResult(); } if (ActionName == "ForumWidget") { iniForumWidget(); } if (ActionName == "SupportWidget") { //$('.clsAlternateViewerDiv').show(); if (typeof (checkSignalRConnected) == "function") { checkSignalRConnected(); } } //Hide Custom Data widget tab if data is not exist. if (ActionName == "CustomDataWidget" && $("#divCustomDataWidget").length == 0) { $('#navlist').find('a[data-href="CustomDataWidget"]').parent("li").hide(); } $("#divProgress").hide(); navBarForSmallScreen(); //#12919: Viewer > Bottom end of Scrollbar partially hidden / Feedback Widget - don't overlay on scroll bar area setFeedbackWidgetButtonOffset(); }); } } } function RefreshCertificate(accordionTabCount, isFromQuize) { $("#CertificationWidget").html(); $("#divProgress").show(); var pageWidgetId = $('a[data-href="CertificationWidget"][data-pagewidgetid]').attr('data-pagewidgetid'); $("#CertificationWidget").src = "/account/customerrequiredinformation?ProgramRegistrantId=" + ProgramRegistrantId + "&IsViewer=true&pageWidgetId=" + pageWidgetId; } //mantis item #18216 function updateCertCompletionStatus(callForcely) { if ($("#CertificationWidget:visible").length > 0 && !callForcely) return; $("#divProgress").hide(); $.post("/items/updatecertcompletionstatus", { 'programRegistrantId': ProgramRegistrantId }, function () { }); } function requiredInformationSuccess() { $("#CertificationWidget").html(""); var pageWidgetId = $('a[data-href="CertificationWidget"][data-pagewidgetid]').attr('data-pagewidgetid'); $("#CertificationWidget").src = "/items/certificate?ProgramRegistrantId=" + ProgramRegistrantId + "&IsViewer=true&pageWidgetId=" + pageWidgetId; } var ItemLength = 1; function ClearText(formname) { $("#" + formname + " input[type=text]").val(""); $("#" + formname + " textarea").val(""); setNotesCount(); setQuestionCount(); if (formname == 'form-notes') { ManageNotes('RemoveItem') } } function ZoomSlides() { var thumb = $("#SlideThumbsWidget img").first().parent(); var source = thumb.attr("data-href"); var marketingurl = thumb.attr("data-marketingurl"); if (marketingurl == "") { marketingurl = "javascript:void(0)" } var hovertext = thumb.attr("data-hovertext"); $("#slidescreen img").attr("src", source); $("#slidescreen a").attr('href', marketingurl).attr('title', hovertext).attr('target', marketingurl == undefined || marketingurl == "" || marketingurl == "javascript:void(0)" ? "" : "_blank"); $(".slideThumb").removeClass("preview"); $("#SlideThumbsWidget img").first().addClass("preview"); } function getSeminar() { $.ajax({ type: 'GET', url: '/showtimewidget/getseminar', dataType: 'json', data: { 'SeminarId': s, 'TimeId': e, 'CustomerId': u, 'ParentEventTimeId': pe, 'ProgramRegistrantId': ProgramRegistrantId, 'MediaPageWidgetId': MediaPageWidgetId, 'archiveMode': archiveMode, 'originalProductId': originalProductId, 'isFromClassroomScheduleTab': (typeof isFromClassroomScheduleTab !== 'undefined' && isFromClassroomScheduleTab == "1") }, success: function (currSeminar) { seminar = currSeminar; seminar.MaxRelativeTime = seminar.LastRelativeTime; // #0018272 if (IsSnapshotPreview) { convertToArchiveMode(); } //Check if seminar is audio only then set size settingForAudioOnly(); //curMediaClip = seminar.MediaClips[0]; $("#seminarTitle").text(seminar.Title); if (seminar.DateFormateType == "ddMMyyyy") { seminar.StartTimeUtc = new Date(seminar.StartTimeUtcInUnix); seminar.EndTimeUtc = new Date(seminar.EndTimeUtcInUnix); } else { seminar.StartTimeUtc = new Date(seminar.StrStartTimeUtc + ' UTC'); seminar.EndTimeUtc = new Date(seminar.StrEndTimeUtc + ' UTC'); } compositionComplete(); initActions(); //Init Attendance Requirment if (AttendanceConfirmation) { ATTENDANCE_REQUIREMENT = new AttendanceConfirmation(seminar); } // Init Sync Viewer #11135 if (seminar.IsLive) { SYNC_VIEWER = new SyncViewer(seminar); } if ($("#SegmentsWidget").length > 0 && seminar.MediaClips != null && seminar.MediaClips.length > 1 && isMoreThanOneSeminarMediaClipAvaialble()) { if (seminar.SeminarTypeId == 4) { if ($("#SegmentsWidget").find(".SegmentsWidget")) { iniVideoSegment(); } else { if ($("a[data-href='SegmentsWidget']")) { var pageWidgetId = $("a[data-href='SegmentsWidget']").attr("data-pagewidgetid"); LoadHtml("SegmentsWidget", "", pageWidgetId, false); } } } } else { //#0014692 $(".SegmentsWidget").parent("li").hide(); } if ($(".SlideThumbsWidget").length == 0 && $("#slidescreen").length > 0 && seminar != null && seminar.Slides !== undefined && seminar.Slides != null && seminar.Slides.length > 0) { $("#slidescreen img").attr('src', seminar.Slides[0].Source); $("#slidescreen a").attr('href', (seminar.Slides[0].MarketingUrl == "" ? "javascript:void(0)" : seminar.Slides[0].MarketingUrl)).attr('title', seminar.Slides[0].HoverText).attr('target', (seminar.Slides[0].MarketingUrl == "" ? "" : "_blank")); curSlideId = 0; } initSlides(); setSlideCount(seminar.Slides.length); checkshowHideMediaSlideTime(); getAllSlideTimes(); // event log ListEventLogs = JSON.parse(seminar.JsonEventLogs); callEventLogs(); if ($(".TwitterWidget").length > 0) { iniTwitter(); } onLoadMediaSlide(); // for chat - Chat Auto load disabled as per dicussion with Kevin and Reid //if ($("#ChatWidget, .ChatWidget").length > 0 && !$('html').is('.ie6, .ie7')) { // // load chats // if ($("a[data-href='ChatWidget']")) { // var pageWidgetId = $("a[data-href='ChatWidget']").attr("data-pagewidgetid"); // LoadHtml("ChatWidget", "", pageWidgetId, false); // } //} if (seminar != null && seminar.IsReplay && seminar.IsArchive == false) { Helper.Interval.set("VIEWER_REPLAYVALIDATION", checkReplayPlayingCorrect, 60); } if (isMobileOrIpad.toLowerCase() == "true") { handlePortraitLandscape(); window.addEventListener("orientationchange", function () { handlePortraitLandscape(); }, false); } //Collapse side panel #5485: Viewer - If the program has slides, let's start the viewer with the side panel collapsed - if it has no slides, keep the side //if (seminar && seminar.Slides.length > 0 && $('#info-toggle').hasClass('glyphicon-chevron-right') && !seminar.IsAudioOnly) { // $('#info-toggle').trigger('click'); // setTimeout(function () { $(window).trigger('resize'); }, 500); //} //Collapse side panel #8416#c6417 :Let's operate off the checkboxes for now - thus "Start with tabbed panel collapsed" UNchecked would show tabs even if the program has slides. //Here condition --$('.viewerHeaderOriginal li.info-toggle-nav').length == 0-- is for, --mantis-- #0010060 if ((IsTabPanelCollapsed == "True" && !seminar.IsAudioOnly) || $('.viewerHeaderOriginal li.info-toggle-nav').length == 0) { $('#info-toggle').trigger('click'); setTimeout(function () { $(window).trigger('resize'); }, 500); if ($('.viewerHeaderOriginal li.info-toggle-nav').length == 0) { //--mantis #0010060 $('#sideBarStatustext').hide(); $('#info-toggle').css('color', 'transparent'); } } if (showinfo) { $('#mediaView').addClass('collapseView').removeClass('expandView'); $('#slideView').addClass('collapseView').removeClass('expandView'); } if (typeof (showChatWidget) === 'function' && !seminar.IsLive && !seminar.IsReplay) { showChatWidget(); } setTimeout(function () { SetForumWigdetTitle(); }, 1000); //#21560 //#0017665: Viewer > Classroom > End of programs triggerClassroomEndActions(); }, error: function (jqXHR, textStatus, errorThrown) { console.log("error: getting seminar"); } }); } function writeErrorLog(jqXHR, textStatus, errorThrown) { // console.error("Error: jqXHR= " + jqXHR + ". textStatus= " + textStatus + ". errorThrown=" + errorThrown); } //#region Event Logs function callEventLogs() { if (ListEventLogs !== undefined && ListEventLogs != null && ListEventLogs.length > 0) { ListEventLogs = ListEventLogs.sort(function (left, right) { return parseInt(left.timestr) > parseInt(right.timestr) ? -1 : 1; }); $("#divEventLogs").html(''); jQuery.each(ListEventLogs, function (index, element) { var tempString = '
  • [' + formatDuration(parseInt(element.timestr)) + '] - ' + element.log + '
  • '; $("#divEventLogs").append(tempString); }); } } function formatDuration(seconds) { var startTimeUtc = seminar.StartTimeUtc; return moment(startTimeUtc).add(seconds, "seconds").format("MM/DD/YYYY HH:mm:ss"); } //#endregin function scrollToAnchor(aid) { var aTag = $("a[id='" + aid + "']"); if (aTag.offset() !== undefined) { $('html,body').animate({ scrollTop: aTag.offset().top }, 'slow'); } } // Note: onLoadMediaSlide() this function is called in Themes/New/Views/ShowtimeWidget/index.cshtml under getSeminar() function. //Seminar slides comes in getSeminar() function and this "window.onload = function ()" called before getSeminar(). So, onLoadMediaSlide() function moved under getSeminar() function. //window.onload = function () { //function onLoadMediaSlide() { // //alert("Size media is working."); // if (seminar.Slides.length > 0) { // //alert("We have slides."); // $("#slideView").show(); // $("#mediaView").removeClass("col-md-12").addClass("col-md-6"); // $("#slideView").removeClass("col-md-12").addClass("col-md-6"); // //$("#media-container_wrapper,div#media-container").css("height", "auto"); // $("#slideSync").show(); // $("#navbar-slide-btn").show(); // $("#navbar-video-btn").show(); // if ($("#navbar-video-btn-disabled").css("display") != "none") { // $("#navbar-video-btn").hide(); // } // if ($("#navbar-slide-btn-disabled").css("display") != "none") { // $("#navbar-slide-btn").hide(); // } // //alert("a3."); // } // else { // //alert("We dont have slides."); // $("#mediaView").removeClass("col-md-6").addClass("col-md-12"); // //$("#media-container_wrapper,div#media-container").css("background-color", "none"); // $("#slideSync").hide(); // $("#navbar-slide-btn").hide(); // $("#navbar-video-btn").hide(); // $("#slideView").hide(); // } //} // #region show slide and video in full at the same time function isPortrait() { // return window.innerHeight > window.innerWidth; return (window.orientation === 0 || window.orientation === 180); } function isLandscape() { return (window.orientation === 90 || window.orientation === -90); } function handlePortraitLandscape() { if (isPortrait()) { if ($("#slidescreen img").attr("src") !== undefined && $("#slidescreen img").attr("src") != "") { $("#styleMedia").html(""); $("#styleMedia").append('@media screen and (orientation:portrait) and (min-width:768px) { #main-panel, #media-container_wrapper, div#media-container { width: 65%; } #slidescreen { width: 65% !important; margin:auto; } }'); $("#styleMedia").append('@media screen and (orientation:portrait) and (min-width:767px) { #main-panel, #media-container_wrapper, div#media-container { width: 70%; } #slidescreen { width: 70% !important; margin:auto; } }'); } else { $("#styleMedia").html(""); $("#styleMedia").append('@media screen and (orientation:portrait) { #main-panel, #media-container_wrapper, div#media-container { width: 100%; } #slidescreen { width: auto; } }'); } } if (isLandscape()) { if ($("#slidescreen img").attr("src") !== undefined || $("#slidescreen img").attr("src") == "") { $("#styleMedia").html(""); $("#styleMedia").append('@media screen and (orientation:landscape) { #main-panel, #media-container_wrapper, div#media-container { width: 100%; } #slidescreen { width: auto; }' + (window.outerWidth <= 991 ? '#mediaView, #slideView { margin-top: 5%; }' : '') + ' }'); } } } // #endregion show slide and video in full at the same time // #region document ready $(document).ready(async function () { //get test video url testVideoUrl = await getTestVideoUrl(); $.ajaxSetup({ cache: false }); if ((window.self !== window.top)) { if (typeof HideViewer == 'function') { HideViewer(); } if (typeof TenantDetailTrim == 'function') { TenantDetailTrim(); } } else { $('#applicationHost').show(); } if ($('html').is('.ie6, .ie7, .ie8, .ie9')) { oldIE = true; } if ((navigator.userAgent.indexOf("Trident") >= 0 || navigator.userAgent.indexOf("MSIE") >= 0)) { $("#browserAlertMessage").removeClass("hidden"); $("#browserAlertMessage").modal({ show: true }); } // #region hide/show video (toggle video screen) //if ($("#slidescreen img").attr("src") === undefined) { // //$("#mediaView").removeClass("col-md-6").addClass("col-md-12"); // //$("#mediaView").removeClass("col-lg-6").addClass("col-lg-12"); //} if ("Weglot" in window) { $("#weglot-visual-buffer").show(); } $("body").on("click", "#video-toggle", function () { toggleVideoSlide("#video-toggle", true, false); SetCurrentVideoSlideView("video-toggle"); }); $("body").on("click", "#default-view", function () { toggleVideoSlide("#default-view", true, false); SetCurrentVideoSlideView("default-view"); }); $("body").on("click", "#slide-toggle", function () { toggleVideoSlide("#slide-toggle", false, false); SetCurrentVideoSlideView("slide-toggle"); }); $("body").on("click", "#video-resize", function () { toggleVideoSlide("#video-resize", false, false); SetCurrentVideoSlideView("video-resize"); }); $("body").on("click", "#video-toggle-interactive", function () { toggleVideoSlideInteractive("#video-toggle-interactive", true); }); $("body").on("click", "#slide-toggle-interactive", function () { toggleVideoSlideInteractive("#slide-toggle-interactive", false); }); $("body").on("click", "#video-toggle-interactive1", function () { toggleVideoSlideInteractive1("#video-toggle-interactive1", true); }); $("body").on("click", "#slide-toggle-interactive1", function () { toggleVideoSlideInteractive1("#slide-toggle-interactive1", false); }); $("body").on("click", "#navlist a", function () { var divid = $(this).attr("data-href"); var targetPageWidgetId = $(this).attr("data-pagewidgetid"); if ($(".alert" + divid)) { $(".alert" + divid).hide(); } $('body').removeClass('chat-fullscreen');//#19708 // upadate forum count time if ($("#navlist .active a").attr("data-href") == "ForumWidget") { $.ajax({ type: 'POST', url: '/ShowtimeWidget/GetUTCTime', success: function (Data) { $("#hfforumLastSyncDateTime").val(Data); //localStorage.setItem('ForumSynchTime_' + forumSettingId, Data); } }); } HideShowNavList(divid, targetPageWidgetId); if ($('#' + divid).length > 0 && $('#' + divid).html() == "") { } else { scrollOnSpecificDiv('#' + divid); } //12919: Viewer > Bottom end of Scrollbar partially hidden / Feedback Widget - don't overlay on scroll bar area setFeedbackWidgetButtonOffset(); //#18282 if (!isImpersonateSession() && (ProgramRegistrantId && ProgramRegistrantId > 0)) sessionStorage.setItem('Active_Viewer_Tab_' + ProgramRegistrantId, targetPageWidgetId); UpdateActiveTabHighlightColor(); UpdateTabColorForUnauthViewer(); }); if ($("a[data-href='QuestionsWidget']")) { var pageWidgetId = $("a[data-href='QuestionsWidget']").attr("data-pagewidgetid"); LoadHtml("QuestionsWidget", "", pageWidgetId, false); iniQuestions(); } if ($("a[data-href='MaterialWidget']")) { var pageWidgetId = $("a[data-href='MaterialWidget']").attr("data-pagewidgetid"); LoadHtml("MaterialWidget", "", pageWidgetId, false); iniMaterials(); } //Load Custom Data Widget tab on ready to make it hide or show if data is not exist.- #13358 if ($("a[data-href='CustomDataWidget']")) { var pageWidgetId = $("a[data-href='CustomDataWidget']").attr("data-pagewidgetid"); LoadHtml("CustomDataWidget", "", pageWidgetId, false); } setQuestionCount(); setNotesCount(); if ($("#hfforumLastSyncDateTime").length > 0) { var pageWidgetId = $("a[data-href='ForumWidget']").attr("data-pagewidgetid"); LoadHtml("ForumWidget", "", pageWidgetId, false); } //// send chats email //$("body").on("click", "#btn-emailChat", function () { // emailChats(); //}); if ($('html').is('.ie6, .ie7')) { $(".ChatWidget").hide(); } $("body").on("click", "#btnSyncSlide", function () { $("#btnSyncSlide").attr("data-issync", $(this).attr("data-issync") == "true" ? "false" : "true"); //toggle data attribute if ($("#btnSyncSlide").attr("data-issync") == "true") { if ($(".SlideThumbsWidget a img.selected").length > 0 && $(".SlideThumbsWidget a img.preview").parent().attr("data-slideid") != $(".SlideThumbsWidget a img.selected").parent().attr("data-slideid")) { $(".SlideThumbsWidget a img.selected").trigger('click'); autoScrollSlide(); } } applySlideScreenStatus(); }); $(document).ajaxStart(function () { $("#divProgress").hide(); }); $(document).ajaxComplete(function () { $("#divProgress").hide(); }); HideShowNavList($("#navlist .active a").attr("data-href"), $("#navlist .active a").attr("data-pagewidgetid")) if ($('.RealtedCourseDiv').parent().hasClass('col-lg-12')) { ItemLength = 3; $('.realtedcourse').children(':first-child').removeClass('col-sm-6').addClass('col-sm-4') } $('.realtedcourse').each(function () { if (ItemLength == 3) { var next = $(this).next(); if (!next.length) { next = $(this).siblings(':first'); } next.children(':first-child').clone().appendTo($(this)); if (next.next().length > 0) { next.next().children(':first-child').clone().appendTo($(this)); } else { $(this).siblings(':first').children(':first-child').clone().appendTo($(this)); } } }); ZoomSlides(); if (IsLayoutPreview) { initializePreview(); } else if (isAudtioVideoWidget == "True") { getSeminar(); $("body").on("click", "#btn_start", function () { initializeMediaPlayer(); hideShowBeginButton(); }); } else { $("#slidescreen img").width('100%'); } $("body").on("click", "#btnNoteSend", function () { var CustomerEmail = $("#txtEmail").val(); if (CustomerEmail.length > 0) { if (validateEmail($("#txtEmail").val())) { $("#msgNoteEmail").hide(); $.ajax({ type: "GET", url: "/showtimewidget/sendnote", dataType: "json", data: { 'seminarid': $(this).attr("data-seminarid"), 'timeid': $(this).attr("data-timeid"), 'noteEmail': CustomerEmail, 'CustomerId': $(this).attr("data-CustomerId") }, success: function (data) { $("#txtEmail").val(""); $('#divNotesEmail').modal('hide'); }, error: function (data) { alert('Error! Please try again later.'); } }); } else { $("#msgNoteEmail").show(); return false; } } }); $("body").on("click", "#SlideThumbsWidget img", function () { var source = $(this).parent().attr("data-href"); var marketingurl = $(this).parent().attr("data-marketingurl"); if (marketingurl == "") { marketingurl = "javascript:void(0)" } var hovertext = $(this).parent().attr("data-hovertext"); $("#slidescreen img").attr("src", source); $("#slidescreen a").attr('href', marketingurl).attr('title', hovertext).attr('target', (marketingurl == "javascript:void(0)" ? "" : "_blank")); $(".slideThumb").removeClass("preview"); $(this).addClass("preview"); syncSlides(); }); $(window).resize(function () { maxWidgetHeight = $(window).height() - 250; if ($('#divTranscript').length > 0) { var transcriptHeight = $(window).height() - 260; if (typeof (isCurrentLiveStream) == undefined && isCurrentLiveStream) { transcriptHeight = $(window).height() - 170; } $('#divTranscript').css('max-height', transcriptHeight); if ($('.ifrmHTMLTranscript').length > 0) { $('.ifrmHTMLTranscript').css('height', transcriptHeight); } } if ($(toggleBtn2).closest('li').hasClass('active') || $(toggleBtn3).closest('li').hasClass('active')) { adjustPIPHeight(); } settingForAudioOnly(); if ($(window).width() <= 991) { removeActivePIPFunctions(); $('#slidescreen img').css('max-height', $(window).height() - 150); } else if ($('#slidescreen img').length > 0) { $('#slidescreen img').css('max-height', ''); if ($('#slidescreen img').height() > $(window).height() && seminar && !seminar.IsAudioOnly) { $('#slidescreen img').css('max-height', $(window).height() - 150); } } //#21770 if (seminar != null && seminar.Slides != null && seminar.Slides.length > 0) { if ($(window).width() > 2640 && $(toggleBtn0).closest('li').hasClass('active') && $("#slideView").hasClass("expandView")) { $('#slidescreen img').css('height', maxWidgetHeight); } else { $("#slidescreen img").css("height", "auto"); } } navBarForSmallScreen(); countDownShowHideWithResizeWindow(); }); $(window).trigger("resize"); var infoToggleState = document.getElementById("info-toggle") if (!IsDemoViewer) { $("body").on("click", "#info-toggle", function () { changeInfoToggleState(); $("#info-panel,#media-panel").removeClass("showinfo"); $('body').removeClass("display-info"); $("#media-panel").removeClass("col-md-7").addClass("col-md-12"); $("#info-panel").removeClass("col-md-5").addClass("col-md-0"); $('#mediaView').removeClass('collapseView').addClass('expandView'); $('#slideView').removeClass('collapseView').addClass('expandView'); //If audio check box is checked in edit seminar, collapse media container to just enough height to show controls #4388 if (IsAudioOnly == true) { settingForAudioOnly(); } else { if (seminar != null && seminar.Slides != null && seminar.Slides.length > 0) { if ($(toggleBtn1).closest('li').hasClass('active') || $(toggleBtn2).closest('li').hasClass('active') || $(toggleBtn3).closest('li').hasClass('active')) { if ($(toggleBtn3).closest('li').hasClass('active')) { toggleBtn3ToggleVideoSlide(); } else { $("#mediaView").removeClass("col-md-6").addClass("col-md-12"); $("#slideView").removeClass("col-md-6").addClass("col-md-12"); $("#slidescreen img").css("height", maxWidgetHeight); } } else { $("#mediaView").removeClass("col-md-12").addClass("col-md-6"); $("#slideView").removeClass("col-md-12").addClass("col-md-6"); $("#slidescreen img").css("height", "auto"); } } else { $("#mediaView").removeClass("col-md-6").addClass("col-md-12"); } } if (!showinfo) { $('#mediaView').addClass('collapseView').removeClass('expandView'); $('#slideView').addClass('collapseView').removeClass('expandView'); $("#info-panel,#media-panel").addClass("showinfo"); $('body').addClass("display-info"); $("#media-panel").removeClass("col-md-12").addClass("col-md-7"); $("#info-panel").removeClass("col-md-0").addClass("col-md-5"); //If audio check box is checked in edit seminar, collapse media container to just enough height to show controls #4388 if (IsAudioOnly == true) { settingForAudioOnly(); } else { if (seminar != null && seminar.Slides != null && seminar.Slides.length > 0) { if ($(toggleBtn1).hasClass("btn-success") || $(toggleBtn2).hasClass("btn-success") || $(toggleBtn3).hasClass("btn-success")) { if ($(toggleBtn3).hasClass("btn-success")) { toggleBtn3ToggleVideoSlide(); } else { $("#mediaView").removeClass("col-md-6").addClass("col-md-12"); $("#slideView").removeClass("col-md-6").addClass("col-md-12"); $("#slidescreen img").css("height", maxWidgetHeight); } } else { $("#mediaView").removeClass("col-md-12").addClass("col-md-6"); $("#slideView").removeClass("col-md-12").addClass("col-md-6"); $("#slidescreen img").css("height", "auto"); } //if ($(toggleBtn1).hasClass("btn-success")) { // toggleVideoSlide("#slide-toggle", false, false); //} //else if ($(toggleBtn2).hasClass("btn-success")) { // toggleVideoSlide("#video-toggle", true, false); //} //else if ($(toggleBtn3).hasClass("btn-success")) { // toggleVideoSlide("#video-resize", false, true); //} //else { // $("#mediaView").removeClass("col-md-12").addClass("col-md-6"); // $("#slideView").removeClass("col-md-12").addClass("col-md-6"); // $("#slidescreen img").css("height", "auto"); // //alert("4."); //} //$("#navbar-slide-btn").show(); //$("#navbar-video-btn").show(); //$("#slideSync").show(); } else { $("#mediaView").removeClass("col-md-6").addClass("col-md-12"); //alert("7b."); } } } showinfo = !showinfo; if (!$(toggleBtn3).hasClass("btn-success") || !$(toggleBtn1).hasClass("btn-success")) { $(window).resize(); } if ($(toggleBtn3).hasClass("btn-success")) { setTimeout(function () { toggleBtn3ToggleVideoSlide(); }, 500); // Half second } VideoWidgetPIP(); changeTextonBottomNav(); //SlideWidgetPIP(); }); function changeTextonBottomNav() { if (showinfo) { $('.bottom-nav-view').addClass('col-md-2').removeClass('col-md-7'); $('#sideBarStatustext').addClass("status-right"); } else { $('.bottom-nav-view').addClass('col-md-7').removeClass('col-md-2'); $('#sideBarStatustext').removeClass("status-right"); } //#22112 $("#largeSideBarStatustext").toggleClass("hidden", !showinfo); $("#sideBarStatustext i").attr("data-content", showinfo ? "Collapse side panel" : "Expand side panel"); $('#sideBarStatustext').css("padding-left", showinfo ? "0px" : "15px"); $('#bottomNavDiv').find('#sideBarStatustext').css("float", showinfo ? "right" : "left"); $("#navSideBarStatustext").toggleClass("navbar-left", showinfo).toggleClass("navbar-right", !showinfo); changeSideBarStatus(); applySlideScreenStatus(); } function changeSideBarStatus() { if ($('#sideBarStatustext i').hasClass("fa-arrow-from-left")) { $('#sideBarStatustext i').removeClass("fa-arrow-from-left").addClass("fa-arrow-from-right"); $('#bottomNavDiv').addClass("col-md-5"); } else { $('#sideBarStatustext i').removeClass("fa-arrow-from-right").addClass("fa-arrow-from-left"); $('#bottomNavDiv').removeClass("col-md-5"); } } function changeInfoToggleState() { if ($("#info-toggle").hasClass("glyphicon-chevron-right")) { $("#info-toggle").removeClass("glyphicon-chevron-right").addClass("glyphicon-chevron-left"); $("#info-toggle-btn").removeClass("glyphicon-chevron-right").addClass("glyphicon-chevron-left"); } else { $("#info-toggle").removeClass("glyphicon-chevron-left").addClass("glyphicon-chevron-right"); $("#info-toggle-btn").removeClass("glyphicon-chevron-left").addClass("glyphicon-chevron-right"); } } $("body").on("click", ".info-toggle-nav", function (e) { e.preventDefault(); if (!showinfo) { showinfo = !showinfo; $("#info-panel,#media-panel").addClass("showinfo"); $('body').addClass("display-info"); $("#media-panel").removeClass("col-md-12").addClass("col-md-7"); $("#info-panel").removeClass("col-md-0").addClass("col-md-5"); changeTextonBottomNav(); changeInfoToggleState(); //If audio check box is checked in edit seminar, collapse media container to just enough height to show controls #4388 if (IsAudioOnly == true) { settingForAudioOnly(); } else { if (seminar.Slides.length > 0) { if ($(toggleBtn1).hasClass("btn-success") || $(toggleBtn2).hasClass("btn-success") || $(toggleBtn3).hasClass("btn-success")) { if ($(toggleBtn3).hasClass("btn-success")) { toggleBtn3ToggleVideoSlide(); } else { $("#mediaView").removeClass("col-md-6").addClass("col-md-12"); $("#slideView").removeClass("col-md-6").addClass("col-md-12"); $("#slidescreen img").css("height", maxWidgetHeight); //alert("6."); } } else { $("#mediaView").removeClass("col-md-12").addClass("col-md-6"); $("#slideView").removeClass("col-md-12").addClass("col-md-6"); $("#slidescreen img").css("height", "auto"); //alert("7."); } } else { $("#mediaView").removeClass("col-md-6").addClass("col-md-12"); //alert("7a."); } } } if (!$(toggleBtn3).hasClass("btn-success")) { $(window).resize(); } if ($(toggleBtn3).hasClass("btn-success")) { setTimeout(function () { toggleBtn3ToggleVideoSlide(); }, 500); // Half second } toggleNavbarForSmallView(); }); $('#sideBarStatustext').click(function () { $('#info-toggle').trigger('click'); }); } //For Play demo view seminar if (IsDemoViewer) { getDemoViewSeminar(); } //For Text base viewer view seminar if (IsTextBasedViewer && !IsLayoutPreview) { getTextBasedInfo(); } //change font size in viewer transcript : Divyesh 24th Feb 2016 $("body").on("click", ".clsViewerTrascriptFontSize", function () { $("#divTranscript").css('font-size', $(this).attr("data-val")); }); $('#divTranscript').on("contextmenu", function (e) { return false; // disable right click }); $('#divTranscript').bind('cut copy paste', function (e) { e.preventDefault(); //disable cut,copy,paste }); if (detectIE()) { //IF IE then disable cut copy #4857 $('body').bind('cut copy', function (e) { e.preventDefault(); //disable cut,copy,paste }); } $(window).focus(function () { IsBrowserFocus = true; if (ATTENDANCE_REQUIREMENT) { ATTENDANCE_REQUIREMENT.IsBrowserFocus = true; } }); $(window).blur(function () { IsBrowserFocus = false; if (ATTENDANCE_REQUIREMENT) { ATTENDANCE_REQUIREMENT.IsBrowserFocus = false; } }); //takeOverConsole(); //getting BrowserInfo on viewer launch #9202 getBrowserInfo("Launch Viewer"); //onload viewer if ie8,ie9(all OS),safari<7.1(MAC os) show popup #9261 onLoadBrowserUpgradePopup(); onLoadBrowserShowFeedbackFeatures(); //#13253: InitilizeReloadVideoPopover(); InitilizeSideBarBtnPopover(); //#22112 BacktoClassroomScheduletab(); if (IsSnapshotPreview) { $('body').addClass('snapshotPreview'); } ManageNotes('GetItem'); if (!isImpersonateSession() && (ProgramRegistrantId && ProgramRegistrantId > 0)) { var activeTab = sessionStorage.getItem('Active_Viewer_Tab_' + ProgramRegistrantId); var activeTabElement = $("a[data-pagewidgetid=" + activeTab + "]"); if (activeTab && activeTabElement.length > 0) activeTabElement.trigger("click"); } SetCurrentVideoSlideView("default-view"); //#22227 if ($("a[data-href='ChatWidget']").length > 0) { UpdateChatUserOnlineStatus(1); //Online } UpdateActiveTabHighlightColor(); UpdateTabColorForUnauthViewer(); }); // #endregion document ready function refreshQuiz() { $('#quizAlertmodel').modal('hide'); var IsReloadIframe = $('#quizAlertmodel').find('#IsReloadIframe').val() if (IsReloadIframe == "true") { if (typeof (RefreshCert) == 'function') { RefreshCert(); } if (document.getElementsByClassName("mfp-iframe")[0] != null) { document.getElementsByClassName("mfp-iframe")[0].contentWindow.location.reload(); } } } function getDemoViewSeminar() { $.ajax({ type: 'GET', url: '/ShowtimeWidget/GetDemoViewSeminar', dataType: 'json', data: { 'SeminarId': s, 'TimeId': e, 'CustomerId': u }, success: function (data) { if (data != null && data.mediaClip != null) { demoMediaClip = data.mediaClip; demoSlides = data.SlidesList; demoStartTime = data.DemoStartTime != undefined && data.DemoStartTime != null ? data.DemoStartTime : 0; compositionCompleteForDemoVideo(); } else { alert('Video not configured yet, please try later.'); window.close(); } }, error: function (jqXHR, textStatus, errorThrown) { console.log("error: getting seminar"); } }); } //Email Certificate #Divyesh 19 Nov 2015 $("body").on('click', '.certificateEmail', function () { $.magnificPopup.open({ items: { src: $(this).attr("href") }, type: 'iframe', closeOnBgClick: false, mainClass: 'popCertificateEmail' }); return false; }); function closepopup() { $.magnificPopup.close(); } //If seminar is audio only function settingForAudioOnly() { if (seminar != undefined && seminar != null && seminar.IsAudioOnly == true) { IsAudioOnly = seminar.IsAudioOnly; //Change position of div if ($('.SlideWidget').prev().length > 0) { var slideWidget = $('.SlideWidget').clone(); $('.SlideWidget').remove(); $(slideWidget).insertBefore('.AudioVideoWidget'); } if (seminar.Slides.length > 0) { $('.SlideWidget').show(); } else { $('.SlideWidget').hide(); } $("#slideView").removeClass("col-md-6").addClass("col-md-12").css('margin-bottom', '10px'); $("#mediaView").removeClass("col-md-6").addClass("col-md-12"); //set slide height $("#slidescreen img").width('auto'); if ($(window).width() >= 992) { $("#slidescreen img").css("height", ($(window).height() - (251 + 47))); } else { $("#slidescreen img").css("height", "auto"); } //hide extra buttons $("#navbar-slide-btn").closest('li').hide(); $("#navbar-video-btn").closest('li').hide(); $("#navbar-video-resize-btn").closest('li').hide(); // $('#media-container').addClass('audioonly'); $('#parent_msg_panel').addClass('audioonly_Msg'); } disableRightClickForAudioStream(); } function loadCharacterCount() { // load char count $('.charcount').after(function () { if ($('#char' + $(this).attr('id')).length == 0) { return '
    ' + $(this).val().length + ' of ' + $(this).attr("data-val-maxlength-max") + ' characters maximum.
    '; } }).keyup(function () { if ($(this).val().length > $(this).attr("data-val-maxlength-max")) { $(this).val($(this).val().substring(0, $(this).attr("data-val-maxlength-max"))); } $('#char' + $(this).attr('id')).html($(this).val().length + ' of ' + $(this).attr("data-val-maxlength-max") + ' characters maximum.'); }); } (function () { var errrorLog = []; window.onerror = function (errorMsg, url, lineNumber, columnNumber, errorObject) { var arg = { message: errorMsg, url: url, line: lineNumber, column: columnNumber }; if (errorObject) { arg.stack = errorObject.stack; } var errorCount = 1; var errorLogObj = jQuery.grep(errrorLog, function (n, i) { return n.arg.message == arg.message && n.arg.line == arg.line; })[0]; if (errorLogObj != null && errorLogObj != undefined) { errorCount = errorLogObj.count + 1; } if (errorCount <= 10) { $.ajax({ type: 'POST', url: '/JavaScriptError/Log', data: { jsonString: JSON.stringify(arg) }, async: false, success: function (data) { if (errorLogObj != null && errorLogObj != undefined) { errrorLog[errrorLog.indexOf(errorLogObj)].count = errorCount; } else { errrorLog.push({ count: errorCount, arg: arg }); } consoleErrorList.push(arg); }, error: function (jqXHR, textStatus, errorThrown) { consoleErrorList.push(arg); } }); } }; })(); function isShowPopupAlert(element) { //21149: Issue: Quiz Pop Ups at End of Program Doesn't Work Sporadically var relativeTime = Math.ceil((curRelativeTime - curVidDelay) / 1000); //20116: Over the program popup if (element.ViewerPopupType == 2 && element.RelativeTime > 0 && Number(element.RelativeTime) == relativeTime) { return true; } //20116: Show upon Launch until Quiz Completed (Lunch within 30 mins to start the program) if (element.ViewerPopupType == 1) { var startTime, endTime = null; if (seminar.IsLive || seminar.IsReplay) { startTime = Number(-1800); endTime = 0; } if ((seminar.SeminarTypeId == 4 && relativeTime == 0) || relativeTime.between(startTime, endTime) || (element.IsRequired && relativeTime.between(0, seminar.PresenterDuration))) { return true; } } // 20116: Show as a popup after the program else if (element.ViewerPopupType == 3) { //mantis item #21326 - for video replay handled inside the function - isPopUpAlertAvailableToOpen() if (seminar.SeminarTypeId == 3) { return false; } var startDuration = seminar.PresenterDuration + 2; var endDuration = seminar.PresenterDuration + 7; if (seminar.SeminarTypeId == 3) { startDuration = seminar.PresenterDuration + 8; endDuration = startDuration + 5; } else if (seminar.SeminarTypeId == 4) { startDuration = seminar.PresenterDuration; } if (relativeTime.between(startDuration, endDuration)) { return true; } } return false; } //#region Show Popup Alerts var currentPopUpAlert = null; function checkPopUpAlerts(calledimmediatelyAfterProgramEnds, callBackFunction) { if (seminar.PopUpAlerts != null && seminar.PopUpAlerts.length > 0 && u != "-1" && (seminar.SeminarTypeId == 4 || seminar.SeminarTypeId == 3 || seminar.SeminarTypeId == 2)) { //10919 Quiz-Show Quiz as popup over the video - needs to work with Replays (#20116: need to work with webcast) //#20794: Quiz Pop-up Video Playing in Background Issue if (vidPlayer && currentPopUpAlert != null && seminar.SeminarTypeId == 4 && vidPlayer.getCurrentState() == "PLAYING") { vidPlayer.pause(); } jQuery.each(seminar.PopUpAlerts, function (index, element) { //mantis item #21326 var isShowRemainingPopupAlert = calledimmediatelyAfterProgramEnds ? true : isShowPopupAlert(element); if (isShowRemainingPopupAlert && element.IsCompleted == false) { if (currentPopUpAlert != element) { currentPopUpAlert = element; $.magnificPopup.close(); if (vidPlayer && vidPlayer.isFullscreen() === true) { vidPlayer.isFullscreen(false); } if (seminar.SeminarTypeId == 4) { vidPlayer.pause(); } //#0020217 var popupMethod = ""; if (element.EntityType == 1) popupMethod = "QuizPopUp"; else popupMethod = "EvaluationPopUp"; $.magnificPopup.open({ items: { src: '/ShowtimeWidget/' + popupMethod + '?entityId=' + element.EntityId + '&productId=' + s + '&customerId=' + u + '&eventTimeId=' + e + '&programRegistrantId=' + ProgramRegistrantId }, type: 'iframe', closeOnBgClick: false, enableEscapeKey: (element.IsRequired ? false : true), showCloseBtn: (element.IsRequired ? false : true), callbacks: { beforeOpen: function () { $('.segmentPoint').css('z-index', '-1'); }, close: function () { $('.segmentPoint').css('z-index', '9999'); if (seminar.SeminarTypeId == 4) { vidPlayer.play(); } if (currentPopUpAlert != null) { var indexCert = seminar.PopUpAlerts.indexOf(currentPopUpAlert); seminar.PopUpAlerts[indexCert].IsCompleted = true; currentPopUpAlert = null; if (typeof (RefreshCertificate) == "function") { RefreshCertificate(); } } //mantis item #21326 if (typeof (callBackFunction) === "function") { callBackFunction(); } } }, prependTo: $('#media-video'), //#0016052 mainClass: 'popCatalogCertification' }); } } }); } } //#end region //#region Show Viewer PopUp var currentViewerPopUp = null; function checkViewerPopUps() { if (seminar.ViewerPopUps != null && seminar.ViewerPopUps.length > 0) { jQuery.each(seminar.ViewerPopUps, function (index, element) { if (Number(element.RelativeTime) == Math.round((curRelativeTime - curVidDelay) / 1000)) { if (currentViewerPopUp != element) { currentViewerPopUp = element; $.magnificPopup.close(); $.magnificPopup.open({ items: { src: element.Url }, type: 'iframe', closeOnBgClick: false, enableEscapeKey: true, showCloseBtn: true, callbacks: { close: function () { currentViewerPopUp = null; } }, mainClass: 'popViewerProduct' }); } } }); } } //#end region //#region Show Polling Questions var currentPolling = null, currentPollingTimeOut = null; function showPopUpPollingQuestion() { if (seminar.PopUpPollingQuestions != null && seminar.PopUpPollingQuestions.length > 0 && u != "-1") { jQuery.each(seminar.PopUpPollingQuestions, function (index, element) { if (currentPopUpAlert == null) { if (seminar.SeminarTypeId != 4 && (Number(element.AutoDisplayTime) == Math.round((curRelativeTime - curVidDelay) / 1000) || (Number(element.AutoDisplayTime) >= Math.round((curRelativeTime - curVidDelay) / 1000) && seminar.SeminarTypeId == 2)) && Number(element.AutoDisplayTime) > 0) { currentPolling = element; showPollingPopUp(element); } else if (seminar.SeminarTypeId == 4 && (element.IsAnswered || false) === false && Number(element.AutoDisplayTime) == Math.round((curRelativeTime - curVidDelay) / 1000) && Number(element.AutoDisplayTime) > 0) { currentPolling = element; showPollingPopUp(element); } } }); } } function showPollingPopUp(element) { $.magnificPopup.close(); $.magnificPopup.open({ items: { src: "/ShowtimeWidget/ShowPollingQuestion?parentTenantId=" + pt + "&EntityId=" + element.PollQuestionId + "&ProgramRegistrantId=" + ProgramRegistrantId }, type: 'iframe', closeOnBgClick: false, callbacks: { open: function () { $(".segmentPoint").css({ "z-index": "0" }); }, close: function () { $(".segmentPoint").css({ "z-index": "9999" }); }, afterClose: function () { $.getJSON('/showtimewidget/ispollquestionanswerdbycustomer?pollQuestionId=' + element.PollQuestionId + '&programRegistrantId=' + ProgramRegistrantId, function (result) { element.IsAnswered = (result || false); }); //showPopUpPollingResult(); } }, mainClass: 'popPollingQuestion' }); if (element.DisplayResultTime > 0) { if (currentPollingTimeOut) { clearTimeout(currentPollingTimeOut); } currentPollingTimeOut = setTimeout(function () { displayPollQuestionResult(element.PollQuestionId, element.DoNotDisplayPollResults); }, (element.DisplayResultTime * 60 * 1000)) } } function displayPollQuestionResult(pollQuestionId, doNotDisplayPollResults) { $.magnificPopup.close(); getPollingResult(); currentPolling = null; if (doNotDisplayPollResults === false) { showPollResultByQuestion(pollQuestionId, seminar.PollingId); } } function closePollingPopUp() { $.magnificPopup.close(); } function getPollingResult() { if (seminar != undefined && seminar != null) { $("#grid-poll-result-list").load("/ShowtimeWidget/GetPollingResults?parentTenantId=" + pt + "&PollingId=" + seminar.PollingId + "&ProductId=" + ps + "&TimeId=" + pe, function () { }); } } function showPollResultByQuestion(questionId, pollId) { $.magnificPopup.open({ items: { src: "/ShowtimeWidget/ShowPollResult?id=" + pollId + "&parentTenantId=" + pt + "&questionId=" + questionId }, type: 'iframe', closeOnBgClick: false, callbacks: { open: function () { $(".segmentPoint").css({ "z-index": "0" }); }, close: function () { $(".segmentPoint").css({ "z-index": "9999" }); }, afterClose: function () { } }, mainClass: 'popPollResult' }); } //#end region //#region show cert alert icon before 5 minutes in credit tab http://mantis.ce21.com/view.php?id=4861 var isDisplayedCertIcon = false; function checkCertAlertIcon() { if (seminar != null && seminar.CertAlertDisplayTime > 0 && isDisplayedCertIcon == false) { //Get current relative time var relativeTime = Math.round((curRelativeTime - curVidDelay) / 1000); var endTime = seminar.CertAlertDisplayTime + 300; //if not equal to ondemand then and relative time greater than certficate time if (relativeTime > seminar.CertAlertDisplayTime && relativeTime < endTime && seminar.SeminarTypeId != 4 && !seminar.IsArchive) { showCertAlertIcon(); } else if (seminar.SeminarTypeId == 4 && relativeTime < endTime && relativeTime > seminar.CertAlertDisplayTime && seminar.CertAlertDisplayTime >= seminar.MaxRelativeTime) { showCertAlertIcon(); } } } function showCertAlertIcon() { if ($('a[data-href="CertificationWidget"]').length > 0) { $('a[data-href="CertificationWidget"]').append(''); isDisplayedCertIcon = true; } } function hideCertAlertIcon() { $('.certAlertIcon').remove(); } //#end region String.prototype.toHHMMSS = function () { var sec_num = parseInt(this, 10); // don't forget the second param var hours = Math.floor(sec_num / 3600); var minutes = Math.floor((sec_num - (hours * 3600)) / 60); var seconds = sec_num - (hours * 3600) - (minutes * 60); if (hours < 10) { hours = "0" + hours; } if (minutes < 10) { minutes = "0" + minutes; } if (seconds < 10) { seconds = "0" + seconds; } var time = ''; if (hours > 0) { time = hours + ':' + minutes + ':' + seconds; } else { time = minutes + ':' + seconds; } return time; } String.prototype.toDDHHMM = function () { var sec_num = parseInt(this, 10), // don't forget the second param hours = Math.floor(sec_num / 3600), days = Math.floor(hours / 24), minutes = Math.floor((sec_num - (hours * 3600)) / 60), seconds = sec_num - (hours * 3600) - (minutes * 60); var time = ''; if (days > 0) { hours = Math.floor(hours - (days * 24)), time = days + ' day(s) ' + hours + ' hr ' + minutes + ' min'; } else { time = hours + ' hr ' + minutes + ' min ' + seconds + ' secs'; } return time; } function detectIE() { var ua = window.navigator.userAgent; // Test values; Uncomment to check result … // IE 10 // ua = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)'; // IE 11 // ua = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko'; // IE 12 / Spartan // ua = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0'; // Edge (IE 12+) // ua = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Safari/537.36 Edge/13.10586'; var msie = ua.indexOf('MSIE '); if (msie > 0) { // IE 10 or older => return version number return true; //return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10); } var trident = ua.indexOf('Trident/'); if (trident > 0) { // IE 11 => return version number var rv = ua.indexOf('rv:'); return true; //return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10); } var edge = ua.indexOf('Edge/'); if (edge > 0) { // Edge (IE 12+) => return version number return true; //return parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10); } // other browser return false; } $('body').on("click", "#btnSaveBrowserInformation", function () { var element = $(this); //if (typeof (browserReport) == "function") { // $(element).html('  Processing...').prop('disabled', true); // browserReport(function (err, report) { // if (err) { // throw err; // } // report.consoleErrorList = consoleErrorList; // report.jwplayerProcess = vidPlayerProcess; // $.ajax({ // type: 'POST', // url: '/ShowtimeWidget/SubmitBrowser', // dataType: 'json', // data: { // 'programRegistrantId': ProgramRegistrantId, 'settings': JSON.stringify(report) // }, // success: function (tweets) { // $(element).html('Submit My Browser Info').prop('disabled', false); // alert('Browser info submitted successfully.') // }, // error: function (jqXHR, textStatus, errorThrown) { // $(element).html('Submit My Browser Info').prop('disabled', false); // } // }); // }); //} getBrowserInfo("Submit Browser", element); }); //#region Forum Widget $('body').on("click", ".btnPostProductForum", function () { //$("#divProgress").show(); var element = $(this); var productForumId = element.attr('data-ProductForumId'); var parentProductForumId = element.attr('data-ParentProductForumId'); var ForumWidgetPostId = '.ForumWidgetPost' + parentProductForumId; var CommentBoxId = '#txtProductForumComment' + parentProductForumId; var editProductForumId = element.attr('data-editproductforumid'); var forumWidgetMain = $(element).closest('.ForumWidgetMain'); var forumSettingId = element.attr('data-forumSettingId'); var forumSettingType = element.attr('data-forumSettingType'); if (editProductForumId != null && editProductForumId != undefined && editProductForumId != '') { productForumId = editProductForumId; ForumWidgetPostId = '.ForumWidgetPost' + editProductForumId; } var isDisplayAllComment = false; var attachedLink = ''; var postMessage = ''; if (element.attr('data-comment') == "0") {//0 To create a post Post if ($('#txtForumWidgetPost').val() != '') { postMessage = $('#txtForumWidgetPost').val(); element.prop('disabled', true).html(""); if ($(forumWidgetMain).find('.embedLinkDetail').find('.hdnLink').length > 0) { attachedLink = $(forumWidgetMain).find('.embedLinkDetail').find('.hdnLink').val(); } } else { $('#txtForumWidgetPost').focus(); $("#divProgress").hide(); return; } } else//To create a comment { if ($(CommentBoxId).val() != '') { postMessage = $(CommentBoxId).val(); element.prop('disabled', true).html(""); isDisplayAllComment = $(forumWidgetMain).find(".ForumWidgetPost" + parentProductForumId).attr("data-Expanded") == "false" ? false : true; } else { $(CommentBoxId).focus(); $("#divProgress").hide(); return; } } var frm = new FormData(); frm.append("SeminarId", forumSettingType === 'Product' ? ps : s);//manits item : #14531 frm.append("TimeId", forumSettingType === 'Product' ? pe : e); frm.append("CustomerId", u); frm.append("PostMessage", postMessage); frm.append("ProductForumId", productForumId); frm.append("ParentForumId", parentProductForumId); frm.append("forumSettingId", forumSettingId); frm.append("forumSettingType", forumSettingType); frm.append("attachedLink", attachedLink); // File upload :#8939 if ($(forumWidgetMain).find(".uploadImage").length > 0) { var file = $(forumWidgetMain).find(".uploadImage").get(0).files; if (file.length > 0) { frm.append("PostedFile", file[0]); } } $.ajax({ type: 'POST', url: '/showtimewidget/forumwidgetpost', dataType: 'json', global: false, processData: false, contentType: false, data: frm, // { // 'SeminarId': ps, 'TimeId': pe, 'CustomerId': u, 'PostMessage': postMessage, 'ProductForumId': productForumId, 'ParentForumId': parentProductForumId, 'forumSettingId': forumSettingId, 'forumSettingType': forumSettingType //}, success: function (Data) { if (element.attr('data-comment') == "0") { parentProductForumId = Data; removepostedFile(forumWidgetMain); var url = "/showtimewidget/forumwidgetsingle?ParentForumId=" + Data + "&forumSettingId=" + forumSettingId; $('#txtForumWidgetPost').val(''); $(forumWidgetMain).find('.postcom').trigger('keydown'); $('#divAppendPost').load(url, function () { element.prop('disabled', false).html("Post"); var newPost = $('#divAppendPost').html(); $('#divAppendPost').children().remove(); $('.ForumWidget').children(ForumWidgetPostId).remove(); $('.ForumWidget').prepend(newPost); $("#divProgress").hide(); editProductForumId = ''; element.removeAttr('data-editproductforumid'); }); if ($(forumWidgetMain).find(".embedLinkDetail").length > 0) { $(forumWidgetMain).find(".embedLinkDetail").remove(); } } else { url = "/showtimewidget/forumwidgetsingle?ParentForumId=" + parentProductForumId + "&forumSettingId=" + forumSettingId + "&isDisplayAllComments=" + isDisplayAllComment; //$(ForumWidgetPostId).load(url, function () { // element.prop('disabled', false); // $('#divProductForumComment' + productForumId).hide(); // $("#divProgress").hide(); //}); $.get(url, function (data) { var newHtml = $(data).filter(ForumWidgetPostId); //$(forumWidgetMain).find(ForumWidgetPostId).replaceWith(newHtml); $(forumWidgetMain).find(ForumWidgetPostId).find('.viewcomment').replaceWith($(newHtml).find('.viewcomment')); $(forumWidgetMain).find(ForumWidgetPostId).find('.socialPost').replaceWith($(newHtml).find('.socialPost')); $(forumWidgetMain).find('#divProductForumComment' + productForumId).hide(); $("#divProgress").hide(); }) } sendForumData("newforum", forumSettingId, parentProductForumId); }, error: function (jqXHR, textStatus, errorThrown) { element.prop('disabled', false).html("Post"); $("#divProgress").hide(); //$(element).html('Submit My Browser Info').prop('disabled', false); } }); }); $('body').on("click", ".aProductFourmWidgetSetting", function () { var element = $(this); var productForumId = element.attr('data-ProductForumId'); var parentForumId = element.attr('data-parentforumid'); var ProductWidgetForumSettingId = element.attr('data-val'); var ProductForumSettingId = element.attr('data-ProductForumSettingId'); var forumSettingId = $(element).closest('.ForumWidgetMain').attr('data-forumSettingId'); var forumSettingType = $(element).closest('.ForumWidgetMain').attr('data-forumSettingType'); var isDisplayAllComment = false; isDisplayAllComment = $(element).closest('.divForumWidgetPost').attr("data-Expanded") == "false" ? false : true; if (ProductWidgetForumSettingId == 2 || ProductWidgetForumSettingId == 3) { if (!confirm('Are you sure you wants to hide?')) { $("#divProgress").hide(); return false; } } // $("#divProgress").show(); if (productForumId != null && productForumId != undefined && productForumId != '') { $.ajax({ type: 'POST', url: '/ShowtimeWidget/ProductForumSettingWidget', dataType: 'json', global: false, data: { 'ProductForumId': productForumId, 'ForumSettingWidgetId': ProductWidgetForumSettingId, 'ProductForumSettingId': ProductForumSettingId, 'forumSettingId': forumSettingId, 'forumSettingType': forumSettingType }, success: function (Data) { if (ProductWidgetForumSettingId == 2 || ProductWidgetForumSettingId == 3)//2 : Hide this Post,3: Hide Future post from this user { if (ProductWidgetForumSettingId == 3) { var HiddenPost = Data.split(','); for (var i in HiddenPost) { var child = '.ForumWidgetPost' + HiddenPost[i]; $('.ForumWidget').children(child).remove(); } } else { var child = '.ForumWidgetPost' + productForumId $('.ForumWidget').children(child).remove(); $("#divProgress").hide(); } } else if (ProductWidgetForumSettingId == 4)//4 : Mark as Spam { var child = '.ForumWidgetPost' + productForumId $('.ForumWidget').children(child).remove(); $("#divProgress").hide(); } else if (ProductWidgetForumSettingId == 1)//1 : Like { if (ProductForumSettingId == Data) { element.html(" Like"); element.removeAttr('data-productforumsettingid'); element.attr('data-productforumsettingid', '0'); } else { element.text(" Unlike"); element.html(" Unlike"); element.removeAttr('data-productforumsettingid'); element.attr('data-productforumsettingid', Data) } // as per mantis task #7843 if (element.hasClass("childProductFourmWidgetSetting")) { productForumId = element.attr("data-parentForumId"); } var updatedDiv = ".ForumWidgetPost" + productForumId; url = "/showtimewidget/forumwidgetsingle?ParentForumId=" + productForumId + "&forumSettingId=" + forumSettingId + "&isDisplayAllComments=" + isDisplayAllComment; $.get(url, function (result) { // $(updatedDiv).html($(result).filter(updatedDiv).html()); $(updatedDiv).find('.viewcomment').replaceWith($(result).filter(updatedDiv).find('.viewcomment')); $(updatedDiv).find('.socialPost').replaceWith($(result).filter(updatedDiv).find('.socialPost')); sendForumData("newforum", forumSettingId, productForumId); }); } else if (ProductWidgetForumSettingId == 11 || ProductWidgetForumSettingId == 12) { // Speaker Moderator publish/Not Publish var forumId = parentForumId && parentForumId > 0 ? parentForumId : productForumId; var updatedDiv = ".ForumWidgetPost" + forumId; url = "/showtimewidget/forumwidgetsingle?ParentForumId=" + forumId + "&forumSettingId=" + forumSettingId + "&isDisplayAllComments=" + isDisplayAllComment; $.get(url, function (result) { $(updatedDiv).html($(result).filter(updatedDiv).html()); sendForumData("newforum", forumSettingId, forumId); }); } else if (ProductWidgetForumSettingId == 13) { // Speaker Moderator Mark As Spam var updatedDiv = ".ForumWidgetPost" + productForumId; sendForumData("newforum", forumSettingId, productForumId); $(updatedDiv).remove(); } }, error: function (jqXHR, textStatus, errorThrown) { $("#divProgress").hide(); alert('Something went wrong!! please try again.') } }); } }); $('body').on("click", ".ProductForumEditDelete", function () { var element = $(this); var productForumId = element.attr('data-ProductForumId'); var content = element.attr('data-post'); if (content && content.includes('')) { var message = $("").html(content).text(); } else { var message = element.attr('data-post'); } var editDelete = element.attr('data-val'); var forumWidgetMain = $(element).closest('.ForumWidgetMain'); var forumSettingId = $(forumWidgetMain).attr('data-forumsettingid'); if (editDelete == 'D') { if (confirm('Are you sure you want to delete this post?')) { $.ajax({ type: 'POST', url: '/ShowtimeWidget/DeleteForumPost', dataType: 'json', data: { 'ProductForumId': productForumId }, success: function (Data) { if (Data == productForumId) { var child = '.ForumWidgetPost' + Data $('.ForumWidget').children(child).remove(); $("#divProgress").hide(); sendForumData("deleteforumData", forumSettingId, productForumId); } else { //alert(Data); $("#divProgress").hide(); } }, error: function (jqXHR, textStatus, errorThrown) { $("#divProgress").hide(); alert('Something went wrong!! please try again.') //$(element).html('Submit My Browser Info').prop('disabled', false); } }); } } else if (editDelete == 'E') { if (message != null && message != undefined && message != '') { $('#txtForumWidgetPost').val(message); $('#btnPostProductForum').attr('data-editproductforumid', productForumId); $('#txtForumWidgetPost').focus(); if ($(forumWidgetMain).find('#txtForumWidgetPost').val() != "") { autosize($(forumWidgetMain).find('#txtForumWidgetPost')); } } } }); var forumWidgetTimeout; var lastForumSyncTime; function iniForumWidget() { isForumWidgetLoad = true; CE21Forum.connectAll(); setForumPostsRelativeTimer(); } function getProductForums() { $('.ForumWidgetMain').each(function () { var forumWidgetMain = $(this); lastForumSyncTime = $(this).find('.hdnDatetimeUtcNow').val(); var forumSettingId = $(this).attr('data-forumSettingId'); var forumSettingType = $(this).attr('data-forumSettingType'); if (lastForumSyncTime > 0) { $.ajax({ type: 'POST', url: '/ShowtimeWidget/ProductForumGetAllByTime', data: { 'timeId': pe, 'CustomerId': u, 'LastSyncTime': lastForumSyncTime, 'forumSettingId': forumSettingId, 'forumSettingType': forumSettingType }, global: false, async: false, success: function (Data) { if (Data != null) { var currentDate = $(Data).filter('.hdnDatetimeUtcNow').val(); var productForumIdsToRemove = $(Data).filter('.hdnProductForumIdsToRemove').val().split(','); //Data.ProductForumIdsToRemove.split(','); $(forumWidgetMain).find('.hdnDatetimeUtcNow').val(currentDate); var forumIds = $(Data).filter('.divForumWidgetPost').map(function () { return Number($(this).attr('data-ProductForumId')) }).get(); if (forumIds != null && forumIds.length > 0) { // find its own post forumIds var LoggingUserforumIds = $(Data).filter('.divForumWidgetPost').map(function (a, b) { if (u == $(this).attr("data-postCustomerId")) { return Number($(this).attr('data-ProductForumId')); } }).get(); var forumCommentMsgTimeOut; $.each(forumIds, function (index, forumId) { var child = '.ForumWidgetPost' + forumId; var newDiv = $(Data).filter(child) var commentBox = '#txtProductForumComment' + forumId; var currentText = $(commentBox).val(); // display alert when another user has replied to a Post that they CREATED. if (provideViewerAlert && LoggingUserforumIds.indexOf(forumId) != -1) { var lastComment = newDiv.find('.viewcomment .singlereply[data-replyId]:last'); var lastCommentUserName = lastComment.find('div.media-body p strong').text(); var lastcommentUserId = $(lastComment).attr("data-commentedCustomerId"); if (lastCommentUserName != "" && lastCommentUserName != undefined && u != lastcommentUserId) { // for exclude own comments if ($(forumWidgetMain).find('.ForumWidget').children(child).find('.viewcomment .singlereply[data-replyId=' + lastComment.attr('data-replyid') + ']').length == 0) { $("#Forummsg_panel").html("
    " + lastCommentUserName + " has responded to your forum post!
    ").show(); // clear old timeout and add new one if (forumCommentMsgTimeOut) { clearTimeout(forumCommentMsgTimeOut); } forumCommentMsgTimeOut = setTimeout(function () { $("#Forummsg_panel").empty().hide(); }, 10 * 1000); } } } var currentDiv = $('.ForumWidget').children(child).html(); if (currentDiv != '' && currentDiv != null && currentDiv != undefined) { var commentsExpanded = $(forumWidgetMain).find('.ForumWidget').children(child).attr('data-Expanded') == "true"; // $(forumWidgetMain).find('.ForumWidget').children(child).replaceWith(newDiv); //459: Forums - don't refresh comments area - just append to the bottom with Javascript start //$(forumWidgetMain).find('.ForumWidget').children(child).find('.viewcomment').replaceWith($(newDiv).find('.viewcomment')); $(forumWidgetMain).find('.ForumWidget').children(child).find('.socialPost').replaceWith($(newDiv).find('.socialPost')); //if (commentsExpanded) { // $(forumWidgetMain).find('.ForumWidget').children(child).find('.clsExpandAllComment').click(); //} if ($(forumWidgetMain).find('.ForumWidget').children(child).find('.viewcomment .singlereply[data-replyId]').length > 0) { $(newDiv).find('.viewcomment .singlereply[data-replyId]').each(function (i, e) { if ($(forumWidgetMain).find('.ForumWidget').children(child).find('.viewcomment .singlereply[data-replyId=' + $(e).attr('data-replyid') + ']').length == 0) { $(forumWidgetMain).find('.ForumWidget').children(child).find('.viewcomment .singlereply[data-replyId]').last().after($(newDiv).find('.viewcomment .singlereply[data-replyId=' + $(e).attr('data-replyid') + ']')) } }); var cntComment = $(forumWidgetMain).find('.ForumWidget').children(child).find('.viewcomment .singlereply[data-replyId]').length; if (cntComment > 1) { $(forumWidgetMain).find('.ForumWidget').children(child).find('.clsPreviousCommentLink').show(); } } else { $(forumWidgetMain).find('.ForumWidget').children(child).find('.viewcomment').replaceWith($(newDiv).find('.viewcomment')); } // hide other comments if (!commentsExpanded && $(forumWidgetMain).find('.ForumWidget').children(child).find('.divNewComments .singlereply[data-replyid]').length > 1) { $(forumWidgetMain).find('.ForumWidget').children(child).find('.divNewComments .singlereply[data-replyid]').not(':last').hide(); } //459: Forums - don't refresh comments area - just append to the bottom with Javascript End } else { $(forumWidgetMain).find('.ForumWidget').prepend(newDiv); } $(commentBox).val(currentText); if (currentText != '' && currentText != null && currentText != undefined) { $('#divProductForumComment' + forumId).show(); $(commentBox).focus(); } }); } if (productForumIdsToRemove != null && productForumIdsToRemove.length > 0)//Remove deleted or rejected product forums { $.each(productForumIdsToRemove, function (index, productForumId) { var child = '.ForumWidgetPost' + productForumId; $('.ForumWidget').children(child).remove(); }); } $("#divProgress").hide(); } }, error: function (jqXHR, textStatus, errorThrown) { $("#divProgress").hide(); //$(element).html('Submit My Browser Info').prop('disabled', false); } }); } }); //// if (!$("#ForumWidget").is(":visible")) { // updateForumCount(); //// } } //// update forum Counts //function updateForumCount() { // var lastForumcountSyncTime = $("#hfforumLastSyncDateTime").val(); // //localStorage.getItem('ForumSynchTime_' + forumSettingId); // $.ajax({ // type: 'POST', // url: '/ShowtimeWidget/IntegratedProductForumCountGetAllByTime', // data: { // 'CustomerId': u, 'LastSyncTime': lastForumcountSyncTime, 'forumSettingId': forumSettingId, 'onlyPostCount': false, // 'timeId':pe // }, // success: function (Data) { // if (Data != undefined && Data != null) { // $(".baseForumWidget").text(Data); // } // } // }); //} function showCommentBox(element) { var productForumId = $(element).attr('data-val'); $('#divProductForumComment' + productForumId).show(); $('#txtProductForumComment' + productForumId).focus(); } //#endregion Forum Widget End var consoleErrorList = []; function takeOverConsole() { var console = window.console if (!console) return function intercept(method) { var original = console[method] console[method] = function () { // do sneaky stuff if (original.apply) { // Do this for normal browsers original.apply(console, arguments); consoleErrorList.push(arguments); } else { // Do this for IE var message = Array.prototype.slice.apply(arguments).join(' ') original(message) } } } var methods = ['error'] for (var i = 0; i < methods.length; i++) intercept(methods[i]) } //New Support Ticket Pop up $('body').on('click', '.supportTicketPopUp', function () { $.magnificPopup.open({ items: { src: '/CreateSupportTicket?isViewer=true' }, type: 'iframe', closeOnBgClick: false, mainClass: 'popCreateSupportTicket' }); return false; }); //Pre Ans Post Popup var currentPrePostPopup = null; var savePrepostPopupComplete = function () { if (!currentPrePostPopup) { return; } currentPrePostPopup.IsComplete = true; //Save in local storage if (typeof (localStorage) != "undefined") { var key = 'PopUp' + currentPrePostPopup.PopUpType + '-' + ProgramRegistrantId + '-' + e; localStorage.setItem(key, 'true'); } } var checkPrepostPopupComplete = function (popupType) { var key = 'PopUp' + popupType + '-' + ProgramRegistrantId + '-' + e; return typeof (localStorage) != "undefined" && (localStorage.getItem(key) || 'false') == 'true'; } function checkPrePostPopUp() { if (seminar.PrePostPopUp != null && seminar.PrePostPopUp.length > 0) { //Round Relative time var relativeTime = Math.round((curRelativeTime - curVidDelay) / 1000); var startTime = null; var endTime = null; var alreadyDisplayed = false; jQuery.each(seminar.PrePostPopUp, function (index, p) { //Check from storage based on popup type. alreadyDisplayed = checkPrepostPopupComplete(p.PopUpType); // Allow pre popup before seminar start 11091: Catalog > Products > Edit Product - Pre Seminar PopUp Adjustments if (p.PopUpType == "PrePopup" && (seminar.IsLive || seminar.IsReplay)) { startTime = p.PopupDisplayTime == 0 ? -5 : p.PopupDisplayTime; endTime = 0; } else { startTime = p.PopupDisplayTime; endTime = p.PopupDisplayTime + 5; } if (!alreadyDisplayed && !p.IsComplete && currentPrePostPopup != p && relativeTime.between(startTime, endTime)) { currentPrePostPopup = p; prePostRequirement(); } }); } } function prePostRequirement() { if (currentPrePostPopup != null) { vidPlayer.pause(); $.magnificPopup.close(); if (vidPlayer.isFullscreen()) { vidPlayer.isFullscreen(false); } $("#lblPrePostTitle").html(currentPrePostPopup.PopupTitle); $("#lblPrePostBody").html(currentPrePostPopup.PopupBody); $("#btnPrePost").html(currentPrePostPopup.PopupButtonText); $(".clsPrePostPopUp").show(); $.magnificPopup.open({ items: { src: '#prePostPopUp' }, type: 'inline', closeOnBgClick: false, enableEscapeKey: false, showCloseBtn: false, beforeOpen: function () { vidPlayer.pause(); }, callbacks: { afterClose: function () { savePrepostPopupComplete(); vidPlayer.play(); } } }); if (currentPrePostPopup.PopupHeight != null && currentPrePostPopup.PopupHeight != undefined && currentPrePostPopup.PopupHeight != "") { $('.mfp-content').css('height', currentPrePostPopup.PopupHeight); $('.mfp-content > .white-popup').css('min-height', currentPrePostPopup.PopupHeight + 'px'); } else { $('.mfp-content').css('height', 500); $('.mfp-content > .white-popup').css('min-height', '500px'); } if (currentPrePostPopup.PopupWidth != null && currentPrePostPopup.PopupWidth != undefined && currentPrePostPopup.PopupWidth != "") { $('.mfp-content').css('width', currentPrePostPopup.PopupWidth); $('.mfp-content > .white-popup').css('min-width', currentPrePostPopup.PopupWidth + 'px'); } else { $('.mfp-content').css('width', 700); $('.mfp-content > .white-popup').css('min-width', '700px'); } } } function toggleBtn3ToggleVideoSlide() { if ($(toggleBtn3).closest('li').hasClass('active')) { $("#slideView").removeClass("col-md-6").addClass("col-md-12"); $("#mediaView").removeClass("col-md-6").addClass("col-md-12"); $('#media-panel').addClass('PIPR'); $("#media-panel #mainView .row").css("max-width", ""); addPIPMsgPanel(); //var mediaHeight = (maxWidgetHeight / 2); //var slideHeight = (maxWidgetHeight / 2); //var alertHeight = 0; //if (!alertEmpty()) { // alertHeight = 100; // mediaHeight -= (alertHeight / 2); // slideHeight -= (alertHeight / 2); //} //$("#main-panel").css("height", mediaHeight).addClass("container-fluid"); //$("#slidescreen img").css("height", mediaHeight).addClass("container-fluid"); if ($("#media-panel").hasClass("col-md-5") && $("#info-panel").hasClass("col-md-7")) { $("#media-panel").addClass("info-fullscreen"); $("#media-container,#slidescreen").removeClass("container-fluid"); } else { $("#media-panel").removeClass("info-fullscreen"); if ($(toggleBtnState).hasClass("glyphicon-chevron-right")) { if (seminar.AspectRatio == "4:3") { $("#mediaView").css("height", ((maxWidgetHeight / 2))); $("#media-container").css("width", "90%").addClass("container-fluid"); $("#slidescreen").addClass("container-fluid");//.css("width", "45%"); $("#main-panel").css("width", ""); $("#main-panel").css("width", "45%"); } else { $("#mediaView").css("height", ((maxWidgetHeight / 2)) + 20); $("#main-panel").css("width", ""); //$("#main-panel").css("width", "52%"); $("#media-container").css("width", "100%").addClass("container-fluid"); $("#slidescreen").css("width", "50%").addClass("container-fluid"); $("#slidescreen").css("width", "auto"); } } else { if (seminar.AspectRatio == "4:3") { $("#main-panel").css("width", ""); $("#main-panel").css("width", "30%"); $("#media-container").css("width", "90%").addClass("container-fluid"); $("#slidescreen").css("width", "30%").addClass("container-fluid"); $("#slidescreen").css("width", "auto"); } else { $("#mediaView").css("height", ((maxWidgetHeight / 2)) + 20); $("#main-panel").css("width", ""); //$("#main-panel").css("width", "34.599%"); $("#media-container").css("width", "100%").addClass("container-fluid"); $("#slidescreen").css("width", "35%").addClass("container-fluid"); $("#slidescreen").css("width", "auto"); } } } console.log($("#main-panel").height()); //$("#mediaView").css("height", $("#main-panel").height() + 10); //$("#slidescreen img").css('height', (maxWidgetHeight - $("#mediaView").height())); } adjustPartcipationCode(); } function anyResizeMethodActive() { return ($(toggleBtn3).closest('li').hasClass('active') || $(toggleBtn2).closest('li').hasClass('active') || $(toggleBtn1).closest('li').hasClass('active')); } $('body').on('click', '.pipvideominexp', function () { $('#mediaView').toggleClass('minimize'); $('.pipvideominexp').attr('title', ($('#mediaView').hasClass('minimize') ? "Expand Picture-in-Picture (PIP)" : "Minimize Picture-in-Picture (PIP)")); }) $('body').on('click', '.pipslideminexp', function () { $('#slideView').toggleClass('minimize'); $('.pipslideminexp').attr('title', ($('#slideView').hasClass('minimize') ? "Expand Picture-in-Picture (PIP)" : "Minimize Picture-in-Picture (PIP)")); }) function defaultView(forcefully) { if (!anyResizeMethodActive() || forcefully) { //If want active then //For SLide $("#slideView").removeClass("PIPSlide"); $("#slideView").css("height", ""); $("#slideView").showIfNotVisible(); $('#slidescreen').css({ 'float': '', 'width': 'auto' }); $("#slideView").css("bottom", "").css("right", "").css("left", "").css("top", ""); $('#media-panel').removeClass('PIPS'); $('#slideView').removeClass('PIPSlide').removeClass('pip-small').removeClass('pip-medium').removeClass('pip-large'); $('#divPIPClose').remove(); if ($('#slideView').hasClass('ui-draggable')) { $('#slideView').draggable('destroy'); } //Video $("#mediaView").removeClass("PIPVideo"); $("#mediaView").css("bottom", "").css("right", "").css("left", "").css("top", ""); $("#mediaView").css("height", ""); $("#mediaView").showIfNotVisible(); $('#media-panel').removeClass('PIPV'); $('#mediaView').removeClass('PIPVideo').removeClass('pip-small').removeClass('pip-medium').removeClass('pip-large'); $('#divVideoPIPClose').remove(); if ($('#mediaView').hasClass('ui-draggable')) { $('#mediaView').draggable('destroy'); } $("#media-container_wrapper,div#media-container").css({ "height": "" }, { "opacity": "" }).removeClass('hideVideo'); $("#main-panel").removeClass('hideVideo').css("display", ""); $("#playlist_panel").css({ "height": "" }, { "opacity": "" }); //Remove $("#slideView").removeClass("col-md-12").addClass("col-md-6"); $("#mediaView").removeClass("col-md-12").addClass("col-md-6"); $("#mediaView").css("height", ""); $("#main-panel").css("width", ""); $("#main-panel").css("width", "auto"); $("#media-container").css("width", "").removeClass("container-fluid"); $("#media-container").css("width", "auto"); $("#slidescreen").css("width", "").css("display", ""); $("#slidescreen").css("width", "auto").removeClass("container-fluid"); $('#media-panel').removeClass('PIPR'); $("#slidescreen img").css('height', "auto"); } } function SlideWidgetPIP() { if ($(toggleBtn1).closest('li').hasClass('active')) { //If want active then $("#slideView").removeClass('col-md-6').addClass('col-md-12'); $("#mediaView").removeClass("col-md-6").addClass("col-md-12"); $("#media-panel #mainView .row").css("max-width", ""); if ($("#divPIPClose").length == 0) { var divOtherTool = '
    '; divOtherTool += '
    '; //For small button divOtherTool += '
    '; //For medium button divOtherTool += '
    '; //For lasrge button divOtherTool += '
    '; var divDragIcon = '
    D
    '; var divClose = "
    " var divTopBar = "
    " + divOtherTool + " " + divDragIcon + " " + divClose + "
    " $("#slideView #slidescreen").prepend(divTopBar); } $("#slideView").addClass('PIPSlide'); $("#slideView").css("bottom", getBottomOffset('#media-container') + 40); console.log('Test' + getBottomOffset('#media-container') + 40) $("#slideView").css("right", getRightOffset('#media-container') + 50); $('#media-panel').addClass('PIPS'); $('#slidescreen').css({ 'float': 'left', 'width': '100%' }); $("#slideView").css("height", $('#slidescreen').outerHeight()); //Update width of close pip $("#divPIPClose").css("width", $('#slideView').width()); setDragIconWidth(); //Set Default - Medium if (!$('#slideView').hasClass('pip-small') && !$('#slideView').hasClass('pip-medium') && !$('#slideView').hasClass('pip-large')) { $('.pip-tools .pip-medium').addClass('active'); $('#slideView').addClass('pip-medium'); } if (!$('#slideView').hasClass('ui-draggable')) { defaultPIPOverided = false; $('#slideView').draggable({ containment: "#media-container", scroll: false, opacity: 0.85, handle: ".pipdrag", stop: function (event, ui) { defaultPIPOverided = true; calculatePIPOffsetDiff(false); } }); } calculatePIPOffsetDiff(true); } $('.pipslideminexp').attr('title', ($('#slideView').hasClass('minimize') ? "Expand Picture-in-Picture (PIP)" : "Minimize Picture-in-Picture (PIP)")); adjustPartcipationCode(); } var piplastOffsetDiff = 0, piplastHeightOffsetDiff = 0, defaultPIPOverided = false; function VideoWidgetPIP() { if ($(toggleBtn2).closest('li').hasClass('active')) { //If want active then $("#mediaView").removeClass('col-md-6').addClass('col-md-12'); $("#slideView").removeClass('col-md-6').addClass('col-md-12'); //#22112 if ($("#media-panel").hasClass("col-md-5") && $("#info-panel").hasClass("col-md-7")) { $("#slidescreen img").css("height", "auto"); } else { $("#slidescreen img").css("height", maxWidgetHeight); } addPIPMsgPanel(); $('#media-panel').addClass('PIPV'); adjustSlide(); // new code for PIP $("#mediaView").addClass('PIPVideo'); if ($('#divVideoPIPClose').length == 0) { var divOtherTool = '
    '; divOtherTool += '
    '; //For small button divOtherTool += '
    '; //For medium button divOtherTool += '
    '; //For lasrge button divOtherTool += '
    '; var divDragIcon = '
    D
    '; var divClose = "" var divTopBar = "
    " + divOtherTool + " " + divDragIcon + " " + divClose + "
    "; $("#media-container").prepend(divTopBar); } if (!$('#mediaView').hasClass('pip-small') && !$('#mediaView').hasClass('pip-medium') && !$('#mediaView').hasClass('pip-large')) { $('.pip-tools .pip-medium').addClass('active'); $('#mediaView').addClass('pip-medium'); } var extraHeight = $('#msg_panel_pip').outerHeight(); $("#mediaView").addClass('PIPVideo'); //$("#mediaView").css("right", getRightOffset('#slidescreen img') + 35); $("#mediaView").css("bottom", getBottomOffset('#slidescreen img') + 20); $("#mediaView").css("height", $('#main-panel').outerHeight()); //Update width of close pip $("#divVideoPIPClose").css("width", $('#media-container').width()); setDragIconWidth(); if (!$('#mediaView').hasClass('ui-draggable')) { defaultPIPOverided = false; $('#mediaView').draggable({ containment: "#slidescreen img", scroll: false, opacity: 0.85, handle: ".pipdrag", stop: function (event, ui) { defaultPIPOverided = true; calculatePIPOffsetDiff(false); } }); } calculatePIPOffsetDiff(true); } $('.pipvideominexp').attr('title', ($('#mediaView').hasClass('minimize') ? "Expand Picture-in-Picture (PIP)" : "Minimize Picture-in-Picture (PIP)")); adjustPartcipationCode(); } function setDragIconWidth() { if ($("#divPIPClose").length > 0) { $("#divPIPClose").css('display', 'block'); var dragWidth = $("#divPIPClose").width() - $("#divPIPClose .pip-tools").outerWidth() - $("#divPIPClose .pipclose").outerWidth(); $(".pipdrag").css('width', dragWidth - 5); $("#divPIPClose").css('display', ''); } else if ($("#divVideoPIPClose").length > 0) { $("#divVideoPIPClose").css('display', 'block'); var dragWidth = $("#divVideoPIPClose").width() - $("#divVideoPIPClose .pip-tools").outerWidth() - $("#divVideoPIPClose .pipclose").outerWidth(); $(".pipdrag").css('width', dragWidth); $("#divVideoPIPClose").css('display', ''); } } $('body').on('click', '.pip-tools > div', function () { $('.pip-tools > div').removeClass('active'); $(this).addClass('active'); if ($(toggleBtn2).closest('li').hasClass('active')) { //If Video PIP active Then var width = $('#mediaView').outerWidth(); var height = $('#mediaView').outerHeight(); var left = $('#mediaView').position().left; var top = $('#mediaView').position().top; $('#mediaView').removeClass('pip-small').removeClass('pip-medium').removeClass('pip-large'); $('#mediaView').addClass($(this).attr('class')); $("#mediaView").css("height", $('#main-panel').outerHeight()); //set height //Update width of close pip $("#divVideoPIPClose").css("width", $('#media-container').width()); setDragIconWidth(); if (defaultPIPOverided) { var leftOff = (width - $('#mediaView').outerWidth()) + left; var topOff = (height - $('#mediaView').outerHeight()) + top; $('#mediaView').css({ 'left': leftOff, 'top': topOff }); if ($('#mediaView').position().top < $('#slidescreen img').position().top) { $('#mediaView').css('top', $('#slidescreen img').position().top); } if ($('#mediaView').offset().left < $('#slidescreen img').offset().left) { $('#mediaView').css('left', $('#slidescreen img').offset().left - 15); } } } else if ($(toggleBtn1).closest('li').hasClass('active')) { //If Slide PIP active Then var width = $('#slideView').outerWidth(); var height = $('#slideView').outerHeight(); var left = $('#slideView').position().left; var top = $('#slideView').position().top; $('#slideView').removeClass('pip-small').removeClass('pip-medium').removeClass('pip-large'); $('#slideView').addClass($(this).attr('class')); $("#slideView").css("height", $('#slidescreen').outerHeight()); //Update width of close pip $("#divPIPClose").css("width", $('#slideView').width()); setDragIconWidth(); if (defaultPIPOverided) { var leftOff = (width - $('#slideView').outerWidth()) + left; var topOff = (height - $('#slideView').outerHeight()) + top; $('#slideView').css({ 'left': leftOff, 'top': topOff }); if ($('#slideView').position().top < $('#media-container').position().top) { $('#slideView').css('top', $('#media-container').position().top); } if ($('#slideView').offset().left < $('#media-container').offset().left) { $('#slideView').css('left', $('#media-container').offset().left - 15); } } } calculatePIPOffsetDiff(false); }); function calculatePIPOffsetDiff(isUpdate) { //if (vidPlayer && vidPlayer.isFullscreen() == true) //comment due to #10600 // return; //If Video Widget PIP if ($("#mediaView").length > 0 && $('#slidescreen img').length > 0 && $(toggleBtn2).hasClass("btn-success")) { if (isUpdate && defaultPIPOverided) { var localOffset = $('#mediaView').offset().left - $('#slidescreen img').offset().left - 15; var currentOffset = (localOffset * 100) / $('#slidescreen img').width(); if (currentOffset != piplastOffsetDiff) { var adjust = (piplastOffsetDiff * $('#slidescreen img').width()) / 100; $('#mediaView').css('left', $('#slidescreen img').offset().left + adjust); } } var offsetDiff = ($('#mediaView').offset().left - $('#slidescreen img').offset().left) - 15; piplastOffsetDiff = (offsetDiff * 100) / $('#slidescreen img').width(); } //If Slide Widget PIP else if ($("#slideView").length > 0 && $('#media-container').length > 0 && $(toggleBtn1).closest('li').hasClass('active')) { console.log('fired: calculatePIPOffsetDiff'); if (isUpdate && defaultPIPOverided) { //Adjust width offset var localOffset = ($('#slideView').offset().left - $('#media-container').offset().left) - 15; var currentOffset = (localOffset * 100) / $('#media-container').width(); if (currentOffset != piplastOffsetDiff) { var adjust = (piplastOffsetDiff * $('#media-container').width()) / 100; $('#slideView').css('left', $('#media-container').offset().left + adjust); } //Adjust height offset localOffset = ($('#slideView').position().top - $('#media-container').position().top); currentOffset = (localOffset * 100) / $('#media-container').height(); if (currentOffset != piplastHeightOffsetDiff) { var adjust = (piplastHeightOffsetDiff * $('#media-container').height()) / 100; $('#slideView').css('top', $('#media-container').position().top + adjust); } var mediaHeightOffset = ($('#media-container').position().top + $('#media-container').outerHeight()); var slideHeightOffset = ($('#slideView').position().top + $('#slideView').outerHeight()); if (slideHeightOffset > mediaHeightOffset) { $('#slideView').css('top', mediaHeightOffset - $('#slideView').outerHeight()); } var mediaWidthOffset = ($('#media-container').position().left + $('#media-container').outerWidth()); var slideWidthOffset = ($('#slideView').position().left + $('#slideView').outerWidth()); if (slideWidthOffset > mediaWidthOffset) { $('#slideView').css('left', mediaWidthOffset - $('#slideView').outerWidth()); } } //Width Offset var offsetDiff = ($('#slideView').offset().left - $('#media-container').offset().left) - 15; piplastOffsetDiff = (offsetDiff * 100) / $('#media-container').width(); //Height Offset offsetDiff = ($('#slideView').position().top - $('#media-container').position().top); piplastHeightOffsetDiff = (offsetDiff * 100) / $('#media-container').height(); } } function addPIPMsgPanel() { if ($('#msg_panel_pip').length == 0) { var msgPanel = $('#msg_panel').clone(); $(msgPanel).attr('id', 'msg_panel_pip'); var msgHtml = $('
    ').append($(msgPanel)).html(); $('#slideView').append('
    ' + msgHtml + '
    '); } $('#msg_panel_pip').css("width", $('#slidescreen img').width()); } function alertEmpty() { if ($('#msg_panel').length > 0 && $('#msg_panel').html() != undefined && $('#msg_panel').html().length > 0) { return false; } else { return true; } } var getRightOffset = function (childElement) { return ($(mainViewColumn).width() - $(childElement).outerWidth()) - ($(childElement).offset().left - $(mainViewColumn).offset().left); } var getBottomOffset = function (childElement) { return ($(mainViewColumn).height() - $(childElement).outerHeight()) - ($(childElement).offset().top - $(mainViewColumn).offset().top); } function adjustPIPHeight() { //For adjust alert height if (toggleBtn2 != null && $(toggleBtn2).closest('li').hasClass('active')) { VideoWidgetPIP(); } else if (toggleBtn1 != null && $(toggleBtn1).closest('li').hasClass('active')) { SlideWidgetPIP(); } else if (toggleBtn3 != null && $(toggleBtn3).closest('li').hasClass('active')) { toggleBtn3ToggleVideoSlide(); } else { adjustPartcipationCode(); } adjustAlert(); } function adjustPartcipationCode() { if (vidPlayer && vidPlayer.isFullscreen()) { $("#slidescreen .lc_panel").hide(); $("#media-video .lc_panel").css('display', "table"); } else { $("#slidescreen .lc_panel").css('display', ''); $("#media-video .lc_panel").css('display', ''); if (!$("#media-panel").hasClass("PIPV")) { $("#media-panel #mainView .row").css("max-width", ""); } } if ($("#media-video").length > 0 && $("#media-video .lc_panel").length > 0) { var leftPostion = $("#media-video").offset().left + 20; $("#media-video .lc_panel").css('left', leftPostion); } if ($("#slidescreen img").length > 0 && $("#slidescreen .lc_panel").length > 0) { var leftPostion = $("#slidescreen img").offset().left + 20; $("#slidescreen .lc_panel").css('left', leftPostion); } } function removeActivePIPFunctions() { //For adjust alert height if (toggleBtn2 != null && $(toggleBtn2).closest('li').hasClass('active')) {// $(toggleBtn2).hasClass('btn-success') $(toggleBtn2).trigger('click'); } else if (toggleBtn1 != null && $(toggleBtn1).closest('li').hasClass('active')) { $(toggleBtn1).trigger('click'); } else if (toggleBtn3 != null && $(toggleBtn3).closest('li').hasClass('active')) { $(toggleBtn3).trigger('click'); } } function loadAttendanceHistory() { $("#btnRestartSeminarHistory").closest('div > #grid-list').load('/Items/GetAttendanceHistory?entityId=' + Entityid + '&customerId=' + CustomerId + '&programRegistrantId=' + ProgramRegistrantId + '&IsFromViewer=true', function () { }); } // #7808: Viewer Activity Confirmation - "Are you still there?" var globalIdleTime = 0; var idleInterval; jQuery(document).ready(function () { setIdleTime(0, true); //Increment the idle time counter every minute. idleInterval = setInterval(timerIncrement, 60000); // 1 minute //Zero the idle timer on mouse movement. jQuery(this).mousemove(function (e) { setIdleTime(0, true); }); jQuery(this).keypress(function (e) { setIdleTime(0, true); }); }); function timerIncrement() { var idleTime = getIdleTime() + 1; setIdleTime(idleTime, false); if (idleTime >= 120 && new Date().getHours() == 1) { // 120 minutes //And Close at 01:00 AM as per mantis ticket #7808: Viewer Activity Confirmation - "Are you still there?" promptForSession(); } } var setIdleTime = function (count, forcefully) { try { //console.log('Idle Time Called'); if (typeof (localStorage) == undefined || typeof (localStorage) == "undefined") { globalIdleTime = count; } else if (allowToSetIdleTime() || forcefully == true) { localStorage.setItem('idleTime', JSON.stringify({ time: new Date(), count: count })); // console.log('Idle Time Updated'); } } catch (e) { } } var allowToSetIdleTime = function () { if (typeof (localStorage) == undefined || typeof (localStorage) == "undefined") { return true; } else { if (localStorage.getItem('idleTime') != null) { var diffSeconds = (new Date() - new Date(JSON.parse(localStorage.getItem('idleTime')).time)) / 1000; return diffSeconds > 55; } else { return true; } } } var getIdleTime = function () { if (typeof (localStorage) == undefined || typeof (localStorage) == "undefined") { return globalIdleTime; } else { if (localStorage.getItem('idleTime') != null) { return JSON.parse(localStorage.getItem('idleTime')).count; } else { return 0; } } } function promptForSession() { var counter = 300; // ask verification $.SmartMessageBox({ title: " Are you still there ?", content: "

    To protect your account information, when too much time passes with no activity, we schedule an automatic logout.

    A logout is scheduled in 300 seconds.

    To remain logged in, select OK.

    ", buttons: '[OK]' }, function (ButtonPressed) { if (ButtonPressed == "OK") { clearInterval(countdown); //continue session setIdleTime(0, true); idleInterval = setInterval(timerIncrement, 60000); // 1 minute } }); var countdown = setInterval(function () { counter--; if (counter >= 0) { $("#timeCounter").html(counter); } // Display 'counter' wherever you want to display it. if (counter === 0) { clearInterval(countdown); clearInterval(idleInterval); //alert('To protect your account information, you are now automatically logged out of your account due to 5 minutes of inactivity.'); window.location.href = "/account/logoff?returnUrl=" + location.pathname; } }, 1000); } // Forum load more $('body').on('click', '.clsLoadMoreForum', function () { var lastDiv = $(this).closest('div').prev(".divForumWidgetPost:last"); var currentElemet = $(this); if (lastDiv.length > 0) { var previousProductForumId = $(lastDiv).attr("data-ProductForumId"); var forumSettingType = $(this).attr("data-ForumSettingType"); //mantis item : #14531 var fTimeId = e; var fSeminarId = s; //mantis item : #14531 if (forumSettingType === "Product") { fTimeId = pe; fSeminarId = ps; } var PageWidgetID = $(this).attr("data-PageWidgetID"); var entityId = $(this).attr("data-entityId"); //var url = '/showtimewidget/forumwidget?PageWidgetID=' + PageWidgetID + '&SeminarId=' + s + '&TimeId=' + e + '&CustomerId=' + u + '&ParentForumId=0&forumSettingType=' + forumSettingType + '&entityId=' + entityId + "&PreviousProductForumId=" + previousProductForumId; //manits item : #14531 $.get('/showtimewidget/forumwidget', { PageWidgetID: PageWidgetID, SeminarId: fSeminarId, TimeId: fTimeId, CustomerId: u, ParentForumId: 0, forumSettingType: forumSettingType, entityId: entityId, PreviousProductForumId: previousProductForumId, parentSeminarId: ps, parentTimeId: pe }, function (result) { if (result.length > 0) { $($(result).filter("#hdnDatetimeUtcNow")).remove(); $(lastDiv).after($(result)); if (Number($(result).filter("#hdnRemainingPreviousPostCount").val()) > 0) { currentElemet.closest('div').show(); } else { currentElemet.closest('div').hide(); } } else { currentElemet.closest('div').hide(); } }); } }); $('.navbar-toggle, .info-toggle-nav').click(function () { $(window).trigger('resize'); }); $(document).on('click', '.expandCollapseInfo', function () { if ($(this).find('i').hasClass('fa-plus')) { $(this).html(' Event Log'); if ($('#divEventLogs').length > 0 && $('#UlEventLogs').length > 0) { $('#UlEventLogs').html($('#divEventLogs').html()); } $(this).closest('#eventlog').find('.HidedInformationPanel').show('slow'); } else { $(this).html(' Event Log'); $(this).closest('#eventlog').find('.HidedInformationPanel').hide('slow'); } }); $(document).on('click', '.navbar-toggle[data-target=".navbar-collapse"]', function () { setTimeout(function () { navBarForSmallScreen(); }, 300); }); $(document).on('click', '#btnHelpReloadViewer,#btnReloadViewer', function () { if (typeof (compositionComplete) == "function" && vidPlayer) { if (curMediaClip && seminar.IsArchive == false && (seminar.IsLive || seminar.IsReplay)) { //curMediaClip = null; GetLatestSeminarMedia(); } else { var video = videojs('media-video'); video.pause(); var currentTime = video.currentTime(); video.load(); video.one(video, "canplay", () => { video.currentTime(currentTime); video.play(); }); } } else { location.reload(); } }); // get the latest medias #9776 function GetLatestSeminarMedia() { $.ajax({ type: 'GET', url: '/showtimewidget/getseminarmedia', dataType: 'json', data: { 'SeminarId': s }, success: function (currSeminar) { seminar.MediaClips = currSeminar.MediaClips; curMediaClip = null; }, }); } function navBarForSmallScreen() { if ($(window).width() < 768) { var isVisible = $('.navbar.navbar-fixed-top .navbar-collapse').is(':visible'); console.log(isVisible) if (isVisible === true) { var height = $('.navbar-collapse').closest('.navbar.navbar-fixed-top').outerHeight() + 10 + "px !important;"; $('#mobileCss').html('#info-panel{margin-bottom:' + height + '}'); } else { $('#mobileCss').html(''); } } else { $('#mobileCss').html(''); } } function scrollOnSpecificDiv(divid) { if ($(window).width() < 992) { $(window).scrollTop($(divid).offset().top); } } $(document).on('click', '#btnHelpReloadWholeViewer', function () { location.reload(); //mantis #8479 }); // new Forum Start $('body').on("keydown", ".postcom, .txtCommentBox", function () { autosize($(this)) }); function autosize(el) { setTimeout(function () { $(el).css({ 'height': 'auto' }); $(el).css({ 'height': parseInt($(el)[0].scrollHeight) + 10 + 'px' }); }, 0); } $("body").on("click", ".clsExpandAllComment", function () { var ele = $(this); var forumWidget = $(ele).closest('.ForumWidget'); var divId = $(this).attr("data-value"); var forumWidgetMain = $(ele).closest('.ForumWidgetMain'); if ($(ele).attr("data-Expanded") == "false") { if ($(forumWidget).find("#" + divId).length > 0 && $(forumWidget).find("#" + divId).html().length == 0) { expandComments(ele); } $(ele).text("Close previous comments"); $(forumWidget).find("#" + divId).show('slow'); $(ele).attr("data-Expanded", "true"); $(ele).closest(".divForumWidgetPost").attr("data-Expanded", "true"); $(forumWidgetMain).find(forumWidget).find('.viewcomment #divNewComments' + divId + ' .singlereply[data-replyid]').show(); } else { $(ele).text("View previous comments"); $(forumWidget).find("#" + divId).hide('slow'); $(ele).attr("data-Expanded", "false"); $(ele).closest(".divForumWidgetPost").attr("data-Expanded", "false"); if ($(forumWidgetMain).find(forumWidget).find('#divNewComments' + divId + ' .singlereply[data-replyid]').length > 1) { $(forumWidgetMain).find(forumWidget).find('#divNewComments' + divId + ' .singlereply[data-replyid]').not(':last').hide(); } } }); $("body").on("click", ".clsCommentShow", function () { var ele = $(this); var forumWidget = $(ele).closest('.ForumWidget'); var divId = $(this).attr("data-value"); var forumWidgetMain = $(ele).closest('.ForumWidgetMain'); if ($(forumWidget).find("#" + divId).length > 0 && $(forumWidget).find("#" + divId).html().length == 0) { expandComments(ele); } $(forumWidget).find("#" + divId).show('slow'); $(ele).attr("data-Expanded", "true"); $(ele).closest(".divForumWidgetPost").attr("data-Expanded", "true"); $(ele).closest(".divForumWidgetPost").find(".clsExpandAllComment").text("Close previous comments"); $(ele).closest(".divForumWidgetPost").find(".clsExpandAllComment").attr("data-Expanded", "true"); $(forumWidgetMain).find(forumWidget).find('.viewcomment .divNewComments .singlereply[data-replyid]').show(); }); function expandComments(element) { var productForumId = element.closest(".divForumWidgetPost").attr('data-ProductForumId'); var forumWidgetMain = $(element).closest('.ForumWidgetMain'); var forumSettingId = $(forumWidgetMain).attr('data-forumSettingId'); var forumSettingType = $(forumWidgetMain).attr('data-forumSettingType'); var ForumWidgetPostId = '.ForumWidgetPost' + productForumId; var forumWidget = $(element).closest('.ForumWidget'); // for integrated forum dropdown var isIntegratedForum = false; if ($(forumWidgetMain).attr('data-isintegratedfroum') == "true") { isIntegratedForum = true; } var isDisplayAllComment = true; var url = "/showtimewidget/forumwidgetsingle?ParentForumId=" + productForumId + "&forumSettingId=" + forumSettingId + "&isIntegratedForum=" + isIntegratedForum + "&isDisplayAllComments=" + isDisplayAllComment; var updatedDiv = ".ForumWidgetPost" + productForumId; $.get(url, function (result) { //$(forumWidget).find(updatedDiv).html($(result).filter(updatedDiv).html()); $(forumWidget).find(updatedDiv).find('.viewcomment').replaceWith($(result).filter(updatedDiv).find('.viewcomment')); $(forumWidget).find(updatedDiv).find('.socialPost').replaceWith($(result).filter(updatedDiv).find('.socialPost')); }); } $("body").on('focus', '.clstextForumWidgetPost', function () { $(this).closest('.ForumWidgetMain').find(".clsForumWidgetPostBottom").show(); }); function showReplytBox(element) { var productForumId = $(element).attr('data-val'); var settingId = $(element).attr('data-SettingId'); $('#txtProductForumComment' + productForumId + '[data-settingid="' + settingId + '"]').focus(); } function showPreview(objFileInput) { if (objFileInput.files[0]) { var forumWidgetMain = $(objFileInput).closest('.ForumWidgetMain'); var fileExtension = ['gif', 'jpeg', 'jpg', 'png', 'ico', 'bmp','webp','avif']; var File = objFileInput.files[0]; var FileName = File.name; if ($.inArray(FileName.split('.').pop().toLowerCase(), fileExtension) == -1) { alert("Only the following formats are allowed: .jpg, .jpeg, .png, .gif, .bmp, .webp or .avif"); removepostedFile(forumWidgetMain); return; } else { var fileSize = objFileInput.files[0].size; if (fileSize > (1048576 * 5)) { alert("Maximum file size is 5 MB"); removepostedFile(forumWidgetMain); return; } else { var fileReader = new FileReader(); fileReader.onload = function (e) { $(forumWidgetMain).find(".targetLayer").find('img').attr('src', e.target.result); displayPostedFile(forumWidgetMain); } fileReader.readAsDataURL(objFileInput.files[0]); } } } } $('body').on('click', '.removePostedFile', function () { var element = $(this); var forumWidgetMain = $(element).closest('.ForumWidgetMain'); removepostedFile(forumWidgetMain); }); function removepostedFile(forumWidgetMain) { $(forumWidgetMain).find(".uploadImage").val(''); $(forumWidgetMain).find(".divForumPostedFile").hide(''); $(forumWidgetMain).find(".divForumPostedFilebtn").show(''); } function displayPostedFile(forumWidgetMain) { $(forumWidgetMain).find(".divForumPostedFile").show(''); $(forumWidgetMain).find(".divForumPostedFilebtn").hide(''); } $('body').on('click', '.lnkForumPostFile', function () { var element = $(this); var forumWidgetMain = $(element).closest('.ForumWidgetMain'); $(forumWidgetMain).find(".uploadImage").trigger('click'); }); $('body').on('change', '.clstextForumWidgetPost', function () { bindUrlDetails($(this)); }); // pasting any data. $(".clstextForumWidgetPost").bind("paste", function () { var element = $(this); setTimeout(function () { bindUrlDetails(element) }, 1000); }); // if press enter,space or tab $('body').on('keyup', '.clstextForumWidgetPost', function (e) { var element = $(this); var code = e.which || e.keyCode || 0; // recommended to use e.which, it's normalized across browsers if (code == 13) e.preventDefault(); if (code == 32 || code == 13 || code == 9) { bindUrlDetails(element); } }); function bindUrlDetails(element) { var forumWidgetMain = $(element).closest('.ForumWidgetMain'); var words = $(element).val().replace(/(?:\r\n|\r|\n)/g, ' '); words = words.trim().split(' '); var link = ''; $.each(words, function (i, l) { if (l.match(/\b(http|https)(:\/\/)?(\S*)\.(\w{2,4})(.*)/g)) { link = l; } }); if ($(forumWidgetMain).find('.hdnLink').length > 0 && $(forumWidgetMain).find('.hdnLink').val() == link) { return; } if (link != undefined && link != '') { if ($(forumWidgetMain).find(".embedLinkDetail").length > 0) { $(forumWidgetMain).find(".embedLinkDetail").remove(); } if ($(forumWidgetMain).find(".clsLoadPreview").length == 0) { $(forumWidgetMain).find(".clstextForumWidgetPost").closest('div').append('
    Fetching preview....
    '); } var url1 = "/ShowTimeWidget/GetUrlDetail"; $.ajax({ type: 'POST', url: url1, data: { 'url': link }, global: false, success: function (data) { $(forumWidgetMain).find(".clsLoadPreview").remove(); if (data != undefined && data != '') { $(forumWidgetMain).find(".embedLinkDetail").remove(); $(forumWidgetMain).find(".clstextForumWidgetPost").closest('div').append(data); $(forumWidgetMain).find('.hdnLink').val(link); } }, }); } else if ($(forumWidgetMain).find(".embedLinkDetail").length > 0) { $(forumWidgetMain).find(".embedLinkDetail").remove(); } } $('body').on('click', '.closeLinkDiv', function () { $(this).closest('.embedLinkDetail').remove(); }); //START: #9068: Viewer > Move countdown from footer to header (see comment of this ticket) function countDownShowHideWithResizeWindow() { var headerHeight = 0; headerHeight = $('.navbar-fixed-top').height(); if (headerHeight && headerHeight >= 51) { // $('body').addClass('hideMenuCounter'); return false; } else { $('body').removeClass('hideMenuCounter'); } } //END: #9068: Viewer > Move countdown from footer to header (see comment of this ticket) $("body").on('click', '.popUploadImage', function () { $.magnificPopup.open({ items: { src: $(this).attr("href") }, type: 'iframe', closeOnBgClick: false, enableEscapeKey: false, mainClass: 'popUploadImageMainClass' }); return false; }); function ProfilePicUpdatedSuccess() { $.magnificPopup.close(); iniForumWidget(); changeParticipantProfile(Number(u)); } // Pin to Top Forum $('body').on('click', '.popPinForum', function () { var element = $(this); var forumWidgetMain = $(element).closest('.ForumWidgetMain'); var forumSettingId = $(forumWidgetMain).attr('data-forumsettingid'); var productForumId = $(element).attr('data-productforumid'); var url = '/ShowtimeWidget/PintoTopForum?forumSettingId=' + forumSettingId + '&productForumId=' + productForumId; $.magnificPopup.open({ items: { src: url }, type: 'iframe', closeOnBgClick: false, mainClass: 'popPinForum' }); }); function PinForumSuccess(ProductForumId) { $.magnificPopup.close(); $('.ForumWidgetPost' + ProductForumId).each(function (index, fourmWidget) { var forumWidgetMain = $(this).closest('.ForumWidgetMain'); //var newDiv = $(this).html(); $(forumWidgetMain).find('.ForumWidget').prepend($(forumWidgetMain).find('.ForumWidgetPost' + ProductForumId)); }); $('.clsPin' + ProductForumId).removeClass('popPinForum').addClass('unpinForum').text('Unpin Forum'); } $('body').on('click', '.unpinForum', function () { var element = $(this); var forumWidgetMain = $(element).closest('.ForumWidgetMain'); var forumSettingId = $(forumWidgetMain).attr('data-forumsettingid'); var productForumId = $(element).attr('data-productforumid'); if (confirm('Are you sure to unpin this forum?')) { $.ajax({ type: 'POST', url: '/ShowtimeWidget/UnpinForumPost', data: { 'productForumId': productForumId }, global: false, async: false, success: function (data) { if (data != undefined && data == "") { $('.clsPin' + productForumId).addClass('popPinForum').removeClass('unpinForum').text('Pin to Top'); } }, error: function (jqXHR, textStatus, errorThrown) { $("#divProgress").hide(); //$(element).html('Submit My Browser Info').prop('disabled', false); } }); } }); // Forum Notification start $('body').on('click', '.popForumNotifySetting', function () { var element = $(this); var forumWidgetMain = $(element).closest('.ForumWidgetMain'); var forumSettingId = $(forumWidgetMain).attr('data-forumsettingid'); var productForumId = $(element).attr('data-productforumid'); if (Number(ProgramRegistrantId) > 0) { var url = '/ShowtimeWidget/ForumPostNotifySetting?programRegId=' + ProgramRegistrantId; $.magnificPopup.open({ items: { src: url }, type: 'iframe', closeOnBgClick: false, mainClass: 'popForumNotifySettingMainClass' }); } }); // Forum Notification end // Upload video Start $('body').on('click', '.aForumVideoUpload', function () { var element = $(this); var forumWidgetMain = $(element).closest('.ForumWidgetMain'); var forumSettingId = $(forumWidgetMain).attr('data-forumsettingid'); var isIntegratedForum = $(forumWidgetMain).attr('data-isintegratedfroum') var url = '/ShowtimeWidget/UploadVideoPost?productId=' + ps + "&TimeId=" + pe + "&ForumSettingId=" + forumSettingId + "&isIntegratedForum=" + isIntegratedForum; $.magnificPopup.open({ items: { src: url }, type: 'iframe', closeOnBgClick: false, mainClass: 'popForumVideoUploadMainClass' }); }); function VideoUploadSuccess(parentForumId, forumSettingId, isIntegratedForum) { $.magnificPopup.close(); var forumWidgetMain = $(".ForumWidgetMain[data-forumsettingid=" + forumSettingId + "]") removepostedFile(forumWidgetMain); var url = "/showtimewidget/forumwidgetsingle?ParentForumId=" + parentForumId + "&forumSettingId=" + forumSettingId + "&isIntegratedForum=" + isIntegratedForum; $(forumWidgetMain).find('#txtForumWidgetPost').val(''); $(forumWidgetMain).find('#divAppendPost').load(url, function () { var newPost = $(forumWidgetMain).find('#divAppendPost').html(); $(forumWidgetMain).find('#divAppendPost').children().remove(); // $(forumWidgetMain).find('.ForumWidget').children(ForumWidgetPostId).remove(); $(forumWidgetMain).find('.ForumWidget').prepend(newPost); $("#divProgress").hide(); editProductForumId = ''; sendForumData("newforum", forumSettingId, parentForumId); }); if ($(forumWidgetMain).find(".embedLinkDetail").length > 0) { $(forumWidgetMain).find(".embedLinkDetail").remove(); } } // Upload video End //delete forum comment start $("body").on("click", ".deleteForumComment", function () { var element = $(this); var productForumId = element.attr('data-ProductForumId'); var ParentForumId = element.attr('data-parentforumid'); var ProductWidgetForumSettingId = element.attr('data-val'); var ProductForumSettingId = element.attr('data-ProductForumSettingId'); var forumSettingId = $(element).closest('.ForumWidgetMain').attr('data-forumSettingId'); var forumSettingType = $(element).closest('.ForumWidgetMain').attr('data-forumSettingType'); var isIntegratedForum = false; if ($(element).closest('.ForumWidgetMain').attr('data-isintegratedfroum') == "true") { isIntegratedForum = true; } var isDisplayAllComment = false; isDisplayAllComment = $(element).closest('.divForumWidgetPost').attr("data-Expanded") == "false" ? false : true; $("#divProgress").show(); $.ajax({ type: 'POST', url: '/ShowtimeWidget/DeleteForumPost', dataType: 'json', data: { 'ProductForumId': productForumId }, success: function (Data) { loadSingleForumPost(ParentForumId, forumSettingId, isIntegratedForum, isDisplayAllComment); sendForumData("deleteforumData", forumSettingId, productForumId, ParentForumId); }, error: function (data) { alert('Error! Please try again later.'); } }); }); function loadSingleForumPost(ParentForumId, forumSettingId, isIntegratedForum, isDisplayAllComment) { var updatedDiv = ".ForumWidgetPost" + ParentForumId; url = "/showtimewidget/forumwidgetsingle?ParentForumId=" + ParentForumId + "&forumSettingId=" + forumSettingId + "&isIntegratedForum=" + isIntegratedForum + "&isDisplayAllComments=" + isDisplayAllComment; $.ajax({ type: 'Get', url: url, global: false, success: function (result) { $(updatedDiv).html($(result).filter(updatedDiv).html()); }, }); } //delete forum comment end //Turn Off notifications start $('body').on('click', '.clsTurnOnOffNotification', function () { var element = $(this); var turnOff = $(element).attr('data-enabledNofication') == 'true' ? true : false; $.ajax({ type: 'POST', url: '/ShowtimeWidget/TurnoffNotifacionofPost', dataType: 'json', data: { 'productForumId': $(element).attr('data-ProductForumId'), 'turnOffNotifications': turnOff }, success: function (Data) { if (Data != undefined && Data) { if (turnOff == true) { $(element).attr('data-enabledNofication', false); $(element).html('Turn on notifications for this post'); } else { $(element).attr('data-enabledNofication', true); $(element).html('Turn off notifications for this post'); } } }, error: function (data) { alert('Error! Please try again later.'); } }); }); //Turn Off notifications end // get broswerInfo var infoSubmittedFrom = ''; var browserElement; function getBrowserInfo(submittedVia, element) { infoSubmittedFrom = submittedVia; browserElement = element; if (typeof (browserReport) == "function" && Number(ProgramRegistrantId) > 0) { if (infoSubmittedFrom == "Submit Browser") { $(browserElement).html('  Processing...').prop('disabled', true); } browserReport(function (err, report) { if (err) { throw err; } ViewerSettings.BrowserInfo = JSON.stringify(report); //if (infoSubmittedFrom == "Launch Viewer") { // addViewerLaunchLog("Open"); //} if (isImpersonateSession()) return; $.get("/showtimewidget/getcurrurntdatetimewithtimezone", function (data) { if (data != undefined) { report.consoleErrorList = consoleErrorList; report.jwplayerProcess = vidPlayerProcess; report.submittedVia = infoSubmittedFrom; report.SubmmitedDate = data; $.ajax({ type: 'POST', url: '/showtimewidget/submitbrowser', dataType: 'json', data: { 'programRegistrantId': ProgramRegistrantId, 'settings': JSON.stringify(report) }, success: function (Data) { if (infoSubmittedFrom == "Submit Browser") { $(browserElement).html('Submit My Browser Info').prop('disabled', false); alert('Browser info submitted successfully.'); } ViewerAnalyticsId = Data; }, error: function (jqXHR, textStatus, errorThrown) { if (infoSubmittedFrom == "Submit Browser") { $(browserElement).html('Submit My Browser Info').prop('disabled', false); } } }); } else if (infoSubmittedFrom == "Submit Browser") { $(browserElement).html('Submit My Browser Info').prop('disabled', false); } }); }); } } //9152: Presenter > Live Webcast Presenter > Ability to change a slides program into Video Only sections function applySlideScreenStatus() { if (checkSlideScreeenIsVisible() == false) { //$(window).trigger('resize'); onLoadMediaSlide(); } } //START:: onload viewer if ie8,ie9(all OS),safari<7.1(MAC os) show popup #9261 function onLoadBrowserUpgradePopup() { if ($('#upgradeBrowserPop').length > 0 && NewViewer == true && (checkBrowserIEBelowTen() || checkBrowserSafariBelowSevenPointOneOnMacOS())) { $.magnificPopup.open({ items: { src: '#upgradeBrowserPop' }, type: 'inline', closeOnBgClick: false, }); } } function checkBrowserIEBelowTen() { if (((xBrowser === "ie") || (xBrowser === "internetexplorer")) && xVersion <= 9) { return true; } else { return false; } } function checkBrowserSafariBelowSevenPointOneOnMacOS() { if ((xBrowser === "safari") && xVersionWithDouble <= 7 && (navigator.platform.toLowerCase() == "macintel" || navigator.platform.toLowerCase() == "macintosh")) { return true; } else { return false; } } //END:: onload viewer if ie8,ie9(all OS),safari<7.1(MAC os) show popup #9261 // making extension methods for show hide by check if visible or not jQuery.fn.extend({ showIfNotVisible: function () { if (this.is(':visible') == false) { this.show(); } }, hideIfVisible: function () { if (this.is(':visible') == true) { this.hide(); } } }); $('body').on('click', '.btnGetMobileApp,.linkPagerDutySubmit', function () { $.magnificPopup.open({ items: { src: $(this).attr("data-href") }, type: 'iframe', closeOnBgClick: false, callbacks: { close: function () { //do stuff } }, mainClass: 'popPagerDuty' }); return false; }); // initiliging reload video button pop over on document ready #9776 function InitilizeReloadVideoPopover() { if ($("#btnReloadViewer").length > 0) { $('#btnReloadViewer').popover({ trigger: 'hover' }) .on("show.bs.popover", function () { return $(this).data("bs.popover").tip().css({ width: "200px", left: "50px !important" }) }); } } ////START::>> 0010030: Classrooms -> Viewer -> Adding a, 'Return to Classroom,' Link function BacktoClassroomScheduletab() { var tabName = getParameterByName("ClassroomTab"); if (tabName != null && tabName != undefined && tabName != '' && isFromClassroomScheduleTab != null && isFromClassroomScheduleTab != undefined && isFromClassroomScheduleTab != '' && $('.clsReturnToClassroom').length == 1 && $('.viewerHeaderTemporary').length == 1) { var array = tabName.split('_'); var name = array[0]; var id = array[1]; var sc = 0; if (array.length >= 4) { sc = array[3]; } var item = '/viewer/classroom/' + id + "?InnerTab=" + name + "&sc=" + sc; $('.clsReturnToClassroom').attr('href', item).attr('target', 'ce21_classroom_' + id); $('.returnToClassroom').attr('href', item).attr('target', 'ce21_classroom_' + id); $('.clsReturnToClassroomFromCertWidget').attr('href', item).attr('target', 'ce21_classroom_' + id); $('.viewerHeaderTemporary').show(); //in mobile view= on load viewer page(not for resize) onloadBacktoClassroomScheduletab(); //when resizing the window ResizeBacktoClassroomtab(); $('body').addClass('isFromClassroomScheduleTab'); } else { $('.viewerHeaderTemporary').hide(); $('body').removeClass('isFromClassroomScheduleTab'); } } $('body').on('click', '.clsReturnToClassroom, .returnToClassroom, .clsReturnToClassroomFromCertWidget', function () { setTimeout(function () { window.close() }, 500); }); function ResizeBacktoClassroomtab() { $(window).resize(function () { onloadBacktoClassroomScheduletab(); }) } function onloadBacktoClassroomScheduletab() { if ($(window).width() <= 991) { $('.viewerHeaderTemporary').removeClass('cssForHeaderTop').addClass('cssForHeaderBottom'); $('.clsReturnToClassroom').css('padding', '3px 0px 12px 10px').css('font-size', '13px'); $('.viewerHeaderOriginal').addClass('clsViewerHeaderMargin'); $('#info-panel').css('padding-top', '10px').css('margin-bottom', '84px'); $('.clsReturnIcon').css('font-size', '19px'); } else { $('.viewerHeaderTemporary').addClass('cssForHeaderTop').removeClass('cssForHeaderBottom'); $('.clsReturnToClassroom').css('padding', '6px 0 5px 10px').css('font-size', '16px'); $('.viewerHeaderOriginal').removeClass('clsViewerHeaderMargin').css('margin-top', '33px'); $('#info-panel').css('padding-top', '83px').css('margin-bottom', '0px'); $('.clsReturnIcon').css('font-size', '22px'); } } ////END::>> 0010030: Classrooms -> Viewer -> Adding a, 'Return to Classroom,' Link // as per mantis #10767 //"Support Questions? Please click here." When that phrase is clicked on - a user should be directed to the Help tab. $('body').on('click', "#btnSupportQuestion", function () { $("a[data-href='SupportWidget']").trigger("click"); }); function checkArchivePopup() { if (seminar.ArchivePopup != null && seminar.ArchivePopup.IsComplete == false) { //Check from storage based on popup type. var alreadyDisplayedArchive = checkPrepostPopupComplete(seminar.ArchivePopup.PopUpType); if (alreadyDisplayedArchive) return; $.magnificPopup.close(); if (vidPlayer) { vidPlayer.pause(); if (vidPlayer.isFullscreen()) { vidPlayer.isFullscreen(false); } } $("#lblPrePostTitle").html(seminar.ArchivePopup.PopupTitle); $("#lblPrePostBody").html(seminar.ArchivePopup.PopupBody); $("#btnPrePost").html(seminar.ArchivePopup.PopupButtonText); $(".clsPrePostPopUp").show(); $.magnificPopup.open({ items: { src: '#prePostPopUp' }, type: 'inline', closeOnBgClick: false, enableEscapeKey: false, showCloseBtn: false, beforeOpen: function () { vidPlayer.pause(); }, callbacks: { afterClose: function () { seminar.ArchivePopup.IsComplete = true; //Save in local storage if (typeof (localStorage) != "undefined") { var key = 'PopUp' + seminar.ArchivePopup.PopUpType + '-' + ProgramRegistrantId + '-' + e; localStorage.setItem(key, 'true'); } vidPlayer.play(); } } }); $('.mfp-content').css('width', 600); $('.mfp-content > .white-popup').css('min-width', '600px'); } } function setRelativeTime() { if (curRelativeTime && seminar.SeminarTypeId == 4) { $("#hdnRelativeTime").val(Math.round(curRelativeTime / 1000)); } } // make the viewer close entry for this registrant window.addEventListener("beforeunload", function (e) { //mantis item #18684: Viewer: Time Tracking NOT getting recognized until CE21 check if (seminar.PresenterDuration > 0 && Math.round(curRelativeTime / 1000) > 60 && typeof updateCertCompletionStatus === "function") { updateCertCompletionStatus(true); } // saving currenttextdocument duration #0019645 if (IsTextBasedViewer) { saveCurrentTextPageDuration(); } // save logout date #20525 if (Number(ProgramRegistrantId) > 0) { $.ajax({ type: 'POST', url: '/ShowtimeWidget/SubmitLogOutDate', data: { 'viewerAnalyticsId': ViewerAnalyticsId, } }); } //#14143: Viewer > Notes Tab > Prevent users from forgetting to click on "Save Note" to save notes ManageNotes('SetItem'); //#22227 if ($("a[data-href='ChatWidget']").length > 0) { UpdateChatUserOnlineStatus(0); //Offline } }); function addViewerLaunchLog(entityType) { if (Number(ProgramRegistrantId) > 0) { var relativeTime = curRelativeTime ? Math.round(curRelativeTime / 1000) : null; $.ajax({ type: 'POST', url: '/ShowtimeWidget/AddViewerLaunchLog', dataType: 'json', data: { 'programRegistrantId': ProgramRegistrantId, 'entityType': entityType, "relativeTime": relativeTime, "browserInfo": ViewerSettings.BrowserInfo }, success: function () { }, error: function () { } }); } } //#13253: Unauthenticated link to viewer > Give feedback that some features will not show in this view function onLoadBrowserShowFeedbackFeatures() { if ($('#ShowFeedBackFeaturesPopUp').length > 0) { $.magnificPopup.open({ items: { src: '#ShowFeedBackFeaturesPopUp' }, type: 'inline', closeOnBgClick: false }); setTimeout(function () { $.magnificPopup.close(); }, 10000); } } //#12919: Viewer > Bottom end of Scrollbar partially hidden / Feedback Widget - don't overlay on scroll bar area function setFeedbackWidgetButtonOffset() { if ($('.ticket-button.ticket-btn-right').length > 0 && $('.layout-2').length > 0) { var div = document.getElementById('info-panel-content'); var hasVerticalScrollbar = div.scrollHeight > div.clientHeight; if (hasVerticalScrollbar) { $('.ticket-btn-right .ticketwidget-theme').css('right', '0.8%'); } else $('.ticket-btn-right .ticketwidget-theme').css('right', '0'); } } //#region #11807: Viewer > Ability to Expand Slides to Full Screen View w/ Video in small PIP $('body').on('click', '.btnSlideFullScreen, .btnSlideExitFullScreen', function (e) { e.preventDefault(); $('body').toggleClass('slidefullscreen'); var isSlideFullScreen = $('body').hasClass('slidefullscreen'); if (isSlideFullScreen) { GoInFullscreen($("body").get(0)); enterSlideFullScreen(); setTimeout(enterSlideFullScreen, 500); } else { GoOutFullscreen(); //Default View exitSlideFullScreen(); } }); function GoInFullscreen(element) { if (element.requestFullscreen) element.requestFullscreen(); else if (element.mozRequestFullScreen) element.mozRequestFullScreen(); else if (element.webkitRequestFullscreen) element.webkitRequestFullscreen(); else if (element.msRequestFullscreen) element.msRequestFullscreen(); } function GoOutFullscreen() { if (document.exitFullscreen) document.exitFullscreen(); else if (document.mozCancelFullScreen) document.mozCancelFullScreen(); else if (document.webkitExitFullscreen) document.webkitExitFullscreen(); else if (document.msExitFullscreen) document.msExitFullscreen(); } function IsFullScreenCurrently() { var full_screen_element = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement || null; if (full_screen_element === null) return false; else return true; } $(document).on('fullscreenchange webkitfullscreenchange mozfullscreenchange MSFullscreenChange', function () { if (!seminar || (typeof (seminar) != "undefined" && seminar && seminar.Slides.length == 0)) { return; } if (!IsFullScreenCurrently()) { $('body').removeClass('activeFullScreen'); $('body').removeClass('slidefullscreen'); //Default View exitSlideFullScreen(); } else { $('body').addClass('activeFullScreen'); } }); function enterSlideFullScreen() { //Vertically centering slide var slideHeight = (document.querySelector('#slidescreen img') || {}).height || (maxWidgetHeight + 125); $('.slidefullscreen #slidescreen img').css('margin-top', 'calc(50vh - ' + slideHeight + 'px/2)'); //Video PIP if ($(toggleBtn2).closest('li').hasClass('active')) { adjustPIPHeight(); } else { toggleVideoSlide("#video-toggle", true, false); } if ($("#media-panel").hasClass("showinfo")) { $("#media-panel").removeClass("col-md-7").addClass("col-md-12"); } //Default Video PIP Size to small if (!$('body').hasClass('activeFullScreen')) { $('#mediaView').removeClass('pip-small pip-medium pip-large').addClass('pip-small'); $('.pip-tools .pip-small, .pip-tools .pip-medium, .pip-tools .pip-large').removeClass('active'); $('.pip-tools .pip-small').addClass('active'); } } function slideImageLoad() { if ($('body').hasClass('slidefullscreen')) { enterSlideFullScreen(); } $('#slidescreen a[href="javascript:void(0)"],.SlideThumbsWidget a[href="javascript:void(0)"]').removeAttr('href'); } function exitSlideFullScreen() { toggleVideoSlide("#default-view", true, false); $('#slidescreen img').css('margin-top', ''); onLoadMediaSlide(); //#0016822 if ($("#media-panel").hasClass("showinfo")) { $("#media-panel").removeClass("col-md-12").addClass("col-md-7"); } } //#endregion #11807 //#region 15037 - Custom Fields Multi-Select DropDown - START $("body").on('change', '.chkSelecAllCustomFields', function () { checkUncheckAllCustomCheckBox(this); }); $("body").on('click', '.btnClearCustomFields', function () { var txtSearch = $(this).closest('th').find('input[type="text"]'); $(txtSearch).val(''); searchCustomFieldCheckBox(txtSearch); }); function checkUncheckAllCustomCheckBox(ele) { if ($(ele).prop('checked') === true) { $(ele).closest("table").find('input[type="checkbox"]:visible').prop('checked', true); } else { $(ele).closest("table").find('input[type="checkbox"]').prop('checked', false); } } function searchCustomFieldCheckBox(txtSearch) { if (txtSearch) { $(txtSearch).closest("table").find("tbody>tr").filter(function () { $(this).toggle($(this).text().toLowerCase().indexOf($(txtSearch).val().toLowerCase()) > -1) }); } } function checkMultiChoiceValidation(isValid) { //Required validation if all rows rows are hidden $(".tblCustomFieldMultiSelect").each(function () { var table = $(this); if ($(table).find("tbody>tr:visible").length == 0) { if ($(table).find("tbody>tr:hidden").find('input[type="checkbox"]:required').length > 0 && $(table).find("tbody>tr:hidden").find('input[type="checkbox"]:checked').length == 0) { $(table).find("tbody>tr").show(); isValid = false; } } }); return isValid; } //#endregion //#region #15102: Viewer > Audio Only programs allow download despite setting. function disableRightClickForAudioStream() { if (typeof (seminar) != "undefined" && seminar != null && seminar.IsOtherDigital && seminar.SeminarTypeId === 4) { $('div#mediaView video#media-video_Html5_api').bind("contextmenu", function () { return false; }); } } //#endregion //#region #13489: Refreshing the viewer function reInitViewer() { Helper.VIDEOJS.disposePlayer(vidPlayer); Helper.Interval.clear("VIEWER_CHECKTRIGGERTIMES"); if (curMediaClip) curMediaClip = null; if (typeof (videoEl) != "undefined") videoEl = null; getSeminar(); } //#endregion //#region #15901: Certificate Link function redirectToCertificateTab() { closepopup(); $("#navlist a").each(function () { var id = $(this).attr("data-href"); var navSelector = '#' + id; $(navSelector).hide(); $(this).parent().removeClass("active"); if (id === "CertificationWidget") { $(navSelector).show(); $(this).parent().addClass("active"); setTimeout(function () { if ($("#CertificationWidget").html().trim().length == 0) { if (typeof (RefreshCertificate) == "function") { RefreshCertificate(undefined, true); } } else { openInComleteAccordion(); } }, 1500); } }); } function openInComleteAccordion() { if ($("h5.popCertificationSuccess[data-entityType='Download certificate']").length > 0) { $("h5.popCertificationSuccess[data-entityType='Download certificate']").click(); $("h5.popCertificationSuccess[data-entityType='Download certificate']").next().removeClass('collapse'); } else if ($(".popCertificationDanger").length > 0) { $(".popCertificationDanger:first").click(); } } //#endregion function getNewProductForums(forumSettingId, productForumId, parentEventTimeId) { $('.ForumWidgetMain').each(function () { var forumWidgetMain = $(this); lastForumSyncTime = $(this).find('.hdnDatetimeUtcNow').val(); var forumSettingType = $(this).attr('data-forumSettingType'); if ((forumSettingId == $(this).attr('data-forumSettingId') || parentEventTimeId == $(this).attr('data-mainparenteventtimeid'))) { $.ajax({ type: 'POST', url: '/Forum/ProductForumGetById', data: { 'timeId': pe, 'CustomerId': u, 'forumSettingId': forumSettingId, 'forumSettingType': forumSettingType, 'productForumId': productForumId, 'LastSyncTime': lastForumSyncTime }, global: false, async: false, success: function (Data) { if (Data != null) { var currentDate = $(Data).filter('.hdnDatetimeUtcNow').val(); var productForumIdsToRemove = $(Data).filter('.hdnProductForumIdsToRemove').val().split(','); $(forumWidgetMain).find('.hdnDatetimeUtcNow').val(currentDate); var forumIds = $(Data).filter('.divForumWidgetPost').map(function () { return Number($(this).attr('data-ProductForumId')) }).get(); if (forumIds != null && forumIds.length > 0) { // find its own post forumIds var LoggingUserforumIds = $(Data).filter('.divForumWidgetPost').map(function (a, b) { if (u == $(this).attr("data-postCustomerId")) { return Number($(this).attr('data-ProductForumId')); } }).get(); var forumCommentMsgTimeOut; $.each(forumIds, function (index, forumId) { var child = '.ForumWidgetPost' + forumId; var newDiv = $(Data).filter(child) var commentBox = '#txtProductForumComment' + forumId; var currentText = $(commentBox).val(); // display alert when another user has replied to a Post that they CREATED. if (provideViewerAlert && LoggingUserforumIds.indexOf(forumId) != -1) { var lastComment = newDiv.find('.viewcomment .singlereply[data-replyId]:last'); var lastCommentUserName = lastComment.find('div.media-body p strong').text(); var lastcommentUserId = $(lastComment).attr("data-commentedCustomerId"); if (lastCommentUserName != "" && lastCommentUserName != undefined && u != lastcommentUserId) { // for exclude own comments if ($(forumWidgetMain).find('.ForumWidget').children(child).find('.viewcomment .singlereply[data-replyId=' + lastComment.attr('data-replyid') + ']').length == 0) { $("#Forummsg_panel").html("
    " + lastCommentUserName + " has responded to your forum post!
    ").show(); // clear old timeout and add new one if (forumCommentMsgTimeOut) { clearTimeout(forumCommentMsgTimeOut); } forumCommentMsgTimeOut = setTimeout(function () { $("#Forummsg_panel").empty().hide(); }, 10 * 1000); } } } var currentDiv = $('.ForumWidget').children(child).html(); if (currentDiv != '' && currentDiv != null && currentDiv != undefined) { var commentsExpanded = $(forumWidgetMain).find('.ForumWidget').children(child).attr('data-Expanded') == "true"; //$(forumWidgetMain).find('.ForumWidget').children(child).replaceWith(newDiv); //459: Forums - don't refresh comments area - just append to the bottom with Javascript start //$(forumWidgetMain).find('.ForumWidget').children(child).find('.viewcomment').replaceWith($(newDiv).find('.viewcomment')); $(forumWidgetMain).find('.ForumWidget').children(child).find('.socialPost').replaceWith($(newDiv).find('.socialPost')); $(forumWidgetMain).find('.ForumWidget').children(child).find('.midcont').replaceWith($(newDiv).find('.midcont')); //post update //if (commentsExpanded) { // $(forumWidgetMain).find('.ForumWidget').children(child).find('.clsExpandAllComment').click(); //} if ($(forumWidgetMain).find('.ForumWidget').children(child).find('.viewcomment .singlereply[data-replyId]').length > 0) { $(newDiv).find('.viewcomment .singlereply[data-replyId]').each(function (i, e) { if ($(forumWidgetMain).find('.ForumWidget').children(child).find('.viewcomment .singlereply[data-replyId=' + $(e).attr('data-replyid') + ']').length == 0) { $(forumWidgetMain).find('.ForumWidget').children(child).find('.viewcomment .singlereply[data-replyId]').last().after($(newDiv).find('.viewcomment .singlereply[data-replyId=' + $(e).attr('data-replyid') + ']')) } else { $(forumWidgetMain).find('.ForumWidget').children(child).find('.viewcomment .singlereply[data-replyId=' + $(e).attr('data-replyid') + ']').replaceWith($(newDiv).find('.viewcomment .singlereply[data-replyId=' + $(e).attr('data-replyid') + ']')); } }); var cntComment = $(forumWidgetMain).find('.ForumWidget').children(child).find('.viewcomment .singlereply[data-replyId]').length; if (cntComment > 1) { $(forumWidgetMain).find('.ForumWidget').children(child).find('.clsPreviousCommentLink').show(); } } else { $(forumWidgetMain).find('.ForumWidget').children(child).find('.viewcomment').replaceWith($(newDiv).find('.viewcomment')); } // hide other comments if (!commentsExpanded && $(forumWidgetMain).find('.ForumWidget').children(child).find('.divNewComments .singlereply[data-replyid]').length > 1) { $(forumWidgetMain).find('.ForumWidget').children(child).find('.divNewComments .singlereply[data-replyid]').not(':last').hide(); } //459: Forums - don't refresh comments area - just append to the bottom with Javascript End } else { $(forumWidgetMain).find('.ForumWidget').prepend(newDiv); } $(commentBox).val(currentText); if (currentText != '' && currentText != null && currentText != undefined) { $('#divProductForumComment' + forumId).show(); $(commentBox).focus(); } }); } if (productForumIdsToRemove != null && productForumIdsToRemove.length > 0)//Remove deleted or rejected product forums { $.each(productForumIdsToRemove, function (index, productForumId) { var child = '.ForumWidgetPost' + productForumId; $('.ForumWidget').children(child).remove(); }); } $("#divProgress").hide(); var cntNewForums = Number($(Data).filter('.hdnNewForumsCounts').val()); updateNewForumCount(cntNewForums) } }, error: function (jqXHR, textStatus, errorThrown) { $("#divProgress").hide(); //$(element).html('Submit My Browser Info').prop('disabled', false); } }); } }); } function updateNewForumCount(cnt) { if (Number(cnt) > 0) { var oldCount = Number($(".baseForumWidget").text() || ''); if (!$("#ForumWidget").is(':visible')) { $(".baseForumWidget").text("New"); } if (typeof notifyForumInApp == "function") { notifyForumInApp(); } } } function sendForumData(action, forumSettingId, productForumId, parentProductForumId) { var forumData = { "Action": action, "Data": { "forumSettingId": forumSettingId, "productForumId": productForumId, "customerId": u, "parentEventTimeid": $('.ForumWidgetMain').attr('data-mainparenteventtimeid'), "parentProductForumId": parentProductForumId } } CE21Forum.sendAction(forumSettingId, forumData); } function deleteProductForums(productForumId, parentProductForumId, forumSettingId) { if (parentProductForumId > 0) { var forumPost = '.ForumWidgetPost' + parentProductForumId; if ($('.ForumWidget').children(forumPost).find(".singlereply[data-replyid=" + productForumId + "]").length > 0) { $('.ForumWidget').children(forumPost).find(".singlereply[data-replyid=" + productForumId + "]").remove(); var isIntegratedForum = false; if ($('.ForumWidgetMain').attr('data-isintegratedfroum') == "true") { isIntegratedForum = true; } var isDisplayAllComment = false; isDisplayAllComment = $('.ForumWidget').children(forumPost).attr("data-Expanded") == "false" ? false : true; loadSingleForumPost(parentProductForumId, forumSettingId, isIntegratedForum, isDisplayAllComment); } } else { var forumPost = '.ForumWidgetPost' + productForumId; if ($('.ForumWidget').children(forumPost).length > 0) { $('.ForumWidget').children(forumPost).remove(); } } } CE21SignalR.onReady(function () { CE21Forum.connectAll(); //CE21Chat.connectAll(); }); function validateEmail(email) { var expr = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,}|[0-9]{1,3})(\]?)$/; return expr.test(email); }; var isImpersonateSession = function () { return document.cookie.indexOf('ImpersonateId=') != -1; } $("body").on("click", ".supoortSolutionPopup", function () { $.magnificPopup.open({ items: { src: '/Tickets/TicketEmailPopup?isViewer=true' }, type: 'iframe', closeOnBgClick: false, mainClass: 'popSupoortSolution' }); $(".popSupoortSolution").find('iframe').attr("id", "ifrSupportSolution"); $(".popSupoortSolution").attr("data-html2canvas-ignore", "true"); return false; }); function validateBrowserCustomer() { var customerId = Helper.Viewer.getCustomerId() || 0; if (customerId === -1) { return; } $.getJSON('/showtimewidget/validatebrowsercustomer?customerId=' + customerId, function (result) { result = result || false; if (!result) { if (typeof (newChatWindow) !== "undefined" && newChatWindow) { newChatWindow.close(); } location.reload(); } }); } //#region #0017665: Viewer > Classroom > End of programs function triggerClassroomEndActions() { if (!isFromClassroomScheduleTab || !seminar || seminar.IsArchive || seminar.PresenterDuration <= 0 || !curRelativeTime) return false; var seminarcurTime = Math.round((curRelativeTime) / 1000), secondsToShowColor = (seminar.IsLive ? 120 : 5) * 60, backgroundColor = 'black', fontweight = 'normal'; if (seminar.PostRollMediaDuration > 0 && seminarcurTime.between(seminar.PresenterDuration, seminar.PresenterDuration + seminar.PostRollMediaDuration)) { setTimeout(triggerClassroomEndActions, seminar.PostRollMediaDuration * 1000); return false; } if ((!seminar.IsLive || (seminar.IsLive && !isGoLiveOn)) && seminarcurTime.between(seminar.PresenterDuration, seminar.PresenterDuration + secondsToShowColor)) { backgroundColor = '#670101'; fontweight = 'bold'; $('.returnToClassroomOverlay').attr('data-iscomplete', true); } $('.viewerHeaderTemporary').css('background-color', backgroundColor); $('.clsReturnToClassroom').css("font-weight", fontweight); } $('body').on('click', '.returnToClassroomOverlay #btnCloseOverlay', function () { $('.returnToClassroomOverlay').attr('data-isclosed', true); }); //#endregion //#region #0017681: Preview viewer function initializePreview() { if (IsTextBasedViewer) { ViewerCountDown.element.hide(); $('a[data-href="eventlog"]').parent().hide(); $("#info-toggle-btn").closest('li').hide(); //add style to clock message $('#pTextBasedCeClock').closest('li').css({ 'margin-left': '10px', 'margin-top': '5px' }); showHideNext(true); showHidePrev(true); return false; } if (isAudtioVideoWidget != "True") return false; seminar = { IsLive: false, IsReplay: false, AspectRatio: '16:9', PresenterStatusList: [], Alerts: [], MediaClips: [], Slides: [] } compositionComplete(); onLoadMediaSlide(); // collapse side panel #8416#c6417 :Let's operate off the checkboxes for now - thus "Start with tabbed panel collapsed" UNchecked would show tabs even if the program has slides. // here condition --$('.viewerHeaderOriginal li.info-toggle-nav').length == 0-- is for, --mantis-- #0010060 if (IsTabPanelCollapsed == "True" || $('.viewerHeaderOriginal li.info-toggle-nav').length == 0) { setTimeout(function () { $('#info-toggle').trigger('click'); $(window).trigger('resize'); }, 500); if ($('.viewerHeaderOriginal li.info-toggle-nav').length == 0) { //--mantis #0010060 $('#sideBarStatustext').hide(); $('#info-toggle').css('color', 'transparent'); } } if (showinfo) { $('#mediaView').addClass('collapseView').removeClass('expandView'); $('#slideView').addClass('collapseView').removeClass('expandView'); } } //#endregion //#region #0018272: Snapshot Preview function isSnapshotWidget(widgetName) { return $.inArray(widgetName, ['CertificationWidget', 'ChatWidget', 'ForumWidget', 'TwitterWidget']) > -1; } function manageSnapshotPreviewWidgets(actionName) { if (!isSnapshotWidget(actionName)) return false; $("#divProgress").show(); var actionUrl = '/ShowtimeWidget/SnapshotWidget?productId=' + Number(s) + '&actionName=' + actionName; $('#' + actionName).load(actionUrl, function () { $("#divProgress").hide(); }); } function convertToArchiveMode() { if (!seminar || !seminar.IsReplay) return false; seminar.IsArchive = true; seminar.IsLive = false; seminar.IsReplay = false; } //#endregion //mantis item #17430 function forceReloadViewer() { location.reload(); //mantis #8479 } $("body").on('click', '.popCertificationPreview', function () { $.magnificPopup.open({ items: { src: $(this).attr("href") }, type: 'iframe', closeOnBgClick: false, mainClass: 'popCertificationPreviewMainClass' }); return false; }); $('body').on('click', '.previewInfo', function () { $.alert({ title: 'Preview Viewer', content: $(".clsPreviewTextModel").html(), useBootstrap: false, boxWidth: '800px', backgroundDismiss: true, buttons: { cancel: { text: 'Close', btnClass: 'btn-default' } } }); }); /*#19688*/ function toggleNavbarForSmallView() { if ($(window).width() < 992) { setTimeout(function () { $(".navbar-toggle").trigger('click'); }, 500); } } function edgeBrowserLuanch() { window.location = 'microsoft-edge:' + window.location; setTimeout(function () { window.location = 'https://www.microsoft.com/en-us/edge?browser=Chrome&FORM=MG0AU2'; }, 5000); } /*#19708*/ $('body').on('click', '.btnmobileFullScreenClose', function () { $('body').removeClass('chat-fullscreen'); }); $('body').on('click', '.btnmobileFullScreenOpen', function () { $('body').addClass('chat-fullscreen'); }); //mantis item #21326 function isPopUpAlertAvailableToOpen() { if (!seminar || !(seminar.IsArchive || seminar.SeminarTypeId == 3 || seminar.SeminarTypeId == 4) || seminar.PopUpAlerts.length <= 0) return false; if (seminar.IsArchive && !seminar.IsAllowCreditForArchive) return false; var seminarcurTime = Math.round((curRelativeTime) / 1000); if (seminarcurTime <= 0) return false; //var archiveDiff = seminar.PresenterDuration - seminarcurTime; //if (!archiveDiff.between(5, -5)) // return false; //ViewerPopupType == 3 Show as a popup after the program var listAvailablePopups = $.grep(seminar.PopUpAlerts, function (element) { return (element.ViewerPopupType == 3 && element.IsCompleted == false); }); return listAvailablePopups.length > 0; } //#21422 function adjustAlert() { $("#msg_panel").css("max-width", ""); $("#msg_panel_pip").css("max-width", ""); if ($('#media-panel').hasClass('PIPR')) { $("#msg_panel").css("max-width", $("#media-container.clsmediapanelViewer").width()); } if ($('#media-panel').hasClass('PIPV')) { $("#msg_panel_pip").css("max-width", $("#slidescreen img").width()); } } function adjustSlide() { if ($(".PIPV").length > 0) { $(".PIPV #mainView .row").css("max-width", $("#slidescreen img").width() + 40 + "px"); } else { $(".PIPV #mainView .row").css("max-width", ""); } } //#21560 function SetForumWigdetTitle() { if ($("#ForumWidget").length > 0 && seminar != null && (seminar.SeminarTypeId == 2 || seminar.SeminarTypeId == 3 || seminar.SeminarTypeId == 4 || (seminar.SeminarTypeId == 8 && seminar.IsArchive))) { $("#forumTitle").text($("a[data-href='ForumWidget']").attr("data-text")); } } //#14143: Viewer > Notes Tab > Prevent users from forgetting to click on "Save Note" to save notes $('body').on('focusout', '#form-notes textarea', function () { ManageNotes('SetItem'); }); function ManageNotes(operationType) { if (!$("#form-notes textarea").length) { return; } var notesKeyName = "Notes_Text_" + s; if (operationType === 'SetItem') { if (localStorage.getItem(notesKeyName) != $('#form-notes textarea').val()) { localStorage.setItem(notesKeyName, $("#form-notes textarea").val()); } } else if (operationType === 'GetItem') { if (localStorage.getItem(notesKeyName)) { $("#form-notes textarea").val(localStorage.getItem(notesKeyName)); } } else { localStorage.removeItem(notesKeyName); } } //End #14143 //#22036 $('body').on('click', '.aForumDocumentUpload', function () { var element = $(this); var forumWidgetMain = $(element).closest('.ForumWidgetMain'); var forumSettingId = $(forumWidgetMain).attr('data-forumsettingid'); var isIntegratedForum = $(forumWidgetMain).attr('data-isintegratedfroum') var url = '/ShowtimeWidget/UploadDocumentPost?productId=' + ps + "&timeId=" + pe + "&forumSettingId=" + forumSettingId + "&isIntegratedForum=" + isIntegratedForum; $.magnificPopup.open({ items: { src: url }, type: 'iframe', closeOnBgClick: false, mainClass: 'popForumVideoUploadMainClass' }); }); //Start #22112 $("body").on("click", "#largeSideBarStatustext", function () { //change icon var isArrowFromLeft = $(this).find('i').hasClass("fa-arrow-from-left"); $('#largeSideBarStatustext i').toggleClass("fa-arrow-from-right", isArrowFromLeft).toggleClass("fa-arrow-from-left", !isArrowFromLeft); //update view var isExpnadSidePanel = $("#media-panel").hasClass("col-md-7") && $("#info-panel").hasClass("col-md-5"); $("#media-panel").toggleClass("col-md-5", isExpnadSidePanel).toggleClass("col-md-7", !isExpnadSidePanel); $("#info-panel").toggleClass("col-md-7", isExpnadSidePanel).toggleClass("col-md-5", !isExpnadSidePanel); $("#sideBarStatustext").toggleClass("hidden", isExpnadSidePanel); $("#largeSideBarStatustext i").attr("data-content", isExpnadSidePanel ? "Decrease side panel size" : "Increase side panel size"); $('#bottomNavDiv').toggleClass("col-md-7", isExpnadSidePanel).toggleClass("col-md-5", !isExpnadSidePanel); $("#bottomNavDivRight").toggleClass("col-md-5", isExpnadSidePanel).toggleClass("col-md-7", !isExpnadSidePanel); $("#bottomNavDivCenter").find("#largeSideBarStatustext").css("float", isExpnadSidePanel ? "left" : "right"); if (seminar != null && seminar.Slides !== undefined && seminar.Slides != null && seminar.Slides.length > 0) { //default to vertical view if (isExpnadSidePanel) { if ($(toggleBtn3).closest('li').hasClass('active')) $(toggleBtn3).closest('li').removeClass("active"); toggleVideoSlide("#video-resize", false, false); } //get last remember view if (!isExpnadSidePanel) { var currentVideoSlideView = sessionStorage.getItem('Viewer_Video_Slide_View' + ProgramRegistrantId); if (currentVideoSlideView) { toggleVideoSlide("#default-view", true, false); $("#" + currentVideoSlideView).click(); } } } }); function InitilizeSideBarBtnPopover() { if ($("#sideBarStatustext i").length > 0) { $('#sideBarStatustext i').popover({ trigger: 'hover' }) .on("show.bs.popover", function () { return $(this).data("bs.popover").tip().css({ width: "155px", color: $("#largeSideBarStatustext").attr('data-color') }) }); } if ($("#largeSideBarStatustext i").length > 0) { $('#largeSideBarStatustext i').popover({ trigger: 'hover' }) .on("show.bs.popover", function () { return $(this).data("bs.popover").tip().css({ width: "190px", color: $("#largeSideBarStatustext").attr('data-color') }) }); } } function SetCurrentVideoSlideView(currentVideoSlideViewId) { if (!($("#media-panel").hasClass("col-md-5") && $("#info-panel").hasClass("col-md-7"))) sessionStorage.setItem('Viewer_Video_Slide_View' + ProgramRegistrantId, currentVideoSlideViewId); } //End #22112 //#22227 function UpdateChatUserOnlineStatus(onlineStatus) { if (!CE21SignalR.isConnected() && !onlineStatus && !u && !e) return; $.post("/Chat/UpdateChatUserOnlineStatus", { 'customerId': u, 'chatRoomentityId': e, 'chatRoomId': chatRoomId, 'onlineStatus': onlineStatus }, function (data) { chatRoomId = data > 0 ? data : 0; }); isUnloadPage = (onlineStatus == 0) ? true : false; } $("body").on('click', '.pop700', function () { $.magnificPopup.open({ items: { src: $(this).attr("href") }, type: 'iframe', closeOnBgClick: false, enableEscapeKey: false, mainClass: 'pop700MainClass' }); return false; }); function UpdateActiveTabHighlightColor() { $("#navlist li").css("border-top", ""); var activeTabHighlightColor = $("#ActiveTabHighlightColor").val(); $("#navlist li.active").css("border-top", "2px solid " + activeTabHighlightColor); } /* Starts #23057 */ function QuickPurchase() { var productId = $("#quickPurchase").attr("data-productId"); var email = $("#quickPurchase").attr("data-value"); var message = '

    The staff registration will be completed under your customer account email ' + email + '. If there isn\'t a customer or speaker account that exists on this tenant with this email currently, a customer account will be autocreated.

    All staff registrations will ensure the customer account is marked as Test Account in order to keep finances proper.

    '; var quickPurchase = "/showtime/OpenQuickPurchase"; var launchViewerURL, myAccountUrl; var isViewer = $("#quickPurchase").attr('data-viewer'); $('#divProgress').show(); $.ajax({ type: "GET", url: quickPurchase, dataType: "json", data: { 'productId': productId, 'email': email }, success: function (data) { $('#divProgress').hide(); if (data.errorMessage) { alert(data.errorMessage); } else { $.confirm({ title: ' Staff Register', boxWidth: '550px', useBootstrap: false, type: 'red', content: message, buttons: { LaunchViewer: { text: 'LAUNCH VIEWER', btnClass: 'btn-info ' + (isViewer == 'True' ? (data.QuickPurchasebtn == "disabled" ? "" : "hidden") : "hidden"), action: function () { if (!launchViewerURL) { var data = QuickpurchaseAlert(productId, email, false); if (data && data.errorMessage) { alert(data.errorMessage); } else { launchViewerURL = data.ViewerUrl; } } window.open(launchViewerURL, '_blank'); }, }, LaunchAccount: { text: 'LAUNCH ACCOUNT', btnClass: 'btn-info ' + (data.QuickPurchasebtn == "disabled" ? "" : "hidden"), action: function () { if (!myAccountUrl) { var data = QuickpurchaseAlert(productId, email, false); if (data && data.errorMessage) { alert(data.errorMessage); } else { myAccountUrl = data.MyAccountUrl; } } window.open(myAccountUrl, '_blank'); }, }, ok: { text: data.QuickPurchasebtn == "disabled" ? 'Registered' : 'STAFF REGISTER', btnClass: 'btn-success btnQuickPurchase ' + data.QuickPurchasebtn, autoClose: false, action: function () { var data = QuickpurchaseAlert(productId, email); if (data && data.errorMessage) { alert(data.errorMessage); } else { this.buttons.LaunchViewer.removeClass("hidden"); launchViewerURL = data.ViewerUrl myAccountUrl = data.MyAccountUrl if (data.LaunchViewerbtn) { this.buttons.LaunchViewer.addClass(data.LaunchViewerbtn); } this.buttons.LaunchAccount.removeClass("hidden"); this.buttons.ok.hide(); this.buttons.cancel.hide(); this.buttons.close.removeClass("hidden"); return false; } } }, cancel: { text: 'Cancel', btnClass: 'btn-default', action: function () { } }, close: { text: 'CLOSE', btnClass: 'btn-default hidden', action: function () { } }, }, onContentReady: function () { $(".btnQuickPurchase.disabled").css('pointer-events', 'auto'); $(".btnQuickPurchase.disabled").attr({ "disabled": true, 'title': 'Quick purchased on ' + data.QuickPurchasedDate, }); }, }); } } }); function QuickpurchaseAlert(productId, userEmail, isPurchasedProduct) { var quickPurchase = "/showtime/QuickPurchase"; var returndata; $.ajax({ type: "GET", url: quickPurchase, dataType: "json", async: false, data: { 'productId': productId, 'email': userEmail, 'isPurchasedProduct': isPurchasedProduct }, success: function (data) { returndata = data; } }); return returndata; }; } function UpdateTabColorForUnauthViewer() { var viewerTitleColor = $("#ViewerTitleColor").val(); var isCleanUnathViewer = $("#CleanUnathViewer").val(); if (isCleanUnathViewer.toLowerCase() == "true") { $("#navlist li a").css("color", "#fff"); $("#navlist li.active a").css("color", viewerTitleColor); } } /* End #23057 */ // Screen reader navigation helper for side panel $("#sidePanelShowAll").click(function (e) { e.preventDefault(); sidePanelShowAll = true; $("#navlist a:visible").each(function (_, e) { $(e).click(); }); $("#navlist").hide(); $("#sidePanelShowAll").hide(); }); ; var trackingFailedTime = 0; //define(["durandal/events"], function (events) { //#region Helpers function setHeader(xhr) { xhr.setRequestHeader("x-ms-version", "2013-08-15"); xhr.setRequestHeader("MaxDataServiceVersion", "3.0"); xhr.setRequestHeader("Accept", "application/json;odata=nometadata"); xhr.setRequestHeader("Content-Type", "application/json;odata=nometadata"); } function padLeft(nr, n, str) { return Array(n - String(nr).length + 1).join(str || "0") + nr; } Array.prototype.unique = function () { var a = this.concat(); for (var i = 0; i < a.length; ++i) { for (var j = i + 1; j < a.length; ++j) { if (a[i] === a[j]) a.splice(j--, 1); } } return a; }; //#endregion //#region Time Sync var curServerTime = null; var curRelativeTime = null; var orignalRelativeTime = null; var curVidDelay = 0; var curMediaClip = null; var certCount = 0, refreshedCertificate = false; var T_ERROR_KEY = "track-" + padLeft(t, 6) + "-" + padLeft(s, 9); // update serverTime function serverTimeUpdate() { //console.log("startTimeUtc " + seminar.StartTimeUtc); var timeNow = new Date(); var viewerServerOffset = (window.vd - window.sd); // time now adjusted by offset between viewer client time and server time. curServerTime = timeNow - viewerServerOffset; // current duration from beginning of seminar // This is the duration that will be used to determine when to show slides/messages and such. //console.log("curServerTime " + curServerTime); //console.log("curRelativeTime " + curServerTime - seminar.StartTimeUtc); if (seminar.IsLive) { curRelativeTime = (curServerTime - seminar.StartTimeUtc); } else if (seminar.IsReplay) { orignalRelativeTime = Math.round((curServerTime - seminar.StartTimeUtc) / 1000); if (orignalRelativeTime <= seminar.MinimumTriggerTime || !curMediaClip) { curRelativeTime = orignalRelativeTime * 1000; } else { curRelativeTime = calculateRelativeTime(); } } else { if (curMediaClip != null) { curRelativeTime = calculateRelativeTime(); } } if (seminar.IsLive || seminar.IsReplay) { var seminarcurTime = Math.round((curRelativeTime) / 1000); if (certCount == 0) { //if time tracking enable then refresh 91% else 75% var percentage = (seminar.TimeTrackingEnabled ? 91 : 75); //get certificate refresh time var seminarPassTime = (((seminar.SeminarMinutes * percentage) / 100) * 60); if ((seminarcurTime > seminarPassTime) && (seminarcurTime < (seminarPassTime + 5))) { RefreshCertificate(); certCount = 1; } } //100% duration then refresh certificate if (refreshedCertificate == false && seminar != null && seminar.SeminarMinutes != undefined && seminar.TimeTrackingEnabled && (Math.round((curRelativeTime) / 1000) > (seminar.SeminarMinutes * 60)) && (Math.round((curRelativeTime) / 1000) < (seminar.SeminarMinutes * 60) + 5) && $('div.CertificationWidget h5.ui-accordion-header:visible').hasClass('ui-state-active') === false) { refreshedCertificate = true; if ($("#CertificationWidget").length == 0 && typeof updateCertCompletionStatus === "function") { //mantis item #18216 updateCertCompletionStatus(); } else { RefreshCertificate(); } } //When seminar starts then we need to refresh certificate [call: starttime + 5 ] if (seminarcurTime === 5) { RefreshCertificate(); } //After 10 second of seminar end - need to refresh certificate if (seminar.PresenterDuration && seminarcurTime === (seminar.PresenterDuration + 10) && $('div.CertificationWidget h5.ui-accordion-header:visible').hasClass('ui-state-active') === false) { RefreshCertificate(); } //#13709 if (seminar && seminar.IsReplay && seminar.IsArchive === false && seminar.PresenterDuration && Math.round(curRelativeTime / 1000).between(seminar.PresenterDuration, seminar.PresenterDuration + 5) && vidPlayer && typeof (vidPlayer.isFullscreen) === "function" && vidPlayer.isFullscreen()) { vidPlayer.exitFullscreen() } //After 2 second of seminar end - trigger post roll video #13488 if (seminar != null && (seminar.IsReplay || seminar.IsLive) && seminar.PresenterDuration > 0 && seminarcurTime == (seminar.PresenterDuration + 5)) { if (seminar.IsReplay && typeof (reInitViewer) === 'function') { reInitViewer(); } else if (seminar.IsLive && typeof (currentLiveStatus) !== 'undefined' && seminar.PostRollMediaSource) { currentLiveStatus = undefined; } } } //#0017665: Viewer > Classroom > End of programs if (curRelativeTime && seminar && seminar.PresenterDuration > 0 && Math.round(curRelativeTime / 1000) == seminar.PresenterDuration) { if (seminar.IsLive && typeof (currentLiveStatus) !== 'undefined') { currentLiveStatus = undefined; } else if (typeof (triggerClassroomEndActions) === 'function') { triggerClassroomEndActions(); } } //console.log("curRelativeTime " + curRelativeTime); checkCertAlertIcon(); } function triggerPostRoll() { if (seminar.IsReplay && orignalRelativeTime > 0 && orignalRelativeTime >= seminar.PresenterDuration && !showPostRollVideoOrNot() && seminar.IsArchive === false && typeof (reInitViewer) === 'function') { reInitViewer(); } } function calculateRelativeTime() { var vtc = curVidTimeCode == null ? 0 : curVidTimeCode; var tt = curMediaClip.TriggerTime == null ? 0 : Number(curMediaClip.TriggerTime); var ip = curMediaClip.InPoint == null ? 0 : Number(curMediaClip.InPoint); return (vtc - ip + tt) * 1000; } function vidDelayUpdate() { //Only gets called if IsLive/IsReplay if (seminar.IsReplay) { //var div = Math.floor(y/x); //var rem = y % x; //var tTime = am.curMediaClip().triggerTime(); //var inTime = am.curMediaClip().inPoint(); //var d = am.curRelativeTime() - (am.curVidTimeCode() * 1000) - tTime - inTime; curVidDelay = 0; //0s for now } else { curVidDelay = 40000; //40s default for now } } //#endregion //#region Actions // Actions are basically a link for events between the presenter and the viewer. // An event can be thrown in the presenter (viewer:media:changeAspectRatio) and // it will be caught passed over to the viewer and re-thrown on a delay based on // the delay of the streaming media. You can then catch the event (media:changeAspectRatio) // in the viewer and do whatever needs to be done. var actions = []; var actionDelay = 100000; //100s default for now var listActions = []; var tableSasActionUri, tableSasActionTimeout, lastActionQueryTime; function queryActionTable(tableSasUrl) { if (tableSasUrl !== undefined && tableSasUrl != null) { //Use SasActionUrl to query the actions table and store in memory for later use if (!lastActionQueryTime) { lastActionQueryTime = curRelativeTime - curVidDelay; } //var q = tableSasUrl + "&$filter=PartitionKey eq '" + padLeft(t, 6) + "-" + padLeft(s, 9) + "-" + padLeft(e, 9) + "'and RowKey ge '" + padLeft(lastActionQueryTime + 100000000000, 12) + "'"; var rowKey = padLeft(lastActionQueryTime + 100000000000, 12); var partitionKey = padLeft(pt, 6) + "-" + padLeft(ps, 9) + "-" + padLeft(pe, 9); var q = tableSasUrl + "&$filter=PartitionKey eq '" + partitionKey + "'and RowKey ge '" + rowKey + "'"; lastActionQueryTime = curRelativeTime - actionDelay; // if (!oldIE) { if (browserSupportsCors()) { $.ajax({ type: "GET", datatype: "json", url: q, beforeSend: setHeader, // Render the table with all the entities if the request succeeds success: function (res, status, xhr) { //console.log("Got Actions"); //If action aleready executed then remove if (res.value != null && res.value.length > 0) { var responceLength = res.value.length; for (var key = 0; key < responceLength; key++) { var lasAction = jQuery.grep(listActions, function (n, i) { return n.RowKey == res.value[key].RowKey; })[0]; if (lasAction == null || lasAction == undefined) { listActions.push(res.value[key]); } else { //console.log("removed"); res.value.splice(key, 1); responceLength = res.value.length; key = key - 1; } } } actions = actions.concat(res.value).unique(); }, error: function (res, status, xhr) { lastActionQueryTime = curRelativeTime - 60000; console.log("Error: Get Actions"); //store in elmah var objErrorDetail = '[Status]= ' + res.status; objErrorDetail += ',[TableSasUrl]= ' + q; objErrorDetail += ',[Navigator]= ' + navigator.userAgent; objErrorDetail += ',[ResponseText]= ' + res.responseText; objErrorDetail += ',[statusText]= ' + res.statusText; objErrorDetail += ',[FunctionName]= queryActionTable'; $.post("/ShowtimeWidget/WriteToElmah", { message: 'Error: Get Actions', errorDetail: objErrorDetail }); } }); } else { $.ajax({ type: "POST", datatype: "json", data: { //'tstore': encodeURIComponent(tableSasUrl), 'tstore': tableSasUrl, 'partitionKey': partitionKey, 'rowKey': rowKey }, url: '/ShowtimeWidget/QueryTableSaas', // Render the table with all the entities if the request succeeds success: function (res, status, xhr) { //console.log("Got Actions"); //If action aleready executed then remove if (res.value != null && res.value.length > 0) { var responceLength = res.value.length; for (var key = 0; key < responceLength; key++) { var lasAction = jQuery.grep(listActions, function (n, i) { return n.RowKey == res.value[key].RowKey; })[0]; if (lasAction == null || lasAction == undefined) { listActions.push(res.value[key]); } else { //console.log("removed"); res.value.splice(key, 1); responceLength = res.value.length; key = key - 1; } } } actions = actions.concat(res.value).unique(); }, error: function (res, status, xhr) { lastActionQueryTime = curRelativeTime - 60000; var responseText = $(res.responseText).filter('title').text(); if (res.status == 403 || responseText.indexOf('403') > -1) { tableSasActionUri = null; } console.log("Error: Get Actions"); } }); } } } function actionsUpdate() { //Check if SasActionUrl is stale and update if needed if (tableSasActionUri != null && tableSasActionTimeout > moment()) { queryActionTable(tableSasActionUri); } else { $.ajax({ type: "GET", url: "/showtimewidget/getactiontablecustomersasurl?tenantid=" + pt + "&seminarid=" + ps + "&timeid=" + pe + "", headers: { "Authorization": "Bearer " + x }, success: function (res, status, xhr) { // Use the table SAS url to query windows azure storage. //console.log("Got Action SAS"); tableSasActionTimeout = moment().add(25, "m"); tableSasActionUri = xhr.responseText.replace(/"/g, ""); queryActionTable(tableSasActionUri); }, error: function (res, status, xhr) { console.log("Error: SAS Actions"); } }); } } function actionCheck() { if (actions && actions.length > 0) { if (seminar.IsReplay) { jQuery.each(actions, function (index, value) { if (value !== undefined && Number(value.ProductTime) < Math.round((curRelativeTime - curVidDelay) / 1000)) { var data = JSON.parse(value.Data); //am.trigger(value.Action, data); triggerActions(value.Action, data); actions.splice(index, 1); } }); //Cleanout past actions jQuery.each(actions, function (index, value) { if (value !== undefined && Number(value.ProductTime) < Math.round((curRelativeTime - curVidDelay) / 1000)) { actions.splice(index, 1); } }); } else { jQuery.each(actions, function (index, value) { //if (value !== undefined && Number(value.ProductTime) === Math.round((curRelativeTime - curVidDelay) / 1000)) { // var data = JSON.parse(value.Data); // //am.trigger(value.Action, data); // triggerActions(value.Action, data); // actions.splice(index, 1); //} if (value !== undefined && Number(value.ProductTime) >= Math.round(((curRelativeTime - curVidDelay) / 1000) - 5) && Number(value.ProductTime) <= Math.round(((curRelativeTime - curVidDelay) / 1000) + 5)) { //console.log('triggered ' + value.RowKey); var data = JSON.parse(value.Data); //am.trigger(value.Action, data); triggerActions(value.Action, data); //if action is excuted succesfull then set IsExecuted = true http://mantis.ce21.com/view.php?id=4518 setActionExecuted(value.RowKey); actions.splice(index, 1); } }); } } } function triggerActions(actionName, data) { switch (actionName) { case "media:gotoMediaPos": media_gotoMediaPos(data.mediaClipid, data.postime); break; case "media:changeMedia": media_changeMedia(data); break; case "certCode:showCertCode": certCode_showCertCode(data); break; case "alert:showAlert": alert_showAlert(data); break; case "alert_clearAlerts": alert_clearAlerts(data); case "alert:showSpeakerGraphicAlert": //#10505 alert_showSpeakerGraphicAlert(data); break; case "alert_clearSpeakerGraphicAlert"://#10505 alert_clearSpeakerGraphicAlert(data); break; case "slide:changeSlide": slide_changeSlide(data); break; case "slide:addSlide": slide_addSlide(data); break; case "slide:changeOrder": slide_changeOrder(data); break; //case "media:ShowMedia": // media_ShowMedia(data); // break; case "slide:ShowSlide": slide_ShowSlide(data); case "golive:ShowLive": show_LiveMedia(data); break; case "slide:DeleteSlideSet": slide_DeleteSlideSet(data); break; case "polling:changeTime": polling_changeTime(data); break; case "polling:hideQuestion": polling_hideQuestion(data); break; case "polling:resetPoll": polling_resetPoll(); break; case "seminar:audioOnly": seminar_audioOnly(data); break; case "slide:HideSlide": slide_HideSlides(data); break; case "certificate:Reload": ReloadCertificate(); break; case "alert:forceReload": forceReloadViewer();//mantis item #17430 break; default: break; } } function setActionExecuted(rowKey) { jQuery.each(listActions, function (index, value) { if (value !== undefined && value.RowKey == rowKey) { value.IsExecuted = true; } }); } function executeMissedAction() { try { if (listActions != null && listActions.length > 0) { //Get action is not executed var listMissedActions = jQuery.grep(listActions, function (n, i) { return (n != undefined) && (n.IsExecuted == undefined || n.IsExecuted == null || n.IsExecuted == false); }); if (listMissedActions != null && listMissedActions.length > 0) { jQuery.each(listMissedActions, function (index, value) { if (Number(value.ProductTime) < Math.round((curRelativeTime - curVidDelay) / 1000) && (value.Action == "media:changeMedia" || value.Action == "alert:showAlert" || value.Action == "golive:ShowLive" || value.Action == "alert:showSpeakerGraphicAlert")) { var data = JSON.parse(value.Data); triggerActions(value.Action, data); //if action is excuted succesfull then set IsExecuted = true http://mantis.ce21.com/view.php?id=4518 setActionExecuted(value.RowKey); console.log('missed action executed'); } }); } } } catch (e) { } } //#endregion //#region Medias var curVidState; var curVidTimeCode = 0; var curVidMediaClipId = 0; var curMediaClip; //#endregion //#region Tracking function trackLocal() { //Record tracking info to local storage updateState(); if (curVidState === "PLAYING") { if (typeof (Storage) !== "undefined") { var uPadded; if (isNaN(u)) uPadded = u; else uPadded = padLeft(u, 9); var tKey = padLeft(t, 6) + "-" + padLeft(s, 9) + "-" + uPadded + "-" + padLeft(curVidMediaClipId, 9); var posTime = curVidTimeCode; var maxTime = posTime; if (localStorage.getItem(tKey)) { maxTime = Math.max(JSON.parse(localStorage.getItem(tKey)).MaxTime, posTime); } var dict = {}; dict["TenantId"] = parseInt(t); dict["ProductId"] = parseInt(s); dict["ProductTime"] = Math.round((curRelativeTime - curVidDelay) / 1000); //Time from the seminar start time. dict["MediaClipId"] = curVidMediaClipId; //Id of the current media clip. dict["MediaTime"] = posTime; //Time from the beginning of the current media clip. dict["MaxMediaTime"] = maxTime; dict["UserId"] = u; localStorage.setItem(tKey, JSON.stringify(dict)); } } } var tableSasTrackingUri, tableSasTrackingTimeout; var lastTrackMediaTime = 0; // used for onDemand User Time Tracking var trackingClipId = 0; function writeTrackingDb(tableSasUrl) { var mediaTime = curVidTimeCode; if (mediaTime >= lastTrackMediaTime) { lastTrackMediaTime = mediaTime; } if (isNaN(mediaTime)) mediaTime = 0; var productTime = Math.round((curRelativeTime - curVidDelay) / 1000); if (seminar != undefined && seminar != null && seminar.MaxRelativeTime != undefined && productTime >= seminar.MaxRelativeTime) { seminar.MaxRelativeTime = productTime; } var rowTime = seminar.IsLive ? productTime : mediaTime; var uPadded; if (isNaN(u)) uPadded = u; else uPadded = padLeft(u, 9); if (trackingClipId == 0) { trackingClipId = curVidMediaClipId; } var dict = {}; dict["PartitionKey"] = padLeft(t, 6) + "-" + padLeft(s, 9) + "-" + uPadded; dict["RowKey"] = padLeft(trackingClipId, 9) + "-" + padLeft(Math.round(rowTime * 10000000), 18); dict["TenantId"] = parseInt(t); dict["ProductId"] = parseInt(s); dict["ProductTime"] = productTime; //Time from the seminar start time. dict["MediaClipId"] = trackingClipId; //Id of the current media clip. dict["MediaTime"] = mediaTime; //Time from the beginning of the current media clip. dict["UserId"] = u; dict["UserAgent"] = navigator.userAgent; dict["IPAddress"] = seminar.ClientIp; dict["ProgramRegistrantId"] = parseInt(ProgramRegistrantId); var trackingData = JSON.stringify(dict); //if (!oldIE) { if (browserSupportsCors() && trackingFailedTime <= 3) { $.ajax({ type: "POST", datatype: "json", data: trackingData, url: tableSasUrl, beforeSend: setHeader, success: function (res, status, xhr) { //console.log("Write Traking"); calculateTimeTrackingPercentage(mediaTime); lastTrackTime = new Date(); }, error: function (res, status, xhr) { if (res && res.status && res.status != 409) { trackingFailedTime += 1; tableSasTrackingUri = null; console.log("Error: Write Traking- Code:" + res.status); AddToTrackingErrordData(dict); WriteElmahError(res, navigator, "writeTrackingDb_If"); } console.log("Error: Write Traking"); } }); } else { console.log("Write: C# Traking"); //$.ajax({ // type: "POST", // datatype: "json", // data: { // 'tstore': tableSasUrl, // //'tstore': encodeURIComponent(tableSasUrl), // //'trackingData': encodeURIComponent(trackingData) // 'trackingData': trackingData // }, // url: '/ShowtimeWidget/WriteToTracking', // success: function (res, status, xhr) { // console.log("Write Traking"); // calculateTimeTrackingPercentage(mediaTime); // }, // error: function (res, status, xhr) { // var responseText = $(res.responseText).filter('title').text(); // if (res.status == 403 || responseText.indexOf('403') > -1) { // tableSasTrackingUri = null; // } // AddToTrackingErrordData(dict); // console.log("Error: Write Traking"); // } //}); $.ajax({ type: "POST", datatype: "json", data: { 'trackingData': trackingData }, url: '/ShowtimeWidget/WriteToTrackingStorage', success: function () { console.log("Write Traking"); calculateTimeTrackingPercentage(mediaTime); lastTrackTime = new Date(); }, error: function () { tableSasTrackingUri = null; AddToTrackingErrordData(dict); console.log("Error: Write Traking"); } }); } //TODO: Look into doing upsert for table storage. if (seminar.SeminarTypeId == 4) { onDemandVideoCompletion(Number(mediaTime)); } } var totalRequiredDuration = null, lastMediaTime = null; function calculateTimeTrackingPercentage(mediaTime) { if ($('.timetrackingPercentange').length > 0) { if (lastMediaTime == null) { lastMediaTime = mediaTime - 50; } var totalPercentageViewed = Number($('.timetrackingPercentange').text().replace('%', '')); if (totalRequiredDuration == null && totalPercentageViewed <= 100) { //Get Required duration $.ajax({ type: "GET", async: false, url: "/showtimewidget/getrequiredduration?tenantId=" + pt + "&productId=" + ps, success: function (data) { totalRequiredDuration = data; } }); } var productTime = Math.round((curRelativeTime - curVidDelay) / 1000); if ((mediaTime - lastMediaTime) > 0 && seminar.LastRelativeTime != null && productTime > seminar.LastRelativeTime && totalRequiredDuration > 0 && totalPercentageViewed <= 100 && curMediaClip != null && curMediaClip.Required == true) { seminar.LastRelativeTime = productTime; //Get total duration viewed var totalViewedDuration = Math.round((totalPercentageViewed * totalRequiredDuration) / 100); totalViewedDuration += (mediaTime - lastMediaTime); //console.log('Diffrence ' + (mediaTime - lastMediaTime)); //console.log('Percentage ' + Math.round((totalViewedDuration * 100) / totalRequiredDuration) + '%') var percentage = Math.round((totalViewedDuration * 100) / totalRequiredDuration); if (percentage <= 0 || percentage >= 100) { } else { //Referesh certficate tab #4849 if (percentage >= 95 && !isRefreshedCertificated) { if (typeof (RefreshCertificate) == "function") { RefreshCertificate(); isRefreshedCertificated = true; } } $('.timetrackingPercentange').text(percentage + '%'); } } lastMediaTime = mediaTime; } } var isRefreshedCertificated = false; function getTimeTrackingPercentage() { updateState(); if ($('.timetrackingPercentange').length > 0 && seminar.IsLive == false && Number(u) != -1 && curVidState === "PLAYING") { $.ajax({ type: "GET", async: false, url: "/showtimewidget/gettimetrackingpercentage?tenantId=" + t + "&productId=" + s + "&customerId=" + u + "&eventTimeId=" + e + "&programRegistrantId=" + ProgramRegistrantId, success: function (data) { $('.timetrackingPercentange').text(Math.round(data) + '%'); //Referesh certficate tab #4849 if (data >= 90 && !isRefreshedCertificated) { if (typeof (RefreshCertificate) == "function") { RefreshCertificate(); isRefreshedCertificated = true; } } } }); } } function trackDb(forcefullyUpdate) { //10210 add forcefullyUpdate trackingClipId = curVidMediaClipId; updateState(); if (curVidState === "PLAYING" || (forcefullyUpdate && forcefullyUpdate == true)) { //Update track details for on demand if (typeof (updateMediaTrackDetails) == "function") { updateMediaTrackDetails(curVidTimeCode); } if (tableSasTrackingUri != null && tableSasTrackingTimeout > moment()) { writeTrackingDb(tableSasTrackingUri); } else { $.ajax({ type: "GET", url: "/showtimewidget/gettrackingtablecustomersasurl?tenantid=" + t + "&seminarid=" + s + "&userid=" + u + "", //headers: { "Authorization": "Bearer " + x }, success: function (res, status, xhr) { if (xhr && xhr.responseText) { // Use the table SAS url to query windows azure storage. console.log("Got Tracking SAS"); tableSasTrackingTimeout = moment().add(25, "m"); tableSasTrackingUri = xhr.responseText.replace(/"/g, ""); writeTrackingDb(tableSasTrackingUri); } }, error: function (res, status, xhr) { console.log("Error: SAS Traking"); WriteElmahError(res, navigator, "trackDb"); } }); } } } var tableSasTrackingIxUri, tableSasTrackingIxTimeout; function writeTrackingIxDb(tableIxSasUrl) { var uPadded; if (isNaN(u)) uPadded = u; else uPadded = padLeft(u, 9); var ticks = ((Date.now() * 10000) + 621355968000000000); var dict = {}; dict["PartitionKey"] = padLeft(t, 6) + "-" + padLeft(s, 9); dict["RowKey"] = padLeft(ticks, 19); dict["OriginalPartitionKey"] = padLeft(t, 6) + "-" + padLeft(s, 9) + "-" + uPadded; dict["ProgramRegistrantId"] = ProgramRegistrantId; var trackingData = JSON.stringify(dict); //if (!oldIE) { if (browserSupportsCors()) { $.ajax({ type: "POST", datatype: "json", data: trackingData, url: tableIxSasUrl, beforeSend: setHeader, success: function (res, status, xhr) { console.log("Write Traking"); }, error: function (res, status, xhr) { console.log("Error: Write Traking"); } }); } else { $.ajax({ type: "POST", datatype: "json", data: { 'tstore': tableIxSasUrl, 'trackingData': trackingData }, url: '/ShowtimeWidget/WriteToTracking', success: function (res, status, xhr) { console.log("Write Traking"); }, error: function (res, status, xhr) { var responseText = $(res.responseText).filter('title').text(); if (res.status == 403 || responseText.indexOf('403') > -1) { tableSasTrackingIxUri = null; } console.log("Error: Write Traking"); } }); } } function trackIxDb() { updateState(); if (curVidState === "PLAYING") { if (tableSasTrackingIxUri != null && tableSasTrackingIxTimeout > moment()) { writeTrackingIxDb(tableSasTrackingIxUri); } else { $.ajax({ type: "GET", url: "/showtimewidget/gettrackingixtablecustomersasurl?tenantid=" + t + "&seminarid=" + s + "", headers: { "Authorization": "Bearer " + x }, success: function (res, status, xhr) { // Use the table SAS url to query windows azure storage. console.log("Got TrackingIx SAS"); tableSasTrackingIxTimeout = moment().add(25, "m"); tableSasTrackingIxUri = xhr.responseText.replace(/"/g, ""); writeTrackingIxDb(tableSasTrackingIxUri); }, error: function (res, status, xhr) { console.log("Error: SAS TrakingIx"); } }); } } } function finalTrack() { //curVidState = "PLAYING"; //trackLocal(); trackDb(true); //curVidState = "IDLE"; } //#endregion var lastTrackTime = null; var initTrackingInterval = function () { Helper.Interval.set("VIEWER_TRACKING", trackDb, 60); } function setIntervals() { serverTimeUpdate(); Helper.Interval.set("VIEWER_SERVERTIMEUPDATE", function () { try { serverTimeUpdate(); } catch (e) { } try { actionCheck(); } catch (e) { } if (seminar.IsArchive == false && seminar.PrePostPopUp != null && seminar.PrePostPopUp.length > 0) { try { checkPrePostPopUp(); } catch (e) { } } }, 1); //Init Tracking initTrackingInterval(); Helper.Interval.set("VIEWER_TRACKINGVALIDATE", function () { trackIxDb(); // if last 3 minutes tracking not done then Init tracking again if (lastTrackTime && ((new Date() - lastTrackTime) / 1000) > 180) { initTrackingInterval(); } }, 5 * 60); if (seminar.IsReplay) { vidDelayUpdate(); //setInterval(function () { vidDelayUpdate(); }, 300000); //5m //actionsUpdate(); //Kiran: added for Mantis #1682 //setInterval(function () { actionsUpdate(); }, 30000); //Kiran: added for Mantis #1682 } if (seminar.IsLive) { vidDelayUpdate(); //setInterval(function () { vidDelayUpdate(); }, 300000); //5m //actionsUpdate(); //setInterval(function () { actionsUpdate(); }, 30000); //setInterval(function () { executeMissedAction() }, 10000); //10s // check any missed action #9650 } initSlides(); //// Attendance requirment //if (seminar.SeminarTypeId == 4 && seminar.AttendanceRequirements != null && seminar.AttendanceRequirements.length > 0) { // setInterval(function () { checkAttendance(); }, 1000); //1s //} ////Pre post Popups //if (seminar.IsArchive == false && seminar.PrePostPopUp != null && seminar.PrePostPopUp.length > 0) { // setInterval(function () { checkPrePostPopUp(); }, 1000); //1s //} if (!seminar.IsLive) { Helper.Interval.set("VIEWER_GETTIMETRACKINGPERCENTAGE", getTimeTrackingPercentage, 10 * 60); } if ((seminar.IsArchive == false || seminar.IsAllowCreditForArchive) && (seminar.SeminarTypeId == 4 || seminar.SeminarTypeId == 3 || seminar.SeminarTypeId == 2) && seminar.PopUpAlerts != null && seminar.PopUpAlerts.length > 0) { //#11525 show quiz popup for archive If, 'Allow registrants to view archive for credit' is selected Helper.Interval.set("VIEWER_CHECKPOPUPALERTS", checkPopUpAlerts, 1); } if (seminar.IsArchive == false) { Helper.Interval.set("VIEWER_SHOWPOPUPPOLLINGQUESTION", showPopUpPollingQuestion, 1); } Helper.Interval.set("VIEWER_CHECKVIEWERPOPUPS", checkViewerPopUps, 1); // checck if any time tracking entry in local storage then update it UpdateLocalTrackingToServer(); Helper.Interval.set("VIEWER_UPDATELOCALTRACKINGTOSERVER", UpdateLocalTrackingToServer, 5 * 60); } function initActions() { setIntervals(); } //#region Slides var slides = []; var slideTimes = []; var slideIsSynch = true; var curSlide = null; var preSlide = null; var curSlideId = 0; function checkSlideTimes() { // If live webcast then no need to use delay because in live webcast it is not calling intervally. var delay = seminar && seminar.IsLive && !seminar.IsArchive ? 0 : curVidDelay; var slideTimes = []; $.each(seminar.Slides, function (outerIndex, outerElement) { if (outerElement.SlideTimes != null && outerElement.SlideTimes.length > 0) { $.each(outerElement.SlideTimes, function (innerIndex, innerElement) { if (innerElement.ProductTime && innerElement.ProductTime <= Math.round((curRelativeTime - delay) / 1000)) { slideTimes.push(innerElement); } }); } }); if (slideTimes.length > 0) { var maxSlideTimes = slideTimes.sort(function (a, b) { return (a.ProductTime - b.ProductTime); }).pop(); if (maxSlideTimes) { if ((Number(seminar.SeminarTypeId) == 4 || Number(seminar.SeminarTypeId) == 3) || ((Number(seminar.SeminarTypeId) == 2 || Number(seminar.SeminarTypeId) == 8) && seminar.IsArchive == true)) { if (curSlideId != Number(maxSlideTimes.SlideId)) { if ($("#SlideThumbsWidget").css("display") == "none") { $(".SlideThumbsWidget a img").removeClass("selected"); if ($("#btnSyncSlide").attr("data-issync") == "true") { $("#slidescreen img").attr('src', maxSlideTimes.Slide.Source); $("#slidescreen a").attr('href', getSlideMarketingUrl(maxSlideTimes.Slide.MarketingUrl)).attr('title', maxSlideTimes.Slide.HoverText).attr("target", getSlideTarget(maxSlideTimes.Slide.MarketingUrl)); } } else { changeSlide(Number(maxSlideTimes.SlideId), maxSlideTimes.Slide.Source, maxSlideTimes.Slide.MarketingUrl, maxSlideTimes.Slide.HoverText); } curSlideId = Number(maxSlideTimes.SlideId); } else { $(".SlideThumbsWidget a[data-slideid='" + curSlideId + "'] img").addClass("selected"); } } else { curSlideId = maxSlideTimes.Slide.SlideId; if ($("#SlideThumbsWidget").css("display") == "none") { $(".SlideThumbsWidget a img").removeClass("selected"); $("#slidescreen img").attr('src', maxSlideTimes.Slide.Source); $("#slidescreen a").attr('href', getSlideMarketingUrl(maxSlideTimes.Slide.MarketingUrl)).attr('title', maxSlideTimes.Slide.HoverText).attr("target", getSlideTarget(maxSlideTimes.Slide.MarketingUrl)); } else { changeSlide(Number(maxSlideTimes.SlideId), maxSlideTimes.Slide.Source, maxSlideTimes.Slide.MarketingUrl, maxSlideTimes.Slide.HoverText); } } } } else { if (seminar.Slides.length > 0 && seminar.IsLive) { changeSlide(Number(seminar.Slides[0].SlideId), seminar.Slides[0].Source, seminar.Slides[0].MarketingUrl, seminar.Slides[0].HoverText); } else if (seminar.Slides.length > 0) { slideTimes = []; //If Ondemand,Replay or IsArchive $.each(seminar.Slides, function (outerIndex, outerElement) { if (outerElement.SlideTimes != null && outerElement.SlideTimes.length > 0) { $.each(outerElement.SlideTimes, function (innerIndex, innerElement) { slideTimes.push(innerElement); }); } }); var firstSlideTimes = slideTimes.sort(function (a, b) { return (b.ProductTime - a.ProductTime); }).pop(); if (firstSlideTimes) { if (curSlideId != Number(firstSlideTimes.SlideId)) { curSlideId = firstSlideTimes.Slide.SlideId; changeSlide(Number(firstSlideTimes.SlideId), firstSlideTimes.Slide.Source, firstSlideTimes.Slide.MarketingUrl, firstSlideTimes.Slide.HoverText); } } else { if (curSlideId != Number(seminar.Slides[0].SlideId)) { curSlideId = seminar.Slides[0].SlideId; changeSlide(Number(seminar.Slides[0].SlideId), seminar.Slides[0].Source, seminar.Slides[0].MarketingUrl, seminar.Slides[0].HoverText); } } } } if ($("#main-panel").css("display") != "none") { $("#slidescreen img").width('100%'); } if (seminar != null && seminar.IsLive) { onLoadMediaSlide(); } } function getSlideMarketingUrl(marketingUrl) { return marketingUrl != undefined && marketingUrl != null && marketingUrl != "" ? marketingUrl : "javascript:void(0)"; } function getSlideTarget(marketingUrl) { return marketingUrl != undefined && marketingUrl != null && marketingUrl != "" ? "_blank" : ""; } function changeSlide(slideId, source, MarketingUrl, HoverText) { if (slideId !== undefined && slideId != null) { if ($("#SlideThumbsWidget").css("display") == "none") { if ($("#btnSyncSlide").attr("data-issync") == "true") { $("#slidescreen img").attr('src', source); $("#slidescreen a").attr('href', getSlideMarketingUrl(MarketingUrl)).attr('title', HoverText).attr("target", getSlideTarget(MarketingUrl)); } } else { $(".SlideThumbsWidget a img").removeClass("selected"); $(".SlideThumbsWidget a[data-slideid='" + slideId + "'] img").addClass("selected"); if ($("#btnSyncSlide").attr("data-issync") == "true") { $(".SlideThumbsWidget a img").removeClass("preview"); $(".SlideThumbsWidget a[data-slideid='" + slideId + "'] img").addClass("preview"); $("#slidescreen img").attr('src', $(".SlideThumbsWidget a[data-slideid='" + slideId + "']").attr('data-href')); var slideThumb = $(".SlideThumbsWidget a[data-slideid='" + slideId + "']"); if (slideThumb.length > 0) { $("#slidescreen a").attr('href', getSlideMarketingUrl(slideThumb.attr('data-marketingurl'))).attr('title', slideThumb.attr('data-hovertext')).attr("target", getSlideTarget(slideThumb.attr('data-marketingurl'))); } autoScrollSlide(); } } } onLoadMediaSlide(); } // slide:changeSlide function slide_changeSlide(data) { var data = data != null ? data.SlideId : 0; var objSlideTime = { SlideTimeId: 0,//Number(data.slideTimeId), ProductTime: Math.round((curRelativeTime - curVidDelay) / 1000), MediaId: 0, MediaTime: 0, SlideId: Number(data),//Number(data.slideId), Slide: null }; // check for log duplication var slideTimesList = []; $.each(seminar.Slides, function (i, slideElement) { if (slideElement.SlideTimes !== undefined && slideElement.SlideTimes != null && slideElement.SlideTimes.length > 0) { slideTimesList.push.apply(slideTimesList, slideElement.SlideTimes); } }); var alertLog = null; //var alertLog = $.grep(slideTimesList, function (n, i) { // return Number(n.SlideTimeId) == Number(data.slideTimeId); //}).pop(); //$.each(seminar.Slides, function (outerIndex, outerElement) { // if (Number(outerElement.SlideId) == Number(data.slideId)) { // objSlideTime.Slide = outerElement; // outerElement.SlideTimes.push(objSlideTime); // } //}); $.each(seminar.Slides, function (outerIndex, outerElement) { if (Number(outerElement.SlideId) == Number(data)) { objSlideTime.Slide = outerElement; outerElement.SlideTimes.push(objSlideTime); } }); //changeSlide(Number(data.slideId), objSlideTime.Slide.Source); if (objSlideTime.Slide) { curSlideId = data; changeSlide(Number(data), objSlideTime.Slide.Source, objSlideTime.Slide.MarketingUrl, objSlideTime.Slide.HoverText); } if (alertLog === undefined || alertLog == null) { // set event log var log = { time: formatDuration(Math.round((curRelativeTime - curVidDelay) / 1000)), timestr: Math.round((curRelativeTime - curVidDelay) / 1000), full: "Set (slideId: " + data + ")", log: "Set (slideId: " + data + ")" }; if (ListEventLogs !== undefined && ListEventLogs != null) { ListEventLogs.push(log); callEventLogs(); } } } //slide:changeOrder function slide_changeOrder(productslidesetIds) { var slideSetOrder = $('img.slideThumb').closest('a').map(function () { return Number($(this).attr('data-productSlideSetId')); }).get().unique().join(","); if (slideSetOrder != productslidesetIds) { var pageWidgetId = $("a[data-href='SlideThumbsWidget']").attr("data-pagewidgetid"); if (pageWidgetId !== undefined && pageWidgetId != null) { $("#SlideThumbsWidget").load("/showtimewidget/slidethumbswidget?PageWidgetID=" + pageWidgetId + "&SeminarId=" + seminar.SeminarId + "&TimeId=" + e + "&CustomerId=" + u + "&ProgramRegistrantId=" + ProgramRegistrantId, function () { ZoomSlides(); checkSlideTimes(); if (isMobileOrIpad.toLowerCase() == "true") { handlePortraitLandscape(); } }); } } } // slide:addSlide function slide_addSlide(data) { var slideSetId = 0; if (data && data.slideSetId) { slideSetId = data.slideSetId; } var pageWidgetId = $("a[data-href='SlideThumbsWidget']").attr("data-pagewidgetid"); if (pageWidgetId !== undefined && pageWidgetId != null) { $("#SlideThumbsWidget").load("/showtimewidget/slidethumbswidget?PageWidgetID=" + pageWidgetId + "&SeminarId=" + seminar.SeminarId + "&TimeId=" + e + "&CustomerId=" + u + "&ProgramRegistrantId=" + ProgramRegistrantId, function () { ZoomSlides(); checkSlideTimes(); if (isMobileOrIpad.toLowerCase() == "true") { handlePortraitLandscape(); } }); $.ajax({ type: "GET", url: "/showtimewidget/getslidelist?SlideSetId=" + slideSetId + "&ProductId=" + seminar.SeminarId, data: { 'SlideSetId': slideSetId, 'ProductId': seminar.SeminarId }, success: function (data) { if (data !== undefined && data != null && data.length > 0) { //When a customer has a live webcast viewer open and goes full screen on the video and then *initial slides* are added into the program, is it possible to force the viewer to exit full screen mode #4398 if (seminar.Slides != null && seminar.Slides.length == 0) { vidPlayer.exitFullscreen(); if ($('#slideSync').length > 0) { $('#btnSyncSlide').attr("data-issync", true); applySlideScreenStatus(); } $(window).trigger('resize'); } seminar.Slides = seminar.Slides.filter(function (n) { return Number(n.SlideSetId) != Number(slideSetId); }); seminar.Slides.push.apply(seminar.Slides, data); console.log("Add new slides"); if (seminar.Slides.length > 0) { slideExists(); onLoadMediaSlide(); //$("#navbar-slide-btn").show(); } else { //$("#navbar-slide-btn").hide(); } if (isMobileOrIpad.toLowerCase() == "true") { handlePortraitLandscape(); } } setSlideCount(seminar.Slides.length); getAllSlideTimes(); // show notification on new slide come $(".alertSlideThumbsWidget").show(); }, error: function (res, status, xhr) { console.log("Error: Getting New Slides"); } }); } } // slide:ShowSlide function slide_ShowSlide(showSlide) { if (showSlide !== undefined && showSlide != null) { if (showSlide.IsActive == true) { $("#slidescreen").show(); slideExists(); onLoadMediaSlide(); } else { $("#slidescreen").hide(); //noSlides(); } var alertLog = $.grep(seminar.PresenterStatusList, function (n, i) { return n.PresenterStatusId == showSlide.PresenterStatusId; }).pop(); seminar.PresenterStatusList.push(showSlide); if (alertLog === undefined || alertLog == null) { //Push in eventlog var log = { time: formatDuration(Math.round((curRelativeTime - curVidDelay) / 1000)), timestr: Math.round((curRelativeTime - curVidDelay) / 1000), full: (showSlide.IsActive ? "Show " : "Hide ") + (showSlide.EntityType == 1 ? "Video" : "Slide"), log: (showSlide.IsActive ? "Show " : "Hide ") + (showSlide.EntityType == 1 ? "Video" : "Slide"), }; if (ListEventLogs !== undefined && ListEventLogs != null) { ListEventLogs.push(log); callEventLogs(); } } } } //show_LiveMedia function show_LiveMedia(data) { if (data !== undefined && data != null) { var presenterStatus = $.grep(seminar.PresenterStatusList, function (n, i) { return Number(n.PresenterStatusId) == Number(data.PresenterStatusId); }).pop(); if (presenterStatus == null || presenterStatus == undefined) { seminar.PresenterStatusList.push(data); } } } // manager slides and media show/hide function checkshowHideMediaSlideTime() { //var casMedia = []; //var casSlide = []; //$.each(seminar.PresenterStatusList, function (outerIndex, element) { // if (Number(element.EntityType) == 1) { // casMedia.push(element); // } // else if (Number(element.EntityType) == 2) { // casSlide.push(element); // } // //if (element.TriggerTime && Number(element.TriggerTime) <= Math.round((curRelativeTime - curVidDelay) / 1000)) { // // if (Number(element.EntityType) == 1) { // // casMedia.push(element); // // } // // else if (Number(element.EntityType) == 2) { // // casSlide.push(element); // // } // //} //}); // show/hide media //if (casMedia.length > 0) { // var maxMedia = casMedia.sort(function (a, b) { return (Number(a.TriggerTime) - Number(b.TriggerTime)); }).pop(); // if (maxMedia) { // if (maxMedia.IsActive == true) { // curMediaClip = null; // vidPlayer.play(); // $("#main-panel").show(); // } // else { // vidPlayer.stop(); // curMediaClip = null; // $("#main-panel").hide() // } // } //} //if (casSlide.length > 0) { // var maxSlide = casSlide.sort(function (a, b) { return (Number(a.TriggerTime) - Number(b.TriggerTime)); }).pop(); // if (maxSlide) { // if (maxSlide.IsActive == true) { // $("#slidescreen").show(); // } // else { // $("#slidescreen").hide() // } // } //} var maxMedia = jQuery.grep(seminar.PresenterStatusList, function (n, i) { return n.EntityType && n.EntityType == 1; }).sort(function (a, b) { return (a.TriggerTime - b.TriggerTime); }).pop(); if (maxMedia) { if (maxMedia.IsActive == true) { curMediaClip = null; vidPlayer.play(); $("#main-panel").show(); //$("#slidescreen img").width('50%'); } else { vidPlayer.pause(); curMediaClip = null; $("#main-panel").hide(); $("#slidescreen img").width('100%'); } } var maxSlide = jQuery.grep(seminar.PresenterStatusList, function (n, i) { return n.EntityType && n.EntityType == 2; }).sort(function (a, b) { return (a.TriggerTime - b.TriggerTime); }).pop(); if (maxSlide) { if (maxSlide.IsActive == true) { $("#slidescreen").show(); //$("#slidescreen img").width('50%'); slideExists(); } else { $("#slidescreen").hide(); $("#slidescreen img").width('100%'); //noSlides(); } } if ($("#slidescreen img").attr("src") === undefined) { //$("#mediaView").removeClass("col-md-6").addClass("col-md-12"); //$("#mediaView").removeClass("col-lg-6").addClass("col-lg-12"); } } // delete slide set function slide_DeleteSlideSet(data) { var slideSetId = 0; if (data && data.slideSetId) { slideSetId = data.slideSetId; } var pageWidgetId = $("a[data-href='SlideThumbsWidget']").attr("data-pagewidgetid"); if (pageWidgetId !== undefined && pageWidgetId != null) { $("#SlideThumbsWidget").load("/showtimewidget/slidethumbswidget?PageWidgetID=" + pageWidgetId + "&SeminarId=" + seminar.SeminarId + "&TimeId=" + e + "&CustomerId=" + u + "&ProgramRegistrantId=" + ProgramRegistrantId, function () { ZoomSlides(); console.log("Delete slides"); seminar.Slides = seminar.Slides.filter(function (n) { return Number(n.SlideSetId) != Number(slideSetId); }); if (seminar.Slides.length > 0) { slideExists(); isRefreshResize = false; //$("#navbar-slide-btn").show(); } else { //$("#navbar-slide-btn").hide(); if (playerInitialized && vidPlayer.isFullscreen()) { isRefreshResize = true; } $(window).trigger('resize'); } $("#slidescreen img").attr('src', ""); checkSlideTimes(); setSlideCount(seminar.Slides.length); // show notification on new slide come $(".alertSlideThumbsWidget").show(); onLoadMediaSlide(); if (isMobileOrIpad.toLowerCase() == "true") { handlePortraitLandscape(); } }); } } function initSlides() { if (seminar.Slides.length > 0) { checkSlideTimes(); if (Number(seminar.SeminarTypeId) == 4 || Number(seminar.SeminarTypeId) == 3 || seminar.IsArchive) { Helper.Interval.set("VIEWER_CHECKSLIDETIMES", checkSlideTimes, 1); } $("#navbar-slide-btn").show(); $("#navbar-video-resize-btn").show(); syncSlides(); $("#btnSyncSlide").attr("data-issync", true); applySlideScreenStatus(); } else { //noSlides(); $("#navbar-slide-btn").hide(); $("#navbar-video-resize-btn").hide(); syncSlides(); } } function slideExists() { //$("#mediaView").removeClass("col-md-12").addClass("col-md-6"); //$("#mediaView").removeClass("col-lg-12").addClass("col-lg-6"); } function polling_changeTime(data) { if (data != null) { var pollQuestionId = data.PollQuestionId; var autoDisplayTime = data.AutoDisplayTime; $.each(seminar.PopUpPollingQuestions, function (outerIndex, outerElement) { if (Number(outerElement.PollQuestionId) == pollQuestionId) { outerElement.AutoDisplayTime = Number(autoDisplayTime); outerElement.DisplayResultTime = data.DisplayResultTime; } }); } } function polling_hideQuestion(data) { if (data != null) { polling_changeTime(data); if (Number(data.AutoDisplayTime) > 0 && Number(data.DisplayResultTime) > -1) { displayPollQuestionResult(data.PollQuestionId, data.DoNotDisplayPollResults); } else if (Number(data.AutoDisplayTime) == 0 && seminar.SeminarTypeId == 2 && Number(data.ProductTime) > 0) { //#17856 displayPollQuestionResult(data.PollQuestionId, data.DoNotDisplayPollResults); } } } function polling_resetPoll() { //delete any stored poll question times and allow you to manually control display of poll questions. #4856 if (seminar.PopUpPollingQuestions != null && seminar.PopUpPollingQuestions.length > 0 && u != "-1") { $.each(seminar.PopUpPollingQuestions, function (outerIndex, outerElement) { outerElement.AutoDisplayTime = null; outerElement.DisplayResultTime = -1; }); getPollingResult(); } } //#endregion //}); function browserSupportsCors() { //Detect browser support for CORS if ('withCredentials' in new XMLHttpRequest()) { /* supports cross-domain requests */ return true; } else if (typeof XDomainRequest !== "undefined") { //Use IE-specific "CORS" code with XDR console.log("IE8 & IE9") return false; } else { //Time to retreat with a fallback or polyfill return false; } } function seminar_audioOnly(data) { if (seminar.IsAudioOnly != data) { seminar.IsAudioOnly = data; $(window).trigger('resize') if (data == false) { location.reload(); } } } // Hide show Slides function slide_HideSlides(data) { //push to presenterStatus if (data !== undefined && data != null) { var presenterStatus = $.grep(seminar.PresenterStatusList, function (n, i) { return Number(n.PresenterStatusId) == Number(data.PresenterStatusId); }).pop(); if (presenterStatus == null || presenterStatus == undefined) { seminar.PresenterStatusList.push(data); } } } //11387: Presenter > Mark Early Ending > Change to Reset > Live Webcast Viewer doesn't get info in Certificate Tab until reload viewer function ReloadCertificate() { if (typeof (RefreshCertificate) == "function") { RefreshCertificate(); } } //Start : handing the tracking data when error occured and not track it // set array of tracking data to local storage when get tracking error in tracking function AddToTrackingErrordData(dict) { if (!dict) { return; } var trackingErrorData = []; if (localStorage.getItem(T_ERROR_KEY)) { trackingErrorData = JSON.parse(localStorage.getItem(T_ERROR_KEY)); } trackingErrorData.push(dict); localStorage.setItem(T_ERROR_KEY, JSON.stringify(trackingErrorData)); } // check if any error data available of tracking : if available then insert it to tracking function UpdateLocalTrackingToServer() { if (T_ERROR_KEY && localStorage.getItem(T_ERROR_KEY)) { var trackingErrorData = JSON.parse(localStorage.getItem(T_ERROR_KEY)); // check any record in list and internet connected then insert it manually to tracking table if (trackingErrorData && doesConnectionExist() && tableSasTrackingUri) { var arrayRawKey = []; for (var i = 0; i < trackingErrorData.length; i++) { var dict = trackingErrorData[i]; var trackingData = JSON.stringify(dict); if (browserSupportsCors()) { $.ajax({ type: "POST", datatype: "json", data: trackingData, url: tableSasTrackingUri, beforeSend: setHeader, success: function (res, status, xhr) { }, error: function (res, status, xhr) { AddToTrackingErrordData(dict); } }); } else { $.ajax({ type: "POST", datatype: "json", data: { 'trackingData': trackingData }, url: '/ShowtimeWidget/WriteToTrackingStorage', success: function () { }, error: function () { AddToTrackingErrordData(dict); } }); } } } localStorage.removeItem(T_ERROR_KEY); } } function doesConnectionExist() { var xhr = new XMLHttpRequest(); var file = "/Images/noPerson.png"; var randomNum = Math.round(Math.random() * 10000); xhr.open('HEAD', file + "?rand=" + randomNum, false); try { xhr.send(); if (xhr.status >= 200 && xhr.status < 304) { return true; } else { return false; } } catch (e) { return false; } } //End : handing the tracking data when error occured and not track it function WriteElmahError(res, navigator, functionName) { var objErrorDetail = '[Status]= ' + res.status; objErrorDetail += ',[Navigator]= ' + navigator.userAgent; objErrorDetail += ',[ResponseText]= ' + res.responseText; objErrorDetail += ',[statusText]= ' + res.statusText; objErrorDetail += ',[FunctionName]=' + functionName; $.post("/ShowtimeWidget/WriteToElmah", { message: 'Error: Tracking', errorDetail: objErrorDetail }); } ; var actionHub = {}, hubName = 'chatHub'; CE21SignalR.onReady(function () { setSignalRStateMessage('Status: Connected!'); connectGroup(); checkSignalRConnected(); }); CE21SignalR.onStateChange(function () { checkSignalRConnected(); }); CE21SignalR.onConnectionFail(function () { checkSignalRConnected(); }); var GROUP_KEY = padLeft(pt, 6) + "-" + padLeft(ps, 9) + "-" + padLeft(pe, 9); function initsignalR() { if ($("#hdnChatHubUrl").length == 0) return CE21SignalR.setUrl($("#hdnChatHubUrl").val()); CE21SignalR.on(hubName, 'receiveAction', function (Jdict) { console.log('action received'); if (Jdict) { var value = JSON.parse(Jdict); if (value.Action == "alert:showAlert" || value.Action == "alert_clearAlerts" || value.Action == "media:changeAspectRatio" || value.Action == "alert:forceReload" || value.Action == "alert:showSpeakerGraphicAlert" || value.Action == "alert_clearSpeakerGraphicAlert") { var data = JSON.parse(value.Data); triggerActions(value.Action, data); } else { actions.push(value); } } }); CE21SignalR.on(hubName, 'newHandouts', function () { if (typeof (getMetarials) != "undefined") getMetarials(); }); CE21SignalR.on(hubName, 'updateCertCodes', function () { if (typeof (certCode_updateCertCodes) != "undefined") certCode_updateCertCodes(); }); viewerChatWidget(); if (typeof (CE21Forum) != "undefined") { CE21Forum.bindListner(); } if (typeof (CE21Chat) != "undefined") { CE21Chat.bindListner(); } CE21SignalR.start() } //Connect group by partition key function connectGroup() { if (CE21SignalR.getHub(hubName)) { CE21SignalR.getHub(hubName).connectGroup(GROUP_KEY); } } //Disconnect group by partition key function disconnectGroup() { if (CE21SignalR.getHub(hubName)) { CE21SignalR.getHub(hubName).disconnectGroup(GROUP_KEY); } } function viewerChatWidget() { actionHub.addNewMessageToPage = function (name, message, chatTime, seminarId, customerId, profileImage, parentSeminarId, chatId, chatUserImageColor, IsModerator, responseData) { // Add the message to the page. if (chatTime !== undefined && chatTime != null && chatTime.length > 0) { chatTime = new Date(chatTime + ' UTC'); } if (Number(seminarId) == Number(seminar.SeminarId) || (Number(parentSeminarId) > 0 && Number(seminar.SeminarId) == Number(parentSeminarId)) || Number(seminar.ParentSeminarId) == Number(seminarId) || (seminar.IsDistributed == false && Number(seminar.ParentSeminarId) == Number(parentSeminarId) && Number(parentSeminarId) > 0)) { //moment().format("M/D/YYYY hh:mm:ss"); //if (Number(customerId) == seminar.Customer.CustomerId) { // profileImage = seminar.Customer.SeoFilename; //} var isAppendFirstChatMessage = (Number(customerId) == seminar.Customer.CustomerId && responseData && responseData.isFirstChat) || false; if ($("#chatDivWidget .clsChatDIv[data-chatid='" + Number(chatId) + "']") === undefined || $("#chatDivWidget .clsChatDIv[data-chatid='" + Number(chatId) + "']") == null || $("#chatDivWidget .clsChatDIv[data-chatid='" + Number(chatId) + "']").length == 0) { //var htmlChatBody = "
  • " + // "Avatar" + // "" + // "
    " + // "
    " + // " " + name + " " + // "" + moment(chatTime).format("MM/DD/YYYY hh:mm A") + "" + // "
    " + // "

    " + message + "

    " + // "
    " + // "
  • "; //$('#chatDiscussion').append(htmlChatBody); chatUserImageColor: (chatUserImageColor == null || chatUserImageColor == "red" ? "" : chatUserImageColor) if (("#chatDivWidget").length > 0) { var chatData = { ProfilePic: (profileImage == null || profileImage == "" ? "" : profileImage), ChatDateTime: moment(chatTime).format("hh:mm A"), Message: message, FirstName: name, chatNoImageStyle: "background-color: " + chatUserImageColor + " !important", chatId: chatId, customerId: customerId, IsModerator: IsModerator, IsCurrentUserModerator: $("#hdnChatModerator").val() == "true", AllowChatMarkAsImportant: $("#hdnAllowChatMarkAsImportant").val() == "true", ChatImportantText: $("#ChatImportantText").val(), IsFirstChat: responseData && responseData.isFirstChat || false, IsAppendFirstChatMessage: isAppendFirstChatMessage } var chatDetail = $("#chat-Html-template").tmpl(chatData); $('#chatDivWidget').append(chatDetail); $('#chatDivWidget [data-toggle="tooltip"]').tooltip(); } //hide welcome message if customer posted message if ($("#chatDivWidget").find(".clsChatDIv").length > 0) { var arrCustomerId = $("#chatDivWidget").find(".clsChatDIv").map(function () { return parseInt($(this).attr("data-customerid")) }).get(); if (arrCustomerId.length > 0 && arrCustomerId.indexOf(customerId) > -1) { $("#chatWelcomeMessageText" + customerId).hide(); } } //chat scoll if not pined if ($(".clsChatPinned").length == 0 || ($(".clsChatPinned").length > 0 && !$(".clsChatPinned").hasClass("active"))) { //$("#chatDivWidget").scrollTop($('#chatDivWidget')[0].scrollHeight); $(".chatroom #page-content-wrapper").scrollTop($('.chatroom #page-content-wrapper')[0].scrollHeight); } if (Number(customerId) != seminar.Customer.CustomerId) { $(".alertChatWidget").show(); } replaceEmojiWithImages(); if (isAppendFirstChatMessage) { initFirstChatMessage(); } } } //$('#discussion').append('
  • ' + htmlEncode(name) + "(" + dates.toString() + ")" // + ': ' + htmlEncode(message) + '
  • '); }; // Get the user name and store it to prepend to messages. //$('#displayname').val(prompt('Enter your name:', '')); // remove message actionHub.removechat = function (chatId) { if (Number(chatId) > 0) { $("#chatDivWidget .clsChatDIv[data-chatid='" + Number(chatId) + "']").remove(); } }; actionHub.updateChatWindow = function (customerIds, updateStatus, chatUsername) { if (updateStatus === "Blacklist" || updateStatus === "Whitelist") { if (customerIds !== null && customerIds !== undefined) { customerIds.split(',').forEach(function (customerId) { $(".chat-sidebar-nav li[data-CustomerId='" + customerId + "'] .dropdown .dropdown-menu.dropdown-menu-right li").toggleClass("hidden") if (updateStatus === "Blacklist") { if (Number(customerId) != seminar.Customer.CustomerId && $(".chat-main-message-container.clsChatDIv[data-CustomerId='" + customerId + "']").length > 0) { $(".chat-main-message-container.clsChatDIv[data-CustomerId='" + customerId + "']").hide(); } if ($(".chat-sidebar-nav li[data-CustomerId='" + customerId + "'] .name").length > 0) { $(".chat-sidebar-nav li[data-CustomerId='" + customerId + "'] .name").removeClass("name").addClass("name-blacklist"); } if ($(".chat-sidebar-nav li[data-CustomerId='" + customerId + "'] #sUsernameBlacklistLabel").hasClass('hidden')) { $(".chat-sidebar-nav li[data-CustomerId='" + customerId + "'] #sUsernameBlacklistLabel").removeClass('hidden'); } } else if (updateStatus === "Whitelist") { if ($(".chat-sidebar-nav li[data-CustomerId='" + customerId + "'] .name-blacklist").length > 0) { $(".chat-sidebar-nav li[data-CustomerId='" + customerId + "'] .name-blacklist").removeClass("name-blacklist").addClass("name"); } if (!$(".chat-sidebar-nav li[data-CustomerId='" + customerId + "'] #sUsernameBlacklistLabel").hasClass('hidden')) { $(".chat-sidebar-nav li[data-CustomerId='" + customerId + "'] #sUsernameBlacklistLabel").addClass('hidden'); } } }); } } else if (updateStatus === "UpdateChatUsername") { $(".chat-sidebar-nav li[data-customerid='" + customerIds + "'] .name .user-name").text(chatUsername) //$(".chat-sidebar-nav li[data-customerid='" + customerIds + "'] .name .user-name")[0].title = chatUsername; $(".chat-sidebar-nav li[data-customerid='" + customerIds + "'] .name .user-name").attr("title", chatUsername); $(".chat-main-message-container.clsChatDIv[data-CustomerId='" + customerIds + "'] .chat-message-bubble .chat-message-user-name .user-name").text(chatUsername); } }; actionHub.UpdateChatsByStatus = function (chatId, status) { if (status == 3) { $("div[data-chatid='" + chatId + "']").remove(); } }; $('body').on("click", "#btn-chat", function () { if ($('#txtChatMessage').val().trim() != "") { var customerChatName = typeof (seminar.Customer.ChatUserName) != "undefined" && seminar.Customer.ChatUserName != null && seminar.Customer.ChatUserName != '' ? seminar.Customer.ChatUserName : seminar.Customer.FirstName; // Call the Send method on the hub. CE21SignalR.getHub(hubName).send(GROUP_KEY, customerChatName, $('#txtChatMessage').val(), seminar.Customer.CustomerId, seminar.SeminarId, Number(e), Number(t), $("#hdnUserIp").val(), seminar.Customer.SeoFilename, null, seminar.ParentSeminarId); // Clear text box and reset focus for next comment. $('#txtChatMessage').val(""); $('#txtChatMessage').focus(); AutoSizeChatTextBox(); } }); $("body").on("keypress", "#txtChatMessage", function (e) { if ($("#chkChatEnter").prop('checked') == true) { if (e.which == 13) { if ($('#txtChatMessage').val().trim() != "") { $("#btn-chat").trigger('click'); return false; } } } }); $("body").on("change", "#chkChatEnter", function (e) { var isActive = $("#chkChatEnter").is(':checked'); localStorage.setItem('loc-pressentertosend', isActive); }); // blacklist customer show their post actionHub.addNewMessageToMyPage = function (name, message, chatTime, seminarId, customerId, profileImage, parentSeminarId, chatId, chatUserImageColor, IsModerator, responseData) { if (Number(customerId) == seminar.Customer.CustomerId) { // Add the message to the page. if (chatTime !== undefined && chatTime != null && chatTime.length > 0) { chatTime = new Date(chatTime + ' UTC'); } if (Number(seminarId) == Number(seminar.SeminarId) || (Number(parentSeminarId) > 0 && Number(seminar.SeminarId) == Number(parentSeminarId)) || Number(seminar.ParentSeminarId) == Number(seminarId) || (seminar.IsDistributed == false && Number(seminar.ParentSeminarId) == Number(parentSeminarId))) { //moment().format("M/D/YYYY hh:mm:ss"); //if (Number(customerId) == seminar.Customer.CustomerId) { // profileImage = seminar.Customer.SeoFilename; //} var isAppendFirstChatMessage = (Number(customerId) == seminar.Customer.CustomerId && responseData && responseData.isFirstChat) || false; if ($("#chatDivWidget .clsChatDIv[data-chatid='" + Number(chatId) + "']") === undefined || $("#chatDivWidget .clsChatDIv[data-chatid='" + Number(chatId) + "']") == null || $("#chatDivWidget .clsChatDIv[data-chatid='" + Number(chatId) + "']").length == 0) { chatUserImageColor: (chatUserImageColor == null || chatUserImageColor == "red" ? "" : chatUserImageColor) if (("#chatDivWidget").length > 0) { var chatData = { ProfilePic: (profileImage == null || profileImage == "" ? "" : profileImage), ChatDateTime: moment(chatTime).format("hh:mm A"), Message: message, FirstName: name, chatNoImageStyle: "background-color: " + chatUserImageColor + " !important", chatId: chatId, customerId: customerId, IsModerator: IsModerator, IsCurrentUserModerator: $("#hdnChatModerator").val() == "true", AllowChatMarkAsImportant: $("#hdnAllowChatMarkAsImportant").val() == "true", ChatImportantText: $("#ChatImportantText").val(), IsFirstChat: false, IsAppendFirstChatMessage: isAppendFirstChatMessage } var chatDetail = $("#chat-Html-template").tmpl(chatData); $('#chatDivWidget').append(chatDetail); $('#chatDivWidget [data-toggle="tooltip"]').tooltip(); $('#chatDivWidget [data-toggle="tooltip"]').tooltip(); } //chat scoll if not pined if ($(".clsChatPinned").length == 0 || ($(".clsChatPinned").length > 0 && !$(".clsChatPinned").hasClass("active"))) { // $("#chatDivWidget").scrollTop($('#chatDivWidget')[0].scrollHeight); $(".chatroom #page-content-wrapper").scrollTop($('.chatroom #page-content-wrapper')[0].scrollHeight); } if (Number(customerId) != seminar.Customer.CustomerId) { $(".alertChatWidget").show(); } replaceEmojiWithImages(); if (isAppendFirstChatMessage) { initFirstChatMessage(); } } } //$('#discussion').append('
  • ' + htmlEncode(name) + "(" + dates.toString() + ")" // + ': ' + htmlEncode(message) + '
  • '); } }; //get updated chat events actionHub.updateChatEventsRecieve = function (chatId, status, count, customerId, isRevert) { if (status && status == "MarkImportant") { $(".importantChatCount[data-chatId=" + chatId + "]").text(Number(count)); if (Number(count) > 0) { $(".importantChatCount[data-chatId=" + chatId + "]").removeClass('hidden'); } else { $(".importantChatCount[data-chatId=" + chatId + "]").addClass('hidden'); } if (parseInt(u) === customerId) { if (isRevert) { $(".btnMarkChatImportant[data-chatId=" + chatId + "]").removeClass('active'); } else { $(".btnMarkChatImportant[data-chatId=" + chatId + "]").addClass('active'); } } } } actionHub.updateChatProfilePicReceive = function (customerId, url) { if (customerId === u) return; //No need to update in same customer as it will update by other method. var classNames, title, imageTag; //Update image in participants panel. $(".chat-sidebar-nav li[data-customerid='" + customerId + "'] img.chat-message-user-image").attr("src", url); if ($(".chat-sidebar-nav li[data-customerid='" + customerId + "'] .chatParticipantNoImage").length > 0) { classNames = "CE21Chat_participantimage chat-message-user-image"; title = ""; if ($(".chat-sidebar-nav li[data-customerid='" + customerId + "'] .chatParticipantNoImage").hasClass("Moderator")) { classNames += " Moderator"; title = "Moderator / speaker"; } imageTag = ""; $(".chat-sidebar-nav li[data-customerid='" + customerId + "'] .chatParticipantNoImage").replaceWith(imageTag); } //Update image in chat bubbles. $(".chat-main-message-container.clsChatDIv[data-CustomerId='" + customerId + "'] .chat-message-user-image-container img").attr("src", url); if ($(".chat-main-message-container.clsChatDIv[data-CustomerId='" + customerId + "'] .chat-message-user-image-container .userCommentNoImage").length > 0) { classNames = "CE21Chat_image chat-message-user-image"; if ($(".chat-main-message-container.clsChatDIv[data-CustomerId='" + customerId + "'] .chat-message-user-image-container .userCommentNoImage").last().hasClass("Moderator")) { classNames += " Moderator"; } imageTag = ""; $(".chat-main-message-container.clsChatDIv[data-CustomerId='" + customerId + "'] .chat-message-user-image-container .userCommentNoImage").replaceWith(imageTag); } } for (key in actionHub) { CE21SignalR.on(hubName, key, actionHub[key]) } } $(function () { initsignalR(); // commented beacuse of it is called from checkSignalRConnected() undefinded state setInterval(function () { checkSignalRConnected(); }, 15 * 1000); checkSignalRConnected(); }); function checkSignalRConnected() { if ($.connection.hub.state == $.signalR.connectionState.connected) { setSignalRStateMessage('Status: Connected!'); $(".chatWifi").attr("title", "Connected!"); $(".chatWifi").removeClass("chatDisconnected"); return; } else if ($.connection.hub.state == $.signalR.connectionState.connecting) { setSignalRStateMessage("Status: Connecting.. "); $(".chatWifi").attr("title", "Connecting.."); $(".chatWifi").addClass("chatDisconnected"); return; } else if ($.connection.hub.state == $.signalR.connectionState.reconnecting) { setSignalRStateMessage("Status: Reconnecting.. "); $(".chatWifi").attr("title", "Reconnecting.."); $(".chatWifi").addClass("chatDisconnected"); return; } else if ($.connection.hub.state == $.signalR.connectionState.disconnected || $.connection.hub.state == undefined) { setSignalRStateMessage("Status: Disconnected!"); $(".chatWifi").attr("title", "Disconnected!"); $(".chatWifi").addClass("chatDisconnected"); } } function setSignalRStateMessage(message) { var $signalRState = $('#signalRState'); if ($signalRState.length == 1) { //$('#navbar-slide-btn').closest('li').after('
  • ') $('#signalRState').show(); } $('#signalRState').html(message); } //Before leave remove connection from group $(window).bind('beforeunload', function () { if (navigator.userAgent.match('Firefox/')) { disconnectGroup(); } }); $(window).on('unload', function () { disconnectGroup(); }); $(window).on('close', function () { disconnectGroup(); }); function UpdateParticipantStatus(tenantId, entityId, customerId, updateStatus, chatUsername) { CE21SignalR.getHub(hubName).updateChatParticipantStatus(GROUP_KEY, tenantId, entityId, Number(e), customerId, updateStatus, chatUsername); } function UpdateChatStatusById(chatEntityId, chatId, status) { CE21SignalR.getHub(hubName).updateChatStatus(GROUP_KEY, Number(t), chatId, status); } function UpdateChatEventsByIdSend(chatId, status, isRevert) { CE21SignalR.getHub(hubName).updateChatEventsSend(GROUP_KEY, Number(t), seminar.Customer.CustomerId, chatId, status, isRevert); } function updateChatProfilePic(customerId, url) { CE21SignalR.getHub(hubName).updateChatProfilePicSend(GROUP_KEY, customerId, url); }; var SyncViewer = function (seminar) { var self = this; self.seminar = seminar; self.interval = null; self.init = function () { if (self.interval) { clearInterval(self.interval); } self.interval = setInterval(self.sync, 420 * 1000);// 7 minute } self.sync = function () { if (!self.seminar.IsLive) { return; } // getting latest on air Status var maxLiveStatus = jQuery.grep(self.seminar.PresenterStatusList, function (n, i) { return n.EntityType && n.EntityType == 3; }).sort(function (a, b) { return (a.TriggerTime - b.TriggerTime); }).pop(); $.ajax({ type: 'POST', url: '/ShowTimeWidget/SyncViewer', data: { CurrentMediaClipId: (curMediaClip || {}).MediaClipId, PresenterStatusId: (maxLiveStatus || {}).PresenterStatusId, ParentTenantId: pt, ParentProductId: ps, ParentEventTimeId: pe, CurrentRelativeTime: Math.round((curRelativeTime - curVidDelay)/ 1000), CurrentSlideId: typeof (curSlideId) != 'undefined' ? curSlideId : 0 }, success: function (data) { if (data) { // If Current media Clip and latest clip not matched then add it in medias if (data.ClipMismatched && data.ClipMismatched == true && data.LatestmediaClip) { self.seminar.MediaClips.push(data.LatestmediaClip); } // If Current air status and latest air status not matched then add it in presenterStatusList if (data.AirMismatched && data.AirMismatched == true && data.LatestAirStatus) { self.seminar.PresenterStatusList.push(data.LatestAirStatus); } // If Current slide and latest Slide not matched then call the silde data if (data.SlideMismatched) { self.getSildes(); } } }, error: function (jqXHR, textStatus, errorThrown) { } }); }; self.getSildes = function () { $.ajax({ type: 'POST', url: '/ShowTimeWidget/GetSlides', data: { 'SeminarId': s }, success: function (data) { if (data) { // If Current slide Clip and latest clip not matched then add it in slide if (data && data.length > 0) { self.seminar.Slides = data; if (typeof (initSlides) == 'function') { initSlides(); } } } }, error: function (jqXHR, textStatus, errorThrown) { } }); }; self.init(); }; ; //#region Media Clip Control var participationAudio1 = document.getElementById("audioCode1"); // this both used for aloud the participant code var participationAudio2 = document.getElementById("audioCode2"); var isGoLiveOn = true; var isShowSlideScreen = true;//#9152 var currentSlideScreenStatus = null;//#9152 var isRefreshResize = false; var isPlayFullTimeLine = false; var curVidTimeCode = 0; var playerInitialized = false; var togoPos = null; var seekBlock = false; var isCurrentLiveStream = false; var curDemoMsg = " "; var currentLiveStatus = undefined; var allmediaTotalDuration = 0; var vidPlayerProcess = []; var isEnableSeekForOnDemand = false; var vidPlayer; var videoEl; var isFocePlay = true; //var isFlash = ((xBrowser === "ie") || (xBrowser === "internetexplorer") || (xUserAgent.indexOf("edge/") > 0) || (xBrowser === "firefox") || (xBrowser === "chrome" && xVersion < 37) || (xBrowser === "safari" && xUserAgent.indexOf('windows') > -1)); var isFlash = false; var iOsDevice = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream; var androidDevice = /Android|webOS|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent); $("#divEventLogs").append('
  • [' + moment().format("MM/DD/YYYY HH:mm:ss") + '] - ' + xBrowser + ' ' + xVersion + ' - Flash? ' + isFlash + '
  • '); $("#divEventLogs").append('
  • [' + moment().format("MM/DD/YYYY HH:mm:ss") + '] - ' + xUserAgent + '
  • '); function hideShowBeginButton() { if (playerInitialized) { $("#btn_start").show(); } else { $("#btn_start").hide(); } } function setAspectRatio() { if (seminar.AspectRatio == "4:3") { $('#mediaView').removeClass('a169').addClass('a43'); $('#slideView').removeClass('a169').addClass('a43'); } else { $('#mediaView').addClass('a169').removeClass('a43'); $('#slideView').addClass('a169').removeClass('a43'); } adjustPIPHeight(); } //#16048: Allow test users to be able to fast forward through a video function isDisallowSkipingAhead() { if (seminar.Customer && seminar.Customer.IsTestAccount) return false; return seminar.DisAllowSkippingAheadInVideo; } function isAllowFullScreenInIos() { return seminar && seminar.IsIosAllowFullScreen; } function isMoreThanOneSeminarMediaClipAvaialble() { if (!seminar || !seminar.MediaClips || seminar.MediaClips.length == 0) return false; return seminar.MediaClips.filter(function (mc) { return mc.IsPreSeminar === false; }).length > 1; } function initializeMediaPlayer() { onLoadMediaSlide(); playerInitialized = true; Helper.VIDEOJS.setVidPlayerSettings(vidPlayer); gotoInitialMediaClip(); setAspectRatio(); //#11378: display a message for webcast/replay/webinar if archive only - no credit if (seminar.IsArchive) { checkArchivePopup() } } function gotoMediaClip(mediaClip, pos) { if (playerInitialized) { pos = pos || null; if (curMediaClip != null && curMediaClip === mediaClip) { togoPos = pos; } else { if (seminar.SeminarTypeId !== 4) { finalTrack(); } if (typeof (curVidTimeCode) != "undefined" && !seminar.IsLive) { curVidTimeCode = null; } curMediaClip = mediaClip; if (curMediaClip != null) { //#13083: Apple Mobile Browser > Viewer with Multiple Segments > Viewer crashes when scrubbed to next segment. var deviceInFullScreenWithiOs = iOsDevice === true && vidPlayer && typeof (vidPlayer.isFullscreen) === "function" && vidPlayer.isFullscreen(); //Video Progress Bar //Calculate Total Duration if (isShowVideoCustomBar() && seminar.MediaClips != null && seminar.MediaClips.length > 0) { allmediaTotalDuration = sumOfMediaClipTotalDuration(seminar.MediaClips, 0); $("#totalDuration").html(secondsToTimeFormat(allmediaTotalDuration)); isPlayFullTimeLine = true; setSegmentPoint(seminar.MediaClips); } curVidMediaClipId = curMediaClip.MediaClipId; var mediaSource = Helper.VIDEOJS.prepareMediaURL(curMediaClip.Media.Source); isEnableSeekForOnDemand = true; //#13083: Apple Mobile Browser > Viewer with Multiple Segments > Viewer crashes when scrubbed to next segment. var changeSrc = function () { removeQualitySwitcher(); if (typeof (videoEl) != "undefined") videoEl = null; vidPlayer.reset(); Helper.VIDEOJS.removeAllRemoteTextTrack(vidPlayer); //Revents the first frame from showing when video has an inpoint if (mediaClip.InPoint && mediaClip.InPoint >= 5) { $("#media-video_Html5_api").hide(); } vidPlayer.src({ "src": mediaSource, "type": Helper.VIDEOJS.getType(mediaSource) }); if (curMediaClip.Media.Captions && curMediaClip.Media.Captions.length > 0) { curMediaClip.Media.Captions.map(function (caption) { Helper.VIDEOJS.addRemoteTextTrack(vidPlayer, { "src": "/getter.ashx?url=" + caption.Src.replace(".ttml", ".vtt"), "srclang": caption.SrcLang, "label": caption.Label, "kind": "captions" }); }); Helper.VIDEOJS.setActiveRemoteTextTrack(vidPlayer); if (Helper.VIDEOJS.hasRemoteTextTrack(vidPlayer)) { $("#subtitle-message").show(); } $(".vjs-subs-caps-button.vjs-menu-button").removeClass("vjs-hidden"); } else { $(".vjs-subs-caps-button.vjs-menu-button").addClass("vjs-hidden"); } }; //#13083: Apple Mobile Browser > Viewer with Multiple Segments > Viewer crashes when scrubbed to next segment. if (deviceInFullScreenWithiOs) { vidPlayer.exitFullscreen(); setTimeout(function () { changeSrc(); }, 100); } else { changeSrc(); } if (iOsDevice && $('#media-container video').length > 0) { $('#media-container video').attr('playsinline', ''); } togoPos = pos; if (seminar.IsReplay && !seminar.IsArchive && togoPos > 0) { //#0018157 curVidTimeCode = togoPos; } isReplayErrorStored = false; setCurrVideoSegment(); if ($("#playlist_panel ul li").length) { $("#playlist_panel ul a").removeClass("selected"); $("#playlist_panel ul a[mediaClipId='" + mediaClip.MediaClipId + "']").addClass("selected"); } chcekIsCurrentLiveStream(); //If ttml file exist the load captions in transcript widget loadCaptions(); Helper.VIDEOJS.setVidPlayerSettings(vidPlayer); //mantis #9534, #15699 } } } // for On Demand if (seminar.SeminarTypeId === 4) { setCurrVideoSegment(); } } var remainSeminarStartTime = 0; function checkGoLiveIsOn() { var maxLiveStatus = jQuery.grep(seminar.PresenterStatusList, function (n, i) { return n.EntityType && n.EntityType == 3; }).sort(function (a, b) { return (a.TriggerTime - b.TriggerTime); }).pop(); if (maxLiveStatus != undefined && maxLiveStatus != null && !maxLiveStatus.IsActive) { return false; } else { return true; } } function showPostRollVideoOrNot() { return seminar && seminar.IsPostRollVideoEnabled; } function showArchive() { $('#divProgress').show(); seminar.ShowArchiveCountDown = false; if (typeof (reInitViewer) === 'function') { reInitViewer(); } else { location.reload(); } } function getTestVideoSource() { var testVideoSource = testVideoUrl; if (seminar != null && seminar.TestVideoSource && seminar.TestVideoSource.length > 0) { testVideoSource = Helper.VIDEOJS.prepareMediaURL(seminar.TestVideoSource); } //#13488: 1 of 3: Manager > Appearance / Viewer Appearance for Video Replay, Live Webcast, Webinars - new Post-roll Option if (showPostRollVideoOrNot() && seminar.PostRollMediaSource) { testVideoSource = Helper.VIDEOJS.prepareMediaURL(seminar.PostRollMediaSource); } else if (seminar && seminar.IsLive && seminar.PostRollMediaSource && Math.round(curRelativeTime / 1000) > seminar.PresenterDuration) { //#13488: Post-Roll video : Presenter is in Live Mode but in OFF AIR testVideoSource = Helper.VIDEOJS.prepareMediaURL(seminar.PostRollMediaSource); } return testVideoSource; } // viewer counter ; (function () { ViewerCountDown = new function () { var self = this; self.element = $("#menuCountDown"); self.textEl = self.element.find('.counterText'); self.sync = function (intTime) { var remaningSeconds, message; // pre seminar countdown if (intTime < 0) { remaningSeconds = 0 - intTime; self.element.show(); message = 'Starts in ' + secondsToDDHHMM(remaningSeconds < 0 ? 0 : remaningSeconds); if (self.element.attr('data-countertype') != 'PreSeminar') self.element.attr('data-countertype', 'PreSeminar'); self.textEl.html(message); } //#13488: 1 of 3: Manager > Appearance / Viewer Appearance for Video Replay, Live Webcast, Webinars - new Post-roll Option else if (seminar.IsReplay && intTime > seminar.PresenterDuration) { remaningSeconds = seminar.ArchiveRelativeTime - intTime; if (seminar.ShowArchiveCountDown) { self.element.show(); message = 'Archive available in ' + secondsToDDHHMM(remaningSeconds < 0 ? 0 : remaningSeconds); if (self.element.attr('data-countertype') != 'Archive') self.element.attr('data-countertype', 'Archive'); self.textEl.html(message); } else if (!seminar.IsAllowToViewArchive) { self.element.show(); self.textEl.html("Program has concluded"); } else { self.element.hide(); } if (remaningSeconds >= -5 && remaningSeconds <= 0) { showArchive(); } } // hide countdown else { if (self.textEl.html()) self.textEl.html(''); if (self.element.attr('data-countertype')) self.element.removeAttr('data-countertype'); self.element.hide(); } } } })(); function checkTriggerTimes() { var intTime = Math.round((curRelativeTime - curVidDelay) / 1000); // sync countdown according to relative time ViewerCountDown.sync(intTime); // check for demo video before seminar start (30 mins before and 20 mins before) remainSeminarStartTime = seminar.StartTimeUtc - new Date(); if (remainSeminarStartTime > 0) { remainSeminarStartTime = (remainSeminarStartTime / 1000) / 60; // convert ms to minutes } if (!ViewerSettings.EnableChat) { showChatWidget(); } showHideLogoBug(); //#0010495 if (showPostRollVideoOrNot()) { return; } if (seminar.IsLive) { var maxLiveStatus = jQuery.grep(seminar.PresenterStatusList, function (n, i) { return n.EntityType && n.EntityType == 3; }).sort(function (a, b) { return (a.TriggerTime - b.TriggerTime); }).pop(); if (maxLiveStatus != undefined && maxLiveStatus != null && !maxLiveStatus.IsActive) { if (currentLiveStatus != maxLiveStatus || currentLiveStatus == undefined) { currentLiveStatus = maxLiveStatus; var testVideoSource = getTestVideoSource(); isGoLiveOn = false; changeVideoSource(testVideoSource); curMediaClip = null; loadCaptions(); //#0017665: Viewer > Classroom > End of programs if (typeof (triggerClassroomEndActions) === 'function') triggerClassroomEndActions(); } return; } else { isGoLiveOn = true; } //#9152: Presenter > Live Webcast Presenter > Ability to change a slides program into Video Only sections checkSlideScreeenIsVisible(); } else if (seminar.IsReplay && orignalRelativeTime < 0 && orignalRelativeTime >= -1800 && vidPlayer) { //As Per mantis task set preroll video #8387: Manager > Appearances > Viewer Layouts > Video Replay Layout ONLY > Add a Preroll Video Option if (!curMediaClip && seminar.PreRollMediaSource && !Helper.VIDEOJS.compareVideoSources(vidPlayer.currentSrc(), seminar.PreRollMediaSource)) { changeVideoSource(seminar.PreRollMediaSource); } if (seminar.ShowPreRollCountDown && !isHidePreRollVideoCountDown()) { curDemoMsg = 'Program begins in ' + secondsToTimeFormat(Math.abs(intTime) < 0 ? 0 : Math.abs(intTime)); if ($("#demoTimer").length > 0) { $("#demoTimer>p").html(curDemoMsg); if (vidPlayer.isFullscreen()) { if (!$("#alert_panel")) $("#media-video").append('

    '); $("#alert_panel>p").text(curDemoMsg); } } else { var text = '

    ' + curDemoMsg + '

    ' $("#media-container").append(text); if (vidPlayer.isFullscreen()) { if (!$("#alert_panel")) $("#media-video").append('

    '); $("#alert_panel>p").text(curDemoMsg); } } //var bottomPosition = getBottomOffset('#media-video'); //$("#demoTimer").css({ 'bottom': (bottomPosition > 0 ? bottomPosition : 0) + 100 }); } else if (seminar.ShowPreRollCountDown && $("#demoTimer").length > 0 && isHidePreRollVideoCountDown()) { $("#demoTimer").remove(); } } else if (seminar.IsReplay && $("#demoTimer").length > 0) { $("#demoTimer").remove(); } if (seminar.IsReplay) { checkSlideScreeenIsVisible(); } if (seminar.IsReplay && curMediaClip && orignalRelativeTime > seminar.MinimumTriggerTime) { makeAvailableCertification(remainSeminarStartTime); return; } var mcs = seminar.MediaClips.filter(function (n) { return n.TriggerTime !== undefined && n.TriggerTime != null && Number(n.TriggerTime) <= Number(intTime); }); var maxMediaClip = mcs.sort(function (a, b) { return (Number(a.TriggerTime) - Number(b.TriggerTime)); }).pop(); if (maxMediaClip) { if (curMediaClip !== maxMediaClip) { isFocePlay = true; var inPoint = maxMediaClip.InPoint; var tcode = intTime - maxMediaClip.TriggerTime + inPoint; if (tcode > 5) { gotoMediaClip(maxMediaClip, tcode); } else { gotoMediaClip(maxMediaClip, null); } } } makeAvailableCertification(remainSeminarStartTime); } //9152: Presenter > Live Webcast Presenter > Ability to change a slides program into Video Only sections function checkSlideScreeenIsVisible() { if (typeof (seminar) == "undefined" || !seminar) { return false; } //Get Slide visible last status based on triggertime var maxSlideHideStatus = null; if (seminar.IsLive) { //Get Slide visible last status based on triggertime maxSlideHideStatus = jQuery.grep(seminar.PresenterStatusList, function (n, i) { return n.EntityType && n.EntityType == 12; }).sort(function (a, b) { return (a.TriggerTime - b.TriggerTime); }).pop(); } else { //Get Slide visible last status based on triggertime for ondemand, replay maxSlideHideStatus = jQuery.grep(seminar.PresenterStatusList, function (n, i) { return n.EntityType && n.EntityType == 12 && hideSlideOrNot(n); }).sort(function (a, b) { return (a.TriggerTime - b.TriggerTime); }).pop(); } if (maxSlideHideStatus != currentSlideScreenStatus) { var isHideSlide = maxSlideHideStatus != null ? maxSlideHideStatus.IsActive : false; currentSlideScreenStatus = maxSlideHideStatus; onLoadMediaSlide(); //if a customer is in full screen video and viewer slides is set to off - no impact. BUT when Viewer slides goes back to ON (after OFF state) - can we take the video player out of full screen mode if (!isHideSlide && playerInitialized && vidPlayer && vidPlayer.isFullscreen()) { //vidPlayer.exitFullscreen(); showSlideinFullscreen();// Display slide in full screen } //#0014677 if (isHideSlide && playerInitialized && vidPlayer && $('body').hasClass('slidefullscreen')) { $('body').removeClass('slidefullscreen'); if (typeof (GoOutFullscreen) == 'function') GoOutFullscreen(); } return !isHideSlide; } else if (currentSlideScreenStatus) { return !currentSlideScreenStatus.IsActive; } else if (!seminar.IsLive) { return seminar.Slides && seminar.Slides.length > 0; } else { return true; } } //#0016822, #0016528 function hideSlideOrNot(presenterStatus) { var triggerTime = Number(presenterStatus.TriggerTime) || 0, isHideSlide = presenterStatus != null ? presenterStatus.IsActive : false, curTime = Math.round((curRelativeTime - curVidDelay) / 1000); // if trigger time is 0 (initial hide) if (triggerTime == 0 && curTime < 0) return true; // ignore future trigger times if (triggerTime > curTime) return false; // if status is slide on - no need to check if (!isHideSlide) return true; // hide if there is no slide trigger times between trigger time and curTime return allSlideTimes && allSlideTimes.filter(function (time) { return time.between(triggerTime, curTime) }).length == 0; } function makeAvailableCertification(remainSeminarStartTime) { if (remainSeminarStartTime <= 0 && moment(new Date()).utc()._i <= seminar.EndTimeUtc) { if ($('input[name="hdnIsAvailableInSeminar"]').length > 0) { $('input[name="hdnIsAvailableInSeminar"]').each(function (index, elem) { if ($(this).val().toLowerCase() == "true" && $($(elem)).prev()) { if (($($(elem)).prev()).val().toLowerCase() == "false") { ($($(elem)).prev()).val("True"); } } }); } } else if (moment(new Date()).utc()._i <= seminar.EndTimeUtc) { if ($('input[name="hdnIsAvailableInSeminar"]').length > 0) { $('input[name="hdnIsAvailableInSeminar"]').each(function (index, elem) { if ($(this).val().toLowerCase() == "true" && $($(elem)).prev()) { ($($(elem)).prev()).val("False"); } }); } } } function changeVideoSource(source) { if (typeof (videoEl) != "undefined") videoEl = null; vidPlayer.reset(); Helper.VIDEOJS.setVidPlayerSettings(vidPlayer); //#15699 Helper.VIDEOJS.removeAllRemoteTextTrack(vidPlayer); vidPlayer.src({ "src": Helper.VIDEOJS.prepareMediaURL(source), "type": Helper.VIDEOJS.getType(source) }); } // switch program from playlist function switchPlaylist(mediaId, element) { // set css for selected program $("#playlist_panel ul a").removeClass("selected"); $(element).addClass("selected"); var selectedMedia = $.grep(seminar.MediaClips, function (e) { return e.MediaClipId == mediaId; }); if (selectedMedia != null && selectedMedia.length > 0) { userOffsetTrackTime = 1; if (onDemandMediaTrack(selectedMedia[0].InPoint || 1, selectedMedia[0])) { gotoMediaClip(selectedMedia[0], null); } } if (seminar.SeminarTypeId != 4) { setCurrVideoSegment(); } } function gotoInitialMediaClip() { if (seminar.IsLive || seminar.IsReplay) { Helper.Interval.set("VIEWER_CHECKTRIGGERTIMES", checkTriggerTimes, 1); } else { Helper.Interval.set("VIEWER_CHECKSLIDESCREEENISVISIBLE", checkSlideScreeenIsVisible, 1); if (seminar.SeminarTypeId == 4 || seminar.IsArchive) { //play last view media if (seminar.LastMediaClip && seminar.LastMediaClip.lastProductTime) { seekSpecificDuration(seminar.LastMediaClip.lastProductTime); } else if (seminar.MediaClips !== undefined && seminar.MediaClips != null && seminar.MediaClips.length > 0) { gotoMediaClip(seminar.MediaClips[0], null); if (seminar.LastMediaClip == null) { seminar.LastMediaClip = { maxMediaClipId: seminar.MediaClips[0].MediaClipId, maxMediaTime: 0, maxProductTime: 0, lastMediaClipId: seminar.MediaClips[0].MediaClipId, lastMediaTime: 0, lastProductTime: 0 }; } } } else if (seminar.MediaClips !== undefined && seminar.MediaClips != null && seminar.MediaClips.length > 0) { gotoMediaClip(seminar.MediaClips[0], null); } } } function handleComplete() { if (seminar.IsLive) { finalTrack(); vidPlayer.pause(); //vidPlayer.stop(); if (seminar.IsLive) { if (curMediaClip !== null && curMediaClip !== undefined && curMediaClip.Media !== undefined && curMediaClip.Media != null && curMediaClip.Media.ContentType && curMediaClip.Media.ContentType == "creative") { setTimeout(function () { vidPlayer.seek(1); }, 100); vidPlayer.play(); } else if (curMediaClip !== null && curMediaClip !== undefined && curMediaClip.Media !== undefined && curMediaClip.Media != null && curMediaClip.Media.ContentType && curMediaClip.Media.ContentType == "program") { vidPlayer.pause(); //vidPlayer.stop(); isFocePlay = false; } else if (curMediaClip == null) { setTimeout(function () { vidPlayer.seek(1); }, 100); } else { vidPlayer.play(); } } else { vidPlayer.play(); } console.log("The End"); } else if (seminar.IsReplay) { handleCompleteforReplay(); } else if (seminar.MediaClips.indexOf(curMediaClip) + 1 < seminar.MediaClips.length) { finalTrack(); lastTrackMediaTime = 0; gotoMediaClip(seminar.MediaClips[seminar.MediaClips.indexOf(curMediaClip) + 1], null); } else { finalTrack(); if (seminar.IsArchive || seminar.SeminarTypeId == 4) { if (seminar.SeminarTypeId == 4) { ////mantis item #21501 - if the video length is not matched with presenter duration setTimeout(function () { callPopUpAlertAfterProgramEnds(); }, 1500); } else if (!isFocePlay) { //mantis item #21326 callPopUpAlertAfterProgramEnds(); } } isFocePlay = false; vidPlayer.pause(); //vidPlayer.stop(); console.log("The End"); } console.log("handleComplete"); isReplayErrorStored = false; } function handleCompleteforReplay() { if (orignalRelativeTime > seminar.MinimumTriggerTime && !showPostRollVideoOrNot() && seminar.MediaClips.indexOf(curMediaClip) + 1 < seminar.MediaClips.length) { finalTrack(); lastTrackMediaTime = 0; gotoMediaClip(seminar.MediaClips[seminar.MediaClips.indexOf(curMediaClip) + 1], null); } else if (curMediaClip == null) { setTimeout(function () { vidPlayer.seek(1); vidPlayer.play(); }, 100); } else { finalTrack(); isFocePlay = false; vidPlayer.pause(); //vidPlayer.stop(); console.log("The End"); //mantis item #21326 if (typeof (isPopUpAlertAvailableToOpen) === "function") { callPopUpAlertAfterProgramEnds(triggerPostRoll); } else { if (typeof (triggerPostRoll) === "function") triggerPostRoll(); } } } function updateState() { if (!vidPlayer) return; if (typeof vidPlayer.getCurrentState == "function") { curVidState = vidPlayer.getCurrentState(); } else { curVidState = Helper.VIDEOJS.getCurrentState(vidPlayer) || "Idle"; } if (curVidState !== getLastState()) { vidPlayerProcess.push({ state: curVidState, time: new Date() }); } $(".srPlayerStatus").hide(); $(".srPlayerStatus[data-status=" + curVidState.toLowerCase() + "]").show(); } var srPlayerControls = { increment: Math.pow(10, 0.3), mute: function () { vidPlayer.muted(true); }, unmute: function () { vidPlayer.muted(false); var minVolume = 1 / Math.pow(srPlayerControls.increment, 4); if (vidPlayer.volume() < minVolume) { vidPlayer.volume(minVolume); } }, louder: function () { vidPlayer.muted(false); vidPlayer.volume(Math.min(1, vidPlayer.volume() * srPlayerControls.increment)); }, quieter: function () { vidPlayer.volume(vidPlayer.volume() / srPlayerControls.increment); }, back30: function () { vidPlayer.currentTime(vidPlayer.currentTime() - 30); }, forward30: function () { vidPlayer.currentTime(vidPlayer.currentTime() + 30); }, } function getLastState() { if (vidPlayerProcess != null && vidPlayerProcess.length > 0) { return vidPlayerProcess[vidPlayerProcess.length - 1].state; } else { return ""; } } //#endregion //#region Alerts var alertTimeout; var curAlert = null; var closeAlertButtonText = ''; function showAlertInFullScreen() { //Show alert in full screen if ($("#msg_panel").length > 0 && $("#msg_panel").html().length > 0 && vidPlayer.isFullscreen() === true) { $(".alert_panel").remove(); var alertText = $("#msg_panel > div").text(); var classDetails = $("#msg_panel").attr('class') != undefined ? $("#msg_panel").attr('class') : ''; var alertBackground = $("#msg_panel").attr("style"); $("#media-video").append('

    ' + closeAlertButtonText + ' ' + alertText + '

    '); } else if (playerInitialized) { $(".alert_panel").remove(); } } function checkAlertTimes() { //console.log("math " + Math.round((curRelativeTime - curVidDelay) / 1000)); var cas = jQuery.grep(seminar.Alerts, function (n, i) { return n.DisplayTime && Number(n.DisplayTime) <= Math.round(curRelativeTime / 1000) && (n.IsStopped == false || n.IsStopped == undefined); }); var maxAlert = cas.sort(function (a, b) { return (Number(a.DisplayTime) - Number(b.DisplayTime)); }).pop(); if (maxAlert) { if (curAlert !== maxAlert) { clearTimeout(alertTimeout); if (Number(maxAlert.DisplayDuration) === 0) { $('body').removeClass('hideSeminarAlert'); curAlert = maxAlert; if (maxAlert.AlertText.trim().length == 0) { resizeLayoutForAlert(); $("#msg_panel:not(.certCode)").empty().hide().removeClass('certCode'); if ($("#msg_panel_pip").length > 0) { $("#msg_panel_pip:not(.certCode)").empty().hide().removeClass('certCode'); } clearAlert(); } else { $("#msg_panel").empty().append(closeAlertButtonText + '
    ' + 'ALERT: ' + maxAlert.AlertText + '
    ').show().removeClass('hidden').removeClass('certCode').css("background-color", maxAlert.AlertColorCode); if ($("#msg_panel_pip").length > 0) { $("#msg_panel_pip").empty().append(closeAlertButtonText + '
    ' + 'ALERT: ' + maxAlert.AlertText + '
    ').show().removeClass('hidden').removeClass('certCode').css("background-color", maxAlert.AlertColorCode);; } resizeLayoutForAlert(); } showAlertInFullScreen(); } else { var timeNow = Math.round(curRelativeTime / 1000); var displayLeft = (Number(maxAlert.DisplayTime) + (Number(maxAlert.DisplayDuration) * 60)) - timeNow; if (displayLeft > 0) { $('body').removeClass('hideSeminarAlert'); curAlert = maxAlert; if (maxAlert.AlertText.trim().length == 0) { resizeLayoutForAlert(); $("#msg_panel:not(.certCode)").empty().hide().removeClass('certCode'); if ($("#msg_panel_pip").length > 0) { $("#msg_panel_pip:not(.certCode)").empty().hide().removeClass('hidden').removeClass('certCode'); } showAlertInFullScreen(); } else { $("#msg_panel").empty().append(closeAlertButtonText + '
    ' + 'ALERT: ' + maxAlert.AlertText + '
    ').show().removeClass('hidden').removeClass('certCode').css("background-color", maxAlert.AlertColorCode); if ($("#msg_panel_pip").length > 0) { $("#msg_panel_pip").empty().append(closeAlertButtonText + '
    ' + 'ALERT: ' + maxAlert.AlertText + '
    ').show().removeClass('hidden').removeClass('certCode').css("background-color", maxAlert.AlertColorCode); } showAlertInFullScreen(); resizeLayoutForAlert(); } alertTimeout = setTimeout(function () { resizeLayoutForAlert(); $("#msg_panel:not(.certCode)").empty().hide().removeClass('certCode'); if ($("#msg_panel_pip").length > 0) { $("#msg_panel_pip:not(.certCode)").empty().hide().removeClass('certCode'); } showAlertInFullScreen(); clearAlert(); }, displayLeft * 1000); } else if (displayLeft < 0) { resizeLayoutForAlert(); $("#msg_panel:not(.certCode)").empty().hide().removeClass('certCode'); if ($("#msg_panel_pip").length > 0) { $("#msg_panel_pip:not(.certCode)").empty().hide().removeClass('certCode'); } clearAlert(); showAlertInFullScreen(); } } } } } function clearAlert() { resizeLayoutForAlert(); if (alertTimeout != null) { clearTimeout(alertTimeout); $("#msg_panel:not(.certCode)").empty().hide().removeClass('certCode'); if ($("#msg_panel_pip").length > 0) { $("#msg_panel_pip:not(.certCode)").empty().hide().removeClass('certCode'); } showAlertInFullScreen(); curAlert = null; } if ($("#msg_panel").length > 0) { $("#msg_panel:not(.certCode)").empty().hide().removeClass('certCode'); curAlert = null; } if ($("#msg_panel_pip").length > 0) { $("#msg_panel_pip:not(.certCode)").empty().hide().removeClass('certCode'); } $('body').removeClass('hideSeminarAlert'); } function resizeLayoutForAlert() { //Set layout again if ($("#msg_panel").is(':visible') || $("#msg_panel_pip").is(':visible')) { setTimeout(function () { adjustPIPHeight(); }, 500); } } $('body').on('click', '.alert-close', function () { $('#msg_panel').addClass('hidden'); $('.alert_panel').addClass('hidden'); $('#msg_panel_pip').addClass('hidden'); $('body').addClass('hideSeminarAlert'); adjustPIPHeight(); if ($('#msg_panel').hasClass('.certCode') || $('#msg_panel_pip').hasClass('.certCode')) { curAlert = null; } }); //#endregion $('body').on('click', '.forumalert-close', function () { $('#Forummsg_panel').addClass('hidden').html(""); }); //#region CertCodes var submitCodeTimeOut = null; function savePartCode(id, order, code, certCodeId) { var message = "You have saved the " + order + " participation code (" + code + ") for this program. You will still need to submit your saved participation codes upon completion of the program." if (submitCodeTimeOut) { clearTimeout(submitCodeTimeOut); } $.ajax({ type: "POST", url: "/items/savecode", dataType: "json", data: { 'ProductParticipationCodeID': id, 'ProgramRegistrantId': ProgramRegistrantId }, success: function (data) { submitCodeTimeOut = setTimeout(function () { $('.certCode').empty().hide().removeClass('certCode'); resizeLayoutForAlert(); curAlert = null; }, 10 * 1000); //10 sec $("#msg_panel").empty().addClass("certCode").append(closeAlertButtonText + '
    ' + message + '
    ').show().removeClass('hidden'); if ($("#msg_panel_pip").length > 0) { $("#msg_panel_pip").empty().addClass("certCode").append(closeAlertButtonText + '
    ' + message + '
    ').show().removeClass('hidden'); } resizeLayoutForAlert(); $(".lc_panel").remove(); // update isCompleted for this $.each(seminar.CertCodes, function (outerIndex, outerElement) { if (outerElement.CertCodeId == certCodeId) { outerElement.IsCompleted = true; } }); checkCertCodeTimes(); if (typeof (CallCertificate) == "function") { CallCertificate(); } //if (typeof (RefreshCertificate) == "function") { // RefreshCertificate(); //#8491 //} }, }); } function removeDisabledSubmit() { $(".participationcode").removeAttr("disabled") $("#dvParticipation").popover("destroy") } var certCodes = []; var certCodeTimes = []; var certCodeTimeout; var curCertCodeTime = null; var maxCertcodeProductTime = 0; function checkCertCodeTimes() { $("#debugCurTime").text(Math.round((curRelativeTime - curVidDelay) / 1000)); if (seminar != null && seminar.IsArchive === true && seminar.IsAllowCreditForArchive === false) { removeDisabledSubmit(); return; } var cas = []; $.each(seminar.CertCodes, function (outerIndex, outerElement) { if (!outerElement.IsCompleted) { $.each(outerElement.CertCodeTimes, function (innerIndex, innerElement) { if (innerElement.ProductTime && Number(innerElement.ProductTime) <= Math.round((curRelativeTime - curVidDelay) / 1000)) { cas.push(innerElement); } //#21206: if (innerElement.IsRepeat == false && innerElement.ProductTime && maxCertcodeProductTime < innerElement.ProductTime) { maxCertcodeProductTime = innerElement.ProductTime; } }); } }); if (seminar.CertCodes && (seminar.CertCodes.length == seminar.CertCodes.filter(x => x.IsCompleted == true).length || Math.round((curRelativeTime - curVidDelay) / 1000) >= maxCertcodeProductTime)) { removeDisabledSubmit(); } var maxCertCodeTime = cas.sort(function (a, b) { return (Number(a.ProductTime) - Number(b.ProductTime)); }).pop(); if (maxCertCodeTime) { if (curCertCodeTime !== maxCertCodeTime) { curCertCodeTime = maxCertCodeTime; $(".lc_panel").remove(); clearTimeout(certCodeTimeout); var timeNow = Math.round((curRelativeTime - curVidDelay) / 1000); var displayLeft = (Number(maxCertCodeTime.ProductTime) + Number(maxCertCodeTime.DisplayDuration)) - timeNow; if (displayLeft > 0) { var id = maxCertCodeTime.CertCodeTimeId; var code = maxCertCodeTime.CertCode.Code; var order = maxCertCodeTime.CertCode.Order; var certCodeId = maxCertCodeTime.CertCodeId; var minProductParticipationCodeID = maxCertCodeTime.CertCode.MinProductParticipationCodeID var displayOrder = maxCertCodeTime.DisplayOrder; //switch (order) { case 1: order = "1st"; break; case 2: order = "2nd"; break; case 3: order = "3rd"; break; default: order = order + "th"; } order = ordinal_suffix_of(order); var msg = 'The ' + order + ' letter code is: ' + code + ''; var tokens = minProductParticipationCodeID + ",'" + order + "','" + code + "'," + certCodeId; var AcknowledgeButton = u != "-1" ? '' : ""; $("#media-video").append('

    ' + msg + '

    ' + AcknowledgeButton + '
    '); $("#slidescreen").append('

    ' + msg + '

    ' + AcknowledgeButton + '
    '); adjustPIPHeight(); IsBrowserFocusOnParticipationCodeShow = IsBrowserFocus; certCodeTimeout = setTimeout(function () { MissedParticipationCodeBroserStatus(minProductParticipationCodeID, displayOrder); }, displayLeft * 1000); //#10615: make the audio code Audible //10863 live webcast or video replay**** the read aloud function should not work. //17780: Lists > Cert Requirements > Participation Codes: Add Setting for Audio Notification when Participation Code Appears if (maxCertCodeTime.SpeakParticipantCode && maxCertCodeTime.VoiceType !== "None" && (seminar.SeminarTypeId === 4 || maxCertCodeTime.VoiceType === "AlertTone")) speakParticipantCode(maxCertCodeTime.CertCode.Order, code, maxCertCodeTime.VoiceType, maxCertCodeTime.CustomAlertTonePath); } } } } //Update Browser Status For Missed Participation Code function MissedParticipationCodeBroserStatus(id, displayOrder) { if ($(".lc_panel").length > 0) { $(".lc_panel").remove(); var browserstatus = "OutFoucus"; if (IsBrowserFocusOnParticipationCodeShow != IsBrowserFocus) { browserstatus = "PartiallyInFocus" } else if (IsBrowserFocus == true) { browserstatus = "InFocus"; } $.ajax({ type: "POST", url: "/Items/SaveBrowserStatusForMissedParticipationCode", dataType: "json", data: { 'ProductParticipationCodeID': id, 'ProgramRegistrantId': ProgramRegistrantId, 'DisplayOrder': displayOrder, 'browserStatus': browserstatus }, success: function (data) { }, }); } } function ordinal_suffix_of(i) { var j = i % 10, k = i % 100; if (j == 1 && k != 11) { return i + "st"; } if (j == 2 && k != 12) { return i + "nd"; } if (j == 3 && k != 13) { return i + "rd"; } return i + "th"; } //Aloud participant Code function speakParticipantCode(order, code, voiceType, customAlertTonePath) { if (order && code) { try { code = code.toLowerCase(); var originalVolume = vidPlayer.volume(); vidPlayer.volume(0.1);// When the code pops up, turn down the video player audio levels to 10% and read the code aloud at 100%. //$.sound_path = "/themes/new/content/participantcodemp3/"; $.sound_path = "https://cdn.pesi23.com/participationcodsounds/"; // alert tone #17780 if (voiceType === 'AlertTone' || voiceType === 'CustomAlertTone') { var tonePath = $.sound_path + 'alert_tone.mp3'; if (voiceType === 'CustomAlertTone' && customAlertTonePath) { tonePath = customAlertTonePath; } participationAudio1.setAttribute('src', tonePath); if (!iOsDevice) { participationAudio1.volume = 1.0; } //OnDemand media type stop the video and play the paricipant code if (seminar.SeminarTypeId === 4) { vidPlayer.pause(); } participationAudio1.play(); participationAudio1.addEventListener('ended', function () { // play code when the order sound ended vidPlayer.volume(originalVolume); //Once the read aloud code audio ends, change video player audio back to 100%. set original which user selected last //OnDemand media type when stop the paricipant code then play video if (seminar.SeminarTypeId === 4) { vidPlayer.play(); } }); return; } participationAudio1.setAttribute('src', $.sound_path + order + (voiceType == "Female" ? "_female" : "") + '.mp3'); if (!iOsDevice) { participationAudio1.volume = 1.0; } //OnDemand media type stop the video and play the paricipant code if (seminar.SeminarTypeId === 4) { vidPlayer.pause(); } participationAudio1.play(); participationAudio2.setAttribute('src', $.sound_path + code + (voiceType == "Female" ? "_female" : "") + '.mp3'); if (!iOsDevice) { participationAudio2.volume = 1.0; } participationAudio1.addEventListener('ended', function () { // play code when the order sound ended participationAudio2.play(); participationAudio2.addEventListener('ended', function () { vidPlayer.volume(originalVolume); //Once the read aloud code audio ends, change video player audio back to 100%. set original which user selected last //OnDemand media type when stop the paricipant code then play video if (seminar.SeminarTypeId === 4) { vidPlayer.play(); } }); }); } catch (e) { } } } var isInitilizeAloudPartCode = false; function InitilizeAloudPartCode() { try { setTimeout(function () { seekBlock = false; }, 500); if (!isInitilizeAloudPartCode) { // if already Initilize then not do anything so it is initilize one time participationAudio1.volume = 0; // set volume 0 so first time it play no sound come participationAudio1.play(); participationAudio2.volume = 0; participationAudio2.play(); isInitilizeAloudPartCode = true; } } catch (e) { isInitilizeAloudPartCode = false; } } //#endregion //#region Event Handlers function media_gotoMediaPos(mediaClipid, postime) { var mediaClip = $.grep(seminar.MediaClips, function (e) { return e.MediaClipId == mediaClipid; }); //var mediaClip = ko.utils.arrayFirst(seminar.MediaClips, function (m) { return mediaClipid === m.MediaClipId(); }); if (mediaClip.length > 0) { gotoMediaClip(mediaClip[0], postime); } } function media_changeAspectRatio(ratio) { seminar.AspectRatio = ratio; setAspectRatio(); if (vidPlayer) { vidPlayer.aspectRatio(ratio); $(window).trigger('resize'); } //if (ratio == "16:9") { // $("#media-container_aspect").css({ 'margin-top': '56.25%' }); //} //else { // $("#media-container_aspect").css({ 'margin-top': '75%' }); //} } function creatreMediaClip(mc) { var objMediaClip = { MediaClipId: mc.mediaClipId, MediaId: mc.mediaId, TriggerTime: mc.triggerTime, InPoint: mc.inPoint, OutPoint: mc.outPoint, Media: objMedia }; return objMediaClip; } function media_changeMedia(mc) { var objMediaClip; var objMedia = null; $.each(seminar.MediaClips, function (index, element) { if (element.Media.MediaId == mc.mediaId) { //element.TriggerTime = mc.triggerTime; element.InPoint = mc.inPoint; element.OutPoint = mc.outPoint; element.Media.Source = mc.source; objMedia = element.Media; } }); if (objMedia == null) { objMedia = { MediaId: mc.mediaId, Source: mc.source, Label: mc.label }; } var objMediaClip = { MediaClipId: mc.mediaClipId, MediaId: mc.mediaId, TriggerTime: mc.triggerTime, InPoint: mc.inPoint, OutPoint: mc.outPoint, Media: objMedia }; //seminar.MediaClips.push(objMediaClip); var alertLog = $.grep(seminar.MediaClips, function (n, i) { return n.MediaClipId == mc.mediaClipId; }).pop(); if (alertLog === undefined || alertLog == null) { seminar.MediaClips.push(objMediaClip); // set event log; var log = { time: formatDuration(Math.round((curRelativeTime - curVidDelay) / 1000)), timestr: Math.round((curRelativeTime - curVidDelay) / 1000), full: "Media: " + mc.label, log: "Media: " + mc.label, }; if (ListEventLogs !== undefined && ListEventLogs != null) { ListEventLogs.push(log); callEventLogs(); } } } function media_ShowMedia(showMedia) { if (showMedia !== undefined && showMedia != null) { if (showMedia.IsActive == true) { curMediaClip = null; vidPlayer.play(); $("#main-panel").show(); $("#slidescreen img").width('50%'); } else { vidPlayer.pause(); //vidPlayer.stop(); curMediaClip = null; curVidState = "PLAYING"; $("#main-panel").hide(); $("#slidescreen img").width('100%'); } var alertLog = $.grep(seminar.PresenterStatusList, function (n, i) { return n.PresenterStatusId == showMedia.PresenterStatusId; }).pop(); seminar.PresenterStatusList.push(showMedia); if (alertLog === undefined || alertLog == null) { //Push in eventlog var log = { time: formatDuration(Math.round((curRelativeTime - curVidDelay) / 1000)), timestr: Math.round((curRelativeTime - curVidDelay) / 1000), full: (showMedia.IsActive ? "Show " : "Hide ") + (showMedia.EntityType == 1 ? "Video" : "Slide"), log: (showMedia.IsActive ? "Show " : "Hide ") + (showMedia.EntityType == 1 ? "Video" : "Slide"), }; if (ListEventLogs !== undefined && ListEventLogs != null) { ListEventLogs.push(log); callEventLogs(); } } } } function certCode_showCertCode(a) { //CertCode //dataProperties: { // certCodeId: { dataType: ID, isNullable: false, isPartOfKey: true }, // order: { dataType: DT.Int32 }, // code: { dataType: DT.String }, // seminarId: { dataType: ID, isNullable: false } //} //create CertCodeTime //var objCertCodeTime = { // CertCodeTimeId: a.certCodeTimeId, // CertCodeId: a.certCodeId, // ProductTime: a.productTime, // DisplayDuration: a.displayDuration //}; $.each(seminar.CertCodes, function (outerIndex, outerElement) { $.each(outerElement.CertCodeTimes, function (innerIndex, innerElement) { if (innerElement.CertCodeTimeId == a.certCodeTimeId) { innerElement.CertCodeId = a.certCodeId; innerElement.ProductTime = a.productTime; innerElement.DisplayDuration = a.displayDuration; } }); }); //var certCodeTime = dc.createCertCodeTime({ // certCodeTimeId: a.certCodeTimeId, // certCodeId: a.certCodeId, // productTime: a.productTime, // displayDuration: a.displayDuration //}); //certCodeTimes.push(certCodeTime); } function certCode_updateCertCodes() { if (!seminar) return false; $.ajax({ type: 'POST', url: '/ShowtimeWidget/GetLatestParticipationCodes', dataType: 'json', data: { 'seminarId': s, 'timeId': e, 'customerId': u, 'programRegistrantId': ProgramRegistrantId, 'parentTenantId': seminar.ParentTenantId, 'parentSeminarId': seminar.ParentSeminarId }, success: function (certCodes) { seminar.CertCodes = certCodes; }, error: function () { console.log("error: getting seminar cert codes"); } }); } function alert_showAlert(a) { // create Alert object var objAlert = { AlertId: Number(a.alertId), AlertText: a.alertText, DisplayTime: a.displayTime, DisplayDuration: a.displayDuration, IsStopped: a.isStopped, AlertColorCode: a.AlertColorCode }; // set event log var alertLog = $.grep(seminar.Alerts, function (n, i) { //return n.full && n.full.toLowerCase() == a.alertText.toLowerCase(); return Number(n.AlertId) == Number(a.alertId); }).pop(); if (alertLog === undefined || alertLog == null) { seminar.Alerts.push(objAlert); var log = { time: formatDuration(Math.round((curRelativeTime - curVidDelay) / 1000)), timestr: Math.round((curRelativeTime - curVidDelay) / 1000), full: a.alertText, log: "Alert: " + (a.alertText.length > 30 ? a.alertText.substring(0, 30) + "..." : a.alertText), }; if (ListEventLogs !== undefined && ListEventLogs != null) { ListEventLogs.push(log); callEventLogs(); } } else { var index = seminar.Alerts.indexOf(alertLog); seminar.Alerts[index].IsStopped = objAlert.IsStopped; seminar.Alerts[index].DisplayTime = objAlert.DisplayTime; //Clear alert if (curAlert != null && curAlert.AlertId == objAlert.AlertId && objAlert.IsStopped != undefined && objAlert.IsStopped == true) { clearAlert(); } } } //#8497 function alert_clearAlerts(alerts) { jQuery.each(alerts, function (index, alertId) { var alertLog = $.grep(seminar.Alerts, function (n, i) { //return n.full && n.full.toLowerCase() == a.alertText.toLowerCase(); return Number(n.AlertId) == Number(alertId); }).pop(); if (alertLog) { var index = seminar.Alerts.indexOf(alertLog); seminar.Alerts[index].IsStopped = true; } }); } //#endregion function mobilecheck() { var check = false; (function (a, b) { if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od|ad)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0, 4))) check = true })(navigator.userAgent || navigator.vendor || window.opera); return check; } function eventLog(msg) { console.log(msg); var tempString = '
  • [' + moment().format("MM/DD/YYYY HH:mm:ss") + '] - ' + msg + '
  • '; $("#divEventLogs").append(tempString); } //################### function updateHLS() { } function compositionComplete() { if (identifyBrowserByName("edge")) { videojs.options.hls.overrideNative = true; videojs.options.html5.nativeAudioTracks = false; videojs.options.html5.nativeVideoTracks = false; } if (!$("#media-video").length) { var vidTag = ''; if (iOsDevice || androidDevice) { vidTag = ''; } $("#media-container").text("").append(vidTag); } var playToggle = true; var fullscreenToggle = true; //If seminar is webcast or replay then no need to show play button if (seminar.IsLive || seminar.IsReplay) { playToggle = false; if (iOsDevice) { playToggle = true; } } if (iOsDevice && !isAllowFullScreenInIos()) { fullscreenToggle = false; } var testVideoSource = getTestVideoSource(); videojs("media-video", { techOrder: isFlash ? ["flash"] : ["html5"], aspectRatio: seminar.AspectRatio, preload: "auto", autoplay: true, controls: true, controlBar: { audioTrackButton: false, progressControl: false, remainingTimeDisplay: false, fullscreenToggle: fullscreenToggle, playToggle: playToggle, skipButtons: { forward: 30, backward: 30 }, volumeMenuButton: { inline: false, vertical: true } }, html5: { vhs: { limitRenditionByPlayerDimensions: true, useDevicePixelRatio: true } }, sources: [{ "src": testVideoSource, "type": Helper.VIDEOJS.getType(testVideoSource) }], }).ready(function () { console.log('Player Ready'); vidPlayer = this; attachRollingBandwidthCalculation(this); vidPlayer.controlBar.subsCapsButton.controlText(Helper.VIDEOJS.CLOSED_CAPTIONS_TEXT); // #0010495 if (seminar && seminar.LogoBugImageURL) { this.bug({ imgSrc: seminar.LogoBugImageURL, padding: '5%', position: 'br', opacity: getLogoBugOpacity() }); setTimeout(resizeLogoBug, 1); } if (typeof ShowLogoUnAuthBugImage == 'function') { ShowLogoUnAuthBugImage(this, (seminar && seminar.LogoBugImageURL)); } this.on("error", function (err) { console.log(err); var msg = this.error().message; var errNo = this.error().code; var duration = this.duration(); eventLog(msg); updateState(); loadCaptions(); $(".current").removeClass("current"); if (errNo == 4 && duration == 0) { if (msg.toLowerCase() == "no compatible source was found for this media." && isFlash) { setErrorHtml(); } } else if (errNo == -2) { setInterValForAutoTry(); } prepareQualitySwitcher(); }); updateHLS(); initializeMediaPlayer(); updateState(); hideShowBeginButton(); this.on("fullscreenchange", function () { if (this.isFullscreen()) { if (iOsDevice && !isAllowFullScreenInIos()) { setTimeout(function () { this.exitFullscreen() }, 50); } //10600: Viewer > If Go Full Screen Video and have Slides in Program - Show Slides in Large PIP showSlideinFullscreen(); } else { //ESC to exit full screen view - the viewer would go back to default view state #10600 if ($("#slideView").length > 0 && seminar.Slides && seminar.Slides.length > 0 && $(window).width() > 991) { $(".SlideWidget").appendTo(".AudioVideoWidget"); //14768 if (typeof (toggleBtn0) != "undefined" && checkSlideScreeenIsVisible() == true) { $(toggleBtn0).trigger('click'); } onLoadMediaSlide(); //#0014676, #0014677 } setTimeout(function () { if (isRefreshResize) { onLoadMediaSlide(); isRefreshResize = false; } }, 100); } showAlertInFullScreen(); adjustPIPHeight(); }); this.on("timeupdate", function () { var curDuration = this.duration(); //Go to the togoPos if available. var rs = 0; try { rs = this.tech_['readyState'](); } catch (e) { } if (togoPos && rs > 0 && curDuration) { isFocePlay = true; if (togoPos > curDuration && curDuration > 0) { togoPos = null; handleComplete(); return; } else { try { isEnableSeekForOnDemand = true; //this.tech_['setCurrentTime'](togoPos); this.currentTime(togoPos); if (curMediaClip && togoPos >= curMediaClip.InPoint && togoPos <= curMediaClip.OutPoint) { seekBlock = true; } togoPos = null; isReplayErrorStored = false; return; } catch (e) { console.log(e); } } if (isCurrentLiveStream) { //Remove auto try interval and reset resetAutoTryAttemtAndInterval(); } } else { if (chcekIsCurrentLiveStream()) { //Remove auto try interval and reset resetAutoTryAttemtAndInterval(); } } if (rs > 0) //#0018157 curVidTimeCode = this.currentTime(); //Calculate custom bar if (isShowVideoCustomBar()) { calculateFullTimeLine(curVidTimeCode, curDuration); } if (seminar.MediaClips.length > 0) { if (curMediaClip != null) { //Prevent playing beyond the the outPoint. if (curMediaClip.OutPoint) { if (Math.floor(curVidTimeCode) > Number(curMediaClip.OutPoint)) { handleComplete(); } } //Prevent playing before the keyframe before the inPoint. if (curMediaClip.InPoint) { if (Math.ceil(curVidTimeCode) < Number(curMediaClip.InPoint) && checkInPointForFlash(Math.ceil(curVidTimeCode), Number(curMediaClip.InPoint))) { if (!seekBlock) { seekBlock = true; isEnableSeekForOnDemand = true; this.currentTime(Number(curMediaClip.InPoint)); if (seminar.SeminarTypeId === 4) { clearAlert(); } } } else { seekBlock = false; } } // If onDemand and user try to forward video then move video to its last track time if (userOffsetTrackTime > 0) { onDemandMediaTrack(userOffsetTrackTime, curMediaClip); } onDemandVideoCompletion(curVidTimeCode); } } if (seminar.IsLive || seminar.IsReplay) $(".vjs-live-control").removeClass("vjs-hidden"); //For Transcript highLightCurrentCaption(curVidTimeCode); // #0018340: Video player speed need to be freezed to default playback rate checkPlaybackRate(); }); this.on("ended", function () { updateState(); console.log('onComplete'); handleComplete(); hideVideoBar(true); }); this.on("play", function () { updateState(); hideVideoBar(false); seekBlock = false; setTimeout(checkReplayPlayingCorrect, 5000); }); this.on("pause", function () { if ((seminar.IsLive || seminar.IsReplay) && isFocePlay) { if (iOsDevice) { setTimeout(function () { vidPlayer.play(); }, 1000); } else { this.play(); } } updateState(); hideVideoBar(false); }); this.on("loadeddata", function () { updateState(); if (playerInitialized) { hideVideoBar(false); seekBlock = false; //Check is current media is stream if (seminar.IsLive) { chcekIsCurrentLiveStream(); } else { isCurrentLiveStream = false; } } if (curMediaClip != null) { setTimeout(function () { finalTrack(); }, 500); } prepareQualitySwitcher(); }); this.on("loadstart", function () { $("video").attr("disablePictureInPicture", "disablePictureInPicture"); console.log('VideojsL loadstart called') prepareQualitySwitcher(); updateHLS(); }); this.on("seeked", function () { if (isEnableSeekForOnDemand === false) { userOffsetTrackTime = this.currentTime(); onDemandMediaTrack(this.currentTime(), curMediaClip); if (seminar.SeminarTypeId === 4) { clearAlert(); } } isEnableSeekForOnDemand = false; setTimeout(function () { $("#media-video_Html5_api").show(); }, 1000); }); this.on("volumechange", function () { Helper.VIDEOJS.saveVidPlayerSettings(this); }); this.on("mediachange", function () { setTimeout(() => { console.log("Rendering quality change: " + vidPlayer.getCurrentQuality()); }, 0); var tempString = '
  • [' + moment().format("MM/DD/YYYY HH:mm:ss") + '] - Rendering quality change: ' + vidPlayer.getCurrentQuality() + '
  • '; $("#divEventLogs").prepend(tempString); prepareQualitySwitcher(); }); this.on("texttrackchange", function () { Helper.VIDEOJS.saveCCSettings(this); manageCaptionLanguageChange(this); }); this.on("loadedmetadata", function (event) { prepareQualitySwitcher(); }); // ratechange is not working with some extensions -- #0018340 //this.on("ratechange", function () { // this.playbackRate(1); //}); //#region Player Polyfill this.seek = function (pos) { this.tech_["setCurrentTime"](pos); } this.getCurrentQuality = function () { try { const qualityLevels = vidPlayer.qualityLevels(); return qualityLevels[qualityLevels.selectedIndex].label; } catch (e) { console.warn(e); return null; } } this.getRenderingMode = function () { return vidPlayer.techName_.toLowerCase(); } this.getCurrentState = function () { if (!vidPlayer.paused()) return "PLAYING"; if (vidPlayer.paused()) return "PAUSED"; if (vidPlayer.seeking() && vidPlayer.bufferedPercent() > 0) return "BUFFERING"; if (vidPlayer.readyState() > 1) return "IDLE"; return undefined; } this.setCurrentQuality = function (level) { } this.resizePlayer = function () { //keep player on the page try { $("#main-panel").css("width", "auto"); var t = parseInt($(".navbar-fixed-top").css("height").replace("px", "")); var b = parseInt($(".navbar-fixed-bottom").css("height").replace("px", "")); var a = parseInt($("body").css("height").replace("px", "")); var vidWidth = parseInt($(".video-js").css("width").replace("px", "")); var vidHeight = parseInt($(".video-js").css("height").replace("px", "")); // Leave space for the text below the video (e.g. "subtitles available") vidHeight += 20; var availHeight = a - t - b - 100; var availWidth = parseInt($("#mediaView").css("width").replace("px", "")); //(availHeight / vidHeight) * vidWidth; var availAspectWidth = (availHeight / vidHeight) * vidWidth; if (vidWidth <= availWidth && vidHeight <= availHeight) { var r = ""; //$("#main-panel").css("width", "auto"); } else { if (availAspectWidth <= availWidth) { if ($('#media-panel').hasClass('PIPS')) { $("#main-panel").css("width", availAspectWidth + 20 + "px"); } else if ($("#slideBox #slideView:visible").length == 0) { $("#main-panel").css("width", availAspectWidth + 15 + "px"); } else { $("#main-panel").css("width", availAspectWidth + "px"); } } else { $("#main-panel").css("width", availWidth + "px"); } } //To adjust space when their is no slide if ($(window).width() < 541 && typeof (seminar) == "object" && seminar.Slides.length <= 0) { $("#main-panel").show().css("height", $('#media-container').height() + 20); } else { $("#main-panel").css('height', ''); } if (typeof adjustPIPHeight == "function") { adjustPIPHeight(); } //#0010495 resizeLogoBug(); } catch (e) { } } //this.on("ready", function (event) { console.log(event.type); }); //this.on("dispose", function (event) { console.log(event.type); }); //this.on("error", function (event) { console.log(event.type); }); //this.on("stageclick", function (event) { console.log(event.type); }); //this.on("controlsvisible", function (event) { console.log(event.type); }); //this.on("loadstart", function (event) { console.log(event.type); }); this.on("waiting", function (event) { console.log(event.type); }); //this.on("canplay", function (event) { console.log(event.type); }); //this.on("canplaythrough", function (event) { console.log(event.type); }); //this.on("playing", function (event) { console.log(event.type); }); //this.on("ended", function (event) { console.log(event.type); }); //this.on("seeking", function (event) { console.log(event.type); }); //this.on("seeked", function (event) { console.log(event.type); }); //this.on("play", function (event) { console.log(event.type); }); //this.on("firstplay", function (event) { console.log(event.type); }); //this.on("pause", function (event) { console.log(event.type); }); //this.on("progress", function (event) { console.log(event.type); }); //this.on("durationchange", function (event) { console.log(event.type); }); //this.on("fullscreenchange", function (event) { console.log(event.type); }); //this.on("error", function (event) { console.log(event.type); }); //this.on("suspend", function (event) { console.log(event.type); }); //this.on("abort", function (event) { console.log(event.type); }); //this.on("emptied", function (event) { console.log(event.type); }); //this.on("stalled", function (event) { console.log(event.type); }); //this.on("loadedmetadata", function (event) { console.log(event.type); }); //this.on("loadeddata", function (event) { console.log(event.type); }); //this.on("timeupdate", function (event) { console.log(event.type); }); //this.on("texttrackchange, function (event) { console.log(event.type); }); //this.on("posterchange", function (event) { console.log(event.type); }); //this.on("vttjsloaded", function (event) { console.log(event.type); }); //this.on("vttjserror", function (event) { console.log(event.type); }); //ready,dispose,error,stageclick,controlsvisible, //loadstart,waiting,canplay,canplaythrough,playing,ended,seeking,seeked,play,firstplay,pause,progress,durationchange,fullscreenchange,error,suspend,abort,emptied,stalled,loadedmetadata,loadeddata,timeupdate,ratechange,volumechange,texttrackchange,loadedmetadata,posterchange, //vttjsloaded,vttjserror //#endregion Helper.Interval.set("VIEWER_CHECKALERTTIMES", checkAlertTimes, 1); Helper.Interval.set("VIEWER_CHECKCERTCODETIMES", checkCertCodeTimes, 1); Helper.Interval.set("VIEWER_CHECKSPEAKERGRAPHICALERTTIMES", checkSpeakerGraphicAlertTimes, 1); $(window).resize(); if (inIframe()) { vidPlayer.muted(true); } }); //timeout cuts down on triggered events var resizeTimeout; $(window).resize(function () { clearTimeout(resizeTimeout); if (vidPlayer) { resizeTimeout = setTimeout(vidPlayer.resizePlayer, 100); } }); if (!seminar.IsLive && !seminar.IsReplay && seminar.MediaClips.length > 1) { if ((Number(seminar.SeminarTypeId) == 2 || Number(seminar.SeminarTypeId) == 8) && seminar.IsArchive) { $("#playlist_panel").show(); //$("#playlist_panel").show(); var playListName = ""; var playLists = "
      "; var selectedClass = ""; $.each(seminar.MediaClips, function (index, element) { if (element.Media.Name != null) { playListName = element.Media.Name; } else if (element.Media.ContentSubType != null) { playListName = element.Media.ContentSubType; } else { playListName = element.Media.ContentType; } selectedClass = (element == curMediaClip ? "selected" : ""); playLists = playLists + '
    • ' + playListName + '
    • '; }); playLists = playLists + "
    " $("#playlist_panel").html(playLists); } } if (typeof resizeCustomBar == 'function') { resizeCustomBar(); } } function checkPlaybackRate() { if (!videoEl) videoEl = document.getElementById(getHTML5VideoElementId()); if (!videoEl || videoEl.playbackRate === 1) return false; // set default playback rate if changed videoEl.playbackRate = 1; } function getHTML5VideoElementId() { return $('#media-panel video') && $('#media-panel video').attr('id') ? $('#media-panel video').attr('id') : 'media-video_Html5_api'; } function prepareQualitySwitcher() { try { vidPlayer.hlsQualitySelector(); } catch (e) {} } function removeQualitySwitcher() { $('.vjs-resolution-button').remove(); } function checkInPointForFlash(locCurrentTime, locInPoint) { return isFlash ? (locInPoint - locCurrentTime) > 3 : true; } // #region OnDemand Media Track function onDemandMediaTrack(offset, clip) { if (Number(u) !== -1 && isDisallowSkipingAhead() && clip !== null) { if (clip.IsPreSeminar) return true; //#0018157 var seekProductTime = calculateRelativeTimeBasedoncurclip(clip, offset); var watchedMaxProductTime = seminar.LastMediaClip != null ? seminar.LastMediaClip.maxProductTime : 0; //If seektime greater than max clip then seek if (seekProductTime > watchedMaxProductTime) { setTimeout(function () { seekSpecificDuration(watchedMaxProductTime); userOffsetTrackTime = 0; clearAlert(); }, 100); return false; } else { onDemandVideoCompletion(offset); userOffsetTrackTime = 0; return true; } } else { userOffsetTrackTime = 0; return true; } } function updateMediaTrackDetails(offset) { if ((seminar.SeminarTypeId === 4 || seminar.IsArchive) && curMediaClip !== null) { var curProductTime = calculateRelativeTimeBasedoncurclip(curMediaClip, offset); if (seminar.LastMediaClip == null) { seminar.LastMediaClip = { maxMediaClipId: curMediaClip.MediaClipId, maxMediaTime: offset, maxProductTime: curProductTime, lastMediaClipId: curMediaClip.MediaClipId, lastMediaTime: offset, lastProductTime: curProductTime }; } else { // Update max time if (curProductTime > seminar.LastMediaClip.maxProductTime) { seminar.LastMediaClip.maxMediaClipId = curMediaClip.MediaClipId; seminar.LastMediaClip.maxMediaTime = offset; seminar.LastMediaClip.maxProductTime = curProductTime; } //Update last watch time seminar.LastMediaClip.lastMediaClipId = curMediaClip.MediaClipId; seminar.LastMediaClip.lastMediaTime = offset; seminar.LastMediaClip.lastProductTime = curProductTime; } } } function calculateRelativeTimeBasedoncurclip(clip, offset) { var tt = clip.TriggerTime == null ? 0 : Number(clip.TriggerTime); var ip = clip.InPoint == null ? 0 : Number(clip.InPoint); return Math.round(offset - ip + tt); } var tableSasVideoTrackUri = null, userOffsetTrackTime = 0; function getSasVideoTrackUri(objMediaClip) { //if (objMediaClip != null && objMediaClip.MediaClipId != null) { if (tableSasVideoTrackUri == null) { $.ajax({ type: "GET", url: "/showtimewidget/gettrackingtablecustomersasurl?tenantid=" + t + "&seminarid=" + s + "&userid=" + u, headers: { "Authorization": "Bearer " + x }, success: function (res, status, xhr) { // Use the table SAS url to query windows azure storage. tableSasVideoTrackUri = xhr.responseText.replace(/"/g, ""); getVideoTrack(tableSasVideoTrackUri, objMediaClip); }, error: function (res, status, xhr) { console.log("Error: making query to video track of user. getSasVideoTrackUri"); } }); } else { getVideoTrack(tableSasVideoTrackUri, objMediaClip); } //} //else { // gotoMediaClip(objMediaClip, null); //} } function getVideoTrack(tableSasUrl, objMediaClip) { var uPadded; if (isNaN(u)) uPadded = u; else uPadded = padLeft(u, 9); var partitionKey = padLeft(t, 6) + "-" + padLeft(s, 9) + "-" + uPadded; var q = tableSasUrl + "&$select=MediaTime,MediaClipId,Timestamp,ProductTime&$filter=(PartitionKey eq '" + partitionKey + "') and (ProductId eq " + seminar.SeminarId + ") and (TenantId eq " + t + ") and (UserId eq '" + u + "')"; //if (!oldIE) { if (browserSupportsCors()) { $.ajax({ type: "GET", datatype: "json", url: q, beforeSend: setHeader, // Render the table with all the entities if the request succeeds success: function (res, status, xhr) { getVideoTrackResult(res, status, xhr, objMediaClip) }, error: function (res, status, xhr) { console.log("Error: getting user video track from user. getVideoTrack"); } }); } else { $.ajax({ type: "POST", datatype: "json", data: { 'tstore': tableSasUrl, //'tstore': encodeURIComponent(tableSasUrl), 'partitionKey': partitionKey, 'productId': seminar.SeminarId, 'tenantId': t, 'userid': u }, url: '/ShowtimeWidget/QueryTableSaasForMedia', // Render the table with all the entities if the request succeeds success: function (res, status, xhr) { getVideoTrackResult(res, status, xhr, objMediaClip) }, error: function (res, status, xhr) { var responseText = $(res.responseText).filter('title').text(); if (res.status == 403 || responseText.indexOf('403') > -1) { tableSasVideoTrackUri = null; } console.log("Error: getting user video track from user. getVideoTrack"); } }); } } function getVideoTrackResult(res, status, xhr, objMediaClip) { finalTrack(); curVidTimeCode = 0; if (res.value.length > 0) { var lastMcs; if ((objMediaClip === undefined || objMediaClip == null) && seminar.MediaClips.length > 0) { // commented on 03-dec-2015 //lastMcs = res.value.sort(function (a, b) { // return (new Date(a.Timestamp) - new Date(b.Timestamp)); //}).pop(); // commented on 11-may-2016 #5048 //lastMcs = res.value.sort(function (a, b) { // return (new Date(a.Timestamp) - new Date(b.Timestamp)); //})[res.value.length - 1]; lastMcs = res.value.sort(function (a, b) { return (Number(a.ProductTime) - Number(b.ProductTime)); })[res.value.length - 1]; objMediaClip = $.grep(seminar.MediaClips, function (n, i) { return n.MediaClipId == lastMcs.MediaClipId }).pop(); //if (objMediaClip == null || objMediaClip === undefined) { // objMediaClip = seminar.MediaClips[0] //} if (objMediaClip === undefined || objMediaClip == null) { gotoMediaClip(seminar.MediaClips[0], null); objMediaClip = seminar.MediaClips[0]; } } //if (objMediaClip != null) { var mcs = jQuery.grep(res.value, function (n, i) { return objMediaClip != null && n.MediaClipId == objMediaClip.MediaClipId; }); if (lastMcs !== undefined && lastMcs != null) { mcs = jQuery.grep(mcs, function (n, i) { return n.Timestamp == lastMcs.Timestamp; }); } var maxTrackTime = mcs.sort(function (a, b) { return (a.MediaTime - b.MediaTime); }).pop(); if (maxTrackTime) { lastTrackMediaTime = Number(maxTrackTime.MediaTime); if (objMediaClip.InPoint != null && Number(objMediaClip.InPoint) > 0 && Number(maxTrackTime.MediaTime) > 0) { gotoMediaClip(objMediaClip, null); if (Number(maxTrackTime.MediaTime) <= Number(objMediaClip.OutPoint)) { vidPlayer.currentTime(Number(maxTrackTime.MediaTime)); } } else { if (Number(objMediaClip.Media.Duration) > 0 && maxTrackTime.MediaTime >= Number(objMediaClip.Media.Duration)) { gotoMediaClip(objMediaClip, null); } else { gotoMediaClip(objMediaClip, maxTrackTime.MediaTime); } } if (Number(objMediaClip.OutPoint) > 0) { if (Number(maxTrackTime.MediaTime) <= Number(objMediaClip.OutPoint)) { onDemandVideoCompletion(Number(maxTrackTime.MediaTime)); } else { onDemandVideoCompletion(Number(objMediaClip.OutPoint)); } } else { if (Number(maxTrackTime.MediaTime) <= Number(objMediaClip.Media.Duration)) { onDemandVideoCompletion(Number(maxTrackTime.MediaTime)); } else { onDemandVideoCompletion(Number(objMediaClip.Media.Duration)); } } } else { lastTrackMediaTime = 0; gotoMediaClip(objMediaClip, null); } setMediasCompletionPer(res.value); //} } else { lastTrackMediaTime = 0; if (objMediaClip == null && seminar.MediaClips !== undefined && seminar.MediaClips != null && seminar.MediaClips.length > 0) { gotoMediaClip(seminar.MediaClips[0], null); } else { gotoMediaClip(objMediaClip, null); } } } function onDemandVideoCompletion(lastMediaTime) { if (curMediaClip != null && curMediaClip.Media != null && curMediaClip.Media.Duration != null && lastMediaTime > 0) { var mediaDuration = Number(curMediaClip.Media.Duration); var inPoint = curMediaClip.InPoint == null ? 0 : Number(curMediaClip.InPoint); var outPoint = curMediaClip.OutPoint == null || curMediaClip.OutPoint == 0 ? Number(curMediaClip.Media.Duration) : Number(curMediaClip.OutPoint); mediaDuration = (outPoint - inPoint) > 0 ? (outPoint - inPoint) : mediaDuration; //console.log("mediaDuration: " + mediaDuration); lastMediaTime = lastMediaTime - inPoint; var perCompleted = (lastMediaTime / mediaDuration) * 100; if (perCompleted > 100) { perCompleted = 100; } // set per in progress bar active if ($("#divVideoSegment div.progress-bar.active").length > 0) { $("#divVideoSegment div.progress-bar.active").html(perCompleted.toFixed() + "%"); } $("#divVideoSegment div.progress-bar:not(.active)").html(''); } } function setMediasCompletionPer(mediaList) { var mediaClipIds = []; for (var i = 0; i < mediaList.length; i++) { if (mediaClipIds.indexOf(mediaList[i].MediaClipId) < 0 && mediaList[i].MediaClipId != 0) { mediaClipIds.push(mediaList[i].MediaClipId); } } for (var i = 0; i < mediaClipIds.length; i++) { //if (Number(curMediaClip.MediaClipId) != Number(mediaClipIds[i])) { var mcsList = mediaList.filter(function (n) { return Number(n.MediaClipId) == Number(mediaClipIds[i]); }); if (mcsList) { var maxTrackTime = mcsList.sort(function (a, b) { return (a.MediaTime - b.MediaTime); }).pop(); // set per in progress bar if (maxTrackTime && $("#divVideoSegment div.progress-bar[data-mediaClipId='" + maxTrackTime.MediaClipId + "']").length > 0) { var maxMediaClip = $.grep(seminar.MediaClips, function (n, i) { return Number(n.MediaClipId) == Number(maxTrackTime.MediaClipId); }).pop(); if (maxMediaClip && maxMediaClip.Media !== undefined) { // set max time var lastMediaTime = maxTrackTime.MediaTime; var mediaDuration = Number(maxMediaClip.Media.Duration); var inPoint = maxMediaClip.InPoint == null ? 0 : Number(maxMediaClip.InPoint); var outPoint = maxMediaClip.OutPoint == null || maxMediaClip.OutPoint == 0 ? maxMediaClip.Media.Duration : Number(maxMediaClip.OutPoint); mediaDuration = (outPoint - inPoint) > 0 ? (outPoint - inPoint) : mediaDuration; lastMediaTime = lastMediaTime - inPoint; //console.log("mediaDuration: " + mediaDuration); var perCompleted = (lastMediaTime / mediaDuration) * 100; if (perCompleted > 100) { perCompleted = 100; } $("#divVideoSegment div.progress-bar[data-mediaClipId='" + maxMediaClip.MediaClipId + "']").html(perCompleted.toFixed() + "%"); } } } //} } } // #endregion OnDemand Media Track //----------------------------Play Demo Video For On Demand And Download------------------------------ function demoGetMediaclipByStartTime() { if (demoMediaClip != null && demoMediaClip != undefined && demoMediaClip.length > 0) { var mcs = jQuery.grep(demoMediaClip, function (n, i) { return (n.TotalDurationByOrder + n.TotalDuration) >= demoStartTime; }); mcs = mcs.sort(function (a, b) { return ((b.TotalDurationByOrder + b.TotalDuration) - (a.TotalDurationByOrder + a.TotalDuration)); }).pop(); if (mcs) { var inpoint = (demoStartTime - mcs.TotalDurationByOrder) + mcs.InPoint; if (curMediaClip != null && curMediaClip == mcs) { vidPlayer.currentTime(inpoint); } else { //gotoMediaClipForReplay(mcs, inpoint); gotoMediaClipForDemoVideo(mcs, inpoint); } } else { handleCompleteForDemoVideo(); } } } function gotoMediaClipForDemoVideo(mediaClip, pos) { if (playerInitialized) { pos = pos || null; if (curMediaClip != null && curMediaClip === mediaClip) { togoPos = pos; } else { curMediaClip = mediaClip; if (curMediaClip != null) { curVidMediaClipId = curMediaClip.MediaClipId; vidPlayer.reset(); Helper.VIDEOJS.removeAllRemoteTextTrack(vidPlayer); vidPlayer.src({ "src": Helper.VIDEOJS.prepareMediaURL(curMediaClip.Media.Source), "type": Helper.VIDEOJS.getType(curMediaClip.Media.Source) }); if (curMediaClip.Media.Captions && curMediaClip.Media.Captions.length > 0) { curMediaClip.Media.Captions.map(function (caption) { Helper.VIDEOJS.addRemoteTextTrack(vidPlayer, { "src": "/getter.ashx?url=" + caption.Src.replace(".ttml", ".vtt"), "srclang": caption.SrcLang, "label": caption.Label, "kind": "captions" }); }); Helper.VIDEOJS.setActiveRemoteTextTrack(vidPlayer); if (Helper.VIDEOJS.hasRemoteTextTrack(vidPlayer)) { $("#subtitle-message").show(); } } togoPos = pos; } } } } var isPlayed = false; function intializeMediaForDemo() { if (!isPlayed) { isPlayed = true; vidPlayer.volume(1.0); demoGetMediaclipByStartTime(); } } function compositionCompleteForDemoVideo() { if (identifyBrowserByName("edge")) { videojs.options.hls.overrideNative = true; videojs.options.html5.nativeAudioTracks = false; videojs.options.html5.nativeVideoTracks = false; } if (!$("#media-video").length) { var vidTag = ''; if (iOsDevice || androidDevice) { vidTag = ''; } $("#media-container").text("").append(vidTag); } $("#mediaView").removeClass("col-md-6").addClass("col-md-12"); $('a[data-href="eventlog"]').hide(); $('.seminarImportantNotice').hide(); if (demoMediaClip != null) { allmediaTotalDuration = sumOfMediaClipTotalDuration(demoMediaClip, 0); if (allmediaTotalDuration === 0 || demoStartTime > allmediaTotalDuration) { handleCompleteForDemoVideo(); } var videoSource = getTestVideoSource(); videojs("media-video", { techOrder: isFlash ? ["flash"] : ["html5"], aspectRatio: '16:9', preload: "auto", autoplay: true, controls: true, controlBar: { audioTrackButton: false, playToggle: false, remainingTimeDisplay: false, progressControl: false, fullscreenToggle: false, skipButtons: { forward: 30, backward: 30 }, volumeMenuButton: { inline: false, vertical: true } }, html5: { vhs: { limitRenditionByPlayerDimensions: true, useDevicePixelRatio: true } }, sources: [{ "src": Helper.VIDEOJS.prepareMediaURL(videoSource), "type": Helper.VIDEOJS.getType(videoSource) }] }).ready(function () { vidPlayer = this; attachRollingBandwidthCalculation(this); vidPlayer.controlBar.subsCapsButton.controlText(Helper.VIDEOJS.CLOSED_CAPTIONS_TEXT); this.on("error", function (err) { var msg = this.error().message; var errNo = this.error().code; var duration = this.duration(); if ((errNo == "4") && (duration == "0")) { if (msg.toLowerCase() == "no compatible source was found for this media." && isFlash) { setErrorHtml(); } } }); playerInitialized = true; intializeMediaForDemo(); updateState(); this.on("timeupdate", function () { if (curMediaClip != null) { if (vidPlayer.getCurrentState() !== "IDLE") { //Go to the togoPos if available. var rs = 0; try { rs = this.tech_['readyState'](); } catch (e) { } if (togoPos) { if (togoPos > vidPlayer.duration() && vidPlayer.duration() > 0) { handleCompleteForDemoVideo(); togoPos = null; return; } else { try { console.log('seeked: togoPos' + togoPos); this.tech_['setCurrentTime'](togoPos); if (curMediaClip && togoPos >= curMediaClip.InPoint && togoPos <= curMediaClip.OutPoint) { seekBlock = true; } togoPos = null; } catch (e) { } } } //Slides curVidTimeCode = curMediaClip.TriggerTime + (this.currentTime() - curMediaClip.InPoint); //console.log(secondsToTimeFormat(curVidTimeCode)); demoCheckSlideTimes(); var currentPos = (curMediaClip.TotalDurationByOrder + (this.currentTime() - curMediaClip.InPoint)); var remaningSeconds = (demoStartTime + (3 * 60)) - currentPos; //if demo video complete then get message and close if (remaningSeconds <= 0) { handleCompleteForDemoVideo(); } curDemoMsg = ' Demo ends in ' + secondsToTimeFormat(remaningSeconds < 0 ? 0 : remaningSeconds); if ($("#demoTimer").length > 0) { $("#demoTimer>p").html(curDemoMsg); if (vidPlayer.isFullscreen()) { if (!$("#alert_panel")) $("#media-video").append('

    '); $("#alert_panel>p").text(curDemoMsg); } } else { var text = '

    ' + curDemoMsg + '

    ' $("#media-container").append(text); if (vidPlayer.isFullscreen()) { if (!$("#alert_panel")) $("#media-video").append('

    '); $("#alert_panel>p").text(curDemoMsg); } } } //Prevent playing beyond the the outPoint. if (curMediaClip && curMediaClip.OutPoint) { if (this.currentTime() > Number(curMediaClip.OutPoint)) { nextPlayDemoVideo(); } } //Prevent playing before the keyframe before the inPoint. if (curMediaClip && curMediaClip.InPoint) { if (this.currentTime() < Number(curMediaClip.InPoint)) { if (!seekBlock) { seekBlock = true; vidPlayer.currentTime(Number(curMediaClip.InPoint)); } } else { seekBlock = false; } } } }); this.on("ended", function () { updateState(); nextPlayDemoVideo(); }); this.on("loadeddata", function () { updateState(); if (playerInitialized) { seekBlock = false; setTimeout(function () { if (vidPlayer.getCurrentState() === "IDLE") vidPlayer.play(); }, 100); } }); this.on("pause", function () { this.play(); updateState(); }); //#region Player Polyfill this.getCurrentQuality = function () { return vidPlayer.getCurrentQuality(); } this.setCurrentQuality = function (level) { vidPlayer.setCurrentQuality(level); } this.getRenderingMode = function () { return vidPlayer.techName_.toLowerCase(); } this.getCurrentState = function () { if (!vidPlayer.paused()) return "PLAYING"; if (vidPlayer.paused()) return "PAUSED"; if (vidPlayer.seeking() && vidPlayer.bufferedPercent() > 0) return "BUFFERING"; if (vidPlayer.readyState() > 1) return "IDLE"; return undefined; } this.resizePlayer = function () { //keep player on the page try { $("#main-panel").css("width", "auto"); var t = parseInt($(".navbar-fixed-top").css("height").replace("px", "")); var b = parseInt($(".navbar-fixed-bottom").css("height").replace("px", "")); var a = parseInt($("body").css("height").replace("px", "")); var vidWidth = parseInt($(".video-js").css("width").replace("px", "")); var vidHeight = parseInt($(".video-js").css("height").replace("px", "")); var availHeight = a - t - b - 100; var availWidth = parseInt($("#mediaView").css("width").replace("px", "")); //(availHeight / vidHeight) * vidWidth; var availAspectWidth = (availHeight / vidHeight) * vidWidth; if (vidWidth <= availWidth && vidHeight <= availHeight) { var r = ""; //$("#main-panel").css("width", "auto"); } else { if (availAspectWidth <= availWidth) { $("#main-panel").css("width", availAspectWidth + "px"); } else { $("#main-panel").css("width", availWidth + "px"); } } if (typeof adjustPIPHeight == "function") { adjustPIPHeight(); } } catch (e) { } } //#endregion }); $("body").on("click", "#info-toggle", function () { $("#info-toggle").removeClass("glyphicon-chevron-right").addClass("glyphicon-chevron-left"); $("#info-toggle-btn").removeClass("glyphicon-chevron-right").addClass("glyphicon-chevron-left"); $("#info-panel,#media-panel").removeClass("showinfo"); $("#media-panel").removeClass("col-md-8").addClass("col-md-12"); $("#info-panel").removeClass("col-md-4").addClass("col-md-0"); var slidesource = $("#slidescreen img").attr('src'); if ($("#slidescreen").length > 0 && slidesource != undefined && slidesource.length > 0) { if ($(toggleBtn1).hasClass("btn-success") || $(toggleBtn2).hasClass("btn-success")) { $("#mediaView").removeClass("col-md-6").addClass("col-md-12"); $("#slideView").removeClass("col-md-6").addClass("col-md-12"); $("#slidescreen img").css("height", maxWidgetHeight); //alert("1."); } else { $("#mediaView").removeClass("col-md-12").addClass("col-md-6"); $("#slideView").removeClass("col-md-12").addClass("col-md-6"); $("#slidescreen img").css("height", "auto"); } } else { $("#mediaView").removeClass("col-md-6").addClass("col-md-12"); $("#media-video").css("height", maxWidgetHeight); } if (!showinfo) { $("#info-toggle").removeClass("glyphicon-chevron-left").addClass("glyphicon-chevron-right"); $("#info-toggle-btn").removeClass("glyphicon-chevron-left").addClass("glyphicon-chevron-right"); $("#info-panel,#media-panel").addClass("showinfo"); $("#media-panel").removeClass("col-md-12").addClass("col-md-8"); $("#info-panel").removeClass("col-md-0").addClass("col-md-4"); var slidesource = $("#slidescreen img").attr('src'); if ($("#slidescreen").length > 0 && slidesource != undefined && slidesource.length > 0) { if ($(toggleBtn1).hasClass("btn-success") || $(toggleBtn2).hasClass("btn-success")) { $("#mediaView").removeClass("col-md-6").addClass("col-md-12"); $("#slideView").removeClass("col-md-6").addClass("col-md-12"); $("#slidescreen img").css("height", maxWidgetHeight); } else { $("#mediaView").removeClass("col-md-12").addClass("col-md-6"); $("#slideView").removeClass("col-md-12").addClass("col-md-6"); $("#slidescreen img").css("height", "auto"); } } else { $("#mediaView").removeClass("col-md-6").addClass("col-md-12"); } } showinfo = !showinfo; $(window).resize(); }); } //timeout cuts down on triggered events var resizeTimeout; $(window).resize(function () { clearTimeout(resizeTimeout); if (vidPlayer) resizeTimeout = setTimeout(vidPlayer.resizePlayer, 500); }); } function nextPlayDemoVideo() { if (demoMediaClip != null && demoMediaClip.indexOf(curMediaClip) + 1 < demoMediaClip.length) { gotoMediaClipForDemoVideo(demoMediaClip[demoMediaClip.indexOf(curMediaClip) + 1], null); } else { handleCompleteForDemoVideo(); } } function handleCompleteForDemoVideo() { if (playerInitialized) { vidPlayer.pause(); //vidPlayer.stop(); } console.log("The End"); curMediaClip = null; alert("The demonstration has concluded."); window.close(); if (vidPlayer) { vidPlayer.reset(); } } function secondsToTimeFormat(totalSec) { //var hours = parseInt(totalSec / 3600) % 24; //var minutes = parseInt(totalSec / 60) % 60; //var seconds = totalSec % 60; //if (hours > 0) { // return (hours < 10 ? "0" + hours : hours) + ":" + (minutes < 10 ? "0" + minutes : minutes) + ":" + (seconds < 10 ? "0" + Math.floor(seconds) : Math.floor(seconds)); //} else { // return (minutes < 10 ? "0" + minutes : minutes) + ":" + (seconds < 10 ? "0" + Math.floor(seconds) : Math.floor(seconds)); //} return totalSec.toString().toHHMMSS(); } function secondsToDDHHMM(totalSec) { return totalSec.toString().toDDHHMM(); } function demoCheckSlideTimes() { var slideTimes = []; if (demoSlides != null && demoSlides.length > 0) { $.each(demoSlides, function (outerIndex, outerElement) { if (outerElement.SlideTimes != null && outerElement.SlideTimes.length > 0) { $.each(outerElement.SlideTimes, function (innerIndex, innerElement) { if (innerElement.ProductTime && innerElement.ProductTime <= curVidTimeCode) { slideTimes.push(innerElement); } }); } }); if (slideTimes.length > 0) { var maxSlideTimes = slideTimes.sort(function (a, b) { return (a.ProductTime - b.ProductTime); }).pop(); if (maxSlideTimes !== undefined && maxSlideTimes != null) { if (Number(maxSlideTimes.SlideId) != Number(curSlideId)) { console.log(maxSlideTimes.Slide.Source); $('#demoTimer').removeClass('demo-12').addClass('demo-6'); $("#slidescreen img").attr('src', maxSlideTimes.Slide.Source); $("#mediaView").removeClass("col-md-12").addClass("col-md-6"); $("#slideView").removeClass("col-md-12 col-md-12").addClass("col-md-6"); curSlideId = maxSlideTimes.SlideId; } } } } } //--------------------Custom Playbar--------------------------------------- function setSegmentPoint(mediaClips) { if (mediaClips != null && mediaClips != undefined && mediaClips.length > 0) { $(".segmentPoint").remove(); jQuery.each(mediaClips, function (index, element) { if (index > 0) { var duration = element.TotalDurationByOrder + 1; var percentage = 100 * duration / allmediaTotalDuration; $("#progressBar").prepend('
    '); } }); } } function calculateFullTimeLine(position, duration) { if (position <= duration) { //Updat Progress Bar if (curMediaClip != null) { var currentInpoint = curMediaClip.InPoint; var currentPos = curMediaClip.TotalDurationByOrder + (position - currentInpoint); //Get currenttime customCurrentTime = currentPos; var maxduration = allmediaTotalDuration; //Get video duration var percentage = 100 * currentPos / maxduration; //in % $('#videoProgress').css('width', percentage + '%'); if (currentPos > 0) { $("#videocurrentTime").html(secondsToTimeFormat(currentPos)); $("#totalDuration").html(secondsToTimeFormat(maxduration)); } } else { allmediaTotalDuration = duration; var currentPos = curVidTimeCode; //Get currenttime customCurrentTime = currentPos; var maxduration = duration; //Get video duration var percentage = 100 * currentPos / maxduration; //in % $('#videoProgress').css('width', percentage + '%'); $("#videocurrentTime").html(secondsToTimeFormat(currentPos)); $("#totalDuration").html(secondsToTimeFormat(maxduration)); } if ($("#videobar").length > 0 && $("#videobar").css("display") == "none" && $("#media-video").height() > 0) { hideVideoBar(false); } } } var startBuffer = function () { var percentage = vidPlayer.bufferedPercent(); $("#bufferBar").css("width", percentage + "%"); }; function sumOfMediaClipTotalDuration(mediaClips, order) { var duration = 0; if (mediaClips != null && mediaClips != undefined && mediaClips.length > 0) { if (order > 0) { jQuery.each(mediaClips, function (index, element) { duration += element.TotalDuration; }); } else { jQuery.each(mediaClips, function (index, element) { duration += element.TotalDuration; }); } } return duration; } function secondsToTimeFormat(totalSec) { return totalSec.toString().toHHMMSS(); } var seekBarTimeout = null; //Setting timeout to handle seek event better #0015199 var timeDrag = false; /* Drag status */ $('#progressBar').mousedown(function (e) { timeDrag = true; seekBarTimeout = setTimeout(function () { if (seekBarTimeout) clearTimeout(seekBarTimeout); updatebar(e.pageX); }, 200); }); $('#progressBar').mousemove(function (e) { $('#video-time-tooltip').show(); var progress = $('#progressBar'); var maxduration = allmediaTotalDuration; //Video duraiton var position = e.pageX - progress.offset().left; //Click pos var percentage = 100 * position / progress.width(); //Check within range if (percentage > 100) { percentage = 100; } if (percentage < 0) { percentage = 0; } var seekDuration = maxduration * percentage / 100; var width = 60; if (seekDuration >= 3600) { width = 72; } $('#video-time-tooltip').html(secondsToTimeFormat(seekDuration)); var left = e.pageX - $(this).offset().left + 115; var top = e.pageY - $(this).offset().top - 27; $('#video-time-tooltip').css({ left: left + "px", width: width + "px" }).show(); }); $('#progressBar').mouseout(function () { $('#video-time-tooltip').hide(); }); $("body").on("mousemove", ".segmentPoint", function (e) { var value = $(this).attr("data-Value"); $('#video-time-tooltip').html(value); var left = e.pageX - $('#progressBar').offset().left + 100; var top = e.pageY - $(this).offset().top - 27; $('#video-time-tooltip').css({ left: left + "px", width: 'auto' }).show(); }); $(document).mouseup(function (e) { if (timeDrag) { timeDrag = false; seekBarTimeout = setTimeout(function () { if (seekBarTimeout) clearTimeout(seekBarTimeout); updatebar(e.pageX); }, 200); } }); $(document).mousemove(function (e) { if (timeDrag) { seekBarTimeout = setTimeout(function () { if (seekBarTimeout) clearTimeout(seekBarTimeout); updatebar(e.pageX); }, 200); } }); //update Progress Bar control var updatebar = function (x) { var progress = $('#progressBar'); var maxduration = allmediaTotalDuration; //Video duraiton var position = x - progress.offset().left; //Click pos var percentage = 100 * position / progress.width(); //Check within range if (percentage > 100) { percentage = 100; } if (percentage < 0) { percentage = 0; } if (isPlayFullTimeLine) { //Update progress bar and video currenttime $('#videoProgress').css('width', percentage + '%'); var seekDuration = maxduration * percentage / 100; seekSpecificDuration(seekDuration, true); } else { //Update progress bar and video currenttime $('#videoProgress').css('width', percentage + '%'); vidPlayer.currentTime(maxduration * percentage / 100); } }; function seekSpecificDuration(seekDuration, getByOrder) { if (seminar.MediaClips != null && seminar.MediaClips != undefined && seminar.MediaClips.length > 0) { //#region 0018157: Pre-Seminar Media addition if (!(getByOrder || false)) { if (seekDuration < seminar.MinimumTriggerTime) seekDuration = seminar.MinimumTriggerTime; // find mediaclip by trigger time var seekToMediaClip = jQuery.grep(seminar.MediaClips, function (n, i) { return (n.TriggerTime <= seekDuration && seekDuration < (n.TriggerTime + n.TotalDuration)) || ((n.TriggerTime + n.TotalDuration) == seekDuration && seekDuration == allmediaTotalDuration); })[0]; // override seek duration using total duration by order if (seekToMediaClip) { var tempInpoint = seekDuration - seekToMediaClip.TriggerTime; seekDuration = seekToMediaClip.TotalDurationByOrder + tempInpoint; } } //#endregion var mcs = jQuery.grep(seminar.MediaClips, function (n, i) { return (n.TotalDurationByOrder + n.TotalDuration) >= seekDuration; }); mcs = mcs.sort(function (a, b) { return ((b.TotalDurationByOrder + b.TotalDuration) - (a.TotalDurationByOrder + a.TotalDuration)); }).pop(); if (mcs && mcs != null) { var inpoint = (seekDuration - mcs.TotalDurationByOrder) + mcs.InPoint; if (isOverideLastTrackTime != undefined && isOverideLastTrackTime == true) { lastTrackMediaTime = inpoint; lastMediaTime = inpoint; isOverideLastTrackTime = false; } $("#videocurrentTime").html(secondsToTimeFormat(seekDuration)); if (onDemandMediaTrack(Number(inpoint), mcs)) { isEnableSeekForOnDemand = true; if (curMediaClip != null && curMediaClip == mcs) { try { vidPlayer.currentTime(inpoint); //For save in tracking db finalTrack(); } catch (e) { console.log(e); } } else { gotoMediaClip(mcs, inpoint); } userOffsetTrackTime = 0; } } else { //For fix mantis item #7087 gotoMediaClip(seminar.MediaClips[0], null); if (seminar.LastMediaClip == null) { seminar.LastMediaClip = { maxMediaClipId: seminar.MediaClips[0].MediaClipId, maxMediaTime: 0, maxProductTime: 0, lastMediaClipId: seminar.MediaClips[0].MediaClipId, lastMediaTime: 0, lastProductTime: 0 }; } } } } $('#playButton').mousedown(function (e) { if ($(this).hasClass('glyphicon-pause')) { $(this).removeClass('glyphicon-pause').addClass('glyphicon-play'); vidPlayer.pause(); } else { $(this).addClass('glyphicon-pause').removeClass('glyphicon-play'); vidPlayer.play(); } }); function hideVideoBar(isHide) { var vidPlayerstats = vidPlayer.getCurrentState(); if (isShowVideoCustomBar()) { if (isHide) { $("#videobar").hide(); } else if (vidPlayerstats !== "IDLE") { $("#videobar").insertBefore($("#media-video>.vjs-control-bar>.vjs-current-time")); $("#videobar").show(); } } } function isShowVideoCustomBar() { if (seminar != null && (seminar.SeminarTypeId == 4 || seminar.IsArchive)) { return true; } else { return false; } } function resizeCustomControlForSafariAndIE() { if (isSafariorIE() && isShowVideoCustomBar() && $("#videobar").length > 0) { var videoBarWidth = $("#videobar").width(); var timerWidth = $(".timer").width(); if (timerWidth <= 5) { timerWidth = 42; } var approxProgressWidth = (videoBarWidth - (timerWidth * 2)) - 40; $(".progress").css({ "width": (approxProgressWidth * 100 / videoBarWidth) + "%" }); } } function isSafariorIE() { if ((navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1) || ($('html').is('.ie6, .ie7, .ie8, .ie9'))) { return true; } else { return false; } } function resizeCustomBar() { Helper.Interval.set("VIEWER_RESIZECUSTOMBAR", resizeCustomBarMethod, 0.1); } function resizeCustomBarMethod() { var currentMediaWidth = null; if (isShowVideoCustomBar() && isSafariorIE()) { var mediaWidth = $("#mediaView").width(); if (currentMediaWidth != mediaWidth) { resizeCustomControlForSafariAndIE(); currentMediaWidth = mediaWidth; //alert('fired!') } } if ($('#media-video').length > 0) { //var mediaHeight = $('#media-video').height(); var mediaHeight = parseInt($("#media-video").css("height").replace("px", "")); if (mediaHeight <= 0) { hideVideoBar(true); } } } function isAppleDevice() { if (navigator.userAgent.toLowerCase().indexOf("ipad") > -1 || navigator.userAgent.toLowerCase().indexOf("ipod") > -1) { return true; } else { return false; } } //----------- Check Replay ------------------------ var isReplayErrorStored = false; function checkReplayPlayingCorrect() { //If playerInitialized and replay then if (seminar && playerInitialized && seminar.IsReplay && seminar.IsArchive == false && orignalRelativeTime > seminar.MinimumTriggerTime) { var vidPlayerState = vidPlayer.getCurrentState(); var vidPlayerPosition = vidPlayer.currentTime(); //If video in play mode then if (vidPlayerState === "PLAYING" && vidPlayerPosition > 0) { //Get current relative time var intTime = orignalRelativeTime; //Get which media clip playing currently var mcs = jQuery.grep(seminar.MediaClips, function (n, i) { return n.TriggerTime !== undefined && n.TriggerTime != null && Number(n.TriggerTime) <= Number(intTime); }); var maxMediaClip = mcs.sort(function (a, b) { return (Number(a.TriggerTime) - Number(b.TriggerTime)); }).pop(); if (maxMediaClip) { var inPoint = Number(maxMediaClip.InPoint); var tcode = intTime - maxMediaClip.TriggerTime + inPoint; var currentPosition = vidPlayerPosition - tcode; //console.log(currentPosition); //if curent curMediaClip and maxMediaClip not same or video duration greater the 25 minute if (curMediaClip != null && (curMediaClip != maxMediaClip || Math.abs(currentPosition) > 1500)) { //Get duration without inpoint var duration = maxMediaClip.Media.Duration - (maxMediaClip.OutPoint != null ? maxMediaClip.OutPoint : 0); if (!isReplayErrorStored && togoPos == null && tcode < duration && vidPlayer.duration() > 0 && intTime > 0) { //Play media if (tcode > 5) { gotoMediaClip(maxMediaClip, tcode); } else { gotoMediaClip(maxMediaClip, null); } var objErrorDetail = 'Error: Replay started over: [Duration]=' + currentPosition + ' [JWPosition]=' + vidPlayerPosition + '[curMediaClip]= ' + curMediaClip.MediaClipId; objErrorDetail += ',[RelTime]= ' + intTime; objErrorDetail += ',[maxMediaClip]= ' + maxMediaClip.MediaClipId; objErrorDetail += ',[CustomerId]= ' + u; objErrorDetail += ',[Navigator]= ' + navigator.userAgent; $.post("/ShowtimeWidget/WriteToElmah", { message: 'Error: Replay started over', errorDetail: objErrorDetail }); //console.log(objErrorDetail); isReplayErrorStored = true; } } } } } } //------------------------------------------------ function setErrorHtml() { var errorHtml = '
    '; errorHtml += '

    Required Flash Player
    not detected in Browser.

    '; errorHtml += '

    The link below will open a new tab and allow you to install Flash Player.

    '; errorHtml += '

    Once installed, refresh or relaunch your program viewer in order to view content.

    '; //errorHtml += '
    '; errorHtml += '' errorHtml += '
    '; errorHtml += '