//navigation.js
var False = false;
var True = true;
var isIE = false;
if (navigator.userAgent.match(/msie/i) || navigator.userAgent.match(/trident/i)) {
    isIE = true;
}
// set to true when you want to refresh the whole page //
var refresh = false;
var findAPITries = 0;
if (typeof (isMobile) === 'undefined') {
    var isMobile = {
        Android: function () {
            return navigator.userAgent.match(/Android/i);
        },
        BlackBerry: function () {
            return navigator.userAgent.match(/BlackBerry/i);
        },
        iOS: function () {
            return navigator.userAgent.match(/iPhone|iPad|iPod/i);
        },
        Opera: function () {
            return navigator.userAgent.match(/Opera Mini/i);
        },
        Windows: function () {
            return navigator.userAgent.match(/IEMobile/i);
        },
        any: function () {
            return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
        }
    };
}

function menuControl(item, image, source) {
    //alert("test");
    //alert(image +" "+ source);

    if (item.style.display != 'block') {
        item.style.display = 'block';
        image.src = source + "/minus.gif";
    } else {
        item.style.display = 'none';
        image.src = source + "/plus.gif";
    }
}

var calendarEvidence = false;
var initActivity = function (course) {
    var submitBtn = 'login_' + course;
    var uploadedFile = 'file_' + course;

    var hasDate = ($('#CalendarEvidence').length > 0);
    if (hasDate) {
        setInterval(function () {
            if ($('#CalendarEvidence').val() !== '') {
                calendarEvidence = true;
                // Have to comment out, it was disabling the submit button even when there is minimum number of file submitted and while selecting the date it was disabling the button.
                // ticket 64333
                //if ($('#file_' + course).length > 0) {
                //    if ($('#file_' + course).val() !== '' && $(this).val() !== '' ) {
                //        $('#login_' + course).removeProp('disabled');
                //    } else {
                //        $('#login_' + course).prop('disabled', 'true');
                //    }
                //} else {                   
                //        $('#login_' + course).removeProp('disabled');                
                //}
            } else {
                calendarEvidence = false;
                //this for attestation evidence file upload - line 88 in learnerview.js
                var isDisabled;
                if ($('button.submit-doc') != undefined) {
                    isDisabled = $('button.submit-doc').prop('disabled');
                    if (isDisabled)
                        $('#login_' + course).prop('disabled', 'true');
                }
                else
                    $('#login_' + course).prop('disabled', 'true');
            }
        }, 1000);
    }
    $('#TextEvidence_' + course).on('keyup', function () {
        if ($('#file_' + course).length > 0) {
            if ($('#file_' + course).val() !== '' && $(this).val() !== '') {
                $('#login_' + course).removeProp('disabled');
                $('#login_' + course).removeAttr('disabled');
            } else {
                $('#login_' + course).prop('disabled', 'true');
            }
        } else {
            if ($(this).val() !== '') {
                $('#login_' + course).removeProp('disabled');
                $('#login_' + course).removeAttr('disabled');
            } else {
                $('#login_' + course).prop('disabled', 'true');
            }
        }
    });
    $('#login_' + course).prop('disabled', true);
    //if (hasDate) {
    //    $('#CalendarEvidence').change(function () {
    //        if ($('#file_' + course).length >0){
    //        if ($('#file_' + course).val() !== '' && $(this).val() !=='') {
    //            $('#login_' + course).removeProp('disabled');
    //        }
    //        } else {
    //            if ($(this).val() !== '') {
    //                $('#login_' + course).removeProp('disabled');
    //            }
    //        }
    //    });
    //}

    $('#file_' + course).change(function () {
        if ($('#TextEvidence_' + course).length > 0) {
            if ($('#TextEvidence_' + course).val() !== '' && $(this).val() !== '') {
                $('#login_' + course).removeProp('disabled');
                $('#login_' + course).removeAttr('disabled');
            } else {
                $('#login_' + course).prop('disabled', 'true');
            }
        } else {
            if (!hasDate) {
                if ($(this).val() !== '') {
                    $('#login_' + course).removeProp('disabled');
                    $('#login_' + course).removeAttr('disabled');
                } else {
                    $('#login_' + course).prop('disabled', 'true');
                }
            } else {
                if ($(this).val() !== '' && calendarEvidence === true) {
                    $('#login_' + course).removeProp('disabled');
                    $('#login_' + course).removeAttr('disabled');
                } else {
                    $('#login_' + course).prop('disabled', 'true');
                }
            }
        }


    });
};

var initSec;
var showing;

// Passess //
/* commented out until somebody figures out what it should actually do
$(document).ready(function () {
    if (programid && $('.PurchaseCoursePasses').length === 0) {
      
        $.ajax(baseUrl + "TilesHandlers/BuyPass.ashx", {
            async: true,
            error: function (e) {
                console.log(e);
                console.log('failed');
            },
            data: { 'type': 'tile', 'programID': programid }
        }).done(function (data) {
            if (data.buyPass_Tile) {
                console.log(data.buyPass_Tile.BuyPassTitle);
                var button = $('<button type="button" class="btn btn-primary btn-lg pass" style="margin-top:5px"><i class="fa fa-ticket"> ' + data.buyPass_Tile.BuyPassTitle + '</i></button>');
                button.on('click', function () {
                    window.location.href = baseUrl + 'Student/eCommerce/purchasecoursepasses.aspx';
                })
                $('.logo_login_bar').before(button);  
            }
        });
    }

});
*/

function showSec(section, position) {
    //alert("section=" + section + " position=" + position + " currsection=" + currSection);
    //alert(position);
    scoPreReq = completionList[position - 2];
    //alert(scoPreReq);
    if (scoPreReq != '0') {
        if (sec_1.style.display == 'block') {
            initSec = sec_1;
        }
        if (section.style.display != 'block') {
            if (initSec == sec_1) {

                if (eval('img_' + currSection) != "undefined") {
                    img = eval('img_' + currSection);
                    img.src = "images/uploaded/mb/geds_topic_unselected.gif";
                }
                td = eval('td_' + currSection);
                td.className = "topicmenu";
                initSec.style.display = 'none';
                section.style.display = 'block';
                currSection = position;

                if (eval('img_' + currSection) != "undefined") {
                    img = eval('img_' + currSection);
                    img.src = "images/uploaded/mb/geds_topic_selected.gif";
                }
                td = eval('td_' + currSection);
                td.className = "topicmenusel";
                initSec = section;
                if (actionList[position - 1] == 0 || actionList[position - 1] == 1) {
                    completionList[position - 1] = 1;
                }
            } else {
                initSec.style.display = 'none';
                section.style.display = 'block';
                initSec = section;
                if (eval('img_' + currSection) != "undefined") {
                    img = eval('img_' + currSection);
                    img.src = "images/uploaded/mb/geds_topic_unselected.gif";
                }
                td = eval('td_' + currSection);
                td.className = "topicmenu";
                currSection = position;
                img = eval('img_' + currSection);
                if (eval('img_' + currSection) != "undefined") {
                    img = eval('img_' + currSection);
                    img.src = "images/uploaded/mb/geds_topic_selected.gif";
                }
                td = eval('td_' + currSection);
                td.className = "topicmenusel";
                if (actionList[position - 1] == 0 || actionList[position - 1] == 1) {
                    completionList[position - 1] = 1;
                }
            }
        }
    } else {
        alert("you have not yet completed the pre-requisite for this section");
    }
    if (currSection > 1) {
        showPrevious();
    } else {
        hidePrevious();
    }
    if (currSection < preReqList.length) {
        showNext();
    } else {
        hideNext();
    }
}

function showBarSec(section, position) {
    //alert("section=" + section + " position=" + position + " currsection=" + currSection);
    //alert(position);
    scoPreReq = completionList[position - 2];
    //alert(scoPreReq);
    if (scoPreReq != '0') {
        if (sec_1.style.display == 'block') {
            initSec = sec_1;
        }
        if (section.style.display != 'block') {
            if (initSec == sec_1) {


                td = eval('td_' + currSection);
                td.className = "bartopicmenu";
                initSec.style.display = 'none';
                section.style.display = 'block';
                currSection = position;


                td = eval('td_' + currSection);
                td.className = "bartopicmenusel";
                initSec = section;
                if (actionList[position - 1] == 0 || actionList[position - 1] == 1) {
                    completionList[position - 1] = 1;
                }
            } else {
                initSec.style.display = 'none';
                section.style.display = 'block';
                initSec = section;

                td = eval('td_' + currSection);
                td.className = "bartopicmenu";
                currSection = position;

                td = eval('td_' + currSection);
                td.className = "bartopicmenusel";
                if (actionList[position - 1] == 0 || actionList[position - 1] == 1) {
                    completionList[position - 1] = 1;
                }
            }
        }
    } else {
        alert("you have not yet completed the pre-requisite for this section");
    }
    if (currSection > 1) {
        showPrevious();
    } else {
        hidePrevious();
    }
    if (currSection < preReqList.length) {
        showNext();
    } else {
        hideNext();
    }
}

function enableNextSection() {
    var tab = eval("tab_" + (currSection + 1));
    tab.style.color = "green";
    if (currSection < preReqList.length) { next.style.color = 'green'; }

}

function hideShowMenu() {
    if (nav.style.display == 'block') {
        nav.style.display = 'none';
        //	menuHideShow.innerHTML = 'SHOW MENU&#160;&#160;&#160;';
    } else {
        nav.style.display = 'block';
        //	menuHideShow.innerHTML = '&#160;HIDE MENU&#160;&#160;';
    }
}

function nextSection() {
    //alert(preReqList);
    if (preReqList.length > 1) {

        if (sec_1.style.display == 'block') {
            initSec = sec_1;
        }
        scoPreReq = completionList[currSection - 1];
        if (scoPreReq != 0) {
            if (currSection < preReqList.length) {
                hide = eval('sec_' + currSection);
                hide.style.display = 'none';
                img = eval('img_' + currSection);
                img.src = "images/uploaded/mb/geds_topic_unselected.gif";
                td = eval('td_' + currSection);
                td.className = "topicmenu";
                tempSection = currSection + 1;
                tempSection = eval('sec_' + tempSection);
                tempSection.style.display = 'block';
                initSec = tempSection;
                var Obj = document.getElementById("previous");
                if (Obj != null) {
                    previous.style.display = 'block';
                    previousButton.style.display = 'block';
                    previous.style.cursor = 'hand';
                }
                currSection = currSection + 1;
                img = eval('img_' + currSection);
                img.src = "images/uploaded/mb/geds_topic_selected.gif";
                td = eval('td_' + currSection);
                td.className = "topicmenusel";
                if (document.next) {
                    if (currSection == preReqList.length) {
                        next.style.color = 'black';
                        next.style.cursor = 'auto';
                    }
                }
                if (actionList[currSection - 1] == 0 || actionList[currSection - 1] == 1) {
                    completionList[currSection - 1] = 1;
                }
            }
        } else {
            alert("you have not yet completed the pre-requisite for this section");
        }

    }
    if (document.previous) {
        if (currSection > 1) {
            showPrevious();
        } else {
            hidePrevious();
        }
        if (currSection < preReqList.length) {
            showNext();
        } else {
            hideNext();
        }
    }
}

function previousSection() {
    if (currSection > 1) {
        //alert("previous section");
        hide = eval('sec_' + currSection);
        hide.style.display = 'none';

        tempSection = currSection - 1;
        tempSection = eval('sec_' + tempSection);
        tempSection.style.display = 'block';

        img = eval('img_' + currSection);
        img.src = "images/uploaded/mb/geds_topic_unselected.gif";

        td = eval('td_' + currSection);
        td.className = "topicmenu";

        initSec = tempSection;
        currSection = currSection - 1;

        td = eval('td_' + currSection);
        td.className = "topicmenusel";

        img = eval('img_' + currSection);
        img.src = "images/uploaded/mb/geds_topic_selected.gif";
        var Obj = document.getElementById("previous");
        if (currSection == 1) {
            if (Obj != null) {
                previous.style.display = "none";
                previousButton.style.display = "none";
                //previous.style.cursor='auto';
            }
        }
        if (currSection < preReqList.length) {
            //next.style.color='green';
            next.style.cursor = 'hand';
        }
    }
    if (currSection > 1) {
        showPrevious();
    } else {
        hidePrevious();
    }
    if (currSection < preReqList.length) {
        showNext();
    } else {
        hideNext();
    }
}

function showPrevious() {
    var Obj = document.getElementById("previous");

    if (Obj != null) {
        previous.style.display = 'block';
        previousButton.style.display = 'block';
    }
    stopMedia();
}

function hidePrevious() {
    var Obj = document.getElementById("previous");

    if (Obj != null) {
        previous.style.display = 'none';
        previousButton.style.display = 'none';
    }
    stopMedia();
}

function showNext() {
    if (document.next) {
        next.style.display = 'block';
        nextButton.style.display = 'block';
    }
}

function stopMedia() {
    var winMediaObj = document.getElementById("mediaPlayer");
    if (winMediaObj != null) {
        winMediaObj.Pause();
    }

    var quckTimeMediaObj = document.getElementById("quicktime");
    if (quckTimeMediaObj != null) {
        quckTimeMediaObj.stop();
    }

    var flashObj = document.getElementById("flashAsset");
    if (flashObj != null) {
        flashObj.StopPlay();
    }
}

function hideNext() {
    if (document.next) {
        next.style.display = 'none';
        nextButton.style.display = 'none';
    }
}

function editSco(vform) {
    sco = vform.scoid.value;
    var url = "EditSco.aspx?id=" + sco;
    window.open(url, 'Fullscreen' + sco, "width=" + (screen.width - 100) + ",height=" + (screen.height - 100) + ",channelmode=0,dependent=0,directories=0,fullscreen=0,location=0,menubar=0,resizable=0,scrollbars=1,status=1,toolbar=0,top=10,left=10");
    history.back();
}

function editMetadata(vform) {
    sco = vform.scoid.value;
    var url = "EditScoMetadata.aspx?id=" + sco;
    window.open(url, 'Fullscreen', "width=" + (screen.width - 100) + ",height=" + (screen.height - 100) + ",channelmode=0,dependent=0,directories=0,fullscreen=0,location=0,menubar=0,resizable=0,scrollbars=1,status=1,toolbar=0,top=10,left=10");
    history.back();
}

function editContent(vform) {
    sco = vform.scoid.value;
    var url = "EditScoContent.aspx?id=" + sco;
    window.open(url, 'Fullscreen', "width=" + (screen.width - 100) + ",height=" + (screen.height - 100) + ",channelmode=0,dependent=0,directories=0,fullscreen=0,location=0,menubar=0,resizable=0,scrollbars=1,status=1,toolbar=0,top=10,left=10");
    history.back();
}

function hideAdvanced(button, panel) {
    if (panel.style.display == "none") {
        panel.style.display = "block";
        button.innerText = "Hide Advanced";
    } else {
        panel.style.display = "none";
        button.innerText = "Show Advanced";
    }
}

var navToShow = null;
var the_timer;

function display(menu) {
    //alert("test " + menu);
    if (navToShow == null) {

        navToShow = eval(menu + '_menu');
        navToShow.style.display = "block";
    } else {
        clearTimeout(the_timer);
        navToShow.style.display = "none";
        navToShow = eval(menu + '_menu');
        navToShow.style.display = "block";
    }
    //alert("test " + menu);
}

function hideMenu() {
    if (navToShow != null) {
        navToShow.style.display = "none";
    }
}

function startTimer() {
    the_timer = setTimeout("hideMenu()", 300);
}

/*********************launch a course window and watch for it to close*************************/

var newwindow = null;
var assessmentWindow = null;
var courseid;

var buyPass = function (passID, allowCoupons, cartType) {
    //change, if allow coupons, stop and ask for coupon
    if (allowCoupons == "True") {
        if ($('#modalAccessCode').length === 0)
            $('body').append('<div id="modalAccessCode" style="display:none"></div>');
        $('#modalAccessCode').html('');

        var modalHTML = '<div id="accessModal" class="modal fade in" tabindex="-1" role="dialog" aria-hidden="True" style="display:;">' +
            '<div class="modal-dialog modal-md">' +
            '<div class="modal-content">' +
            '<div class="modal-body" id="accessModalBodyDiv">' +
            '<div class="controls" id="scope">' +
            '<div class="form-group">' +
            '<div id="msg" class="alert " role="alert" style="display:;">' + Nomenclature.translate('If you have a coupon please enter below') + '</div>' +
            '<input type="text" placeholder="' + Nomenclature.translate('Enter Coupon') + '" runat="server" id="CouponTxt" class="form-control" style="margin:0px 0px 10px 0px;" aria-label="Enter Coupon" />' +
            '<button id="Check_button" onclick="validateAndApplyCouponForPass(\'' + passID + '\');" class="btn btn-default pull-right">' + Nomenclature.translate('Purchase') + '</buton>' +
            '</div>' +
            '<div id="CouponAlert" class="alert " role="alert" style="display:;"></div>' +
            '</div>' +
            '</div>' +
            '</div>' +
            '</div>';

        $("#modalAccessCode").append(modalHTML);
        $('#accessModal').modal('show', { show: true, keyboard: false });
        $('#modalAccessCode').css("display", "block");
        $('#modalAccessCode').addClass('modal-open');
    }

    else {

        if (cartType == "external")
            purchaseExternal(response.url, title, response.price, response.marqueeElement, response.cartURL);
        else
            parent.location = 'Student/eCommerce/AddToCart.aspx?ItemID=' + passID + '&Type=Pass ';
    }
};

function validateAndApplyCouponForPass(passID) {
    //var data1 = { code: code, domainID: domainID };
    var url = baseUrl + 'Student/eCommerce/Coupons.ashx';
    var coupon = $('#CouponTxt').val();
    if (coupon == '')
        parent.location = 'Student/eCommerce/AddToCart.aspx?ItemID=' + passID + '&Type=Pass ';

    var result;
    $.ajax(
        {
            url: url,
            type: 'POST',
            dataType: "json",
            data: { coupon: coupon, passID: passID, op: "redeemCouponForPass" },
            async: false,
            success: function (data) {
                if (data) {
                    if (data.success == 'true' || data.success == 'True' || data.success == true) {
                        parent.location.href = parent.location.href;
                        //$('#modalAccessCode').css("display", "block");
                    }
                    else {
                        $('#CouponAlert').html(data.message);
                        $('#CouponAlert').css('display', 'block');
                    }
                }
            },
            error: function (data) {
                if (data.isValid == 'false' || data.isValid == 'FALSE') {
                    $('#CouponAlert').html('Error..');
                    $('#CouponAlert').css('display', 'block');
                    //console.log('Error in access code' + '! ' + code);
                }
            }
        });
    return result;
}

var showPass = function (passid, purchased) {

    $.ajax({
        url: 'student/eCommerce/UserPasses.ashx',
        data: {
            op: 'getPassDetails',
            passID: passid
        },
        success: function (data) {
            /*
            {"PassID":"d94253b2-2af1-47b8-ad76-5d6193dcacd6",
            "Code":"12364",
            "Name":"Pass for Webinar Purchase",
            "Description":"Pass for Webinar Purchase",
            "ExpirationUnit":"days",
            "ExpirationNumber":"30",
            "ExpirationMode":"AfterPurchase",
            "ExpirationDate":"",
            "HasStartDate":"False",
            "StartDate":"",
            "Price":"0.10",
            "altPricesJson":[[]],
            "activities":[
                {"courseID":"be63abfc-121c-466d-91f3-353bc765a3ba",
                "description":"Elearning Course 26th April - 1",
                "code":"Elearning Course 26th April - 1"
                }]}

            */

            var activities = '';
            var metadatas = '';
            var expTime = data.ExpirationNumber;
            var expDate = data.ExpirationDate;
            var expFormat = data.ExpirationUnit;
            var tempMode = data.ExpirationMode.split(/(?=[A-Z])/);
            var expMode = "";
            if (expDate === '') {
                $.each(tempMode, function () {
                    expMode += this.toLowerCase() + ' ';
                });
            } else {
                expMode = new Date(expDate).toLocaleDateString();
            }
            var startdate = (data.StartDate != '') ? '<div><label>Starts :</label> ' + ((dateFormat !== "") ? new Date(data.StartDate).toString(dateFormat) : data.StartDate.split(' ')[0]) + '</div>' : '';
            var price = data.Price;

            var expiration = (expDate == '') ? 'Expires ' + expTime + ' ' + expFormat + ' ' + expMode :
                'Expires on ' + expMode;

            //metadata for pass, please review
            $.each(data.metadata, function () {
                metadatas += '<div><b>' + this.name + '</b>:';
                var val = "";
                $.each(this.values, function () {
                    if (val.length > 0)
                        val += ",";
                    val += this;
                })

                metadatas += '<span>' + val + '</span></div>';
            })


            $.each(data.activities, function () {
                activities += '<tr style="list-style-type:none;"><td><b>' + this.title + '</b></td>' +
                    '<td>' + this.code + '</td>' +
                    '<td style="word-wrap:break-word;">' + this.description + '</td>' +
                    '</tr>';
            })
            if ($('#modalAccessCode').length === 0)
                $('body').append('<div id="modalAccessCode" style="display:none"></div>');
            $('#modalAccessCode').html('');
            var purchaseButton = (purchased) ? '' : '<button id="Check_button" onclick="buyPass(\'' + data.PassID + '\',\'' + data.AllowCoupons + '\' );" class="btn btn-default pull-right">Purchase</buton>';
            var modalHTML = '<div id="accessModal" class="modal fade in" tabindex="-1" role="dialog" aria-labelledby="accessModalLabel" aria-hidden="True"">' +
                '<div class="modal-dialog modal-md" style="width:70%;">' +
                '<div class="modal-content">' +
                '<div class="modal-header">' +
                '<h1 class="modal-title" style="display:inline-block;">' + data.Name + '</h1>' +
                '<button class="close" data-dismiss="modal" data-bs-dismiss="modal" tabindex="0" aria-label="Close">' +
                '<span aria-hidden="true">&times;</span>' +
                '</button>' +
                '</div>' +
                '<div class="modal-body" id="accessModalBodyDiv">' +
                '<h2>' + data.Code + '</h2>' +
                '<p class="description" style="margin-top:20px;">' + data.Description + '</p>' +
                startdate +
                '<div><label>Price :</label> ' + price + '</div>' +
                '<div style="margin:0px 0px 10px 0px"><i>*' + expiration + '</i></div>' +
                '<div style="margin:0px 0px 10px 0px"><i>' + metadatas + '</i></div>' +
                '<h3>Activities included in this Pass</h3>' +
                '<table class="table table-striped;"><thead><tr><th>Title</th><th>Code</th><th>Description</th></tr></thead><tbody>' + activities + '</tbody></table>' +
                '<div class="controls" id="scope">' +
                '<div class="form-group tc-btn-group">' +
                purchaseButton +
                '<button id="Close_button" data-dismiss="modal" data-bs-dismiss="modal" class="btn btn-default pull-right" tabindex="0" aria-label="Close">Close</button>' +

                '</div>' +
                '<div id="AccessCodeAlert" class="alert " role="alert" style="display:;"></div>' +
                '</div>' +
                '</div>' +
                '</div>' +
                '</div>';

            $("#modalAccessCode").append(modalHTML);

            $('#accessModal').modal('show', { show: true, keyboard: false });
            $('#modalAccessCode').css("display", "block");
            $('#modalAccessCode').addClass('modal-open');
        },
        error: function (e) {
            console.log(e);
        }
    });

}

var redeemCodeFromCatalogue = function (domainID, courseID, studentID, callback, title, type, b, active, el) {
    if ($('#modalAccessCode').length === 0)
        $('body').append('<div id="modalAccessCode" style="display:none"></div>');
    $('#modalAccessCode').html('');

    var modalHTML = '<div id="accessModal" class="modal fade in" tabindex="-1" role="dialog" aria-labelledby="accessModalLabel" aria-hidden="True" style="display:;">' +
        '<div class="modal-dialog modal-md">' +
        '<div class="modal-content">' +
        '<div class="modal-body" id="accessModalBodyDiv">' +
        '<div class="controls" id="scope">' +
        '<div class="form-group">' +
        '<input type="text" placeholder="Enter Access Code" runat="server" id="CodeTxt" class="form-control" style="margin:0px 0px 10px 0px;"/>' +
        '<button id="Check_button" onclick="checkAccessCodeInCatalogue(\'' + domainID + '\',\'' + courseID + '\',\'' + studentID + '\',\'' + callback + '\',\'' + title + '\',\'' + type + '\',' + b + ',\'' + active + '\',\'' + el + '\');" class="btn btn-default pull-right">Check Access Code</buton>' +
        '</div>' +
        '<div id="AccessCodeAlert" class="alert " role="alert" style="display:;"></div>' +
        '</div>' +
        '</div>' +
        '</div>' +
        '</div>';

    $("#modalAccessCode").append(modalHTML);

    $('#accessModal').modal('show', { show: true, keyboard: false });
    $('#modalAccessCode').css("display", "block");
    $('#modalAccessCode').addClass('modal-open');
}

function AccessCodeModal(domainID, courseID, learningPathID, attempt, height, width, modal, title, returnUrl, call, studentID) {
    if ($('#modalAccessCode').length === 0)
        $('body').append('<div id="modalAccessCode" style="display:none"></div>');
    $('#modalAccessCode').html('');

    var modalHTML = '<div id="accessModal" class="modal fade in" tabindex="-1" role="dialog" aria-labelledby="accessModalLabel" aria-hidden="True" style="display:;">' +
        '<div class="modal-dialog modal-md">' +
        '<div class="modal-content">' +
        '<div class="modal-body" id="accessModalBodyDiv">' +
        '<div class="controls" id="scope">' +
        '<div class="form-group">' +
        '<input type="text" placeholder="Enter Access Code" runat="server" id="CodeTxt" class="form-control" style="margin:0px 0px 10px 0px;"/>' +
        '<button id="Check_button" onclick="checkAccessCode(\'' + domainID + '\',\'' + courseID + '\',\'' + learningPathID + '\',\'' + attempt + '\',\'' + height + '\',\'' + width + '\',\'' + modal + '\',\'' + title + '\',\'' + returnUrl + '\',\'' + call + '\',\'' + studentID + '\');" class="btn btn-default pull-right">Check Access Code</buton>' +
        '</div>' +
        '<div id="AccessCodeAlert" class="alert " role="alert" style="display:;"></div>' +
        '</div>' +
        '</div>' +
        '</div>' +
        '</div>';

    $("#modalAccessCode").append(modalHTML);

    $('#accessModal').modal('show', { show: true, keyboard: false });
    $('#modalAccessCode').css("display", "block");
    $('#modalAccessCode').addClass('modal-open');
};

var checkAccessCodeInCatalogue = function (domainID, courseID, studentID, callback, title, type, b, active, el) {
    var code = document.getElementById("CodeTxt");
    var type = "course";
    var result = validateRegistrationCode(code.value, domainID, 'course', courseID, studentID);
    //var result = true;
    if (result == true) {
        $("#Check_button").attr("data-dismiss", "modal");

        //OpenExpressStart = function (baseurl, courseID, programID, title, type, el, enrolled)
        //AddToCartNoFastStart(\'' + baseUrl + '\',\'' + this.id + '\',\'' + this.programID + '\',\'' + this.title + '\',\'' + this.type + '\', this, false,\'available\')"'
        var cb = eval(callback);
        if (callback === 'AddToCartNoFastStart') {
            cb(baseUrl, courseID, domainID, title, type, $(el), false, 'available');
        } else {
            cb(baseUrl, courseID, domainID, title, type, $(el), b);
        }
    }
    else {
        openAccessModal(false);
    }
    return false;
}

function checkAccessCode(domainID, courseID, learningPathID, attempt, height, width, modal, title, returnUrl, call, studentID) {
    var code = document.getElementById("CodeTxt");
    var type = "course";
    var result = validateRegistrationCode(code.value, domainID, 'course', courseID, studentID);
    if (result == true) {
        $("#Check_button").attr("data-dismiss", "modal");
        launchEnterClassrooom(courseID, domainID, learningPathID, attempt, height, width, modal, title, returnUrl, call, fullscreen)

    }
    else {
        openAccessModal(false);
    }
    return false;
}

function openAccessModal(isvalid) {
    if (isvalid) {
        $("#AccessCodeAlert").html("Access Code is Valid.");
        $("#AccessCodeAlert").attr("class", "alert-success");
        $("#AccessCodeAlert").css("display", "block");
        $("#Check_button").value('Continue');
        $("#Check_button").attr('Onclick', 'closePopUp()');

    } else {
        $("#accessModal").modal({
            backdrop: 'static',
            keyboard: false
        });
        $("#AccessCodeAlert").attr("class", "alert-danger");
        $("#AccessCodeAlert").css("display", "block");
        $("#AccessCodeAlert").html("Access Code is InValid.");
    }
}

var closePopUp = function () {
    $("#accessModal").modal('hide');
}

function AccessCodeModalforLink(link, domainID, courseID, studentID) {
    if ($('#modalAccessCode').length === 0)
        $('body').append('<div id="modalAccessCode" style="display:none"></div>');
    $('#modalAccessCode').html('');
    //$('.modal.learning-activity-feedback .modal-body').html('');

    var modalHTML = '<div id="accessModal" class="modal fade in" tabindex="-1" role="dialog" aria-labelledby="accessModalLabel" aria-hidden="True" style="display:;">' +
        '<div class="modal-dialog modal-md">' +
        '<div class="modal-content">' +
        '<div class="modal-body" id="accessModalBodyDiv">' +
        '<div class="controls" id="scope">' +
        '<div class="form-group">' +
        '<input type="text" placeholder="Enter Access Code" runat="server" id="CodeTxt" class="form-control" style="margin:0px 0px 10px 0px;"/>' +
        '<button id="Check_button" onclick="LinkcheckAccessCode(\'' + link + '\',\'' + domainID + '\',\'' + courseID + '\',\'' + studentID + '\');return false;" class="btn btn-default pull-right">Check Access Code</buton>' +
        '</div>' +
        '<div id="AccessCodeAlert" class="alert " role="alert" style="display:;"></div>' +
        '</div>' +
        '</div>' +
        '</div>' +
        '</div>';


    $("#modalAccessCode").append(modalHTML);
    //$('.modal.learning-activity-feedback .modal-body').append(spinner);
    //$('#formhtml').append(dom);
    $('#accessModal').modal('show', { show: true, keyboard: false });
    $('#modalAccessCode').css("display", "block");
    $('#modalAccessCode').addClass('modal-open');
    return false;
};

//function AccessCodeModalforAccessedcourse(link, domainID, courseID, studentID) {
//    if ($('#modalAccessCode').length === 0)
//        $('body').append('<div id="modalAccessCode" style="display:none"></div>');
//    $('#modalAccessCode').html('');
//    //$('.modal.learning-activity-feedback .modal-body').html('');

function AccessCodeModalFaststart(baseUrl, courseID, domainID, title, type, el, active) {
    if ($('#modalAccessCode').length === 0)
        $('body').append('<div id="modalAccessCode" style="display:none"></div>');
    $('#modalAccessCode').html('');
    //$('.modal.learning-activity-feedback .modal-body').html('');

    var modalHTML = '<div id="accessModal" class="modal fade in" tabindex="-1" role="dialog" aria-labelledby="accessModalLabel" aria-hidden="True" style="display:;">' +
        '<div class="modal-dialog modal-md">' +
        '<div class="modal-content">' +
        '<div class="modal-body" id="accessModalBodyDiv">' +
        '<div class="controls" id="scope">' +
        '<div class="form-group" id="faststartAccesscode">' +
        '<input type="text" placeholder="Enter Access Code" runat="server" id="CodeTxt" class="form-control" style="margin:0px 0px 10px 0px;"/>'
    '</div>' +
        '<div id="AccessCodeAlert" class="alert " role="alert" style="display:;"></div>' +
        '</div>' +
        '</div>' +
        '</div>' +
        '</div>';


    $("#modalAccessCode").append(modalHTML);
    var button1 = "<button id='faststartAccesscode_button' class='btn btn-default pull-right'>Check Access Code</button>";

    $("div #faststartAccesscode").append(button1);

    $("#faststartAccesscode_button").click(function () { checkAccessCodeCatalogue(el, baseUrl, courseID, domainID, title, type, active, ''); });
    $('#accessModal').modal('show', { show: true, keyboard: false });
    $('#modalAccessCode').css("display", "block");
    $('#modalAccessCode').addClass('modal-open');
    return false;
};

function LinkcheckAccessCode(link, domainID, courseID, studentID) {
    event.stopPropagation();
    var code = document.getElementById("CodeTxt");
    var type = "course";
    var result = validateRegistrationCode(code.value, domainID, 'course', courseID, studentID);
    if (result == true) {
        $("#Check_button").attr("data-dismiss", "modal");
        window.location.href = link;
    }
    else {
        openAccessModal(false);
    }
    return false;
}

var checkAccessCodeCatalogue = function (el, baseurl, courseID, domainID, title, type, isenrolled, studentID) {
    var code = document.getElementById("CodeTxt");
    var type = "course";
    var result = validateRegistrationCode(code.value, domainID, 'course', courseID, studentID);
    //var result = true;
    if (result == true) {
        $("#faststartAccesscode_button").attr("data-dismiss", "modal");
        OpenExpressStart(baseurl, courseID, domainID, title, type, $(el), isenrolled, '');
    }
    else {
        openAccessModal(false);
    }
    return false;
}

function AccessCodeModalforOpenModal(baseUrl, courseID, domainID, title, fastaction, backbtn, type, returnurl, studentID) {

    if ($('#modalAccessCode').length === 0)
        $('body').append('<div id="modalAccessCode" style="display:none"></div>');
    $('#modalAccessCode').html('');
    //$('.modal.learning-activity-feedback .modal-body').html('');
    var modalHTML = '<div id="accessModal" class="modal fade in" tabindex="-1" role="dialog" aria-labelledby="accessModalLabel" aria-hidden="True" style="display:;">' +
        '<div class="modal-dialog modal-md">' +
        '<div class="modal-content">' +
        '<div class="modal-body" id="accessModalBodyDiv">' +
        '<div class="controls" id="scope">' +
        '<div class="form-group">' +
        '<input type="text" placeholder="Enter Access Code" runat="server" id="CodeTxt" class="form-control" style="margin:0px 0px 10px 0px;"/>' +
        '<button id="Check_button"  onclick="openModalaccesscode(\'' + baseUrl + '\',\'' + courseID + '\',\'' + domainID + '\',\'' + title + '\',\'' + fastaction + '\',\'' + backbtn + '\',\'' + type + '\',\'' + returnurl + '\',\'' + studentID + '\');" class="btn btn-default pull-right">Check Access Code</buton>' +
        '</div>' +
        '<div id="AccessCodeAlert" class="alert " role="alert" style="display:;"></div>' +
        '</div>' +
        '</div>' +
        '</div>' +
        '</div>';
    $("#modalAccessCode").append(modalHTML);
    //$('.modal.learning-activity-feedback .modal-body').append(spinner);
    //$('#formhtml').append(dom);
    $('#accessModal').modal('show', { show: true, keyboard: false });
    $('#modalAccessCode').css("display", "block");
    $('#modalAccessCode').addClass('modal-open');
};

function AccessCodeModalforCatalogCategory(baseUrl, courseID, domainID, returnurl) {

    if ($('#modalAccessCode').length === 0)
        $('body').append('<div id="modalAccessCode" style="display:none"></div>');
    $('#modalAccessCode').html('');
    //$('.modal.learning-activity-feedback .modal-body').html('');
    var modalHTML = '<div id="accessModal" class="modal fade in" tabindex="-1" role="dialog" aria-labelledby="accessModalLabel" aria-hidden="True" style="display:;">' +
        '<div class="modal-dialog modal-md">' +
        '<div class="modal-content">' +
        '<div class="modal-body" id="accessModalBodyDiv">' +
        '<div class="controls" id="scope">' +
        '<div class="form-group">' +
        '<input type="text" placeholder="Enter Access Code" runat="server" id="CodeTxt" class="form-control" style="margin:0px 0px 10px 0px;"/>' +
        '<button id="Check_button"  onclick="LinkcheckAccessCode(\'' + baseUrl + '\',\'' + domainID + '\',\'' + courseID + '\');" class="btn btn-default pull-right">Check Access Code</buton>' +
        '</div>' +
        '<div id="AccessCodeAlert" class="alert " role="alert" style="display:;"></div>' +
        '</div>' +
        '</div>' +
        '</div>' +
        '</div>';
    $("#modalAccessCode").append(modalHTML);
    //$('.modal.learning-activity-feedback .modal-body').append(spinner);
    //$('#formhtml').append(dom);
    $('#accessModal').modal('show', { show: true, keyboard: false });
    $('#modalAccessCode').css("display", "block");
    $('#modalAccessCode').addClass('modal-open');
};

function openModalaccesscode(baseurl, courseID, programID, title, fastaction, entermode, backbtn, type, returnUrl, studentID) {
    var code = document.getElementById("CodeTxt");
    var type = "course";
    var result = validateRegistrationCode(code.value, programID, 'course', courseID, studentID);
    if (result == true) {
        openModal(baseurl, courseID, programID, title, fastaction, entermode, backbtn, type, returnUrl)
    }
    else {
        openAccessModal(false);
    }
    return false;
}

var attendanceCodeForCatalogPage = function (domainID, courseID, studentID, callback, title, type, b, active, el) {

    if ($('#modalAttendanceCode').length === 0)
        $('body').append('<div id="modalAttendanceCode" style="display:none"></div>');
    $('#modalAttendanceCode').html('');

    var modalHTML = '<div id="AttendanceCodeModal" class="modal fade in" tabindex="-1" role="dialog" aria-labelledby="attendanceModalLabel" aria-hidden="True" style="display:;" width>' +
        '<div class="modal-dialog modal-md">' +
        '<div class="modal-content">' +
        '<div class="modal-body" id="attendanceModalBodyDiv">' +
        '<div class="controls" id="scope">' +
        '<div class="form-group">' +
        '<input type="text" placeholder="Enter Attendance Code" runat="server" id="CodeTxt" class="form-control" style="margin:0px 0px 10px 0px;"/>' +
        '<button id="Check_button" onclick="checkAttendanceCodeInCatalogue(\'' + domainID + '\',\'' + courseID + '\',\'' + studentID + '\',\'' + callback + '\',\'' + title + '\',\'' + type + '\',' + b + ',\'' + active + '\',\'' + el + '\');" class="btn btn-default pull-right">Check Attendance Code</buton>' +
        '</div>' +
        '<div id="AttendanceCodeAlert" class="alert " role="alert" style="display:none;">In-Valid Attendance Code.</div>' +
        '</div>' +
        '</div>' +
        '</div>' +
        '</div>';

    $("#modalAttendanceCode").append(modalHTML);

    $('#AttendanceCodeModal').modal('show', { show: true, keyboard: false });
    $('#modalAttendanceCode').css("display", "block");
    $('#modalAttendanceCode').addClass('modal-open');

}

var checkAttendanceCodeInCatalogue = function (domainID, courseID, studentID, callback, title, type, b, active, el) {
    // var code = document.getElementById("CodeTxt");
    var type = "course";
    var result = checkAttendanceCode('', domainID, courseID, 'true');
    //var result = true;

    if (typeof (result) != 'undefined') {
        if (result.isValid == 'True' || result.isValid == true || result.isValid == 'true') {
            //  $("#Check_button").attr("data-dismiss", "modal");

            //OpenExpressStart = function (baseurl, courseID, programID, title, type, el, enrolled)
            //AddToCartNoFastStart(\'' + baseUrl + '\',\'' + this.id + '\',\'' + this.programID + '\',\'' + this.title + '\',\'' + this.type + '\', this, false,\'available\')"'
            var cb = eval(callback);
            if (callback === 'AddToCartNoFastStart') {
                cb(baseUrl, courseID, domainID, title, type, $(el), false, 'available');
            } else {
                cb(baseUrl, courseID, domainID, title, type, $(el), b);
            }
        }
        else {
            $("#AttendanceCodeModal #AttendanceCodeAlert").css("display", "block");
            $("#AttendanceCodeModal #AttendanceCodeAlert").text(result.message);
        }
    }
    return false;
}

var attendanceCodeCatalogueXsl = function (baseurl, courseID, programID, title, type, el, enrolled, lp) {

    if ($('#modalAttendanceCode').length === 0)
        $('body').append('<div id="modalAttendanceCode" style="display:none"></div>');
    $('#modalAttendanceCode').html('');

    var modalHTML = '<div id="AttendanceCodeModal" class="modal fade in" tabindex="-1" role="dialog" aria-labelledby="attendanceModalLabel" aria-hidden="True" style="display:;" width>' +
        '<div class="modal-dialog modal-md">' +
        '<div class="modal-content">' +
        '<div class="modal-body" id="attendanceModalBodyDiv">' +
        '<div class="controls" id="scope">' +
        '<div class="form-group">' +
        '<input type="text" placeholder="Enter Attendance Code" runat="server" id="CodeTxt" class="form-control" style="margin:0px 0px 10px 0px;"/>' +
        '<button id="Check_button" onclick="checkAttendanceCodeForCatalougeXsl(\'' + baseUrl + '\',\'' + courseID + '\',\'' + programID + '\',\'' + title + '\',\'' + type + '\',\'' + el + '\',\'' + enrolled + '\',\'' + lp + '\');return false;" class="btn btn-default pull-right">Check Attendance Code</buton>' +
        '</div>' +
        '<div id="AttendanceCodeAlert" class="alert " role="alert" style="display:none;">In-Valid Attendance Code.</div>' +
        '</div>' +
        '</div>' +
        '</div>' +
        '</div>';

    $("#modalAttendanceCode").append(modalHTML);

    $('#AttendanceCodeModal').modal('show', { show: true, keyboard: false });
    $('#modalAttendanceCode').css("display", "block");
    $('#modalAttendanceCode').addClass('modal-open');
}

var checkAttendanceCodeForCatalougeXsl = function (baseurl, courseID, domainID, title, type, el, enrolled, lp) {
    var type = "course";
    var result = checkAttendanceCode('', domainID, courseID, 'true');
    if (typeof (result) != 'undefined') {
        if (result.isValid == true) {
            OpenEnrollingCourse(baseurl, courseID, domainID, title, type, el, enrolled, lp);
        }
        else {
            $("#AttendanceCodeModal #AttendanceCodeAlert").css("display", "block");
            $("#AttendanceCodeModal #AttendanceCodeAlert").text(result.message);
        }
    }
    return false;
}

function AttendanceCodeModal(baseUrl, domainID, courseID, lpId) {
    if ($('#modalAttendanceCode').length === 0)
        $('body').append('<div id="modalAttendanceCode" style="display:none"></div>');
    $('#modalAttendanceCode').html('');
    var modalHTML = '<div id="AttendanceCodeModal" class="modal fade in" tabindex="-1" role="dialog" aria-labelledby="attendanceModalLabel" aria-hidden="True" style="display:;" width>' +
        '<div class="modal-dialog modal-md">' +
        '<div class="modal-content">' +
        '<div class="modal-body" id="attendanceModalBodyDiv">' +
        '<div class="controls" id="scope">' +
        '<div class="form-group">' +
        '<input type="text" placeholder="Enter Attendance Code" runat="server" id="CodeTxt" class="form-control" style="margin:0px 0px 10px 0px;"/>' +
        '<button id="Check_button" onclick="checkAttendanceCode(\'' + baseUrl + '\',\'' + domainID + '\',\'' + courseID + '\');" class="btn btn-default pull-right">Check Attendance Code</buton>' +
        '</div>' +
        //' <div id="validCoupon" class="hidden"> <hr />'+                      
        // '<h3>PIN Successful</h3>'+
        //'<p>This is a PIN for <span id="validfor_course"></span>. If this is not the course you wish to take, please stop here and check with your Distributor.</p>'+
        //'<p><input type="checkbox" name="confirm_pin_use" id="confirm_pin_use" onclick="activate_pin_continue();" /><span id="validfor_course_confirm"></span> is the course I wish to take.</p>'+
        //'</div>'+
        '<div id="AttendanceCodeAlert" class="alert " role="alert" style="display:none;">In-Valid Attendance Code.</div>';
    if (lpId != 'undefined' && lpId != '')
        modalHTML += '<input type="hidden" id="LpID" value="' + lpId + '" />';

    modalHTML += '</div>' +
        '</div>' +
        '</div>' +
        '</div>';

    $("#modalAttendanceCode").append(modalHTML);

    $('#AttendanceCodeModal').modal('show', { show: true, keyboard: false });
    $('#modalAttendanceCode').css("display", "block");
    $('#modalAttendanceCode').addClass('modal-open');
};

function checkAttendanceCode(baseUrl, domainID, CourseID, EnrollBtn) {
    var Code_value = $("#AttendanceCodeModal #CodeTxt").val();
    var LPId = '';
    // check if the page is a learning path
    if (typeof (isLP) !== 'undefined' && isLP) {
        LPId = getParameterByName('id');
    } else {
        LPId = $("#AttendanceCodeModal #LpID").val();
    }

    console.log("Code=" + Code_value);
    var result = false;
    $.ajax({
        url: "Student/eCommerce/ValidateCoupon.ashx",
        dataType: "json",
        async: false,
        data: {
            coupon: Code_value,
            op: 'ApplyAttendanceCode',
            courseID: CourseID
        },
        error: function () { },
        success: function (data) {
            if (data) {
                if (typeof (EnrollBtn) == 'undefined' || EnrollBtn == "") {
                    console.log("data.isValid = " + data.isValid);
                    if (data.isValid === 'true' || data.isValid === 'True') {
                        var activity_cart_URL = baseUrl + '/Student/eCommerce/AddToCart.aspx?ItemID=' + data.courseID + '&Type=Course&back=catalogue' + '&coupon=' + Code_value;
                        //if (Operation == 'ApplyAttendanceCode') {
                        if (LPId != 'undefined' && LPId != '') {
                            if(location.href.indexOf("MyLP.aspx") >= 0)
                                activity_cart_URL = baseUrl + '/Student/MyLP.aspx?id=' + LPId;
                            else
                                activity_cart_URL = baseUrl + '/Student/MyCourse.aspx?id=' + LPId;

                        }else
                            activity_cart_URL = baseUrl + '/Student/MyCourse.aspx?id=' + data.courseID;
                        // }
                        console.log("activity_cart_URL = " + activity_cart_URL);
                        window.location.href = activity_cart_URL;
                    } else {

                        if ((data.isValid === 'false' || data.isValid === 'False')) {
                            $("#AttendanceCodeModal #AttendanceCodeAlert").css("display", "block");
                            $("#AttendanceCodeModal #AttendanceCodeAlert").text(data.LearnerInstruction);
                        }
                        else
                            $("#AttendanceCodeModal #AttendanceCodeAlert").css("display", "block");
                    }
                }
                else {
                    result = data;
                    //  return result;
                }
            }
        }
    });

    return result;
}

function validateRegistrationCode(code, domainID, type, courseID, studentID) {
    //var data1 = { code: code, domainID: domainID };
    //var baseurl = baseUrl + 'ValidateAccessCodeHandler.ashx';
    var result;
    $.ajax(
        {
            url: baseUrl + 'ValidateAccessCodeHandler.ashx',
            type: 'POST',
            dataType: "json",
            data: {
                Accesscode: code,
                domain: domainID,
                type: type,
                Course: courseID,
                StudentID: studentID
            },
            async: false,
            success: function (data) {
                if (data) {
                    if (data.isValid == 'true' || data.isValid == 'True') {
                        //window.alert('Access code is valid.');
                        // showPopup(true);
                        result = true;
                    }
                    else {
                        result = false;
                    }

                }
            },
            error: function (data) {
                if (data.isValid == 'false' || data.isValid == 'FALSE') {

                    console.log('Error in access code' + '! ' + code);
                }
            }
        });
    return result;
}

function ReenrollandReviewModal(courseID, domainID, learningPathID, attempt, height, width, modal, title, returnUrl, call, studentID, hasAccesscode, baseUrl, type, mapID, authenticationType) {
    if ($('#modalAccessCode').length === 0)
        $('body').append('<div id="modalRenrollandReview" style="display:none"></div>');
    $('#modalAccessCode').html('');

    var modalHTML = '<div id="RenrollandReviewmodal" class="modal fade in" tabindex="-1" role="dialog" aria-labelledby="RenrollandRevieModalLabel" aria-hidden="True" style="display:;">' +
        '<div class="modal-dialog modal-md">' +
        '<div class="modal-content">' +
        '<div class="modal-header" style="height:45px;">' +
        '<button type="button" class="close" data-dismiss="modal" data-bs-dismiss="modal" aria-hidden="true">&#215;</button>' +
        '<p class="modal-title">You have completed this course. Would you like to review the completed content or start a new enrollment? </p>' +
        '</div>' +
        '<div class="modal-body" id="RenrollandRevieModalBodyDiv">' +
        '<div class="controls" id="scope">' +
        '<div class="form-group">' +
        '<button id="Review_button" onclick="OpenEnrollingCourse(\'' + baseUrl + '\',\'' + courseID + '\',\'' + domainID + '\',\'' + title + '\',\'' + authenticationType + '\',\'this\',\'true\',\'' + mapID + '\');return false;" class="btn btn-default pull-right" style="margin-left:0.5em;">Start new enrollment</buton>' +
        '<button id="Review_button" onclick="reviewCourse(\'' + courseID + '\',\'' + domainID + '\',\'' + learningPathID + '\',\'' + attempt + '\',\'' + height + '\',\'' + width + '\',\'' + modal + '\',\'' + title + '\',\'' + returnUrl + '\',\'' + call + '\',\'' + studentID + '\');return false;" class="btn btn-default pull-right" style="margin-left:0.5em;">Review completed content</buton>' +
        '</div>' +
        '</div>' +
        '</div>' +
        '</div>' +
        '</div>';

    $("#modalAccessCode").append(modalHTML);
    $('#RenrollandReviewmodal').modal('show', { show: true, keyboard: false });
    $('#modalAccessCode').css("display", "block");
    $('#modalAccessCode').addClass('modal-open');
    $('.activity-modal').modal('hide');
};

function reviewCourse(courseID, domainID, learningPathID, attempt, height, width, modal, title, returnUrl, call, studentID, hasAccesscode, baseUrl, type, mapID) {
    if (hasAccesscode == 'true')
        AccessCodeModal(domainID, courseID, learningPathID, attempt, height, width, modal, title, returnUrl);
    else
        launchEnterClassrooom(courseID, domainID, learningPathID, attempt, height, width, modal, title, returnUrl);

}

//enter classroom opener that works with Firefox
function launchEnterClassrooom(courseID, programID, learningPathID, attempt, height, width, modal, title, returnUrl, call, fullscreen) {
    TC.currentCourse = courseID;
    if (browser_type.indexOf('Safari') >= 0) {
        console.log('safari bug fix');
        // $('body').css('position', 'fixed');
    }

    if (typeof (isLP) !== 'undefined' && isLP && typeof (lastAccessed) == 'undefined')
        lastAccessed = courseID;
    let margin = "";
    let fs = false;
    if ((typeof (courseFullScreen) !== 'undefined' && courseFullScreen === true) || (typeof (fullscreen) !== 'undefined' && fullscreen.toLowerCase() === 'true')) {
        height = $(window).innerHeight() + 'px';
        width = $(document).innerWidth() + 'px';
        //height = "99vh";
        //width = "90%";
        margin = 'margin:0px auto !important;';
        fs = true;
    } else {

        if (!height) {
            var height = '600';
        }
        if (!width) {
            var width = '800';
        }
        width = width + 'px';
        height = height + 'px';

    }
    if (!title) {
        var title = " ";
    }

    //PLEASE MIND THE PARAMETER CASE
    //PLEASE GO TO ENTERCLASSROOM NOT VIEWCOURSE!!! < Check out the passive aggressive explanation marks. Must be serious.

    var redirectURL = baseUrl + "Student/Course/EnterClassroom.aspx?Modal=true&CourseID=" + courseID + "&ProgramID=" + programID + "&Attempt=" + attempt;
    if (typeof (call) != 'undefined' && call)
        redirectURL += "&hasDisclaimer=1";
    if (learningPathID.length > 0)
        redirectURL += "&lpID=" + learningPathID;

    //open the course in a new tab or a new window depending on how the user has the browser set
    if (modal === 'DefaultBrowserSettings') {
        courseid = courseID;
        if (newwindow !== null && !newwindow.closed) {
            newwindow.location.href = redirectURL;
        } else {

            newwindow = window.open(redirectURL, 'CourseWindow');
        }
        //if(!isLP)
        interval = setInterval("checkParentWindow(false,'" + courseID + "')", 5000);
        try {
            $("#myModalDisc").modal('hide');
            $("#myModalDisc").remove();
        }
        catch (e) { }
    }
    else if (modal === 'ModalWindow') {
        try {
            $("#myModalDisc").modal('hide');
            $("#myModalDisc").remove();
        }
        catch (e) { }
        var mobile = (isMobile.any() !== null) ? "width:99%;" : "";

        // remove the modal if it exists
        console.log("tryhing to append the modal");
        $('#myModal').remove();
        if (!isIE) {
            if (mobile !== "") {
                console.log("modal a");
                $("body").append('<div aria-modal="true" class="modal fade course" id="myModal" runat="server" tabindex="-1" role="dialog" aria-hidden="true"><div class="modal-dialog" style="margin-top:5px!important;height:100%!important;' + mobile + '"><div tabindex="0"></div><div class="modal-content course_' + courseID + '" style="height:95%"><div class="modal-header header_' + courseID + '" style="height:45px;"><button type="button" class="close" data-bs-dismiss="modal"  data-dismiss="modal" aria-hidden="true" aria-label="Close button"><span class="glyphicon glyphicon-remove"></span></button><h4 class="modal-title">' + title.replace('&amp;', '&') + '</h4></div><div class="modal-body" style="height:calc(100% - 45px);"><iframe data-id="' + courseID + '" id="viewCourseModal" allowFullScreen = "true" webkitallowfullscreen = "true" mozallowfullscreen = "true" name = "viewCourse"  frameborder = "0" height = "100%" width = "100%" ></iframe ></div ></div ></div > <div tabindex="0"></div></div > ');
            } else {
                console.log("modal b");
                var modal = '<div class="modal fade course" id="myModal" runat="server" tabindex="-1"><div tabindex="0"></div><div role="dialog"  aria-modal="true"  class="modal-dialog" style="height:' + height + '!important; width:' + width + '!important;' + margin + '"><div style="height:100%;" class="modal-content course_' + courseID + '"><div class="modal-header header_' + courseID + '" style="height:45px;"><button type="button" class="close"  data-bs-dismiss="modal" data-dismiss="modal" aria-hidden="true" aria-label="Close button"><span class="glyphicon glyphicon-remove"></span></button><h4 class="modal-title">' + title.replace('&amp;', '&') + '</h4></div><div class="modal-body" style="height:calc(100% - 45px);"><div class="responsive-embed" style="height:100%"><iframe data-id="' + courseID + '" id="viewCourseModal" class="responsive-embed-item" allowFullScreen="true" webkitallowfullscreen="true" mozallowfullscreen="true" name="viewCourse" scrolling="auto"  frameborder "0" height="' + (parseInt(height) - 50) + '" width="' + width + '" tabindex="1"></iframe></div></div></div></div><div tabindex="0"></div></div>';
                $("body").append(modal);
            }
        } else {
            if (mobile !== "") {
                console.log("modal c");
                $("body").append('<div aria-modal="true" class="modal fade course" id="myModal" runat="server" tabindex="-1" role="dialog" aria-hidden="true"><div class="modal-dialog" style="margin-top:5px!important;height:100%!important;' + mobile + '"><div class="modal-content course_' + courseID + '" style="height:95%"><div class="modal-header header_' + courseID + '" style="height:45px;"><button type="button" class="close"  data-bs-dismiss="modal" data-dismiss="modal" aria-hidden="true" aria-label="Close button"><span class="glyphicon glyphicon-remove"></span></button><h4 class="modal-title">' + title.replace('&amp;', '&') + '</h4></div><div class="modal-body" style="calc(100% - 45px);"><iframe data-id="' + courseID + '" id="viewCourseModal" allowFullScreen="true" webkitallowfullscreen="true" mozallowfullscreen="true" name="viewCourse"  frameborder = "0" height="100%" width="100%"></iframe></div></div></div></div>');
            } else {
                console.log("modal d");
                $("body").append('<div aria-modal="true" class="modal fade course" id="myModal" runat="server" tabindex="-1" role="dialog" aria-hidden="true"><div class="modal-dialog" style="height:' + height + 'px!important; width:' + width + 'px!important;' + margin + '"><div class="modal-content course_' + courseID + '"><div class="modal-header header_' + courseID + '" style="height:45px;"><button type="button" class="close"  data-bs-dismiss="modal" data-dismiss="modal" aria-hidden="true" aria-label="Close button"><span class="glyphicon glyphicon-remove"></span></button><h4 class="modal-title">' + title.replace('&amp;', '&') + '</h4></div><div class="modal-body"><iframe data-id="' + courseID + '" id="viewCourseModal" allowFullScreen="true" webkitallowfullscreen="true" mozallowfullscreen="true" name="viewCourse"  frameborder = "0" height="' + (parseInt(height) - 50) + '" width="' + width + '"></iframe></div></div></div></div>');
            }
        }
        $('#myModal').modal('show', { show: true, keyboard: false, backdrop: 'static' });
        if (isMobile.iOS() || fs) {
            $('.modal.course iframe').css('height', '100%');
        } else {
            $('.modal.course iframe').css('height', height - 60);
        }
        $('.modal.course iframe').css('display', 'none');
        $('.modal.course iframe').css('margin', '0 auto');
        $('.modal.course iframe').wrap('<div class="coursemodule" style="height:100%;"></div>');
        if (browser_type.indexOf('Fire') >= 0)
            setTimeout(function () { $('#myModal').removeClass('in'); $('#myModal').removeClass('fade'); $('#myModal .modal-body').css('padding', '0px'); }, 1000);
        $("#viewCourseModal").attr('src', redirectURL);
        $('.modal.course iframe').css('display', 'block');
        // $('#myModal').unbind('click');

        setTimeout(function () {
            if (!fs)
                $('.modal.course iframe').attr('height', ($('.course_' + courseID).innerHeight() - $('.header_' + courseID).outerHeight() - 10) + 'px');
            else {
                $('.modal.course iframe').css('height', '100%;');
                $('.modal.course iframe').css('width', '100%;');
            }
        }, 2000)
        $('#myModal').on('hidden.bs.modal', function () {


            var w = $('#viewCourseModal')[0].contentWindow;
            try {
                w.config.modalclose = true;
                // w.config.finished = true;
                try {
                    w.API.LMSFinish();
                } catch (e) {
                    try {
                        w.API.ajaxTerminate();
                    } catch (e) {
                    }
                }
            } catch (e) { }

            $('#myModal').modal('hide');

            //this causes problems when you Enroll (enroll.aspx) , then go to list of courses,enter course then close it.It goes back to enroll in course.I have removed history back
            if (typeof (isLP) == 'undefined') {
                setTimeout(function () {
                    if (typeof (learningPathID) !== 'undefined' && learningPathID !== '')
                        courseID = learningPathID;
                    $('#myModal').remove();

                    if (returnUrl && returnUrl != null && returnUrl.length > 0 && window.location.href.indexOf('MyCourse') < 0 && returnUrl.toLowerCase().indexOf('browsecat') < 0) {
                        window.location.href = returnUrl;
                    } else {
                        var url = window.location.href;
                        var path = window.location.pathname;
                        switch (true) {
                            case url.indexOf('MyLearningActivities.aspx') >= 0:
                                {
                                    if (redirectToDetailsPage == 'undefined' || redirectToDetailsPage) {
                                        url = baseUrl + 'Student/MyCourse.aspx?id=' + courseID + '&ProgramID=' + programID + '&returnUrl=' + window.location.href;
                                    }
                                    else {
                                        url = baseUrl + 'Student/MyLearningActivities.aspx';
                                    }
                                }

                                break;
                            case url.indexOf('Catalogue') >= 0:
                                {
                                    if (redirectToDetailsPage == 'undefined' || redirectToDetailsPage) {
                                        url = baseUrl + 'Student/MyCourse.aspx?id=' + courseID + '&ProgramID=' + programID + '&returnUrl=' + url;
                                    }
                                    else {
                                        url = window.location.href;
                                    }
                                }
                                break;
                            case url.indexOf('type=lp') >= 0: url = url;
                                break;
                            case url.indexOf('MyCourses.aspx') >= 0:
                                {
                                    if (redirectToDetailsPage == 'undefined' || redirectToDetailsPage) {
                                        url = baseUrl + 'Student/MyCourse.aspx?id=' + courseID + '&ProgramID=' + programID + '&returnUrl=' + url;
                                    }
                                    else {
                                        url = baseUrl + 'Student/MyCourses.aspx';
                                    }
                                }
                                break;
                            //default: if (redirectToDetailsPage !== 'undefined' && redirectToDetailsPage) url = baseUrl + 'Student/MyCourse.aspx?id=' + courseID + '&ProgramID=' + programID + '&returnUrl=' + url; else url = window.location.href; url = url.replace('&start=true', '');

                            case typeof (TC.Catalogue) !== 'undefined':
                                {
                                    if (typeof (TC.Catalogue.settings) !== 'undefined') {
                                        if (TC.Catalogue.settings.RedirectToDetailsPage)
                                            url = 'Student/MyCourse.aspx?id=' + courseID;
                                        else
                                            url = window.location.href;
                                    } else {
                                        url = window.location.href;
                                    }

                                }
                                break;
                            default: url = window.location.href; url = url.replace('&start=true', '');
                                break;
                        }
                        window.location.href = url;
                    }//window.location.href + '&returnUrl=' + returnUrl;
                }, 2000);//parent.history.back();
            } else {
                $('#myModal .modal-dialog').remove();
                $('#myModal').remove();
                //$('#myModal .modal-dialog').remove();
                TC.checkLPStatus();
                $('body').removeClass('modal-open');
                //setTimeout(function () { TC.checkLPStatus(); }, 1000);

            }
        });
    }
    else {//open in a new window/tab
        courseid = courseID;
        if (newwindow !== null) {
            newwindow.location.href = redirectURL;
        } else {
            newwindow = window.open(redirectURL, 'CourseWindow', 'fullscreen=yes,scrollbars=1,width=' + width + 'px,height=' + height + 'px,resizable=1');
        }//
        $("#myModalDisc").modal('hide');
        $("#myModalDisc").remove();
        $('#myModal').modal('hide');
        $('#myModal').remove();
        //
        if (typeof (isLP) == 'undefined') {
            interval = setInterval(function () {
                var url = window.location.href;
                var path = window.location.pathname;
                if (typeof (returnUrl) !== 'undefined' && returnUrl !== "") {
                    url = returnUrl;
                }
                else if (typeof (learningPathID) !== 'undefined' && learningPathID !== "") {
                    baseUrl + 'Student/MyCourse.aspx?id=' + learningPathID + '&ProgramID=' + programID + '&returnUrl=' + url;
                } else {
                    switch (true) {
                        case url.indexOf('MyLearningActivities.aspx') >= 0:
                            {
                                if (redirectToDetailsPage == 'undefined' || redirectToDetailsPage) {
                                    url = baseUrl + 'Student/MyCourse.aspx?id=' + courseID + '&ProgramID=' + programID + '&returnUrl=' + window.location.href;
                                }
                                else {
                                    url = baseUrl + 'Student/MyLearningActivities.aspx';
                                }
                            }
                            break;
                        case url.indexOf('type=lp') >= 0: url = baseUrl + 'Student/MyCourse.aspx?id=' + learningPathID + '&ProgramID=' + programID + '&returnUrl=' + url;
                            break;
                        case url.indexOf('Catalogue') >= 0:
                            {
                                if (redirectToDetailsPage == 'undefined' || redirectToDetailsPage) {
                                    url = baseUrl + 'Student/MyCourse.aspx?id=' + courseID + '&ProgramID=' + programID + '&returnUrl=' + url;
                                }
                                else {
                                    url = window.location.href
                                }
                            }
                            break;
                        case url.indexOf('MyCourses.aspx') >= 0:
                            {
                                if (redirectToDetailsPage == 'undefined' || redirectToDetailsPage) {
                                    url = baseUrl + 'Student/MyCourse.aspx?id=' + courseID + '&ProgramID=' + programID + '&returnUrl=' + url;
                                }
                                else {
                                    url = baseUrl + 'Student/MyCourses.aspx';
                                }
                            }
                            break;
                        case typeof (TC.Catalogue) !== 'undefined':
                            {
                                if (typeof (TC.Catalogue.settings) !== 'undefined') {
                                    if (TC.Catalogue.settings.RedirectToDetailsPage)
                                        url = 'Student/MyCourse.aspx?id=' + courseID;
                                    else
                                        url = window.location.href;
                                } else {
                                    url = window.location.href;
                                }

                            }
                            break;
                        default: if (redirectToDetailsPage !== 'undefined' && redirectToDetailsPage) url = baseUrl + 'Student/MyCourse.aspx?id=' + courseID + '&ProgramID=' + programID + '&returnUrl=' + url; else url = window.location.href; url = url.replace('&start=true', '');
                            //  default:url = window.location.href; url = url.replace('&start=true', '');
                            break;
                    }
                }
                checkParentWindow(url, courseID)
            }, 5000);
        } else {
            interval = setInterval(function () {
                if (newwindow.closed) {
                    newwindow = null;
                    clearInterval(interval);
                    if (typeof (ajaxTerminate) !== 'undefined') {
                        try {
                            ajaxTerminate("mycourse");
                        } catch (e) { }
                    }
                    TC.checkLPStatus();
                }
            }, 5000);
        }
    }

    return false;
}

//enter classroom opener that works with Firefox
function launchEnterAssessment(courseID, programID, learningPathID, attempt, height, width, modal, title, returnUrl) {
    if (!height) {
        var height = 600;
    }
    if (!width) {
        var width = 800;
    }
    if (!title) {
        var title = " ";
    }

    //PLEASE MIND THE PARAMETER CASE
    //PLEASE GO TO ENTERCLASSROOM NOT VIEWCOURSE!!!
    var redirectURL = baseUrl + "Student/Course/EnterClassroom.aspx?CourseID=" + courseID + "&AssessmentID=" + courseID + "&ProgramID=" + programID + "&Attempt=" + attempt;
    if (learningPathID.length > 0)
        redirectURL += "&lpID=" + learningPathID;

    //open the course in a new tab or a new window depending on how the user has the browser set
    if (modal === 'DefaultBrowserSettings') {
        courseid = courseID;
        if (bookmark.getBK('openAssessment') !== 'true') {
            if (assessmentWindow !== null) {
                assessmentWindow.location.href = redirectURL;
            } else {
                assessmentWindow = window.open(redirectURL, 'Test');
                newwindow = assessmentWindow;
                bookmark.setBK('openAssessment', true);
            }
        }
    }
    else if (modal === 'ModalWindow') {
        if (isMobile.iOS()) {
            $("body").append('<div class="modal fade course" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"><div class="modal-dialog" style="margin-top:0px!important;height:95%!important; width:100%!important;"><div class="modal-content" style="height:90%"><div class="modal-header" style="height:45px;"><button type="button" class="close" data-dismiss="modal" data-bs-dismiss="modal" aria-hidden="true"><span class="glyphicon glyphicon-remove"></span></button><h4 class="modal-title">' + title + '</h4></div><div class="modal-body" style="height:100%;"><iframe id="viewCourseModal" allowFullScreen="true" webkitallowfullscreen="true" mozallowfullscreen="true" name="viewCourse"  frameborder = "0" height="100%" width="100%"></iframe></div></div></div></div>');
        } else {
            $("body").append('<div class="modal fade course" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"><div class="modal-dialog" style="height:' + height + 'px!important; width:' + width + 'px!important;"><div class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" data-bs-dismiss="modal" aria-hidden="true"><span class="glyphicon glyphicon-remove"></span></button><h4 class="modal-title">' + title + '</h4></div><div class="modal-body"><iframe id="viewCourseModal" allowFullScreen="true" webkitallowfullscreen="true" mozallowfullscreen="true" name="viewCourse"  frameborder = "0" height="' + height + '" width="' + width + '"></iframe></div></div></div></div>');
        }
        $('#myModal').modal('show', { show: true, keyboard: false });
        if (isMobile.iOS()) {
            $('.modal.course iframe').css('height', '100%');
        } else {
            $('.modal.course iframe').css('height', height);
        }
        if (browser_type.indexOf('Fire') >= 0)
            setTimeout(function () { $('#myModal').removeClass('in'); $('#myModal').removeClass('fade'); $('#myModal .modal-body').css('padding', '0px'); }, 1000);
        $('.modal.course iframe').css('display', 'none');
        $('.modal.course iframe').css('margin', '0 auto');
        $('.modal.course iframe').wrap('<div class="coursemodule" style="height:100%;"></div>');

        $("#viewCourseModal").attr('src', redirectURL);
        $('.modal.course iframe').css('display', 'block');
        $('#myModal').unbind('click');
        $('.modal-header button.close').on('click', function () {
            var w = $(".modal.course iframe")[0].contentWindow;
            try {
                w.config.modalclose = true;
                // w.config.finished = true;
                try {
                    w.API.LMSFinish();
                } catch (e) {
                    try {
                        w.API.Terminate();
                    } catch (e) {
                    }
                }
            } catch (e) { }

            $("#viewCourseModal").attr('src', '');
            $('#myModal').modal('hide');
            // $('#myModal').delay(5500).remove();

            //this causes problems when you Enroll (enroll.aspx) , then go to list of courses,enter course then close it.It goes back to enroll in course.I have removed history back
            setTimeout(function () {
                $('#myModal').remove();
                if (returnUrl && returnUrl.length > 0)
                    window.location.href = returnUrl;

            }, 1000);//parent.history.back();

        });

        /* $('#myModal').on('click', function () {
             var w = $("iframe")[0].contentWindow;
             w.config.finished = true;
             try {
                 w.API.LMSFinish();
             } catch (e) {
                 try {
                     w.API.Terminate();
                 } catch (e) {
                 }
             }
 
             $('.modal.course iframe').attr('src', '');
             window.location.href = window.location.href;
         });*/

    }
    else {
        courseid = courseID;
        //if (bookmark.getBK('openAssessment') !== 'true') {
        if (assessmentWindow !== null) {
            assessmentWindow = window.open(redirectURL, 'Test', 'fullscreen=yes,scrollbars=1,width=' + width + 'px,height=' + height + 'px,resizable=1');
        } else {
            assessmentWindow = window.open(redirectURL, 'Test', 'fullscreen=yes,scrollbars=1,width=' + width + 'px,height=' + height + 'px,resizable=1');
            newwindow = assessmentWindow;
            setTimeout(function () { bookmark.setBK('openAssessment', true); }, 1000);

        }
        // } else {
        // window.alert('You already have this test open in another window. Close the window to open the test.')
        // }
        setTimeout(function () {
            if (assessmentWindow) {
                assessmentWindow.onbeforeunload = function () {
                    assessmentWindow = null;
                    bookmark.clearBK('openAssessment');
                }
            }
        }, 500);


        // newwindow = window.open(redirectURL, '_blank', 'fullscreen=yes,scrollbars=1,width=' + width + 'px,height=' + height + 'px,resizable=1');
        interval = setInterval(
            function () {
                checkParentWindow();
            }, 5000);
    }

    return false;
}

//enter classroom opener for new type of assessments
function launchEnterQuiz(courseID, programID, attempt, height, width, modal, title, returnUrl) {
    if (!height) {
        var height = 600;
    }
    if (!width) {
        var width = 800;
    }
    if (!title) {
        var title = " ";
    }

    //PLEASE MIND THE PARAMETER CASE
    //PLEASE GO TO ENTERCLASSROOM NOT VIEWCOURSE!!!
    var redirectURL = baseUrl + "Student/Course/ViewCourse.aspx?CourseID=" + courseID + "&AssessmentID=" + courseID + "&ProgramID=" + programID + "&Attempt=" + attempt;
    if (learningPathID.length > 0)
        redirectURL += "&lpID=" + learningPathID;

    //open the course in a new tab or a new window depending on how the user has the browser set
    if (modal === 'DefaultBrowserSettings') {
        courseid = courseID;
        if (bookmark.getBK('openAssessment') !== 'true') {
            if (assessmentWindow !== null) {
                assessmentWindow.location.href = redirectURL;
            } else {
                assessmentWindow = window.open(redirectURL, 'Test');
                newwindow = assessmentWindow;
                bookmark.setBK('openAssessment', true);
            }
        }
    }
    else if (modal === 'ModalWindow') {
        if (isMobile.iOS()) {
            $("body").append('<div class="modal fade course" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"><div class="modal-dialog" style="margin-top:0px!important;height:95%!important; width:100%!important;"><div class="modal-content" style="height:90%"><div class="modal-header" style="height:45px;"><button type="button" class="close" data-dismiss="modal" data-bs-dismiss="modal" aria-hidden="true"><span class="glyphicon glyphicon-remove"></span></button><h4 class="modal-title">' + title + '</h4></div><div class="modal-body" style="height:100%;"><iframe id="viewCourseModal" allowFullScreen="true" webkitallowfullscreen="true" mozallowfullscreen="true" name="viewCourse"  frameborder = "0" height="100%" width="100%"></iframe></div></div></div></div>');
        } else {
            $("body").append('<div class="modal fade course" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"><div class="modal-dialog" style="height:' + height + 'px!important; width:' + width + 'px!important;"><div class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" data-bs-dismiss="modal" aria-hidden="true"><span class="glyphicon glyphicon-remove"></span></button><h4 class="modal-title">' + title + '</h4></div><div class="modal-body"><iframe id="viewCourseModal" allowFullScreen="true" webkitallowfullscreen="true" mozallowfullscreen="true" name="viewCourse"  frameborder = "0" height="' + height + '" width="' + width + '"></iframe></div></div></div></div>');
        }
        $('#myModal').modal('show', { show: true, keyboard: false });
        if (isMobile.iOS()) {
            $('.modal.course iframe').css('height', '100%');
        } else {
            $('.modal.course iframe').css('height', height);
        }
        if (browser_type.indexOf('Fire') >= 0)
            setTimeout(function () { $('#myModal').removeClass('in'); $('#myModal').removeClass('fade'); $('#myModal .modal-body').css('padding', '0px'); }, 1000);
        $('.modal.course iframe').css('display', 'none');
        $('.modal.course iframe').css('margin', '0 auto');
        $('.modal.course iframe').wrap('<div class="coursemodule" style="height:100%;"></div>');

        $("#viewCourseModal").attr('src', redirectURL);
        $('.modal.course iframe').css('display', 'block');
        $('#myModal').unbind('click');
        $('.modal-header button.close').on('click', function () {
            var w = $(".modal.course iframe")[0].contentWindow;
            try {
                w.config.modalclose = true;
                // w.config.finished = true;
                try {
                    w.API.LMSFinish();
                } catch (e) {
                    try {
                        w.API.Terminate();
                    } catch (e) {
                    }
                }
            } catch (e) { }

            $("#viewCourseModal").attr('src', '');
            $('#myModal').modal('hide');
            // $('#myModal').delay(5500).remove();

            //this causes problems when you Enroll (enroll.aspx) , then go to list of courses,enter course then close it.It goes back to enroll in course.I have removed history back
            setTimeout(function () {
                $('#myModal').remove();
                if (returnUrl && returnUrl.length > 0)
                    window.location.href = returnUrl;

            }, 1000);//parent.history.back();

        });

        /* $('#myModal').on('click', function () {
             var w = $("iframe")[0].contentWindow;
             w.config.finished = true;
             try {
                 w.API.LMSFinish();
             } catch (e) {
                 try {
                     w.API.Terminate();
                 } catch (e) {
                 }
             }
 
             $('.modal.course iframe').attr('src', '');
             window.location.href = window.location.href;
         });*/

    }
    else {
        courseid = courseID;
        //if (bookmark.getBK('openAssessment') !== 'true') {
        if (assessmentWindow !== null) {
            assessmentWindow = window.open(redirectURL, 'Test', 'fullscreen=yes,scrollbars=1,width=' + width + 'px,height=' + height + 'px,resizable=1');
        } else {
            assessmentWindow = window.open(redirectURL, 'Test', 'fullscreen=yes,scrollbars=1,width=' + width + 'px,height=' + height + 'px,resizable=1');
            newwindow = assessmentWindow;
            setTimeout(function () { bookmark.setBK('openAssessment', true); }, 1000);

        }
        // } else {
        // window.alert('You already have this test open in another window. Close the window to open the test.')
        // }
        setTimeout(function () {
            if (assessmentWindow) {
                assessmentWindow.onbeforeunload = function () {
                    assessmentWindow = null;
                    bookmark.clearBK('openAssessment');
                }
            }
        }, 500);


        // newwindow = window.open(redirectURL, '_blank', 'fullscreen=yes,scrollbars=1,width=' + width + 'px,height=' + height + 'px,resizable=1');
        interval = setInterval(
            function () {
                checkParentWindow();
            }, 5000);
    }

    return false;
}

//redirect user to lp details page by clicking upon moreinfo
function moreInfoButtonRedirection(courseID, programID, DisclaimerProcessed) {
    $("#myModalDisc").modal('hide');
    $("#myModalDisc").remove();
    $("#myModal").modal('hide');
    $("#myModal").remove();

    var url = window.location.href;
    var path = window.location.pathname;
    if (typeof (courseID) !== 'undefined' && courseID !== "") {
        switch (true) {
            case url.indexOf('MyLearningActivities.aspx') >= 0:
                {
                    if (redirectToDetailsPage == 'undefined' || redirectToDetailsPage) {
                        url = baseUrl + 'Student/MyCourse.aspx?id=' + courseID + '&ProgramID=' + programID + '&DisclaimerProcessed=' + DisclaimerProcessed + '&returnUrl=' + window.location.href;
                    }
                    else {
                        url = baseUrl + 'Student/MyLearningActivities.aspx';
                    }
                }
                break;
            case url.indexOf('type=lp') >= 0: url = baseUrl + 'Student/MyCourse.aspx?id=' + courseID + '&ProgramID=' + programID + '&DisclaimerProcessed=' + DisclaimerProcessed + '&returnUrl=' + url;
                break;
            case url.indexOf('Catalogue') >= 0:
                {
                    if (redirectToDetailsPage == 'undefined' || redirectToDetailsPage) {
                        url = baseUrl + 'Student/MyCourse.aspx?id=' + courseID + '&ProgramID=' + programID + '&DisclaimerProcessed=' + DisclaimerProcessed + '&returnUrl=' + url;
                    }
                    else {
                        url = window.location.href
                    }
                }
                break;
            case url.indexOf('MyCourses.aspx') >= 0:
                {
                    if (redirectToDetailsPage == 'undefined' || redirectToDetailsPage) {
                        url = baseUrl + 'Student/MyCourse.aspx?id=' + courseID + '&ProgramID=' + programID + '&DisclaimerProcessed=' + DisclaimerProcessed + '&returnUrl=' + url;
                    }
                    else {
                        url = baseUrl + 'Student/MyCourses.aspx';
                    }
                }
                break;
            default: if (redirectToDetailsPage !== 'undefined' && redirectToDetailsPage) url = baseUrl + 'Student/MyCourse.aspx?id=' + courseID + '&ProgramID=' + programID + '&DisclaimerProcessed=' + DisclaimerProcessed + '&returnUrl=' + url; else url = window.location.href; url = url.replace('&start=true', '');
                //  default:url = window.location.href; url = url.replace('&start=true', '');
                break;
        }
    }
    window.location.href = url;
}

//redirect user to lp details page by clicking upon moreinfo 
function moreInfoButtonRedirection(courseID, programID, DisclaimerProcessed) {
    $("#myModalDisc").modal('hide');
    $("#myModalDisc").remove();
    $("#myModal").modal('hide');
    $("#myModal").remove();

    var url = window.location.href;
    var path = window.location.pathname;
    if (typeof (courseID) !== 'undefined' && courseID !== "") {
        switch (true) {
            case url.indexOf('MyLearningActivities.aspx') >= 0:
                {
                    if (redirectToDetailsPage == 'undefined' || redirectToDetailsPage) {
                        url = baseUrl + 'Student/MyCourse.aspx?id=' + courseID + '&ProgramID=' + programID + '&DisclaimerProcessed=' + DisclaimerProcessed + '&returnUrl=' + window.location.href;
                    }
                    else {
                        url = baseUrl + 'Student/MyLearningActivities.aspx';
                    }
                }
                break;
            case url.indexOf('type=lp') >= 0: url = baseUrl + 'Student/MyCourse.aspx?id=' + courseID + '&ProgramID=' + programID + '&DisclaimerProcessed=' + DisclaimerProcessed + '&returnUrl=' + url;
                break;
            case url.indexOf('Catalogue') >= 0:
                {
                    if (redirectToDetailsPage == 'undefined' || redirectToDetailsPage) {
                        url = baseUrl + 'Student/MyCourse.aspx?id=' + courseID + '&ProgramID=' + programID + '&DisclaimerProcessed=' + DisclaimerProcessed + '&returnUrl=' + url;
                    }
                    else {
                        url = window.location.href
                    }
                }
                break;
            case url.indexOf('MyCourses.aspx') >= 0:
                {
                    if (redirectToDetailsPage == 'undefined' || redirectToDetailsPage) {
                        url = baseUrl + 'Student/MyCourse.aspx?id=' + courseID + '&ProgramID=' + programID + '&DisclaimerProcessed=' + DisclaimerProcessed + '&returnUrl=' + url;
                    }
                    else {
                        url = baseUrl + 'Student/MyCourses.aspx';
                    }
                }
                break;
            default: if (redirectToDetailsPage !== 'undefined' && redirectToDetailsPage) url = baseUrl + 'Student/MyCourse.aspx?id=' + courseID + '&ProgramID=' + programID + '&DisclaimerProcessed=' + DisclaimerProcessed + '&returnUrl=' + url; else url = window.location.href; url = url.replace('&start=true', '');
                //  default:url = window.location.href; url = url.replace('&start=true', '');
                break;
        }
    }
    window.location.href = url;
}

function closeModalCourse() {
    $('#myModal').trigger("click");
}

function exitCourse() {
    $('#myModal').trigger("click");
}

function checkParentWindow(url, courseid) {
    if (assessmentWindow) {
        if (assessmentWindow.closed) {
            bookmark.clearBK('openAssessment');
        }
    }

    if (newwindow) {
        if (!newwindow.closed) {

        } else {
            if (typeof (ajaxTerminate) !== 'undefined') {
                try {
                    ajaxTerminate("mycourse");
                } catch (e) { } 
            }
            clearInterval(interval);
            if (bookmark) {
                var xx = bookmark.setBK("challenge", "false");
            }
            //reload the parent page when the course page closed
            //append the courseid to the parent page url for processing if completed

            var reloadUrl = window.location.href;
            
            if (typeof (isLP) === 'undefined' || !isLP) {
                if (typeof (url) === 'undefined' || url === false) {
                    if (!url && typeof (courseid) !== 'undefined') {
                        if (typeof (TC.Catalogue.settings) !== 'undefined') {
                            if (typeof (TC.Catalogue.settings.RedirectToDetailsPage) !== 'undefined' && TC.Catalogue.settings.RedirectToDetailsPage) {
                                window.location.href = 'Student/MyCourse.aspx?id=' + courseid;
                            } else {
                                window.location.href = reloadUrl;
                            }
                        }
                    } else {
                        window.location = reloadUrl; //window.location.href;
                    }

                }
                else {
                    if (typeof (TC.Catalogue) !== 'undefined' && typeof (TC.Catalogue.settings) !== 'undefined') {
                        if (TC.Catalogue.settings.RedirectToDetailsPage)
                            window.location.href = 'Student/MyCourse.aspx?id=' + courseid;
                        else
                            window.location = reloadUrl;
                    } else {
                        window.location.href = url;
                    }
                }

            } else {
                TC.checkLPStatus();
                CheckClosedCourseStatus();
            }
        }
    }
}

var CheckClosedCourseStatus = function () {
    $.ajax({
        url: baseUrl + "Student/GetUserFeedbackRequired.ashx",
        dataType: "text",
        async: false,
        cache: false,
        data: { "id": courseid }
    }).done(function (data) {
        if (data == 'true') {
            if (browser_type.indexOf("Chrome") > -1) {
                window.open(baseUrl + 'Student/CourseFeedback.aspx?CourseID=' + courseid, 'courseFeedback', 'width=1284,height=600,location=0,toolbar=yes,scrollbars=yes,resizable=yes,status=0,menubar=0');
            } else {
                window.open(baseUrl + 'Student/CourseFeedback.aspx?CourseID=' + courseid, 'courseFeedback', 'width=1284,height=600,location=0,toolbar=1,scrollbars=1,resizable=1,status=0,menubar=0');
            }
        }
    });
}

//used in xsl\browse_courses.xsl, template match="Course" mode="Search" ?? is that one used or we can remove it
function launchEnterClassrooomFromRoot(courseID, programID, height, width) {
    url = "Student/Course/EnterClassroom.aspx?CourseID=" + courseID + "&amp;ProgramID=" + programID;

    if (newwindow !== null) {
        newwindow.location.href = url;
    } else {
        newwindow = window.open(url, 'CourseWindow', 'fullscreen=yes,scrollbars=1,width=' + width + ',height=' + height);
    }

    interval = setInterval("checkParentWindow()", 5000);
    return false;
}

function launchEnterClassrooomLP(courseID, programID, learningPathID, height, width) {
    var agt = navigator.userAgent.toLowerCase();
    if (agt.indexOf('gecko') != -1) {
        url = "Student/Course/EnterClassroom.aspx?CourseID=" + courseID + "&ProgramID=" + programID + "&lpID=" + learningPathID;
    }
    else if (agt.indexOf('msie') != -1) {
        url = "../Student/Course/EnterClassroom.aspx?CourseID=" + courseID + "&ProgramID=" + programID + "&lpID=" + learningPathID;
    }
    //alert(url);
    if (newwindow !== null) {
        newwindow.location.href = url;
    } else {
        newwindow = window.open(url, 'CourseWindow', 'fullscreen=yes,scrollbars=1,width=' + width + ',height=' + height);

    }
    interval = setInterval("checkParentWindow()", 5000);
    return false;
}

//popup ViewSample for a course
var sampleWindow = null;
function launchCourseSample(baseURL, courseID) {
    url = baseURL + "Student/Sample/ViewSample.aspx?CourseID=" + courseID;
    //alert(url);
    if (sampleWindow !== null) {
        sampleWindow.location.href = url;
    } else {
        sampleWindow = window.open(url, 'CourseWindow', 'fullscreen=yes,scrollbars=1');
    }
    setTimeout(function () {
        if (sampleWindow) {
            sampleWindow.onbeforeunload = function () {
                sampleWindow = null;
                //bookmark.clearBK('openAssessment');
            }
        }
    }, 500);
    return false;
}

//popup ViewSample for a course
var previewWindow = null;
function launchCoursePreview(baseURL, courseID) {

    var height = 600;
    var width = 800;


    url = baseURL + "Student/Preview/ViewCourse.aspx?CourseID=" + courseID;
    //alert(url);
    if (previewWindow !== null) {
        previewWindow.location.href = url;
    } else {
        previewWindow = window.open(url, 'CourseWindow', 'fullscreen=yes,scrollbars=1,width=' + width + 'px,height=' + height + 'px,resizable=1');
    }

    setTimeout(function () {
        if (previewWindow) {
            previewWindow.onbeforeunload = function () {
                previewWindow = null;
                //bookmark.clearBK('openAssessment');
            }
        }
    }, 500);

    return false;
}

//popup survey directly from open, use this for anon survey
var surveyWindow = null;
function launchSurvey(baseURL, courseID, programID) {

    var height = 600;
    var width = 800;


    url = baseURL + "Student/CourseFeedback.aspx?CourseID=" + courseID + "&ProgramID=" + programID + "&modal=true";
    //alert(url);
    if (surveyWindow !== null) {
        surveyWindow.location.href = url;
    } else {
        surveyWindow = window.open(url, 'CourseWindow', 'fullscreen=yes,scrollbars=1,width=' + width + 'px,height=' + height + 'px,resizable=1');
    }

    setTimeout(function () {
        if (surveyWindow) {
            surveyWindow.onbeforeunload = function () {
                surveyWindow = null;
                //bookmark.clearBK('openAssessment');
            }
        }
    }, 500);

    return false;
}

//Smarandita;please change and/or move it where appropriate
function getWorkbookList() {
    if (API) {
        workbook_list = API.GetValue("cmi.workbooks._list");
    }
};

//preview courses shared by a rule into the domain
function openPreview(ruleID) {

    var url = 'Admin/PreviewMatchingCourses.aspx?RuleID=' + ruleID;
    var panelhtml = "<iframe id='previewContentFrame' class='contentFrame' style='height:100%;width:100%' frameborder='0' src='" + url + "' />";

    var modal =
        '<div class="modal fade out" id="AdminActionModal" tabindex="-1" role="dialog" aria-labelledby="AdminActionModalLabel" aria-hidden="false">' +
        '   <div class="modal-dialog" style="width:95%;height:80%;">' +
        '       <div class="modal-content" style="width:100%;height:100%;">' +
        '           <div class="modal-header">' +
        '               <a class="pull-right close-fa" data-dismiss="modal" data-bs-dismiss="modal">' +
        '                   <i class="fa fa-times-circle"></i>' +
        '                   <span class="sr-only">Close</span>' +
        '               </a>' +
        '               <h4 class="modal-title" id="PreviewRule" translate="true">Preview</h4>' +
        '           </div>' +
        '       <div class="modal-body spinner" id="AdminActionModalBody" style="width:100%;height:90%;">' +
        panelhtml +
        '   </div>' +
        '   <div class="modal-footer"></div>' +
        '</div>';
        //'</div>' +
        //'</div>';
    $('body').append(modal);
    $(modal).modal('show');
    return false;
}

function openPreviewCategoryRule(ruleID, categoryID, domainID) {

    var url = 'Admin/Catalogue/CategoryMatchingCourses.aspx?modal=true&ruleID=' + ruleID + '&programID=' + domainID + '&id=' + categoryID;
    var panelhtml = "<iframe id='previewContentFrame' class='contentFrame' style='height:100%;width:100%' frameborder='0' src='" + url + "' />";
    var modal = '<div class="modal fade out" id="AdminActionModal" tabindex="-1" role="dialog" aria-labelledby="AdminActionModalLabel" aria-hidden="false">' +
        '<div class="modal-dialog" style="width:95%;height:80%;">' +
        '<div class="modal-content" style="width:100%;height:100%;">' +
        '<div class="modal-header">' +
        '<a class="pull-right close-fa" data-dismiss="modal" data-bs-dismiss="modal">' +
        '<i class="fa fa-times-circle"></i>' +
        '<span class="sr-only">Close</span>' +
        '</a>' +
        '<h4 class="modal-title" id="PreviewRule" translate="true">Preview</h4>' +
        '</div>' +
        '<div class="modal-body spinner" id="AdminActionModalBody" style="width:100%;height:90%;">' +
        panelhtml +
        '</div>' +
        '<div class="modal-footer">' +
        '</div>' +
        '</div>' +
        '</div>' +
        '</div>';
    $('body').append(modal);
    $(modal).modal('show');
    return false;
}

function openPreviewUsers(ruleID, type, programID) {
    var url = 'ProgramMgr/PreviewMatchingUsers.aspx?RuleID=' + ruleID + '&RuleType=' + type + '&ProgramID=' + programID;


    $("body").append('<div class="modal fade course" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"><div class="modal-dialog" style="height:700px!important; width:700px!important;"><div class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" data-bs-dismiss="modal" aria-hidden="true"><span aria-hidden="true">x</span></button><h4 class="modal-title">Preview Rule Users</h4></div><div class="modal-body"><iframe id="previewContentFrame" class="contentFrame" style="height:700px!important; width:650px!important;" frameborder="0" src="' + url + '" /></div></div></div></div>');
    $('#myModal').modal('show', { show: true, keyboard: false });
    //$('.modal.course iframe').css('height', '700px');
    $('.modal.course iframe').css('display', 'block');
    $('.modal-header button.close').on('click', function () {
        var w = $(".modal.course iframe")[0].contentWindow;
        $('#myModal').modal('hide');
        setTimeout(function () { $('#myModal').remove(); }, 1000)
    });
    return false;
}

function openPreviewGroupRulesUsers(courseID, programID, matchAll, groupID) {

    var url = 'ProgramMgr/PreviewMatchingUsers.aspx?CourseID=' + courseID + '&ProgramID=' + programID + '&all=' + matchAll + '&groupID=' + groupID;

    if ($('#myModal1').length) {
        $('#previewContentFrame').prop('src', 'about:blank');//to prevent seeing the previous loaded data when closing and opening again with a different url
        $('#myModal1 .modal-body').removeClass('off');
        //
        setTimeout(function () {
            $('#previewContentFrame').prop('src', url);
            //var onclick = "openHelpModalFooter(\'url\'); return false;";
            //$('#myModal1 .modal-footer #helpLink').prop('onclick', onclick);
        }, 100);
    }
    else
        $("body").append('<div class="modal fade course" id="myModal1" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"><div class="modal-dialog" style="height:700px!important; width:700px!important;"><div class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" data-bs-dismiss="modal" aria-hidden="true"><span aria-hidden="true">x</span></button><h4 class="modal-title">Preview Rule Users</h4></div><div class="modal-body"><iframe id="previewContentFrame" class="contentFrame" style="height:700px!important; width:650px!important;" frameborder="0" src="' + url + '" /></div></div></div></div>');
    $('#myModal1').modal('show', { show: true, keyboard: false });
    $('#previewContentFrame').load(function () {
        if ($(this).contents()[0].URL.indexOf('blank') < 0) {
            $('#myModal1 .modal-body').addClass('off');
        }
    });
    //$('.modal.course iframe').css('height', '700px');
    $('.modal.course iframe').css('display', 'block');
    return false;
}

function openPreviewRuleUsers(fieldID, fieldValue, programID) {


    var url = 'ProgramMgr/PreviewMatchingUsers.aspx?FieldID=' + fieldID + '&FieldValues=' + encodeURIComponent(fieldValue) + '&ProgramID=' + programID;
    var Exporturl = 'ProgramMgr/PreviewMatchingUsersExport.aspx?FieldID=' + fieldID + '&FieldValues=' + encodeURIComponent(fieldValue) + '&ProgramID=' + programID;


    $("body").append('<div class="modal fade course" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">' +
        '<div class="modal-dialog" style="height:700px!important; width:900px!important;">' +
        '   <div class="modal-content">' +
        '       <div class="modal-header">' +
        '           <button type="button" class="close" data-dismiss="modal" data-bs-dismiss="modal" aria-hidden="true">' +
        '               <span aria-hidden="true">x</span>' +
        '           </button>' +
        '           <h4 class="modal-title">Preview Rule Users</h4>' +
        '       </div>' +
        '       <div class="modal-body">' +
        '           <iframe id="previewContentFrame" class="contentFrame" style="height:700px!important; width:650px!important;" frameborder="0" src="' + url + '" />' +
        '       </div>' +
        '       <div>' +
        '           <input type="button" value="Export" style="width : 60px; color: rgb(255, 255, 255); background-color: rgb(83, 163, 198); border-color: rgb(83, 163, 198); margin: 2px 0px; border: 1px solid transparent;border-radius: 4px;" class="export" onclick="window.open(\'' + baseUrl + '/' + Exporturl + '&export=true\')" />' +
        '       </div>' +
        '   </div>' +
        '</div>' +
        '</div>');
    $('#myModal').modal('show', { show: true, keyboard: false });
    //$('.modal.course iframe').css('height', '700px');
    $('.modal.course iframe').css('display', 'block');
    $('.modal-header button.close').on('click', function () {
        var w = $(".modal.course iframe")[0].contentWindow;
        $('#myModal').modal('hide');
        setTimeout(function () { $('#myModal').remove(); }, 1000)
    });
    return false;
}

function openPreviewAllRulesUsers(courseID, programID, tabID, matchAll) {

    var url = 'ProgramMgr/PreviewMatchingUsers.aspx?CourseID=' + courseID + '&ProgramID=' + programID + '&TabID=' + tabID + '&all=' + matchAll;

    if ($('#myModal1').length) {
        $('#previewContentFrame').prop('src', 'about:blank');//to prevent seeing the previous loaded data when closing and opening again with a different url
        $('#myModal1 .modal-body').removeClass('off');
        //
        setTimeout(function () {
            $('#previewContentFrame').prop('src', url);
            //var onclick = "openHelpModalFooter(\'url\'); return false;";
            //$('#myModal1 .modal-footer #helpLink').prop('onclick', onclick);
        }, 100);
    }
    else
        $("body").append('<div class="modal fade course" id="myModal1" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"><div class="modal-dialog" style="height:700px!important; width:700px!important;"><div class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" data-bs-dismiss="modal" aria-hidden="true"><span aria-hidden="true">x</span></button><h4 class="modal-title">Preview Rule Users</h4></div><div class="modal-body"><iframe id="previewContentFrame" class="contentFrame" style="height:700px!important; width:650px!important;" frameborder="0" src="' + url + '" /></div></div></div></div>');
    $('#myModal1').modal('show', { show: true, keyboard: false });
    $('#previewContentFrame').load(function () {
        if ($(this).contents()[0].URL.indexOf('blank') < 0) {
            $('#myModal1 .modal-body').addClass('off');
        }
    });
    //$('.modal.course iframe').css('height', '700px');
    $('.modal.course iframe').css('display', 'block');
    return false;
}

//it is not used for now S.P.
function openPreviewAllAnnouncementRulesUsers(courseID, programID, matchAll, matchExcludeAll) {
    var url = 'ProgramMgr/PreviewMatchingUsers.aspx?CourseID=' + courseID + '&ProgramID=' + programID + '&TabID=' + tabID + '&all=' + matchAll;

    if ($('#myModal1').length) {
        $('#previewContentFrame').prop('src', 'about:blank');//to prevent seeing the previous loaded data when closing and opening again with a different url
        $('#myModal1 .modal-body').removeClass('off');
        //
        setTimeout(function () {
            $('#previewContentFrame').prop('src', url);
            //var onclick = "openHelpModalFooter(\'url\'); return false;";
            //$('#myModal1 .modal-footer #helpLink').prop('onclick', onclick);
        }, 100);
    }
    else
        $("body").append('<div class="modal fade course" id="myModal1" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"><div class="modal-dialog" style="height:700px!important; width:700px!important;"><div class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" data-bs-dismiss="modal" aria-hidden="true"><span aria-hidden="true">x</span></button><h4 class="modal-title">Preview Rule Users</h4></div><div class="modal-body"><iframe id="previewContentFrame" class="contentFrame" style="height:700px!important; width:650px!important;" frameborder="0" src="' + url + '" /></div></div></div></div>');
    $('#myModal1').modal('show', { show: true, keyboard: false });
    $('#previewContentFrame').load(function () {
        if ($(this).contents()[0].URL.indexOf('blank') < 0) {
            $('#myModal1 .modal-body').addClass('off');
        }
    });
    //$('.modal.course iframe').css('height', '700px');
    $('.modal.course iframe').css('display', 'block');
    return false;
}

function openPreviewMembershipRuleUsers(fieldsValues, ruleDomainID, ruleParentDomainID) {
    var url = 'ProgramMgr/PreviewMatchingMembershipRuleUsers.aspx?vals=' + encodeURIComponent(fieldsValues) + '&rdid=' + ruleDomainID + '&did=' + ruleParentDomainID;
    //
    $("body").append('<div class="modal fade course" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">' +
        '<div class="modal-dialog" style="height:700px!important; width:900px!important;">' +
        '   <div class="modal-content">' +
        '       <div class="modal-header">' +
        '           <button type="button" class="close" data-dismiss="modal" data-bs-dismiss="modal" aria-hidden="true">' +
        '               <span aria-hidden="true">x</span>' +
        '           </button>' +
        '           <h4 class="modal-title">Preview Rule Users</h4>' +
        '       </div>' +
        '       <div class="modal-body">' +
        '           <iframe id="previewContentFrame" class="contentFrame" style="height:700px!important; width:850px!important;" frameborder="0" src="' + url + '" />' +
        '       </div>' +
        '       <div>' +
        '           <button type="button" class="export">' +
        '               <span aria-hidden="true">Export</span>' +
        '           </button>' +
        '       </div>' +
        '   </div>' +
        '</div>' +
        '</div>');
    $('#myModal').modal('show', { show: true, keyboard: false });
    //$('.modal.course iframe').css('height', '700px');
    $('.modal.course iframe').css('display', 'block');
    $('.modal-header button.close').on('click', function () {
        var w = $(".modal.course iframe")[0].contentWindow;
        $('#myModal').modal('hide');
        setTimeout(function () { $('#myModal').remove(); }, 1000)
    });
    return false;
}

function openPreviewMembershipRuleUsers(fieldsValues, ruleDomainID, ruleParentDomainID) {
    var url = 'ProgramMgr/PreviewMatchingMembershipUsers.aspx?vals=' + encodeURIComponent(fieldsValues) + '&rdid=' + ruleDomainID + '&did=' + programID;
    //
    $("body").append('<div class="modal fade course" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">' +
        '<div class="modal-dialog" style="height:700px!important; width:900px!important;">' +
        '   <div class="modal-content">' +
        '       <div class="modal-header">' +
        '           <button type="button" class="close" data-dismiss="modal" data-bs-dismiss="modal" aria-hidden="true">' +
        '               <span aria-hidden="true">x</span>' +
        '           </button>' +
        '           <h4 class="modal-title">Preview Rule Users</h4>' +
        '       </div>' +
        '       <div class="modal-body">' +
        '           <iframe id="previewContentFrame" class="contentFrame" style="height:700px!important; width:650px!important;" frameborder="0" src="' + url + '" />' +
        '       </div>' +
        '       <div>' +
        '           <button type="button" class="export">' +
        '               <span aria-hidden="true">Export</span>' +
        '           </button>' +
        '       </div>' +
        '   </div>' +
        '</div>' +
        '</div>');
    $('#myModal').modal('show', { show: true, keyboard: false });
    //$('.modal.course iframe').css('height', '700px');
    $('.modal.course iframe').css('display', 'block');
    $('.modal-header button.close').on('click', function () {
        var w = $(".modal.course iframe")[0].contentWindow;
        $('#myModal').modal('hide');
        setTimeout(function () { $('#myModal').remove(); }, 1000)
    });
    return false;
}

var updateCohort = function (el) {
    if ($(el).find(":selected").val() !== null) {
        LMS.cohortSelected = $(el).find(":selected").val();

        if (LMS.cohortSelected != "") {
            //$('.btn.cohort.details').removeClass('disabled');
            //$('.btn.cohort.fast-start').removeClass('disabled');
            //$('.btn.btn-disabled.enrol-disabled').removeClass('btn-disabled');

            $(el).parent().find('.btn.cohort.details').removeClass('disabled');
            $(el).parent().find('.btn.cohort.fast-start').removeClass('disabled');
            $(el).parent().find('.btn.btn-disabled.enrol-disabled').removeClass('btn-disabled');
            $(el).parent().find('.btn.btn-disabled.enrol-disabled').removeProp('disabled');
            $(el).parent().find('.btn.cohort.details').removeProp('disabled');
            $(el).parent().find('.btn.cohort.fast-start').removeProp('disabled');
            $(el).parent().find('.btn.btn-disabled.enrol-disabled').removeAttr('disabled');
            $(el).parent().find('.btn.cohort.details').removeAttr('disabled');
            $(el).parent().find('.btn.cohort.fast-start').removeAttr('disabled');
        }
        else {
            $(el).parent().find('.btn.cohort.details').addClass('disabled');
            $(el).parent().find('.btn.cohort.fast-start').addClass('disabled');
            $(el).parent().find('.btn.btn-disabled.enrol-disabled').addClass('btn-disabled');

            $(el).parent().find('.btn.btn-disabled.enrol-disabled').prop('disabled', 'true');
            $(el).parent().find('.btn.cohort.details').prop('disabled', 'true');
            $(el).parent().find('.btn.cohort.fast-start').prop('disabled', 'true');
        }

    }
};

var buildCohorts = function (courseID) {
    var dd = $('#cohortDD_' + courseID + ' option');
    var cohorts = []

    $.each(dd, function () {
        cohorts.push({ CohortID: this.id, CohortName: $(this).text() });
    });
    return cohorts;
};

// called from catalogue
var OpenExpressStart = function (baseurl, courseID, programID, title, type, el, enrolled, mapid, disclaimer, fullscreen) {

    if (typeof (isLP) !== 'undefined' && isLP) {
        let actPanel = $('#activitypanel_' + courseID);
        if (actPanel.length > 0) {
            let objPanel = (actPanel.closest('.activity-group').length > 0) ? actPanel.closest('.activity-group').data().activitygroupid
                : (actPanel.closest('.active.in').length > 0) ? actPanel.closest('.active.in').data().activitygroupid : '';

            if (objPanel !== '')
                location.hash = objPanel;
        }
    }

    let fromDisclaimer = (typeof (disclaimer) !== 'undefined') ? disclaimer : false;
    let certificationAttempt = (typeof (el) !== 'undefined' && el !== null && $(el).length > 0 && typeof ($(el).data().attempt) !== 'undefined') ? $(el).data().attempt : 0;
    if (typeof (el) !== 'undefined' && el) {
        var cog = $(el).find('i');
        if (cog.length > 0)
            cog.remove();
    }
    if (typeof (enrolled) !== 'undefined' && enrolled !== true && enrolled !== 'True' && $(el).hasClass('cohort')) {
        if (!$(el).hasClass('disabled') && !$(el).hasClass('details')) {
            $('#cohortModal').remove();
            LMS.cohortSelected = null;
            if ($('#cohortDD_' + courseID + ' option').length > 0) {
                var cohorts = buildCohorts(courseID);
            } else {
                var cohorts = ($(el).data('cohorts').cohorts) ? $(el).data('cohorts').cohorts : null;
            }

            if (cohorts !== null && cohorts.length > 0) {
                var cohortDD = $('<select class="cohort"></select>');
                var optionNone = $('<option id="" value="">Please Select Cohort</option>');
                cohortDD.append(optionNone);
                $.each(cohorts, function () {
                    var option = $('<option id="' + this.CohortID + '" value="' + this.CohortID + '">' + this.CohortName + '</option>');
                    cohortDD.append(option);
                    $('button.cohort').removeClass('disabled');
                })
                cohortDD.on('change', function () {
                    LMS.cohortSelected = $(this).find(":selected").val();
                    console.log(LMS.cohortSelected);
                });
                var modal = $('<div class="modal fade course" id="cohortModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">' +
                    '<div class="modal-dialog" style="margin-top:auto!important;height:600px!important; width:800px!important;">' +
                    '<div class="modal-content">' +
                    '<div class="modal-header" style="height:45px;">' +
                    '<button type="button" class="close" data-dismiss="modal" data-bs-dismiss="modal" aria-hidden="true"><span class="glyphicon glyphicon-remove"></span></button>' +
                    '<h4 class="modal-title">' + title + '</h4>' +
                    '</div>' +
                    '<div class="modal-body">' +
                    '</div>' +
                    '</div>' +
                    '</div>' +
                    '</div>');
                $("body").append(modal);

                var cohortContainer = $('<div style="width:400px;height:300px;margin:50px auto;"></div>');
                cohortContainer.append('<label>Select a cohort:</label>');
                cohortContainer.append(cohortDD);
                var btn = $('<button type="button" style="btn btn-default disabled cohort">Start</button>');
                btn.on('click', function () {
                    if (LMS.cohortSelected !== null && LMS.cohortSelected !== "") {
                        cohortEnroll(courseID, programID, type, LMS.cohortSelected, title, el, null, null, fullscreen);
                        $('#cohortModal').modal('hide');
                        return false;
                    }
                });
                cohortContainer.append(btn);
                $("#cohortModal .modal-body").append(cohortContainer);

                $('#cohortModal').modal('show');
            }
        } else {
            if (!$(el).hasClass('disabled') && $(el).hasClass('details'))
                cohortEnroll(courseID, programID, type, LMS.cohortSelected, title, el, null, null, fullscreen);
            return false;
        }
    } else {
        if ($(el).length > 0)
            $(el).prepend('<i class="fa fa-cog fa-spin" style="margin-right:5px;"></i>');
        setTimeout(function () {
            cohortEnroll(courseID, programID, type, null, title, el, mapid, fromDisclaimer, fullscreen);
        }, 800);

        return false;
    }
    //
    return false;
}

//clicked on the enrollment or purchase button for an item in the catalog; returns the options available for the user
var cohortEnroll = function (courseID, programID, type, cohortID, title, el, mapid, disclaimer, fullscreen) {
    let certificationAttempt = (typeof (el) !== 'undefined' && el !== null && $(el).length > 0 && typeof ($(el).data().attempt) !== 'undefined') ? $(el).data().attempt : 0;

    if (typeof (el) !== 'undefined' && el) {
        var cog = $(el).find('.fa-cog');
    } else {
        var cog = null;
    }
    //
    if (cohortID === null) {
        cohortID = LMS.cohortSelected;
    }
    //
    var inLP = (typeof (mapid) !== 'undefined' && mapid) ? mapid : '';
    $.ajax({//check if the user is enrolled; if not, how the user can enroll
        url: baseUrl + "Student/Course/DoExpressStart.ashx",
        dataType: "json",
        async: false,
        button: cog,
        cache: false,
        mapid: inLP,
        data: {
            "CourseID": courseID,
            "ProgramID": programID,
            "Type": type,
            "mapID": inLP,
            "CohortID": cohortID,
            op: "checkexpressstartaction",
            disclaimer: disclaimer
        },
        error: function (data, text, error) {
            console.log('data');
            console.log(data);
            console.log('text')
            console.log(text);
            //
            if (this.button !== null) {
                this.button.removeClass('fa-spin');
                this.button.removeClass('fa-cog');
                this.button.addClass('fa-exclamation-circle');
            }
            //
            showError(text);
        }
    }).done(function (data) {
        if (this.button !== null)
            this.button.remove();
        if (data) {
            var response = data;//eval("[" + data + "]")[0];
            var s = response.success;
            var m = response.message;
            if (s == false || s == "false") {
                launchExpressStartReason(m, title);
            }
            else {
                var a = response.action;
                var h = response.height;
                var w = response.width;
                var openin = response.modal;
                var fullscreen = (typeof (response.openInScreenSize) !== 'undefined' && response.openInScreenSize == 'True') ? 'True' : 'False';
                if (a === 'enterWDisclaimer') {
                    // call this
                    //openModal = function (baseurl, courseID, programID, title, fastaction, entermode, backbtn, type, returnUrl, activityCount, buttonType)
                    openModal(baseUrl, courseID, programID, '', true, '', '', type, '', this.mapid, '');
                }
                if (a == "enter") {
                    //launchEnterClassrooomLP(courseID, programID, learningPathID, height, width)
                    if (this.mapid) {
                        launchEnterClassrooom(courseID, programID, this.mapid, certificationAttempt, h, w, openin, title, '', '', fullscreen)
                        // launchEnterClassrooomLP(courseID, programID, this.mapid, '1', h, w, openin, title);
                    } else {
                        launchEnterClassrooom(courseID, programID, '', certificationAttempt, h, w, openin, title, '', '', fullscreen);
                    }
                }
                if (a == "enterActivity") {
                    launchEnterActivity(courseID, programID, '', certificationAttempt, title, type);
                }
                else if (a == "goto") {
                    let u;

                    let from = (inLP) ? `&from=${$('html').data().pagetitle}|${inLP}` : '';
                    let last = getParameterByName('lastPageTitle');
                    if (inLP) {
                        // in a learning path
                        last = (last !== '') ? `&lastPageTitle=${last}` : '';
                    } else {
                        last = `&lastPageTitle=${$('html').data().pagetitle}|${$('html').data().pageid}`;
                    }
                    if (response.url.toLowerCase().indexOf('login') < 0) {
                        u = response.url + '&returnUrl=' + encodeURIComponent(location.href.split('&returnUrl')[0]) + from + last;
                    } else {
                        u = response.url + from;
                    }
                    if (typeof (disclaimer) !== 'undefined' && disclaimer === true) {
                        window.location = u + '&DisclaimerProcessed=true';
                    } else {
                        window.location = u;
                    }

                }
                else if (a == "buy") {//user can purchase the course, add to shopping cart if external or send to the shopping cart page if using the LMS shopping cart
                    if (response.url.indexOf('.ashx') >= 0) //external cart
                        purchaseExternal(response.url, title, response.price, response.marqueeElement, response.cartURL);
                    else
                        window.location = response.url;//internal shopping cart
                }
                else if (a == "token") {//user can redeem a course token, ask for the token
                    if ($("#tokenModal").length == 0) {
                        var tokensModal = $('<div class="modal fade course" id="tokenModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">' +
                            '<div class="modal-dialog" style="margin-top:auto!important;height:300px!important; width:500px!important;">' +
                            '<div class="modal-content">' +
                            '<div class="modal-header" style="height:45px;">' +
                            '<button type="button" class="close" data-dismiss="modal" data-bs-dismiss="modal" aria-hidden="true"><span class="glyphicon glyphicon-remove"></span></button>' +
                            '<h4 class="modal-title">' + title + '</h4>' +
                            '</div>' +
                            '<div class="modal-body">' +
                            '</div>' +
                            '</div>' +
                            '</div>' +
                            '</div>');
                        //
                        $("body").append(tokensModal);

                        var pageFastStart = "unknown";
                        if (typeof (TC.Catalogue) !== 'undefined' && typeof (TC.Catalogue.settings) !== 'undefined' && typeof (TC.Catalogue.settings.AllowFastStart) !== 'undefined') {
                            if (!TC.Catalogue.settings.AllowFastStart)
                                pageFastStart = "false";
                        }


                        //
                        var tokenContainer = $('<div style="width:400px;margin:50px auto;"></div>');
                        tokenContainer.append('<label>Enter Token:</label><input type = "text" id="token" value=""></input>');
                        //tokenContainer.append(cohortDD);
                        var btn = $('<button type="button" style="btn btn-default disabled cohort">Submit</button>');
                        var mapID = this.mapid;
                        btn.on('click', function () {
                            var tokenValue = $('#token').val();
                            $.ajax({
                                url: baseUrl + "Student/Course/DoExpressStart.ashx",
                                dataType: "json",
                                async: false,
                                cache: false,
                                data: {
                                    "CourseID": courseID,
                                    "ProgramID": programID,
                                    "Type": type,
                                    "mapID": mapID,
                                    "CohortID": cohortID,
                                    "PageFastStart": pageFastStart,
                                    token: tokenValue,
                                    op: "enrollwithtoken"
                                },
                                error: function (jqXHR) {
                                    $('#tokenModal').modal('hide');
                                    bootbox.alert('Failed to redeem the token! Error: ' + jqXHR.responseText);
                                }
                            }).done(function (data) {
                                if (data && data.success) {
                                    $('#tokenModal').modal('hide');
                                    if (data.action == "enter") {
                                        launchEnterClassrooom(courseID, programID, '', certificationAttempt, h, w, openin, title);
                                    }
                                    if (data.action == "enterActivity") {
                                        launchEnterActivity(courseID, programID, '', certificationAttempt, title, type);
                                    }
                                    else if (data.action == "goto") {
                                        window.location = data.url;
                                    }
                                }
                                else {
                                    bootbox.alert('Failed to redeem the token! Error: ' + data.message);
                                }
                            });
                        });
                        tokenContainer.append(btn);
                        $("#tokenModal .modal-body").append(tokenContainer);
                    }
                    //
                    $('#token').val('');
                    $('#tokenModal').modal('show');
                }
                else if (a == "globalTokens") {//user can redeem global tokens, show the confirmation dialog; redeem tokens and enter course if confirmed
                    //var globalTokensValue = response.globalTokensValue;
                    var mapID = this.mapid;
                    bootbox.confirm(m, function (result) {
                        //console.log('This was logged in the callback: ' + result);
                        if (result === true) {
                            $.ajax({
                                url: baseUrl + "Student/Course/DoExpressStart.ashx",
                                dataType: "json",
                                async: false,
                                cache: false,
                                data: {
                                    "CourseID": courseID,
                                    "ProgramID": programID,
                                    "Type": type,
                                    "mapID": mapID,
                                    "CohortID": cohortID,
                                    op: "enrollwithglobaltokens"
                                },
                                error: function (jqXHR) {
                                    bootbox.alert('Failed to redeem the global tokens! Error: ' + jqXHR.responseText);
                                }
                            }).done(function (data) {
                                if (data && data.success) {
                                    if (data.action == "enter") {
                                        launchEnterClassrooom(courseID, programID, '', '0', h, w, openin, title);
                                    }
                                    if (data.action == "enterActivity") {
                                        launchEnterActivity(courseID, programID, '', '0', title, type);
                                    }
                                    else if (data.action == "goto") {
                                        window.location = data.url;
                                    }
                                }
                                else {
                                    bootbox.alert('Failed to redeem the global tokens! Error: ' + data.message);
                                }
                            });
                        }
                    });
                }
                else if (a == "couponOnly") {//user can redeem a 100 % coupon only , ask for the coupon
                    if ($("#couponModal").length > 0) {
                        $("#couponModal").remove();
                    }
                    if ($("#couponModal").length == 0) {
                        var couponModal = $('<div class="modal fade course" id="couponModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">' +
                            '<div class="modal-dialog" style="margin-top:auto!important;height:300px!important; width:500px!important;">' +
                            '<div class="modal-content">' +
                            '<div class="modal-header" style="height:45px;">' +
                            '<button type="button" class="close" data-dismiss="modal" data-bs-dismiss="modal" aria-hidden="true"><span class="glyphicon glyphicon-remove"></span></button>' +
                            '<h4 class="modal-title">' + title + '</h4>' +
                            '</div>' +
                            '<div class="modal-body">' +
                            '</div>' +
                            '</div>' +
                            '</div>' +
                            '</div>');
                        //
                        $("body").append(couponModal);
                        //
                        var couponContainer = $('<div style="width:400px;margin:50px auto;"></div>');
                        couponContainer.append('<label>Enter Coupon:</label><input type = "text" id="coupon" value=""></input>');
                        //tokenContainer.append(cohortDD);
                        var btn = $('<button type="button" style="btn btn-default disabled cohort">Submit</button>');
                        var lpid = this.mapid;
                        btn.on('click', function () {
                            var couponValue = $('#coupon').val();
                            $.ajax({
                                url: baseUrl + "Student/eCommerce/ValidateCoupon.ashx",
                                dataType: "json",
                                async: false,
                                cache: false,
                                data: {
                                    "courseID": courseID,
                                    "domainID": programID,
                                    "Type": type,
                                    "mapID": lpid,
                                    "CohortID": cohortID,
                                    coupon: couponValue,
                                    op: "RedeemFullCouponCodeEnroll"
                                },
                                error: function (jqXHR) {
                                    $('#couponModal').modal('hide');
                                    bootbox.alert('Failed to redeem the coupon! Error: ' + jqXHR.responseText);
                                    $(`.panel[data-id='${courseID}'] button.enter`).removeAttr('disabled').removeProp('disabled');
                                    $(`.panel[data-id='${courseID}'] button.enter i.fa`).remove();
                                }
                            }).done(function (data) {
                                if (data && data.success) {
                                    $('#couponModal').modal('hide');
                                    if (data.action == "enter") {
                                        launchEnterClassrooom(courseID, programID, '', certificationAttempt, h, w, openin, title);
                                    }
                                    if (data.action == "enterActivity") {
                                        launchEnterActivity(courseID, programID, '', certificationAttempt, title, type);
                                    }
                                    else if (data.action == "goto") {
                                        window.location = data.url;
                                    }
                                }
                                else {
                                    bootbox.alert('Failed to redeem the coupon! Error: ' + data.LearnerInstruction);

                                    $(`.panel[data-id='${courseID}'] button.enter`).removeAttr('disabled').removeProp('disabled');
                                    $(`.panel[data-id='${courseID}'] button.enter i.fa`).remove();
                                }
                            });
                        });
                        couponContainer.append(btn);
                        $("#couponModal .modal-body").append(couponContainer);
                    }
                    //
                    $('#coupon').val('');
                    $('#couponModal').modal('show');
                }
            }
        }
        return false;
    });
    return false;
}

//using an externa shopping cart, add the item in the shopping cart (either redirect inside AddToCart or directly to handler for ASHP)
var purchaseExternal = function (url, title, price, marqueeElement, cartURL) {
    $.ajax({
        url: url,
        dataType: "json",
        async: false,
        cache: false,
        // data: { "pid": courseID, "ProgramID": programID, "ptype": type, "q": qtyValue, op: "additemtoshoppingcart" },
        //data: { "cid": courseID, "did": programID, "type": type, "qty": qtyValue, op: "additemtoshoppingcart" },
        error: function (jqXHR) {
            bootbox.alert('Failed to add to cart! Error: ' + jqXHR.responseText);
        }
    }).done(function (data) {
        if (data && data.success) {
            if (data.url)
                window.location = data.url;
            //if the external shopping cart handler returns to refresh the cart, call the function to do that (shoudl not be hard-coded to ASHP)
            if (data.checkCart === true)
                TC.checkCart();
            //if not redirecting to another page, show the added to cart confirmation modal
            $('#singleBuyModal').remove();
            // if ($("#singleBuyModal").length == 0) {
            var singleBuyModal = $('<div class="modal fade purchase-alert" id="singleBuyModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">' +
                '<div class="modal-dialog" style="margin-top:auto!important;height:500px!important; width:500px!important;">' +
                '<div class="modal-content">' +
                '<div class="modal-header" style="height:45px;">' +
                '<button type="button" class="close" data-dismiss="modal" data-bs-dismiss="modal" aria-hidden="true"><span class="glyphicon glyphicon-remove"></span></button>' +
                '<h4 class="modal-title">Added to Cart</h4>' +
                '</div>' +
                '<div class="modal-body">' +
                '<div>Your Item was added to the cart</div>' +
                '<div class="purchase-item">' +
                ((typeof (marqueeElement) !== 'undefined') ? ('<span class="marquee_wrap"><img src=\"' + marqueeElement + '" class=\"marquee\"></span>') : '') +
                '<div class="purchase-title">' + title + '</div>' +
                '<div class="purchase-price">' + price + '</div>' +
                '<div class="purchase-quantity">Quantity: 1</div>' +
                '</div>' +
                '<div><button type="button" class="btn btn-default" data-dismiss="modal" data-bs-dismiss="modal">Continue Shopping</button> <a class="btn btn-default" href="' + cartURL + '">Continue to Cart</a></div>' +
                '</div>' +
                //'<button id=\"wizardClearButton\" type=\"button\" class=\"button btn btn-default clear\" value=\"Continue\" title=\"Continue Shopping\" onclick=\"parent.location = \'Student/Catalogue/BrowseCatalogue.aspx\';\" >Continue Shopping</button>' +
                //'<button id=\"wizardNextButton\" type=\"button\" class=\"button btn btn-default next\"  onclick=\"parent.location = "Student/MyLearningActivities.aspx";\">Checkout</button>' +
                //'</div>' +
                '</div>' +
                '</div>' +
                '</div>');
            //}
            //
            $("body").append(singleBuyModal);
            $('#singleBuyModal').modal('show');
        }
        else {
            bootbox.alert('Failed to add to cart! Error: ' + data.message);
        }
    });
};

var OpenEnrollingCourse = function (baseurl, courseID, programID, title, type, el, enrolled, lp) {
    console.log(baseurl + " " + courseID + " " + programID + " " + title + " " + type);
    //
    if (typeof (lp) === 'undefined') {
        // let's see if we can get the lp from the breadcrumbs
        let mapid = getParameterByName('mapID');
        if (mapid !== '') {
            lp = mapid;
        }
    }
    if (enrolled !== true && enrolled !== 'True' && $(el).hasClass('cohort')) {
        if (LMS.cohortSelected !== null && LMS.cohortSelected !== "")
            // OpenExpressStart(baseurl, courseID, programID, title, type, el, enrolled, lp, false);
            enrollCoursNoFastStart(baseurl, courseID, programID, type, LMS.cohortSelected, title, lp, el, true);

    } else {
        enrollCoursNoFastStart(baseurl, courseID, programID, type, null, title, lp, el, true);
        //OpenExpressStart(baseurl, courseID, programID, title, type, el, enrolled, lp, false);
    }
    return false;
}

/// this needs to change
var enrollCoursNoFastStart = function (baseurl, courseID, programID, type, cohort, title, lp, btn, fs) {
    let certificationAttempt = (typeof (el) !== 'undefined' && el !== null && typeof ($(el).data().attempt) !== 'undefined') ? $(el).data().attempt : 0;
    let disclaimer = (typeof (btn) !== 'undefined' && $(btn).data().disclaimer === 'True') ? true : false;
    if (typeof (btn) !== 'undefined') {
        $(btn).prop('disabled', 'true');
        $(btn).prepend('<i class="fa fa-cog fa-spin" style="margin-right:5px;"></i>');
    }
    let faststart = (typeof (fs) !== 'undefined' && fs === true) ? fs : false;
    var inLP = (typeof (lp) !== 'undefined' && lp) ? lp : false;
    setTimeout(function () {
        $.ajax({
            url: baseurl + "Student/EnrollInCourse.ashx",
            async: false,
            cache: false,
            mapid: inLP,
            button: btn,
            eventdata: {
                baseurl: baseurl,
                disclaimer: disclaimer,
                courseid: courseID,
                programid: programID,
                type: type,
                cohort: cohort,
                lpid: inLP,
                faststart: faststart
            },
            data: {
                "CourseID": courseID,
                "ProgramID": programID,
                "Type": type,
                "CohortID": cohort,
                "mapID": inLP,
                "redirectToDetailsPage": redirectToDetailsPage
            }
        }).done(function (result) {
            if (result) {
                var s = result.success;
                var m = result.message;
                if (s == false || s == "false") {
                    var a = result.action;
                    if (a == "goto") {
                        window.location = result.url;
                    }
                    launchExpressStartReason(m, title);
                    if (typeof (this.button) !== 'undefined') {
                        $(this.button).find('.fa-cog').remove();
                    }
                }
                else {
                    var a = result.action;
                    var h = result.height;
                    var w = result.width;
                    var openin = result.modal;
                    if (a === 'enter' && this.eventdata.faststart === true) {
                        if (this.mapid) {
                            launchEnterClassrooom(courseID, programID, this.mapid, certificationAttempt, h, w, openin, title, '', '')
                            // launchEnterClassrooomLP(courseID, programID, this.mapid, '1', h, w, openin, title);
                        } else {
                            launchEnterClassrooom(courseID, programID, '', certificationAttempt, h, w, openin, title);
                        }
                    }
                    if (a == "enter" && this.eventdata.faststart === false) {
                        // don't enter this is method is only for when a catalogue page has fast start turned off//
                        if (typeof (this.button) !== 'undefined') {
                            $(this.button).removeProp('disabled');
                            $(this.button).removeAttr('disabled');
                            $(this.button).find('.fa-cog').remove();
                            $(this.button).text(Nomenclature.translate('Start'));
                            $(this.button).data().enrollment = 'enrolled';
                            $(this.button).data().status = 'Active';

                            $(this.button).removeProp('onclick');
                            let data = {

                                baseurl: this.eventdata.baseurl,
                                courseid: this.eventdata.courseid,
                                programid: this.eventdata.programid,
                                lpid: this.eventdata.lpid,
                                type: this.eventdata.type,
                                cohort: this.eventdata.cohort,

                            };
                            /// now we need to bind the new event to the button ///
                            $(this.button).on('click', data, function (e) {
                                console.log(e.data);
                                let disclaimer = ($(this).data().disclaimer === 'True') ? true : false;
                                if (disclaimer) {
                                    openModal(e.data.baseurl, e.data.courseid, e.data.programid, '', true, null, null, e.data.type, null, e.data.lpid, null);
                                    //openModal = function (baseurl, courseID, programID, title, fastaction, entermode, backbtn, type, returnUrl, activityCount, buttonType)
                                } else {
                                    OpenExpressStart(e.data.baseurl, e.data.courseid, e.data.programid, '', e.data.type, this, true, e.data.lpid, false);
                                }
                            });
                        }

                    }
                    if (a == "goto") {
                        window.location = result.url;
                    }
                    else if (a == "buy")
                        window.location = result.url;
                    else if (a == "showMsg") {
                        launchExpressStartReason(m, title);
                    }
                    else if (a == "seriesEnrollmentRequired") {
                        seriesEnrollmentWizard.show('LPActivityEquivalenciesSelection', courseID, userID, result.url, true, true, false);
                        $('#LPActivityEquivalenciesSelection').modal('toggle');
                    }
                    else if (a == "token") {//user can redeem a course token, ask for the token
                        if ($("#tokenModal").length == 0) {
                            var tokensModal = $('<div class="modal fade course" id="tokenModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">' +
                                '<div class="modal-dialog" style="margin-top:auto!important;height:300px!important; width:500px!important;">' +
                                '<div class="modal-content">' +
                                '<div class="modal-header" style="height:45px;">' +
                                '<button type="button" class="close" data-dismiss="modal" data-bs-dismiss="modal" aria-hidden="true"><span class="glyphicon glyphicon-remove"></span></button>' +
                                '<h4 class="modal-title">' + title + '</h4>' +
                                '</div>' +
                                '<div class="modal-body">' +
                                '</div>' +
                                '</div>' +
                                '</div>' +
                                '</div>');
                            //
                            $("body").append(tokensModal);
                            //
                            var tokenContainer = $('<div style="width:400px;margin:50px auto;"></div>');
                            tokenContainer.append('<label>Enter Token:</label><input type = "text" id="token" value=""></input>');
                            //tokenContainer.append(cohortDD);
                            var btn = $('<button type="button" style="btn btn-default disabled cohort">Submit</button>');
                            var mapID = this.mapid;
                            btn.on('click', function () {
                                var tokenValue = $('#token').val();
                                $.ajax({
                                    url: baseUrl + "Student/Course/DoExpressStart.ashx",
                                    dataType: "json",
                                    async: false,
                                    cache: false,
                                    data: {
                                        "CourseID": courseID,
                                        "ProgramID": programID,
                                        "Type": type,
                                        "mapID": mapID,
                                        "CohortID": cohort,
                                        "PageFastStart": "false",
                                        token: tokenValue,
                                        op: "enrollwithtoken"
                                    },
                                    error: function (jqXHR) {
                                        $('#tokenModal').modal('hide');
                                        bootbox.alert('Failed to redeem the token! Error: ' + jqXHR.responseText);
                                    }
                                }).done(function (data) {
                                    if (data && data.success) {
                                        var h = data.height;
                                        var w = data.width;
                                        var openin = data.modal;
                                        $('#tokenModal').modal('hide');
                                        if (data.action == "enter") {
                                            launchEnterClassrooom(courseID, programID, '', '0', h, w, openin, title);
                                        }
                                        if (data.action == "enterActivity") {
                                            launchEnterActivity(courseID, programID, '', '0', title, type);
                                        }
                                        else if (data.action == "goto") {
                                            window.location = data.url;
                                        }
                                    }
                                    else {
                                        bootbox.alert('Failed to redeem the token! Error: ' + data.message);
                                        $(`.panel[data-id='${courseID}] button.enter`).removeAttr('disabled').removeProp('disabled');
                                    }
                                });
                            });
                            tokenContainer.append(btn);
                            $("#tokenModal .modal-body").append(tokenContainer);
                        }
                        //
                        $('#token').val('');
                        $('#tokenModal').modal('show');
                    }
                    else if (a == "globalTokens") {//user can redeem global tokens, show the confirmation dialog; redeem tokens and enter course if confirmed
                        //var globalTokensValue = response.globalTokensValue;
                        var mapID = this.mapid;
                        bootbox.confirm(m, function (result) {
                            //console.log('This was logged in the callback: ' + result);
                            if (result === true) {
                                $.ajax({
                                    url: baseUrl + "Student/Course/DoExpressStart.ashx",
                                    dataType: "json",
                                    async: false,
                                    cache: false,
                                    data: {
                                        "CourseID": courseID,
                                        "ProgramID": programID,
                                        "Type": type,
                                        "mapID": mapID,
                                        "CohortID": cohort,
                                        "PageFastStart": "false",
                                        op: "enrollwithglobaltokens"
                                    },
                                    error: function (jqXHR) {
                                        bootbox.alert('Failed to redeem the global tokens! Error: ' + jqXHR.responseText);
                                    }
                                }).done(function (data) {
                                    if (data && data.success) {
                                        var h = data.height;
                                        var w = data.width;
                                        var openin = data.modal;
                                        if (data.action == "enter") {
                                            launchEnterClassrooom(courseID, programID, '', '0', h, w, openin, title);
                                        }
                                        if (data.action == "enterActivity") {
                                            launchEnterActivity(courseID, programID, '', '0', title, type);
                                        }
                                        else if (data.action == "goto") {
                                            window.location = data.url;
                                        }
                                    }
                                    else {
                                        bootbox.alert('Failed to redeem the global tokens! Error: ' + data.message);
                                    }
                                });
                            }
                        });
                    }
                    else if (a == "couponOnly") {//user can redeem a 100 % coupon only , ask for the coupon
                        if ($('#couponModal').length > 1) {
                            $('#couponModal').remove();
                        }
                        if ($("#couponModal").length == 0) {
                            var couponModal = $('<div class="modal fade course" id="couponModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">' +
                                '<div class="modal-dialog" style="margin-top:auto!important;height:300px!important; width:500px!important;">' +
                                '<div class="modal-content">' +
                                '<div class="modal-header" style="height:45px;">' +
                                '<button type="button" class="close" data-dismiss="modal" data-bs-dismiss="modal" aria-hidden="true"><span class="glyphicon glyphicon-remove"></span></button>' +
                                '<h4 class="modal-title">' + title + '</h4>' +
                                '</div>' +
                                '<div class="modal-body">' +
                                '</div>' +
                                '</div>' +
                                '</div>' +
                                '</div>');
                            //
                            $("body").append(couponModal);
                            //
                            var couponContainer = $('<div style="width:400px;margin:50px auto;"></div>');
                            couponContainer.append('<label>Enter Coupon:</label><input type = "text" id="coupon" value=""></input>');
                            //tokenContainer.append(cohortDD);
                            var btn = $('<button type="button" style="btn btn-default disabled cohort">Submit</button>');
                            var lpid = "";
                            try {
                                lpid = e.data.lpid;
                            }
                            catch { }

                            btn.on('click', function () {
                                var couponValue = $('#coupon').val();
                                $.ajax({
                                    url: baseUrl + "Student/eCommerce/ValidateCoupon.ashx",
                                    dataType: "json",
                                    async: false,
                                    cache: false,
                                    data: {
                                        "courseID": courseID,
                                        "domainID": programID,
                                        "Type": type,
                                        "mapID": lpid,
                                        "CohortID": cohort,
                                        coupon: couponValue,
                                        op: "RedeemFullCouponCodeEnroll"
                                    },
                                    error: function (jqXHR) {
                                        $('#couponModal').modal('hide');
                                        bootbox.alert('Failed to redeem the coupon! Error: ' + jqXHR.responseText);

                                        $(`.panel[data-id='${courseID}'] button.enter`).removeAttr('disabled').removeProp('disabled');
                                        $(`.panel[data-id='${courseID}'] button.enter i.fa`).remove();
                                    }
                                }).done(function (data) {
                                    if (data && data.success) {
                                        $('#couponModal').modal('hide');
                                        if (data.ButtonURL !== "" && data.ButtonText != "") {

                                            bootbox.confirm({
                                                title: data.ButtonText,
                                                message: data.LearnerInstruction,
                                                buttons: {
                                                    confirm: {
                                                        label: '<i class="fa fa-check"></i> ' + data.ButtonText
                                                    }
                                                },
                                                callback: function (result) {
                                                    if (result == true)
                                                        window.location = data.ButtonURL;
                                                }
                                            });
                                        }
                                    }
                                    else {
                                        bootbox.alert('Failed to redeem the coupon! Error: ' + data.LearnerInstruction);
                                        $(`.panel[data-id='${courseID}'] button.enter`).removeAttr('disabled').removeProp('disabled');
                                        $(`.panel[data-id='${courseID}'] button.enter i.fa`).remove();
                                    }
                                });
                            });
                            couponContainer.append(btn);
                            $("#couponModal .modal-body").append(couponContainer);
                        }
                        //
                        $('#coupon').val('');
                        $('#couponModal').modal('show');
                    }
                }
            }
            return false;
        });
    }, 500);
}


var chooseCohort = function (baseurl, courseID, programID, title, type, el, enrolled, backMode) {
    var btn = $(el);
};

var AddToCartNoFastStart = function (baseurl, courseID, programID, title, type, el, enrolled, backMode) {
    console.log("navigation.js::AddToCartNoFastStart - baseUrl: " + baseurl + ", courseID: " + courseID + ", programID: " + programID + ", type: " + type);
    //
    if (enrolled !== true && enrolled !== 'True' && $(el).hasClass('cohort')) {
        if (LMS.cohortSelected !== null && LMS.cohortSelected !== "")
            parent.location = baseurl + 'Student/eCommerce/AddToCart.aspx?ItemID=' + courseID + '&Type=' + type + '&back=' + backMode + '&ProgramID=' + programID + '&CohortID=' + LMS.cohortSelected;
    } else {
        parent.location = baseurl + 'Student/eCommerce/AddToCart.aspx?ItemID=' + courseID + '&Type=' + type + '&back=' + backMode + '&ProgramID=' + programID;
    }
    return false;
}

///////////////////////////////////
//popup window, ask how many and if they want one code or multiples
//make it go to doaddtocart handler, then decide what custom cart
var AddToCartForOthers = function (baseurl, courseID, programID, title, type, el, backMode) {
    console.log(baseurl + " " + courseID + " " + programID + " " + type);
    //////////////////////////////
    $('#multipleBuyModal').remove();
    if ($("#multipleBuyModal").length == 0) {
        var multipleBuyModal = $('<div class="modal fade course" id="multipleBuyModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">' +
            '<div class="modal-dialog" style="margin-top:auto!important;height:500px!important; width:500px!important;">' +
            '<div class="modal-content">' +
            '<div class="modal-header" style="height:45px;">' +
            '<button type="button" class="close" data-dismiss="modal" data-bs-dismiss="modal" aria-hidden="true"><span class="glyphicon glyphicon-remove"></span></button>' +
            '<h4 class="modal-title">' + title + ' - Purchase for Others</h4>' +
            '</div>' +
            '<div class="modal-body">' +
            '</div>' +
            '</div>' +
            '</div>' +
            '</div>');
        //
        $("body").append(multipleBuyModal);
        //
        //var modeContainer = $('<div style="width:500px;margin:50px auto;"></div>');
        //modeContainer.append('<span class="th attended"><input type="radio" id="oneCode" name="codesMode"  />Create one reusable code</span>');
        //modeContainer.append('<span class="th attended"><input type="radio" id="multipleCodes" name="codesMode"  />Create multiple codes</span>');

        //$("#multipleBuyModal .modal-body").append(modeContainer);

        var qtyContainer = $('<div style="width:400px;margin:50px auto;"></div>');
        qtyContainer.append('<label>Quantity:</label><input type = "text" id="qty" value=""></input>');
        var btn = $('<button type="button" class="btn btn-default">Submit</button>');

        btn.on('click', function () {
            var qtyValue = $('#qty').val();
            //if (qtyValue == 1)//buy for yourself then ?ItemID='+passID + '&Type=Pass 
            // parent.location = baseurl + "Student/eCommerce/AddToCart.aspx?ItemID= " + courseID + "&Type=Course"; 

            $.ajax({
                // url: baseurl + "Student/CustomPages/ASHPHandler.ashx",
                url: baseurl + "Student/eCommerce/DoAddToCart.ashx",
                dataType: "json",
                async: false,
                cache: false,
                data: { "ItemID": courseID, "ProgramID": programID, "type": type, "Quantity": qtyValue, op: "purchaseForOthers" },
                //data: { "cid": courseID, "did": programID, "type": type, "qty": qtyValue, op: "additemtoshoppingcart" },
                error: function (jqXHR) {
                    $('#multipleBuyModal').modal('hide');
                    bootbox.alert('Failed to add to cart! Error: ' + jqXHR.responseText);
                }
            }).done(function (data) {
                if (data && data.success) {

                    if (data.url)
                        window.location = data.url;
                    //if the external shopping cart handler returns to refresh the cart, call the function to do that (shoudl not be hard-coded to ASHP)
                    if (data.checkCart === true)
                        TC.checkCart();
                    //if not redirecting to another page, show the added to cart confirmation modal
                    var popupBody = $('#multipleBuyModal .modal-body');
                    var wizardDiv = $("<div style='width: 600px; margin: 50px auto;' />");
                    wizardDiv.append('<span>Your Item was added to the cart</span><br/>');
                    //var wizardClearButtonDiv = $("<button id=\"wizardClearButton\" type=\"button\" class=\"button btn btn-default clear\" value=\"Continue\" title=\"Continue Shopping\" onclick=\"parent.location = 'Student/Catalogue/BrowseCatalogue.aspx';\" >Continue Shopping</button>");
                    //var wizardNextButtonDiv = $("<button id=\"wizardNextButton\" type=\"button\" class=\"button btn btn-default next\"  onclick=\"parent.location = 'Student/MyLearningActivities.aspx';\">Go to My Courses</button>");
                    //wizardDiv.append(wizardClearButtonDiv);
                    //wizardDiv.append(wizardNextButtonDiv);
                    //
                    popupBody.empty();
                    popupBody.append(wizardDiv);
                }
                else {
                    bootbox.alert('Failed to add to cart! Error: ' + data.message);
                }
            });
        });
        qtyContainer.append(btn);
        $("#multipleBuyModal .modal-body").append(qtyContainer);
    }
    //
    $('#multipleBuyModal').modal('show');
    return false;
}

var AddToCartExternal = function (baseurl, courseID, programID, title, type, el, enrolled, backMode) {
    var cohortID = "";
    if (enrolled !== true && enrolled !== 'True' && $(el).hasClass('cohort')) {
        if (LMS.cohortSelected !== null && LMS.cohortSelected !== "")
            cohortID = LMS.cohortSelected;
    }
    cohortEnroll(courseID, programID, type, cohortID, title, el, null)
}

//enter classroom opener that works with Firefox
function launchExpressStartReason(reason, title) {
    var dialog = bootbox.dialog({
        title: title,
        message: "<p>" + reason + "</p>",
        size: 'large',
        buttons: {
            ok: {
                label: "Close",
                className: 'btn-info'
            }
        }
    });

    /*no need for all this, it's just a message!
    if (!height) {
        var height = 600;
    }
    if (!width) {
        var width = 800;
    }

    if (isMobile.iOS()) {
        $("body").append('<div class="modal fade course" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"><div class="modal-dialog" style="margin-top:0px!important;height:95%!important; width:95%!important;"><div class="modal-content"><div class="modal-header" style="height:45px;"><button type="button" class="close" data-dismiss="modal" data-bs-dismiss="modal" aria-hidden="true"><span class="glyphicon glyphicon-remove"></span></button><h4 class="modal-title">' + title + '</h4></div><div class="modal-body"><iframe allowtransparency="true" style="height:100%;background-repeat:no-repeat;background-position: center;"id="viewCourseModal" allowFullScreen="true" webkitallowfullscreen="true" mozallowfullscreen="true" name="viewCourse"  frameborder = "0" height="100%" width="100%"></iframe></div></div></div></div>');
    } else {
        $("body").append('<div class="modal fade course" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"><div class="modal-dialog" style="height:' + height + 'px!important; width:' + width + 'px!important;"><div class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" data-bs-dismiss="modal" aria-hidden="true"><span class="glyphicon glyphicon-remove"></span></button><h4 class="modal-title">' + title + '</h4></div><div class="modal-body"><iframe allowtransparency="true" style="background-repeat:no-repeat;background-position: center;" id="viewCourseModal" allowFullScreen="true" webkitallowfullscreen="true" mozallowfullscreen="true" name="viewCourse"  frameborder = "0" height="' + height + '" width="' + width + '"></iframe></div></div></div></div>');
    }
    $('#myModal').modal('show', { show: true, keyboard: false });
    if (isMobile.iOS()) {
        $('.modal.course iframe').css('height', '100%');
    } else {
        $('.modal.course iframe').css('height', height);
    }
    $('.modal.course iframe').css('display', 'none');
    $('.modal.course iframe').css('margin', '0 auto');
    $('.modal.course iframe').wrap('<div class="coursemodule"><span>' + reason + '</span></div>');
    if (browser_type.indexOf('Fire') >= 0)
        setTimeout(function () { $('#myModal').removeClass('in'); $('#myModal').removeClass('fade'); $('#myModal .modal-body').css('padding', '0px'); }, 1000);
    //$("#viewCourseModal").attr('src', redirectURL);
    $('.modal.course iframe').css('display', 'block');
    $('#myModal').unbind('click');
    $('.modal-header button.close').on('click', function () {
        var w = $("iframe")[0].contentWindow;

        //$("#viewCourseModal").attr('src', '');
        $('#myModal').modal('hide');//parent.history.back();
        setTimeout(function () { $('#myModal').remove(); }, 1000)
    });
    */
    return false;
}

//enter classroom opener that works with Firefox
function launchExpressStartActivityModal(reason, title) {
    if (!height) {
        var height = 600;
    }
    if (!width) {
        var width = 800;
    }

    if (isMobile.iOS()) {
        $("body").append('<div class="modal fade course" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"><div class="modal-dialog" style="margin-top:0px!important;height:95%!important; width:95%!important;"><div class="modal-content"><div class="modal-header" style="height:45px;"><button type="button" class="close" data-dismiss="modal" data-bs-dismiss="modal" aria-hidden="true"><span class="glyphicon glyphicon-remove"></span></button><h4 class="modal-title">' + title + '</h4></div><div class="modal-body"><iframe allowtransparency="true" style="height:100%;background-repeat:no-repeat;background-position: center;"id="viewCourseModal" allowFullScreen="true" webkitallowfullscreen="true" mozallowfullscreen="true" name="viewCourse"  frameborder = "0" height="100%" width="100%"></iframe></div></div></div></div>');
    } else {
        $("body").append('<div class="modal fade course" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"><div class="modal-dialog" style="height:' + height + 'px!important; width:' + width + 'px!important;"><div class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" data-bs-dismiss="modal" aria-hidden="true"><span class="glyphicon glyphicon-remove"></span></button><h4 class="modal-title">' + title + '</h4></div><div class="modal-body"><iframe allowtransparency="true" style="background-repeat:no-repeat;background-position: center;" id="viewCourseModal" allowFullScreen="true" webkitallowfullscreen="true" mozallowfullscreen="true" name="viewCourse"  frameborder = "0" height="' + height + '" width="' + width + '"></iframe></div></div></div></div>');
    }
    $('#myModal').modal('show', { show: true, keyboard: false });
    if (isMobile.iOS()) {
        $('.modal.course iframe').css('height', '100%');
    } else {
        $('.modal.course iframe').css('height', height);
    }
    $('.modal.course iframe').css('display', 'none');
    $('.modal.course iframe').css('margin', '0 auto');
    $('.modal.course iframe').wrap('<div class="coursemodule"><span>' + reason + '</span></div>');
    if (browser_type.indexOf('Fire') >= 0)
        setTimeout(function () { $('#myModal').removeClass('in'); $('#myModal').removeClass('fade'); $('#myModal .modal-body').css('padding', '0px'); }, 1000);
    //$("#viewCourseModal").attr('src', redirectURL);
    $('.modal.course iframe').css('display', 'block');
    $('#myModal').unbind('click');
    $('.modal-header button.close').on('click', function () {
        var w = $(".modal.course iframe")[0].contentWindow;

        //$("#viewCourseModal").attr('src', '');
        $('#myModal').modal('hide');//parent.history.back();
        setTimeout(function () { $('#myModal').remove(); }, 1000)
    });
    return false;
}

var openModal = function (baseurl, courseID, programID, title, fastaction, entermode, backbtn, type, returnUrl, learningpathID, buttonType) {

    // var redirectURL = baseurl + "Student/Disclaimer.aspx?courseID=" + courseID + "&programID=" + programID + "&fastaction=" + fastaction + "&entermode=" + entermode + "&backbutton=" + backbtn + "&type=" + type;
    var redirectURL = baseurl + "Student/Disclaimer.aspx?courseID=" + courseID + "&programID=" + programID + "&fastaction=" + fastaction + "&entermode=" + entermode + "&learningpathID=" + learningpathID + "&backbutton=" + backbtn + "&type=" + type + "&buttonType=" + buttonType;

    $("body").append('<div class="modal fade course" id="myModalDisc" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"><div class="modal-dialog" style="height:800px!important; width:800px!important;"><div class="modal-content"><div class="modal-header"><h4 class="modal-title">' + title + '</h4></div><div class="modal-body"><iframe id="viewDisclaimerModal" allowFullScreen="true" webkitallowfullscreen="true" mozallowfullscreen="true" name="viewDisclaimer"  frameborder = "0" height="800" width="800" /></div></div></div></div>');
    $('#myModalDisc').modal('show', { show: true, keyboard: false });


    // $('.modal.course iframe').css('display', 'none');
    // $('.modal.course iframe').css('margin', '0 auto');
    if (browser_type.indexOf('Fire') >= 0)
        setTimeout(function () { $('#myModalDisc').removeClass('in'); $('#myModalDisc').removeClass('fade'); $('#myModalDisc .modal-body').css('padding', '0px'); }, 1000);
    $("#viewDisclaimerModal").attr('src', redirectURL);
    $('.modal.course iframe').css('display', 'block');
    $('#myModalDisc').unbind('click');

    $('.modal-header button.close').on('click', function () {
        var w = $(".modal.course iframe")[0].contentWindow;

        $("#viewDisclaimerModal").attr('src', '');
        $('#myModalDisc').modal('hide');

        setTimeout(function () {
            $('#myModalDisc').remove();
            if (returnUrl && returnUrl.length > 0)
                window.location.href = returnUrl;
        }, 1000);

    });
    return false;
}


//?? what is this used for. 
var openModal = function (baseurl, courseID, programID, title, fastaction, entermode, backbtn, type, returnUrl, activityCount, buttonType) {
    /// for testing localally


    if (typeof (activityCount) !== 'undefined' && activityCount.length == 36)
        var redirectURL = baseurl + "Student/Disclaimer.aspx?modal=true&courseID=" + courseID + "&programID=" + programID + "&fastaction=" + fastaction + "&entermode=" + entermode + "&learningpathID=" + activityCount + "&backbutton=" + backbtn + "&type=" + type + "&buttonType=" + buttonType;
    else
        var redirectURL = baseurl + "Student/Disclaimer.aspx?modal=true&courseID=" + courseID + "&programID=" + programID + "&fastaction=" + fastaction + "&entermode=" + entermode + "&backbutton=" + backbtn + "&type=" + type + "&activityCount=" + activityCount + "&buttonType=" + buttonType;
    //window.location = response;
    var mobile = (isMobile.any() !== null) ? "width:95%;" : "";
    let closeButton = (location.href.indexOf('ContentPage.aspx') >= 0) ? '<button type="button" class="close" data-dismiss="modal" data-bs-dismiss="modal" aria-hidden="true" aria-label="Close button"><span class="glyphicon glyphicon-remove"></span></button>' : '';
    $("body #content.container").append('<div class="modal fade course" id="myModal" runat="server" tabindex="-1" role="dialog" aria-hidden="true"><div class="modal-dialog" style="margin-top:5px!important;height:100%!important;' + mobile + '"><div class="modal-content course_' + courseID + '" style="height:95%"><div class="modal-header header_' + courseID + '" style="height:45px;"><h4 class="modal-title">' + title + '</h4>' + closeButton + '</div><div class="modal-body" style="height:100%;"><iframe id="viewDisclaimerModal" allowFullScreen="true" webkitallowfullscreen="true" mozallowfullscreen="true" name="viewDisclaimerModal"  frameborder = "0" height="100%" width="100%" /></div></div></div></div>');
    $('#myModal').modal('show', { show: true, keyboard: false });

    $('.modal.course iframe').css('display', 'none');
    $('.modal.course iframe').css('margin', '0 auto');
    //$('.modal.course iframe').wrap('<div class="coursemodule" style="height:100%;"></div>');
    if (browser_type.indexOf('Fire') >= 0)
        setTimeout(function () { $('#myModal').removeClass('in'); $('#myModal').removeClass('fade'); $('#myModal .modal-body').css('padding', '0px'); }, 1000);
    $("#viewDisclaimerModal").attr('src', redirectURL);
    $('.modal.course iframe').css('display', 'block');
    $('#myModal').unbind('click');

    setTimeout(function () {
        $('.modal.course iframe').attr('height', ($('.course_' + courseID).innerHeight() - $('.header_' + courseID).outerHeight() - 10) + 'px');
    }, 1000)

    $('.modal-header button.close').on('click', function () {
        var w = $(".modal.course iframe")[0].contentWindow;

        $("#viewDisclaimerModal").attr('src', '');
        $('#myModal').modal('hide');

        setTimeout(function () {
            $('#myModal').remove();
            if (location.href.indexOf('ContentPage.aspx') < 0) {
                /// don't refresh page if they close the disclaimer
                if (returnUrl && returnUrl.length > 0)
                    window.location.href = returnUrl;//window.location.href + '&returnUrl=' + returnUrl;
            }
        }, 1000);//parent.history.back();

    });
    return false;
}

//enter classroom opener that works with Firefox
function launchEnterActivity(courseID, programID, learningPathID, attempt, title, type) {
    if (location.href.indexOf('MyLearningActivities.aspx') >= 0)
        $('#activity_' + courseID).remove();
    if ($('#activity_' + courseID).length === 0) {
        if (browser_type.indexOf('Safari') >= 0) {
            console.log('safari bug fix');
        }
        if (!title) {
            var title = " ";
        }
        //PLEASE MIND THE PARAMETER CASE
        var redirectURL = baseUrl + "Student/MyCourse.aspx?modal=true&id=" + courseID + "&ProgramID=" + programID + "&popup=true&Attempt=" + attempt;
        if (learningPathID.length > 0)
            redirectURL += "&lpID=" + learningPathID;

        try {
            $("#myModalDisc").modal('hide');
            $("#myModalDisc").remove();

            $("#myModal").modal('hide');
            $("#myModal").remove();

        }
        catch (e) { }

        $('#myActivityModal').remove();
        if (isMobile.iOS()) {
            $("body").append('<div class="modal fade course ' + type + '" id="myActivityModal" data-id="' + courseID + '" tabindex="-1" role="dialog" aria-labelledby="myActivityModalLabel" aria-hidden="true"><div class="modal-dialog" style="margin-top:0px!important;height:95%!important; width:100%!important;"><div class="modal-content" style="height:90%"><div class="modal-header" style="height:45px;"><button type="button" class="close" data-dismiss="modal" data-bs-dismiss="modal" aria-hidden="true"><span class="glyphicon glyphicon-remove"></span></button><h4 class="modal-title" id="myModalLabel">' + title + '</h4></div><div class="modal-body" style="height:100%;"><iframe id="viewActivityModal" allowFullScreen="true" webkitallowfullscreen="true" mozallowfullscreen="true" name="viewActivity"  frameborder = "0" height="100%" width="100%"></iframe></div></div></div></div>');
        } else {
            var h = Math.floor($(window).height() * .80);
            var w = Math.floor($(window).width() * .75);
            $("body").append('<div class="modal fade course ' + type + '" id="myActivityModal" data-id="' + courseID + '"  tabindex="-1" role="dialog" aria-labelledby="myActivityModalLabel" aria-hidden="true"><div class="modal-dialog" style="height:' + h + 'px !important; width:' + w + 'px !important;"><div class="modal-content" style="width:100%;height:100%"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" data-bs-dismiss="modal" aria-hidden="true"><span class="glyphicon glyphicon-remove"></span></button><h4 class="modal-title" id="myModalLabel">' + title + '</h4></div><div class="modal-body" style="width:100%;height:100%"><iframe id="viewActivityModal" allowFullScreen="true" webkitallowfullscreen="true" mozallowfullscreen="true" name="viewActivity"  frameborder = "0" height="100%" width="100%"></iframe></div></div></div></div>');
        }
        if (typeof (isLP) !== 'undefined' && isLP) {
            $('#myActivityModal').on('hidden.bs.modal', function () {
                let activity = $(this).data().id;
                TC.checkLPStatus();
            });
        }

        $('#myActivityModal').modal('show', { show: true, keyboard: false });


        if (isMobile.iOS()) {
            $('.modal.course iframe').css('height', '100%');
        } else {
            $('.modal.course iframe').css('height', '100%');
        }
        $('.modal.course iframe').css('display', 'none');
        $('.modal.course iframe').css('margin', '0 auto');
        $('.modal.course iframe').wrap('<div class="coursemodule" style="height:100%;"></div>');
        if (browser_type.indexOf('Fire') >= 0)
            setTimeout(function () { $('#myActivityModal').removeClass('in'); $('#myActivityModal').removeClass('fade'); $('#myActivityModal .modal-body').css('padding', '0px'); }, 1000);
        $("#viewActivityModal").attr('src', redirectURL);
        $('.modal.course iframe').css('display', 'block');

        //$("#myActivityModal").on("shown.bs.modal", function () {
        //    $('h1.page_title').remove();
        //});
        $('h1.page_title').remove();
        $('#myActivityModal').unbind('click');


        $('.modal-header button.close').on('click', function () {
            $('#myActivityModal').modal('hide');
            // refresh the catalogue when an activity is closed
            // check the lp status instead of refreshing
            //if (isLP) {
            //    TC.checkLPStatus();
            //} else {

            setTimeout(function () {
                if (typeof (learningPathID) !== 'undefined' && learningPathID !== '')
                    courseID = learningPathID;
                $('#myActivityModal').remove();
                //if (returnUrl && returnUrl != null && returnUrl.length > 0 && window.location.href.indexOf('MyCourse') < 0) {
                //    window.location.href = returnUrl;
                //} else {
                var url = window.location.href;
                var path = window.location.pathname;
                switch (true) {
                    case url.indexOf('MyLearningActivities.aspx') >= 0:
                        {
                            if (redirectToDetailsPage == 'undefined' || redirectToDetailsPage) {
                                url = baseUrl + 'Student/MyCourse.aspx?id=' + courseID + '&ProgramID=' + programID + '&returnUrl=' + window.location.href;
                            }
                            else {
                                url = baseUrl + 'Student/MyLearningActivities.aspx';
                            }
                        }

                        break;
                    case url.indexOf('Catalogue') >= 0:
                        {
                            if (redirectToDetailsPage == 'undefined' || redirectToDetailsPage) {
                                url = baseUrl + 'Student/MyCourse.aspx?id=' + courseID + '&ProgramID=' + programID + '&returnUrl=' + url;
                            }
                            else {
                                url = window.location.href;
                            }
                        }
                        break;
                    case url.indexOf('type=lp') >= 0: url = url;
                        break;
                    case url.indexOf('MyCourses.aspx') >= 0:
                        {
                            if (redirectToDetailsPage == 'undefined' || redirectToDetailsPage) {
                                url = baseUrl + 'Student/MyCourse.aspx?id=' + courseID + '&ProgramID=' + programID + '&returnUrl=' + url;
                            }
                            else {
                                url = baseUrl + 'Student/MyCourses.aspx';
                            }
                        }
                        break;
                    //default: if (redirectToDetailsPage !== 'undefined' && redirectToDetailsPage) url = baseUrl + 'Student/MyCourse.aspx?id=' + courseID + '&ProgramID=' + programID + '&returnUrl=' + url; else url = window.location.href; url = url.replace('&start=true', '');


                    default: url = window.location.href; url = url.replace('&start=true', '');
                        break;
                }
                window.location.href = url;
                // }//window.location.href + '&returnUrl=' + returnUrl;
            }, 2000);

            //}
        });

    }
    else {
        $('#activity_' + courseID).modal('show');
    }
}

function ScriptSelfSignOff(CourseID, DomainID, CourseType, CertiAttempt) {

    var result = false;
    $.ajax({
        url: "Student/DoEnrollInCourse.ashx",
        dataType: "json",
        async: false,
        data: {
            type: CourseType,
            op: 'accessiblityscriptcompletion',
            cid: CourseID,
            did: DomainID,
            attept: CertiAttempt
        },
        error: function () {
            $("#ErrorMessage").css("display", "block");
        },
        success: function (data) {
            if (data) {
                if (data.isSuccess === 'ok' || data.isSuccess === 'Ok') {
                    var activity_cart_URL = baseUrl + '/Student/MyCourse.aspx?id=' + CourseID;
                    window.location.href = activity_cart_URL;
                } else {
                    $("#ErrorMessage").css("display", "block");
                }
            }
        }

    });
    return result;
}


/// Form values change checking
if (typeof (TC) === 'undefined')
    TC = {};

if (typeof (closeMessage) === 'undefined') {
    var closeMessage = function () {
        // canClose = confirm("You have unsaved changes.")

        return true;//canClose;
    }
}

TC.formWatch = {

    changed: false,
    subBtn: {
        el: null,
        id: null,
        clicked: false
    },
    init: function (btn) {
        canClose = true;
        this.subBtn.el = $(btn);
        this.subBtn.id = $(btn).prop('id');
        console.log('subBtn id: ' + this.subBtn.id);
        if (typeof (formSaved) === 'undefined') {
            if (typeof (isPostBack) !== 'undefined') {
                if (isPostBack === 'False' /*|| (typeof (checkformWatch) !== 'undefined' && checkformWatch == 'true')*/) {
                    this.subBtn.el.prop('disabled', 'true');
                } else {
                    this.subBtn.el.removeProp('disabled');
                    this.subBtn.el.removeAttr('disabled');
                    TC.formWatch.changed = true;
                    canClose = false;
                }
            }

            //can't show a custom dialog at onbeforunload, return false with setting the text to show is all that can be done
            window.onbeforeunload = function () {
                if (TC.formWatch.changed === true//things changed on the page
                    && TC.formWatch.subBtn.clicked === false//not clicked the submit button used when initializing
                    && (typeof (checkformWatch) !== 'undefined' && checkformWatch == 'true')//page is set to watch for changes
                    && (typeof (isPostBack) === 'undefined' || isPostBack === 'False')//is not PostBack
                ) {
                    //console.log('unload with changes!');
                    //
                    return false;
                }
            }

            this.subBtn.el.on('click', function () {
                TC.formWatch.subBtn.clicked = true;
                canClose = true;
            });

            $(':input').on('input', function () {
                console.log(':input input!');
                if (TC.formWatch.changed === false) {
                    TC.formWatch.enable();
                    TC.formWatch.changed = true;
                    canClose = false;
                }
            });

            //need this for date controls when a date is selected not added by hand; there is no input event in that case, but a change
            $(':input').on('change', function () {
                console.log('input change!');
                if (TC.formWatch.changed === false) {
                    TC.formWatch.enable();
                    TC.formWatch.changed = true;
                    canClose = false;
                }
            });

            $('button[type="submit"]').on('mousedown', function () {
                //TC.formWatch.changed = true;
                //if (this.id.toLowerCase() !== 'backbutton')
                if (this.id?.toLowerCase() === TC.formWatch.subBtn.id?.toLowerCase())//only if clicked on the initialized submit button
                    TC.formWatch.subBtn.clicked = true;
            });

            $('input[type=checkbox]').on('click', function () {
                console.log('input[type=checkbox] click!');
                if (TC.formWatch.changed === false) {
                    TC.formWatch.enable();
                    TC.formWatch.changed = true;
                    canClose = false;
                }
            });

            $('.checkbox').on('click', function () {
                console.log('.checkbox click!');
                if (TC.formWatch.changed === false) {
                    TC.formWatch.enable();
                    TC.formWatch.changed = true;
                    canClose = false;
                }
            });

            $('textarea').on('input', function () {
                console.log('textarea input!');
                if (TC.formWatch.changed === false) {
                    TC.formWatch.enable();
                    TC.formWatch.changed = true;
                    canClose = false;
                }
            });
        }
    },
    enable: function () {
        canClose = false;
        this.subBtn.el.removeProp('disabled');
        this.subBtn.el.removeAttr('disabled');
    }
}

//$(document).ready(function () {
//    if (window.location.href.indexOf('Registrar/ViewTranscript_v2.aspx') >= 0) {
//        $.getScript('responsive/js/badges/badges.js', function () {
//            TC.LearnerBadges.loadBadges('#badges', learnerid, 'admin');
//        })
//    }
//});

var showError = function (t) {
    bootbox.alert('There has been an issue starting this course. Details: ' + t);
    /*
    if ($("#errorModal").length == 0) {
        var errorModal = $('<div class="modal fade course" id="errorModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">' +
                    '<div class="modal-dialog" style="margin-top:auto!important;height:300px!important; width:500px!important;">' +
                        '<div class="modal-content">' +
                            '<div class="modal-header" style="height:45px;">' +
                                '<button type="button" class="close" data-dismiss="modal" data-bs-dismiss="modal" aria-hidden="true"><i class="fa fa-close"></i></button>' +
                                '<h4 class="modal-title">Error</h4>' +
                            '</div>' +
                        '<div class="modal-body" style="height:300px;padding:50px;">There has been an issue starting this course.</div>' +
                    '</div>' +
                '</div>' +
            '</div>');
        //
        $("body").append(errorModal);

    }
    */
    // $("#errorModal").modal('show');
};

var doLPRollupRefresh = function (lpid, uid, returnURL) {
    $('#refreshLPSpan').hide();
    $.ajax({
        url: baseUrl + "/Student/MyLPHandler.ashx",
        async: false,
        cache: false,
        data: { "lpid": lpid, "uid": uid, "op": "doLPRollup" }
    }).done(function (result) {
        if (result) {
            var s = result.result;
            var m = result.error;
            if (s == false || s == "false") {
                bootbox.alert('Failed to rollup the learning path');
            }
            else {
                // bootbox.alert('rolled up the learning path');
                window.location = returnURL;
            }
        }
        return false;
    });
};

var doCertRefresh = function (cid, uid, rid) {
    $('#refreshLPSpan').hide();
    $.ajax({
        url: baseUrl + "/Student/StudentLOHandler.ashx",
        async: false,
        cache: false,
        data: { "learnerID": uid, "learningObjectID": cid, "rid": rid, "op": "doCertRefresh" }
    }).done(function (result) {
        if (result) {
            var s = result.result;
            var m = result.error;
            if (s == false || s == "false") {
                bootbox.alert('Failed to clear certificate.');
            }
            else {
                bootbox.alert('Cleared certificate.');
            }
        }
        return false;
    });
}

$(document).ready(function () {
    // let's add an and after each rule row
    $.each($('div.rule-grouping'), function () {
        let rules = $(this).find('tr');
        let multirule = $(this).find('.multi-rule-matching');
        if (rules.length < 3) {
            multirule.hide();
        }

    });
    $.each($('table.rules-table tr ul'), function () {
        let rules = $(this).find('li');
        $.each(rules, function (index) {
            if (index < rules.length - 1)
                $("<li style='list-style-type:none;padding-left:20px;'>and</li>").insertAfter($(this));
        });

    });

    $(document).on('click', '#submenu .nav a', function (e) {
        e.preventDefault();
        const url = $(this).attr('href');
        const overlay = `<div class="overlay" style="height:100%;width:100%;position:absolute;background-color:rgba(39,39,39,0.5);z-index:9999;top:0;"><div class="dash-loader"></div> </div>`;
        $('body').append(overlay).css('position', 'relative').css('overflow', 'hidden').css('pointer-events', 'none');
        window.location = url;
    });
});


